返回 CodeWhale
fleet_setup.rs
根目录 / crates / tui / src / tui / views / fleet_setup.rs
1 //! Legacy-profile setup — a progressive "set up your agent team" flow.
2 //!
3 //! `/fleet setup` routes here only when no named v2 Fleet is selected. When a
4 //! v2 Fleet is selected, the host opens that Fleet's exact detail editor so a
5 //! save can never appear to update a member while writing an ignored legacy
6 //! `.codewhale/agents/*.toml` profile.
7 //!
8 //! Replaces the old six-column config matrix (#3791). Fleet is presented as an
9 //! agent team: the shortest valid path remains role → provider/model →
10 //! save/apply. From the Model step, `c` opens an optional, pure composition
11 //! advisory built only from configured routes; accept/edit/reject all return to
12 //! this same human-reviewed save path.
13 //! The review step shows resolved provider, model, auth/readiness, profile
14 //! availability, and overwrite consequences once before anything is written. Thinking defaults to
15 //! inherit and can be adjusted on the review step without an extra wizard
16 //! screen. "Save profile" persists the exact rendered TOML bytes.
17 //!
18 //! NOTE (audit #7 / #3167): the role/model taxonomy and copy below are
19 //! intentionally English for now; #3167 reworks this into an interactive
20 //! provider/model picker that will churn most of this text. The command entry
21 //! (`CmdFleetDescription`) is already localized.
22
23 use std::borrow::Cow;
24 use std::cell::RefCell;
25 use std::collections::BTreeSet;
26 use std::path::{Path, PathBuf};
27
28 use codewhale_workflow::fleet_composition::{
29 CompositionError, CompositionRole, ConfiguredModel, FleetCompositionProposal,
30 FleetCompositionRequest, RatificationState, RoleSuggestion,
31 };
32 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
33 use ratatui::{
34 buffer::Buffer,
35 layout::{Constraint, Direction, Layout, Rect},
36 style::Style,
37 text::{Line, Span},
38 widgets::{Padding, Paragraph, Widget, Wrap},
39 };
40
41 use crate::tui::app::App;
42 use crate::tui::views::{
43 ActionHint, ModalKind, ModalView, SurfaceFrame, ViewAction, ViewEvent, centered_modal_area,
44 render_modal_footer_with_gutter, render_rounded_modal, truncate_view_text,
45 };
46 use codewhale_agent_contract::role::public_role_label;
47 use codewhale_engine::fleet::profile::FleetProfileScope;
48 use codewhale_localization::{MessageId, tr};
49 use codewhale_palette as palette;
50 use codewhale_runtime::config::Config;
51 use codewhale_tui_kit::menu_style;
52
53 const PROFILE_DIR: &str = ".codewhale/agents";
54
55 /// Rows one PageUp/PageDown travels on choice steps. Pages clamp at the ends
56 /// per the shared vocabulary instead of wrapping (#6290).
57 const SETUP_PAGE: usize = 10;
58 /// Lines one PageUp/PageDown scrolls on the Review step (unchanged).
59 const REVIEW_SCROLL_PAGE: usize = 8;
60
61 /// The only two truthful destinations for `/fleet setup`.
62 #[derive(Debug, Clone, PartialEq, Eq)]
63 pub(crate) enum FleetSetupEditTarget {
64 /// No named v2 Fleet is selected, so the legacy profile wizard remains
65 /// the effective roster-authoring surface.
66 LegacyProfiles,
67 /// A named v2 Fleet is selected; edit that exact file and scope.
68 SelectedFleet {
69 name: String,
70 scope: codewhale_engine::fleet::store::FleetScope,
71 },
72 }
73
74 /// Resolve setup independently of project-profile trust. A broken explicit
75 /// selection fails closed instead of being mistaken for "no Fleet" and
76 /// silently opening the legacy profile writer.
77 pub(crate) fn resolve_fleet_setup_edit_target(
78 workspace: &Path,
79 ) -> Result<FleetSetupEditTarget, String> {
80 match codewhale_engine::fleet::store::resolve_selected_fleet(workspace) {
81 Ok(Some(selected)) => Ok(FleetSetupEditTarget::SelectedFleet {
82 name: selected.name,
83 scope: selected.scope,
84 }),
85 Ok(None) => Ok(FleetSetupEditTarget::LegacyProfiles),
86 Err(_) => Err(
87 "Selected Fleet is missing or unreadable; open /fleet teams to repair or clear the selection. Legacy profiles were not opened."
88 .to_string(),
89 ),
90 }
91 }
92
93 /// A selectable choice in a wizard step: a short identifier `label`, a one-line
94 /// `summary`, and a longer `description` shown (wrapped) in the detail pane.
95 #[derive(Clone)]
96 struct Choice {
97 label: Cow<'static, str>,
98 summary: Cow<'static, str>,
99 description: Cow<'static, str>,
100 }
101
102 const CHOICE_LIST_WIDTH: u16 = 22;
103 const CHOICE_DETAIL_MIN_WIDTH: u16 = 58;
104 const CHOICE_TWO_COLUMN_MIN_WIDTH: u16 = CHOICE_LIST_WIDTH + CHOICE_DETAIL_MIN_WIDTH;
105
106 struct ChoiceSpec {
107 label: &'static str,
108 summary: MessageId,
109 description: MessageId,
110 }
111
112 impl ChoiceSpec {
113 fn resolve(&self, locale: codewhale_localization::Locale) -> Choice {
114 Choice {
115 label: Cow::Borrowed(self.label),
116 summary: tr(locale, self.summary),
117 description: tr(locale, self.description),
118 }
119 }
120 }
121
122 /// Agent-team roles. `label` doubles as the profile `role_hint` and file stem,
123 /// so these strings are part of the generated-profile contract.
124 const ROLES: [ChoiceSpec; 9] = [
125 ChoiceSpec {
126 label: "manager",
127 summary: MessageId::FleetRoleManagerSummary,
128 description: MessageId::FleetRoleManagerDescription,
129 },
130 ChoiceSpec {
131 label: "explore",
132 summary: MessageId::FleetRoleExploreSummary,
133 description: MessageId::FleetRoleExploreDescription,
134 },
135 ChoiceSpec {
136 label: "implement",
137 summary: MessageId::FleetRoleImplementSummary,
138 description: MessageId::FleetRoleImplementDescription,
139 },
140 ChoiceSpec {
141 label: "reviewer",
142 summary: MessageId::FleetRoleReviewerSummary,
143 description: MessageId::FleetRoleReviewerDescription,
144 },
145 ChoiceSpec {
146 label: "test",
147 summary: MessageId::FleetRoleTestSummary,
148 description: MessageId::FleetRoleTestDescription,
149 },
150 ChoiceSpec {
151 label: "advisor",
152 summary: MessageId::FleetRoleAdvisorSummary,
153 description: MessageId::FleetRoleAdvisorDescription,
154 },
155 ChoiceSpec {
156 label: "synthesizer",
157 summary: MessageId::FleetRoleSynthesizerSummary,
158 description: MessageId::FleetRoleSynthesizerDescription,
159 },
160 ChoiceSpec {
161 label: "general",
162 summary: MessageId::FleetRoleGeneralSummary,
163 description: MessageId::FleetRoleGeneralDescription,
164 },
165 ChoiceSpec {
166 label: "custom",
167 summary: MessageId::FleetRoleCustomSummary,
168 description: MessageId::FleetRoleCustomDescription,
169 },
170 ];
171
172 const THINKING_CHOICES: &[&str] = &["inherit", "off", "low", "medium", "high", "max", "auto"];
173
174 #[derive(Debug, Clone)]
175 pub struct FleetSetupSnapshot {
176 workspace: PathBuf,
177 locale: codewhale_localization::Locale,
178 /// Whether the active provider has a key or local runtime — gates the
179 /// model-draft offer, mirroring the constitution card's `provider_ready`.
180 provider_ready: bool,
181 provider: String,
182 model: String,
183 reasoning: String,
184 subagents_enabled: bool,
185 max_subagents: usize,
186 launch_concurrency: usize,
187 max_admitted: usize,
188 subagent_spawn_depth: u32,
189 fleet_spawn_depth: u32,
190 api_timeout_secs: u64,
191 heartbeat_timeout_secs: u64,
192 /// Lowercased roster member ids with their origin labels (built-in /
193 /// config / project), so the wizard can say when a chosen role would
194 /// override an existing roster member.
195 roster_members: Vec<(String, String)>,
196 /// Saved (file-backed) roster members keyed by lowercased id: where the
197 /// file lives and the route it pins, so reopening a saved profile from
198 /// `/fleet` starts from what is on disk instead of the wizard defaults.
199 roster_details: Vec<RosterMemberDetail>,
200 /// Whether project-scope profiles are enabled for this launch
201 /// (`--no-project-config` disables them). When false, "This project" is
202 /// offered disabled with that reason instead of writing a file nothing
203 /// will load.
204 project_profiles_enabled: bool,
205 /// Resolved personal profile directory (`$CODEWHALE_HOME/agents`), or the
206 /// reason it could not be resolved. Captured once at snapshot time so the
207 /// wizard never re-reads the environment while painting and tests can
208 /// point it at a temp dir.
209 personal_profile_dir: Result<PathBuf, String>,
210 /// `(exact provider id, model id, readiness label, selectable)` routes for a worker,
211 /// drawn from ALL configured providers — not only the active one (#4093).
212 /// Shown after `inherit` in the Model step so a Fleet worker can be pinned
213 /// to a route independent of the parent/current provider. The provider id
214 /// is a canonical built-in id or the exact named custom table key, not a
215 /// display label — see [`cross_provider_model_routes`].
216 available_models: Vec<(
217 String,
218 String,
219 codewhale_engine::provider_readiness::ResolvedProviderReadiness,
220 )>,
221 }
222
223 /// A file-backed roster member as it exists on disk (project or personal).
224 #[derive(Debug, Clone, PartialEq, Eq)]
225 pub struct RosterMemberDetail {
226 id: String,
227 scope: FleetProfileScope,
228 source: PathBuf,
229 provider: Option<String>,
230 model: Option<String>,
231 reasoning_effort: Option<String>,
232 }
233
234 impl FleetSetupSnapshot {
235 #[must_use]
236 pub fn from_app(app: &App, config: &Config) -> Self {
237 let provider = app.effective_route_identity_display().0;
238 let model = if app.auto_model {
239 app.last_effective_model
240 .as_deref()
241 .map(|effective| format!("auto -> {effective}"))
242 .unwrap_or_else(|| "auto".to_string())
243 } else {
244 app.model.clone()
245 };
246 let fleet_spawn_depth = config
247 .fleet
248 .as_ref()
249 .map(|fleet| fleet.exec.max_spawn_depth)
250 .unwrap_or_else(|| codewhale_config::FleetExecConfig::default().max_spawn_depth);
251 let roster = codewhale_engine::fleet::roster::FleetRoster::load(
252 &config.fleet_config(),
253 &app.workspace,
254 );
255 let roster_members = roster
256 .members()
257 .iter()
258 .map(|member| (member.id.to_lowercase(), member.origin.to_string()))
259 .collect();
260 let roster_details = roster
261 .members()
262 .iter()
263 .filter_map(|member| {
264 let scope = match member.origin {
265 codewhale_engine::fleet::roster::ProfileOrigin::Workspace => {
266 FleetProfileScope::Project
267 }
268 codewhale_engine::fleet::roster::ProfileOrigin::Personal => {
269 FleetProfileScope::Personal
270 }
271 _ => return None,
272 };
273 Some(RosterMemberDetail {
274 id: member.id.to_lowercase(),
275 scope,
276 source: member.source.clone(),
277 provider: member.profile.provider.clone(),
278 model: member.profile.model.clone(),
279 reasoning_effort: member.profile.reasoning_effort.clone(),
280 })
281 })
282 .collect();
283 let identity = app
284 .provider_identity
285 .as_ref()
286 .filter(|identity| config.verify_provider_identity(identity).is_ok());
287 let provider_ready = identity.is_some_and(|identity| {
288 codewhale_engine::provider_readiness::resolve_for_model(
289 config,
290 identity,
291 if app.auto_model { "auto" } else { &app.model },
292 &app.provider_health,
293 )
294 .can_attempt()
295 });
296
297 Self {
298 workspace: app.workspace.clone(),
299 locale: app.ui_locale,
300 provider_ready,
301 provider,
302 model,
303 reasoning: app.reasoning_effort_display_label(),
304 subagents_enabled: identity.map_or_else(
305 || config.subagents_enabled(),
306 |identity| config.subagents_enabled_for_provider(identity),
307 ),
308 max_subagents: identity.map_or_else(
309 || config.max_subagents(),
310 |identity| config.max_subagents_for_provider(identity),
311 ),
312 launch_concurrency: identity.map_or_else(
313 || config.launch_concurrency(),
314 |identity| config.launch_concurrency_for_provider(identity),
315 ),
316 max_admitted: identity.map_or_else(
317 || config.max_admitted_subagents(),
318 |identity| config.max_admitted_subagents_for_provider(identity),
319 ),
320 subagent_spawn_depth: identity.map_or_else(
321 || config.subagent_max_spawn_depth(),
322 |identity| config.subagent_max_spawn_depth_for_provider(identity),
323 ),
324 fleet_spawn_depth,
325 api_timeout_secs: identity.map_or_else(
326 || config.subagent_api_timeout_secs(),
327 |identity| config.subagent_api_timeout_secs_for_provider(identity),
328 ),
329 heartbeat_timeout_secs: identity.map_or_else(
330 || config.subagent_heartbeat_timeout_secs(),
331 |identity| config.subagent_heartbeat_timeout_secs_for_provider(identity),
332 ),
333 roster_members,
334 roster_details,
335 project_profiles_enabled:
336 codewhale_engine::fleet::roster::project_agent_profiles_enabled(),
337 personal_profile_dir: codewhale_engine::fleet::profile::personal_agent_profile_dir()
338 .map_err(|err| format!("{err:#}")),
339 available_models: cross_provider_model_routes(config, identity, &app.provider_health),
340 }
341 }
342 }
343
344 /// Build the `(canonical provider id, model id)` pairs selectable for a worker
345 /// from EVERY configured provider — not only the active one (#4093). Fleet
346 /// workers can be pinned to a route independent of the parent/current provider,
347 /// so the Model step must offer the same cross-provider catalog the model
348 /// picker does, instead of the active provider's models alone.
349 ///
350 /// The provider id here is the exact non-secret configured route key. Built-ins
351 /// use their canonical id; named custom routes keep their table key so saved
352 /// Fleet profiles can rebuild the same child client.
353 /// Callers derive a human-readable label from it for UI text.
354 pub(crate) fn cross_provider_model_routes(
355 config: &Config,
356 active: Option<&codewhale_runtime::config::ProviderIdentity>,
357 health: &codewhale_engine::provider_readiness::ProviderReadinessSnapshot,
358 ) -> Vec<(
359 String,
360 String,
361 codewhale_engine::provider_readiness::ResolvedProviderReadiness,
362 )> {
363 let Some(active) = active.filter(|identity| config.verify_provider_identity(identity).is_ok())
364 else {
365 return Vec::new();
366 };
367 let mut routes = Vec::new();
368 for identity in config.provider_identities() {
369 if identity.provider == codewhale_config::ProviderKind::Antigravity
370 || !codewhale_engine::provider_readiness::provider_is_configured_for_active(
371 config, &identity, active,
372 )
373 {
374 continue;
375 }
376 append_provider_model_routes(&mut routes, config, active, &identity, health);
377 }
378 routes
379 }
380
381 fn append_provider_model_routes(
382 routes: &mut Vec<(
383 String,
384 String,
385 codewhale_engine::provider_readiness::ResolvedProviderReadiness,
386 )>,
387 config: &Config,
388 active: &codewhale_runtime::config::ProviderIdentity,
389 identity: &codewhale_runtime::config::ProviderIdentity,
390 health: &codewhale_engine::provider_readiness::ProviderReadinessSnapshot,
391 ) {
392 let mut models = Vec::new();
393 if let Some(model) = config
394 .provider_config_for(identity)
395 .and_then(|entry| entry.model.as_deref())
396 {
397 push_unique_model(&mut models, model);
398 }
399 if identity == active {
400 let model = config.default_model();
401 if !model.trim().eq_ignore_ascii_case("auto") {
402 push_unique_model(&mut models, &model);
403 }
404 }
405 for model in codewhale_engine::provider_lake::models_for_provider(config, identity) {
406 push_unique_model(&mut models, &model);
407 }
408 for model in models {
409 let readiness = codewhale_engine::provider_readiness::resolve_for_model(
410 config, identity, &model, health,
411 );
412 routes.push((identity.key.to_string(), model, readiness));
413 }
414 }
415
416 fn push_unique_model(models: &mut Vec<String>, model: &str) {
417 let model = model.trim();
418 if !model.is_empty() && !models.iter().any(|existing| existing == model) {
419 models.push(model.to_string());
420 }
421 }
422
423 /// Human-readable label for a built-in provider id, falling back to an exact
424 /// named custom id verbatim.
425 /// Does this provider/model route match a typed filter?
426 ///
427 /// Substring over the model id, the provider id, and the provider's display
428 /// label, because a person types "sonnet", "anthropic", or "Claude" and means
429 /// the same row. The inherit row also answers to the words describing it.
430 /// Shared so the setup wizard and the Fleet editor cannot disagree about what
431 /// a query means — the editor had no filter at all, which made picking one
432 /// model out of every configured route an arrow-key errand.
433 pub(super) fn route_matches_query(
434 query: &str,
435 provider: &str,
436 model: &str,
437 is_inherit_row: bool,
438 ) -> bool {
439 let query = query.trim().to_ascii_lowercase();
440 if query.is_empty() {
441 return true;
442 }
443 model.to_ascii_lowercase().contains(&query)
444 || provider.to_ascii_lowercase().contains(&query)
445 || provider_display_label(provider)
446 .to_ascii_lowercase()
447 .contains(&query)
448 || (is_inherit_row && "inherit same as session current".contains(&query))
449 }
450
451 pub(super) fn provider_display_label(provider_id: &str) -> String {
452 codewhale_config::ProviderKind::parse(provider_id)
453 .filter(|provider| provider.as_str() == provider_id)
454 .map(|provider| provider.provider().display_name().to_string())
455 .unwrap_or_else(|| provider_id.to_string())
456 }
457
458 /// Which focused screen of the wizard is showing.
459 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
460 enum Step {
461 /// Pick the team role.
462 Role,
463 /// Review an inert role-to-model suggestion built from configured routes.
464 Composition,
465 /// Pick the model-routing class.
466 Model,
467 /// Choose where the profile is saved (this project or personal).
468 Destination,
469 /// Review the full posture and save.
470 Review,
471 }
472
473 /// The two save destinations, in the order the Destination step lists them.
474 const DESTINATION_ORDER: [FleetProfileScope; 2] =
475 [FleetProfileScope::Project, FleetProfileScope::Personal];
476
477 /// Resolved facts about one save destination, computed off the paint path
478 /// (on entering the Destination/Review steps and when the role changes).
479 #[derive(Debug, Clone, PartialEq, Eq)]
480 struct DestinationStatus {
481 scope: FleetProfileScope,
482 /// `None` when the destination can be written; otherwise the localized
483 /// reason it is offered disabled.
484 unavailable_reason: Option<String>,
485 /// Exact file that saving would write.
486 target: PathBuf,
487 /// Whether `target` already exists (saving would replace it).
488 target_exists: bool,
489 original: Option<String>,
490 }
491
492 /// Which control on the Review step owns keyboard focus.
493 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
494 enum ReviewFocus {
495 Save,
496 ChangeDestination,
497 Back,
498 }
499
500 impl ReviewFocus {
501 const ORDER: [Self; 3] = [Self::Save, Self::ChangeDestination, Self::Back];
502
503 fn next(self) -> Self {
504 let idx = Self::ORDER.iter().position(|f| *f == self).unwrap_or(0);
505 Self::ORDER[(idx + 1) % Self::ORDER.len()]
506 }
507
508 fn prev(self) -> Self {
509 let idx = Self::ORDER.iter().position(|f| *f == self).unwrap_or(0);
510 Self::ORDER[(idx + Self::ORDER.len() - 1) % Self::ORDER.len()]
511 }
512 }
513
514 /// The workflow-owned request and its validated, deliberately unratified
515 /// proposal. Keeping the request beside the proposal lets the UI re-run the
516 /// workflow validator at the exact point where a human accepts a suggestion.
517 #[derive(Debug, Clone)]
518 struct CompositionAdvisory {
519 request: FleetCompositionRequest,
520 proposal: FleetCompositionProposal,
521 }
522
523 impl CompositionAdvisory {
524 fn validated_route_for_role(
525 &self,
526 role: &str,
527 ) -> Result<Option<(String, String)>, CompositionError> {
528 let proposal =
529 FleetCompositionProposal::validate(&self.request, self.proposal.suggestions.clone())?;
530 Ok(proposal
531 .suggestions
532 .iter()
533 .find(|suggestion| suggestion.role.eq_ignore_ascii_case(role))
534 .map(|suggestion| (suggestion.provider.clone(), suggestion.model.clone())))
535 }
536 }
537
538 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
539 enum CompositionDecision {
540 Pending,
541 Accepted,
542 Edited,
543 Rejected,
544 }
545
546 /// Per-row Fleet Model step interaction state.
547 ///
548 /// Replaces the old `model_selectable: Vec<bool>` so a dormant external-consent
549 /// route can require explicit activation (#v092-fleet-routes-fix) while
550 /// genuinely unconfigured routes stay blocked with a reason.
551 #[derive(Debug, Clone, PartialEq, Eq)]
552 enum FleetModelRowState {
553 Ready,
554 NeedsActivation,
555 Blocked { reason: String },
556 }
557
558 impl FleetModelRowState {
559 fn from_readiness(
560 readiness: &codewhale_engine::provider_readiness::ResolvedProviderReadiness,
561 ) -> Self {
562 if readiness.requires_explicit_activation() {
563 return Self::NeedsActivation;
564 }
565 if let Some(reason) = readiness.blocked_reason() {
566 return Self::Blocked {
567 reason: reason.into_owned(),
568 };
569 }
570 if readiness.can_attempt() {
571 return Self::Ready;
572 }
573 Self::Blocked {
574 reason: readiness
575 .blocked_reason()
576 .map(std::borrow::Cow::into_owned)
577 .unwrap_or_else(|| readiness.label().into_owned()),
578 }
579 }
580 }
581
582 /// Build the setup-time advisory from routes the wizard already resolved from
583 /// the operator's configured providers. The adapter is intentionally pure: it
584 /// sorts and de-duplicates the redacted provider/model pairs, assigns them to
585 /// the built-in roles in stable round-robin order, then asks the workflow
586 /// schema to validate every assignment against that exact pool.
587 fn deterministic_composition_advisory(
588 available_models: &[(
589 String,
590 String,
591 codewhale_engine::provider_readiness::ResolvedProviderReadiness,
592 )],
593 ) -> Option<CompositionAdvisory> {
594 let mut seen = BTreeSet::new();
595 let mut pool: Vec<ConfiguredModel> = available_models
596 .iter()
597 // Do not recommend a route the Model step would refuse or require the
598 // operator to activate first. Such rows remain available for explicit
599 // human selection in the existing picker.
600 .filter(|(_, _, readiness)| {
601 FleetModelRowState::from_readiness(readiness) == FleetModelRowState::Ready
602 })
603 .filter_map(|(provider, model, _)| {
604 let key = (provider.clone(), model.clone());
605 seen.insert(key.clone())
606 .then(|| ConfiguredModel::new(key.0, key.1, None))
607 })
608 .collect();
609 pool.sort_by(|left, right| {
610 left.provider
611 .cmp(&right.provider)
612 .then_with(|| left.model.cmp(&right.model))
613 });
614
615 let roles: Vec<CompositionRole> = ROLES
616 .iter()
617 // `custom` is an invitation to author a posture, not a semantic Fleet
618 // role, so it stays on the manual Model path.
619 .filter(|role| role.label != "custom")
620 .map(|role| {
621 let summary = tr(codewhale_localization::Locale::En, role.summary);
622 CompositionRole::new(role.label.to_string(), Some(&summary))
623 })
624 .collect();
625 let request = FleetCompositionRequest::new(pool, roles).ok()?;
626 let suggestions = request
627 .roles
628 .iter()
629 .enumerate()
630 .map(|(idx, role)| {
631 let configured = &request.pool[idx % request.pool.len()];
632 RoleSuggestion {
633 role: role.role.clone(),
634 provider: configured.provider.clone(),
635 model: configured.model.clone(),
636 reason: Some(
637 "Stable round-robin assignment from the configured model pool.".to_string(),
638 ),
639 }
640 })
641 .collect();
642 let proposal = FleetCompositionProposal::validate(&request, suggestions).ok()?;
643 Some(CompositionAdvisory { request, proposal })
644 }
645
646 /// A role assignment edits only route keys in the original document. The
647 /// source and possible destinations are captured before opening the picker.
648 enum RouteTemplate {
649 Toml(toml::Table),
650 Markdown(String),
651 }
652
653 struct RouteAssignment {
654 id: String,
655 template: RouteTemplate,
656 original_member: codewhale_engine::fleet::profile::AgentProfile,
657 source: Option<(PathBuf, String)>,
658 source_scope: Option<FleetProfileScope>,
659 destinations: Vec<(PathBuf, Option<String>)>,
660 provider: Option<String>,
661 model: Option<String>,
662 reasoning: Option<String>,
663 }
664
665 /// The wizard answers a model draft was requested against (U09-03).
666 #[derive(Debug, Clone, PartialEq, Eq)]
667 struct ModelDraftRequest {
668 role: String,
669 route: Option<(String, String)>,
670 reasoning_effort: Option<String>,
671 }
672
673 pub struct FleetSetupView {
674 editor_id: uuid::Uuid,
675 snapshot: FleetSetupSnapshot,
676 assignment: Option<RouteAssignment>,
677 step: Step,
678 role_idx: usize,
679 model_idx: usize,
680 thinking_idx: usize,
681 profile_scope: FleetProfileScope,
682 /// Whether the user has explicitly chosen (or a saved profile supplied) the
683 /// save destination. Until then the header says the choice is still ahead
684 /// instead of silently presenting a default as a decision.
685 scope_decided: bool,
686 /// Highlighted row on the Destination step (index into DESTINATION_ORDER).
687 destination_idx: usize,
688 /// Resolved destination facts for both scopes. Recomputed on entry to the
689 /// Destination/Review steps and when the role (file name) changes; the
690 /// draw path never touches the filesystem (#3908).
691 destinations: Option<[DestinationStatus; 2]>,
692 /// Focused control on the Review step (Tab/Shift-Tab/←/→ move it).
693 review_focus: ReviewFocus,
694 /// Replacing an existing file needs a second Enter on the save control.
695 replace_armed: bool,
696 /// One-line inline notice (e.g. why a model row cannot be selected).
697 /// Cleared on the next navigation key.
698 notice: Option<String>,
699 review_scroll: usize,
700 /// A model-drafted profile awaiting save (already sanitized and
701 /// bounded by the untrusted gate). Cleared when the selection changes so
702 /// a stale draft can never be saved against fresh answers.
703 model_draft: Option<Box<codewhale_engine::fleet::profile::FleetProfileDraft>>,
704 /// Exact rendered TOML preview for `model_draft` (header comment + the
705 /// deterministic bytes saving would persist). Rendered inline on the
706 /// Review step — never in a separate pager (#4093): a standalone pager
707 /// view owns its own `g`/`G` scroll bindings, which silently swallowed
708 /// the save keypress and left users unable to save without first
709 /// pressing Esc. Keeping the preview and the save control in the same
710 /// view means the footer's `g`/Enter hints are never a lie.
711 model_draft_preview: Option<String>,
712 /// The answers the in-flight model draft (`m` on Review) was requested
713 /// against. Cleared with the draft whenever an answer changes, so a
714 /// draft that lands late is refused instead of being installed onto
715 /// answers it was never written for.
716 model_draft_request: Option<ModelDraftRequest>,
717 /// Model-step rows: `inherit` followed by one row per concrete model from
718 /// every configured provider (#4093).
719 model_choices: Vec<Choice>,
720 /// `(provider, model)` aligned with `model_choices`. Index 0 is `inherit`
721 /// (the active route); later rows pin a concrete, possibly cross-provider
722 /// route. Drives the review/copy so a pinned route names its own provider.
723 model_routes: Vec<(String, String)>,
724 /// Interaction state for each aligned Model row. Distinguishes ready rows,
725 /// dormant external-consent rows that need explicit activation, and
726 /// genuinely blocked rows with a short reason.
727 model_row_states: Vec<FleetModelRowState>,
728 /// Typed filter for the Model step (#4639): substring match over
729 /// provider and model id, so provider-heavy catalogs (e.g. OpenRouter)
730 /// stay navigable without a provider→model drill-down.
731 model_query: String,
732 /// Whether the Model step's filter input is capturing keystrokes (`/`
733 /// toggles it; Enter keeps the filter, Esc clears it).
734 model_filter_active: bool,
735 /// Pure workflow-schema proposal shown before the Model picker. It has no
736 /// save, spawn, launch, or snapshot capability.
737 composition: Option<CompositionAdvisory>,
738 composition_decision: CompositionDecision,
739 /// Selectable rows registered by the latest render. Keeping mouse geometry
740 /// in the view gives the Fleet walkthrough the same row ownership as its
741 /// keyboard path without coupling the host to this modal's layout.
742 row_hitboxes: RefCell<Vec<(Rect, usize)>>,
743 }
744
745 impl FleetSetupView {
746 /// Refresh row states from a freshly built snapshot while preserving the
747 /// user's current selection position and draft state. Used after the host
748 /// validates a dormant external-consent route so the same row becomes
749 /// Ready without closing and reopening the modal.
750 pub fn refresh_from_snapshot(&mut self, snapshot: FleetSetupSnapshot) {
751 let old_editor_id = self.editor_id;
752 let old_step = self.step;
753 let old_role_idx = self.role_idx;
754 let old_model_idx = self.model_idx;
755 let old_thinking_idx = self.thinking_idx;
756 let old_profile_scope = self.profile_scope;
757 let old_scope_decided = self.scope_decided;
758 let old_destination_idx = self.destination_idx;
759 let old_review_focus = self.review_focus;
760 let old_model_query = self.model_query.clone();
761 let old_model_filter_active = self.model_filter_active;
762 let old_review_scroll = self.review_scroll;
763 let old_model_draft = self.model_draft.clone();
764 let old_model_draft_preview = self.model_draft_preview.clone();
765 let old_model_draft_request = self.model_draft_request.clone();
766
767 *self = Self::from_snapshot(snapshot);
768
769 self.editor_id = old_editor_id;
770 self.step = old_step;
771 self.role_idx = old_role_idx;
772 self.model_idx = old_model_idx.min(self.filtered_model_indices().len().saturating_sub(1));
773 self.thinking_idx = old_thinking_idx;
774 self.profile_scope = old_profile_scope;
775 self.scope_decided = old_scope_decided;
776 self.destination_idx = old_destination_idx;
777 self.review_focus = old_review_focus;
778 self.model_query = old_model_query;
779 self.model_filter_active = old_model_filter_active;
780 self.review_scroll = old_review_scroll;
781 self.model_draft = old_model_draft;
782 self.model_draft_preview = old_model_draft_preview;
783 self.model_draft_request = old_model_draft_request;
784 if self.step == Step::Composition && !self.has_composition_for_selected_role() {
785 self.step = Step::Model;
786 }
787 if matches!(self.step, Step::Destination | Step::Review) {
788 self.refresh_destinations();
789 }
790 }
791
792 #[must_use]
793 pub fn new(app: &App, config: &Config) -> Self {
794 Self::from_snapshot(FleetSetupSnapshot::from_app(app, config))
795 }
796
797 /// Open setup for a role the operator already selected in `/fleet`.
798 /// Unknown/custom roster roles map to the explicit custom authoring row;
799 /// Left or Esc still exposes Role so the carried choice is never sticky.
800 #[must_use]
801 pub fn new_for_role(app: &App, config: &Config, role: &str) -> Self {
802 Self::from_snapshot_for_role(FleetSetupSnapshot::from_app(app, config), role)
803 }
804
805 pub(crate) fn new_for_route_assignment(
806 app: &App,
807 config: &Config,
808 id: &str,
809 ) -> Result<Self, String> {
810 let roster = codewhale_engine::fleet::identity::load_effective_roster(
811 &config.fleet_config(),
812 &app.workspace,
813 Some(app.plugin_registry.as_ref()),
814 );
815 let member = roster
816 .members()
817 .iter()
818 .find(|member| member.id == id)
819 .ok_or_else(|| "This role is no longer available. Reopen Fleet.".to_string())?;
820 if matches!(
821 member.origin,
822 codewhale_engine::fleet::roster::ProfileOrigin::Plugin
823 | codewhale_engine::fleet::roster::ProfileOrigin::Config
824 ) {
825 return Err(format!(
826 "{} is managed by {} ({}). Change its model there; copying it into a profile would discard its original controls.",
827 member.id,
828 member.origin,
829 member.source.display()
830 ));
831 }
832 if member.origin == codewhale_engine::fleet::roster::ProfileOrigin::BuiltIn
833 && (member.profile.permissions != Default::default()
834 || member.profile.delegation != Default::default())
835 {
836 return Err("This role has controls that cannot be copied into a profile. Edit its defining configuration.".into());
837 }
838 let mut view = Self::new_for_role(app, config, id);
839 let source_scope = match member.origin {
840 codewhale_engine::fleet::roster::ProfileOrigin::Workspace => {
841 Some(FleetProfileScope::Project)
842 }
843 codewhale_engine::fleet::roster::ProfileOrigin::Personal => {
844 Some(FleetProfileScope::Personal)
845 }
846 _ => None,
847 };
848 let source = if let Some(scope) = source_scope {
849 Some((
850 member.source.clone(),
851 codewhale_engine::fleet::profile::read_agent_profile_document(
852 scope,
853 &app.workspace,
854 &member.source,
855 )
856 .map_err(|err| err.to_string())?
857 .ok_or_else(|| "The saved role disappeared. Reopen Fleet.".to_string())?,
858 ))
859 } else {
860 None
861 };
862 let template = if let Some((path, text)) = &source {
863 if path.extension().is_some_and(|ext| ext == "md") {
864 RouteTemplate::Markdown(text.clone())
865 } else {
866 RouteTemplate::Toml(toml::from_str(text).map_err(|err| err.to_string())?)
867 }
868 } else {
869 let draft = codewhale_engine::fleet::profile::FleetProfileDraft {
870 id: member.id.clone(),
871 display_name: member.display_name.clone(),
872 description: member.description.clone(),
873 role_hint: member.profile.role.name.clone(),
874 model_class_hint: Some(member.profile.loadout.as_str().to_string()),
875 model: member.profile.model.clone(),
876 provider: member.profile.provider.clone(),
877 reasoning_effort: member.profile.reasoning_effort.clone(),
878 instructions: member.profile.role.instructions.clone(),
879 };
880 RouteTemplate::Toml(
881 toml::from_str(&draft.render_toml()).map_err(|err| err.to_string())?,
882 )
883 };
884 view.assignment = Some(RouteAssignment {
885 id: member.id.clone(),
886 template,
887 original_member: member.clone(),
888 source,
889 source_scope,
890 destinations: Vec::new(),
891 provider: member.profile.provider.clone(),
892 model: member.profile.model.clone(),
893 reasoning: member.profile.reasoning_effort.clone(),
894 });
895 view.refresh_destinations();
896 let targets = view
897 .destinations
898 .as_ref()
899 .into_iter()
900 .flatten()
901 .filter(|destination| destination.unavailable_reason.is_none())
902 .map(|destination| (destination.target.clone(), destination.original.clone()))
903 .collect();
904 view.assignment.as_mut().unwrap().destinations = targets;
905 view.step = Step::Destination;
906 Ok(view)
907 }
908
909 pub(crate) fn route_pick_request(&self) -> ViewAction {
910 self.assignment.as_ref().map_or(ViewAction::None, |_| {
911 ViewAction::Emit(ViewEvent::FleetProfileRoutePickRequested {
912 editor_id: self.editor_id,
913 })
914 })
915 }
916
917 pub(crate) fn profile_commit_matches(&self, editor_id: uuid::Uuid) -> bool {
918 self.editor_id == editor_id && self.assignment.is_none() && self.step == Step::Review
919 }
920
921 pub(crate) fn profile_save_failed(&mut self, reason: String) {
922 self.notice = Some(reason);
923 self.replace_armed = false;
924 self.review_scroll = 0;
925 }
926
927 pub(crate) fn assignment_context(&self) -> (String, String) {
928 (self.selected_role(), self.saves_to_line())
929 }
930
931 pub(crate) fn route_selection(
932 &self,
933 editor_id: uuid::Uuid,
934 ) -> Option<super::fleet_detail::FleetRouteSelection> {
935 let assignment = self
936 .assignment
937 .as_ref()
938 .filter(|_| self.editor_id == editor_id)?;
939 Some(super::fleet_detail::FleetRouteSelection {
940 provider: assignment.provider.clone(),
941 model: assignment.model.clone(),
942 reasoning: assignment.reasoning.as_deref().and_then(|value| {
943 codewhale_engine::reasoning_preference::ReasoningEffort::parse_strict(value).ok()
944 }),
945 allow_inherit: true,
946 })
947 }
948
949 pub(crate) fn accept_route(
950 &mut self,
951 editor_id: uuid::Uuid,
952 provider: String,
953 model: String,
954 reasoning: Option<codewhale_engine::reasoning_preference::ReasoningEffort>,
955 ) -> bool {
956 let Some(assignment) = self
957 .assignment
958 .as_mut()
959 .filter(|_| self.editor_id == editor_id)
960 else {
961 return false;
962 };
963 assignment.provider = (model != "auto").then_some(provider);
964 assignment.model = (model != "auto").then_some(model);
965 assignment.reasoning = reasoning.map(|effort| effort.as_setting().to_string());
966 self.step = if self.scope_decided {
967 Step::Review
968 } else {
969 Step::Destination
970 };
971 self.refresh_destinations();
972 true
973 }
974
975 pub(crate) fn commit_route_assignment(
976 &self,
977 editor_id: uuid::Uuid,
978 app: &App,
979 config: &Config,
980 ) -> Result<String, String> {
981 let assignment = self
982 .assignment
983 .as_ref()
984 .filter(|_| self.editor_id == editor_id)
985 .ok_or_else(|| "This assignment is no longer open.".to_string())?;
986 if !matches!(
987 resolve_fleet_setup_edit_target(&app.workspace),
988 Ok(FleetSetupEditTarget::LegacyProfiles)
989 ) {
990 return Err("The selected team changed. Reopen Fleet before saving.".into());
991 }
992 let roster = codewhale_engine::fleet::identity::load_effective_roster(
993 &config.fleet_config(),
994 &app.workspace,
995 Some(app.plugin_registry.as_ref()),
996 );
997 if !roster
998 .members()
999 .iter()
1000 .any(|member| member == &assignment.original_member)
1001 {
1002 return Err(
1003 "This role changed while you were choosing. Reopen Fleet before saving.".into(),
1004 );
1005 }
1006 if !self.scope_decided || !self.selected_destination_available() {
1007 return Err("Choose an available save destination first.".into());
1008 }
1009 if self.profile_scope == FleetProfileScope::Project
1010 && !codewhale_engine::fleet::roster::project_agent_profiles_enabled()
1011 {
1012 return Err("Project profiles are disabled for this launch.".into());
1013 }
1014 if let Some(provider) = assignment.provider.as_deref()
1015 && let Some(reason) = crate::commands::fleet_provider_rejection(app, config, provider)
1016 {
1017 return Err(reason);
1018 }
1019 if let (Some(scope), Some((path, expected))) = (assignment.source_scope, &assignment.source)
1020 && codewhale_engine::fleet::profile::read_agent_profile_document(
1021 scope,
1022 &app.workspace,
1023 path,
1024 )
1025 .map_err(|err| err.to_string())?
1026 .as_ref()
1027 != Some(expected)
1028 {
1029 return Err("This role changed on disk. Reopen Fleet before saving.".into());
1030 }
1031 let target = &self
1032 .destination_for(self.profile_scope)
1033 .ok_or("Save destination unavailable")?
1034 .target;
1035 let expected = assignment
1036 .destinations
1037 .iter()
1038 .find(|(path, _)| path == target)
1039 .ok_or("Save destination changed. Reopen Fleet.")?;
1040 let text = match &assignment.template {
1041 RouteTemplate::Markdown(raw) => {
1042 codewhale_engine::fleet::profile::set_markdown_profile_route(
1043 target,
1044 raw,
1045 assignment.provider.as_deref(),
1046 assignment.model.as_deref(),
1047 assignment.reasoning.as_deref(),
1048 )
1049 .map_err(|err| err.to_string())?
1050 }
1051 RouteTemplate::Toml(template) => {
1052 let mut table = template.clone();
1053 for alias in [
1054 "model",
1055 "model_hint",
1056 "model_id",
1057 "provider",
1058 "reasoning_effort",
1059 "thinking",
1060 "reasoning",
1061 ] {
1062 table.remove(alias);
1063 }
1064 for (key, value) in [
1065 ("model", &assignment.model),
1066 ("provider", &assignment.provider),
1067 ("reasoning_effort", &assignment.reasoning),
1068 ] {
1069 if let Some(value) = value {
1070 table.insert(key.into(), toml::Value::String(value.clone()));
1071 }
1072 }
1073 table.insert("loadout".into(), toml::Value::String("inherit".into()));
1074 toml::to_string_pretty(&table).map_err(|err| err.to_string())?
1075 }
1076 };
1077 codewhale_engine::fleet::profile::save_agent_profile_document(
1078 self.profile_scope,
1079 &app.workspace,
1080 target,
1081 expected.1.as_deref(),
1082 &assignment.id,
1083 &text,
1084 )
1085 .map_err(|err| err.to_string())?;
1086 Ok(format!(
1087 "{} model saved · {}",
1088 assignment.id,
1089 target.display()
1090 ))
1091 }
1092
1093 fn from_snapshot_for_role(snapshot: FleetSetupSnapshot, role: &str) -> Self {
1094 let mut view = Self::from_snapshot(snapshot);
1095 let role = public_role_label(role);
1096 view.role_idx = ROLES
1097 .iter()
1098 .position(|choice| choice.label.eq_ignore_ascii_case(&role))
1099 .unwrap_or(ROLES.len() - 1);
1100 view.step = Step::Model;
1101 // Reopening a SAVED member edits what is on disk: preselect its route,
1102 // thinking tier, and — most importantly — the scope it was saved in,
1103 // so "edit" can never quietly land in the other destination.
1104 let role_id = role.trim().to_ascii_lowercase();
1105 let saved = view
1106 .snapshot
1107 .roster_details
1108 .iter()
1109 .find(|detail| detail.id == role_id || public_role_label(&detail.id) == role)
1110 .cloned();
1111 if let Some(saved) = saved {
1112 view.profile_scope = saved.scope;
1113 view.scope_decided = true;
1114 view.destination_idx = DESTINATION_ORDER
1115 .iter()
1116 .position(|scope| *scope == saved.scope)
1117 .unwrap_or(0);
1118 if let Some(model) = saved.model.as_deref() {
1119 let idx = view.model_routes.iter().position(|(provider, candidate)| {
1120 candidate == model
1121 && saved
1122 .provider
1123 .as_deref()
1124 .is_none_or(|p| p.eq_ignore_ascii_case(provider))
1125 });
1126 if let Some(idx) = idx {
1127 view.model_idx = idx;
1128 }
1129 }
1130 if let Some(effort) = saved.reasoning_effort.as_deref()
1131 && let Some(idx) = THINKING_CHOICES
1132 .iter()
1133 .position(|choice| choice.eq_ignore_ascii_case(effort))
1134 {
1135 view.thinking_idx = idx;
1136 }
1137 }
1138 view
1139 }
1140
1141 fn from_snapshot(snapshot: FleetSetupSnapshot) -> Self {
1142 let mut model_choices = vec![Choice {
1143 label: tr(snapshot.locale, MessageId::FleetModelInheritLabel),
1144 summary: tr(snapshot.locale, MessageId::FleetModelInheritSummary),
1145 description: tr(snapshot.locale, MessageId::FleetModelInheritDescription),
1146 }];
1147 // `inherit` (index 0) maps to the active route; every later row pins a
1148 // concrete (provider, model) drawn from all configured providers.
1149 let mut model_routes = vec![(snapshot.provider.clone(), snapshot.model.clone())];
1150 let mut model_row_states = vec![FleetModelRowState::Ready];
1151 for (provider, model, readiness) in &snapshot.available_models {
1152 let provider_label = provider_display_label(provider);
1153 let readiness_summary = readiness.detail().map_or_else(
1154 || readiness.label().into_owned(),
1155 |detail| format!("{}: {detail}", readiness.label()),
1156 );
1157 // Capability badges from the existing catalog/registry owners
1158 // (#5038): shown in the word-wrapped detail pane so the picker
1159 // list stays narrow-terminal friendly. Unknown models honestly
1160 // omit the sentence instead of blocking selection.
1161 let capability_note =
1162 codewhale_engine::fleet::capability_badges::resolve_route_capability_badges(
1163 Some(provider),
1164 model,
1165 )
1166 .map(|badges| format!(" Capabilities: {}.", badges.summary()))
1167 .unwrap_or_default();
1168 model_choices.push(Choice {
1169 label: Cow::Owned(model.clone()),
1170 summary: Cow::Owned(format!(
1171 "Pin this model ({provider_label}) · {readiness_summary}"
1172 )),
1173 description: Cow::Owned(format!(
1174 "Route this agent to {model} on {provider_label} instead of inheriting the session route.{capability_note}"
1175 )),
1176 });
1177 // Canonical provider id (not the display label above) — this is
1178 // what gets persisted into the saved profile (#4093).
1179 model_routes.push((provider.clone(), model.clone()));
1180 model_row_states.push(FleetModelRowState::from_readiness(readiness));
1181 }
1182 let composition = deterministic_composition_advisory(&snapshot.available_models);
1183 Self {
1184 editor_id: uuid::Uuid::new_v4(),
1185 snapshot,
1186 assignment: None,
1187 step: Step::Role,
1188 role_idx: 0,
1189 model_idx: 0,
1190 thinking_idx: 0,
1191 // Profiles authored for a person should follow that person across
1192 // repositories by default. Project scope remains one `s` away and
1193 // keeps higher roster precedence when explicitly selected.
1194 profile_scope: FleetProfileScope::Personal,
1195 scope_decided: false,
1196 destination_idx: DESTINATION_ORDER.len() - 1,
1197 destinations: None,
1198 review_focus: ReviewFocus::Save,
1199 replace_armed: false,
1200 notice: None,
1201 review_scroll: 0,
1202 model_draft: None,
1203 model_draft_preview: None,
1204 model_draft_request: None,
1205 model_choices,
1206 model_routes,
1207 model_row_states,
1208 model_query: String::new(),
1209 model_filter_active: false,
1210 composition,
1211 composition_decision: CompositionDecision::Pending,
1212 row_hitboxes: RefCell::new(Vec::new()),
1213 }
1214 }
1215
1216 /// Install a sanitized, bounded model draft. The exact TOML preview
1217 /// (returned here for the caller's status message) renders inline on the
1218 /// Review step — not in a separate pager — so the footer's `g`/Enter
1219 /// ratify hints stay true the instant the draft lands (#4093).
1220 ///
1221 /// `None` refuses a draft that no longer matches the wizard: an answer
1222 /// changed (or the draft was discarded) while it was in flight. The
1223 /// request generation only orders requests; it cannot see an edit made
1224 /// after the last `m`, so the wizard checks its own answers (U09-03).
1225 pub fn install_model_draft(
1226 &mut self,
1227 mut draft: Box<codewhale_engine::fleet::profile::FleetProfileDraft>,
1228 model_label: String,
1229 picked_route: Option<(String, String)>,
1230 reasoning_effort: Option<String>,
1231 ) -> Option<(String, String)> {
1232 let current = self.current_draft_request();
1233 if self.model_draft_request.as_ref() != Some(&current)
1234 || current.route != picked_route
1235 || current.reasoning_effort != reasoning_effort
1236 {
1237 return None;
1238 }
1239 self.model_draft_request = None;
1240 // Re-inject the route the operator picked at `m`-press time (#4093). A
1241 // model draft comes from `from_untrusted_json`, which hard-sets
1242 // `provider: None` and echoes whatever `model` the model happened to
1243 // emit — so ratifying it verbatim would drop a concrete cross-provider
1244 // pick and persist the ambiguous, provider-scoped profile #4093 exists
1245 // to prevent. Pinning BOTH fields from the CARRIED route keeps the route
1246 // the user actually chose (the model only authored the prose); the
1247 // check above already refused a draft whose answers changed in flight.
1248 // `inherit` (a `None` route) leaves `model`/`provider` untouched,
1249 // matching the deterministic Enter path.
1250 if let Some((provider, model)) = picked_route {
1251 draft.model = Some(model);
1252 draft.provider = Some(provider);
1253 }
1254 draft.reasoning_effort = reasoning_effort;
1255 let (title, header) = (
1256 tr(self.snapshot.locale, MessageId::FleetDraftTitle)
1257 .replace("{model_label}", &model_label),
1258 tr(self.snapshot.locale, MessageId::FleetDraftHeader)
1259 .replace("{name}", &draft.file_name())
1260 .replace("{model_label}", &model_label),
1261 );
1262 let rendered = draft.render_toml();
1263 let file_name = draft.file_name();
1264 let target_changed = self
1265 .destination_for(self.profile_scope)
1266 .is_none_or(|destination| {
1267 destination
1268 .target
1269 .file_name()
1270 .and_then(|name| name.to_str())
1271 != Some(file_name.as_str())
1272 });
1273 self.model_draft = Some(draft);
1274 if target_changed {
1275 self.refresh_destinations();
1276 }
1277 let content = format!("{}{}", self.scope_preview_header(header), rendered);
1278 self.model_draft_preview = Some(content.clone());
1279 self.review_scroll = 0;
1280 Some((title, content))
1281 }
1282
1283 /// The planner role chosen (drives the profile file name and `role_hint`).
1284 fn selected_role(&self) -> String {
1285 self.assignment
1286 .as_ref()
1287 .map(|assignment| assignment.id.clone())
1288 .unwrap_or_else(|| ROLES[self.role_idx.min(ROLES.len() - 1)].label.to_string())
1289 }
1290
1291 fn has_composition_for_selected_role(&self) -> bool {
1292 let role = self.selected_role();
1293 self.composition.as_ref().is_some_and(|advisory| {
1294 advisory
1295 .proposal
1296 .suggestions
1297 .iter()
1298 .any(|suggestion| suggestion.role.eq_ignore_ascii_case(&role))
1299 })
1300 }
1301
1302 /// Re-validate the entire proposal against its original explicit pool,
1303 /// then return the selected role's route. An out-of-pool proposal never
1304 /// reaches `model_idx`, even if the in-memory advisory were corrupted.
1305 fn validated_composition_route(&self) -> Option<(String, String)> {
1306 self.composition
1307 .as_ref()?
1308 .validated_route_for_role(&self.selected_role())
1309 .ok()?
1310 }
1311
1312 fn select_model_route(&mut self, route: &(String, String)) -> bool {
1313 let Some(idx) = self
1314 .model_routes
1315 .iter()
1316 .position(|candidate| candidate == route)
1317 else {
1318 return false;
1319 };
1320 self.model_query.clear();
1321 self.model_filter_active = false;
1322 self.model_idx = idx;
1323 true
1324 }
1325
1326 fn accept_composition(&mut self) -> ViewAction {
1327 let Some(route) = self.validated_composition_route() else {
1328 return ViewAction::None;
1329 };
1330 if !self.select_model_route(&route) {
1331 return ViewAction::None;
1332 }
1333 self.composition_decision = CompositionDecision::Accepted;
1334 // Accepting a suggestion still routes through the Destination step:
1335 // where the file lives is a human decision, not part of the advisory.
1336 self.step = Step::Destination;
1337 self.refresh_destinations();
1338 ViewAction::None
1339 }
1340
1341 fn edit_composition(&mut self) -> ViewAction {
1342 let Some(route) = self.validated_composition_route() else {
1343 return ViewAction::None;
1344 };
1345 if !self.select_model_route(&route) {
1346 return ViewAction::None;
1347 }
1348 self.composition_decision = CompositionDecision::Edited;
1349 self.step = Step::Model;
1350 ViewAction::None
1351 }
1352
1353 fn reject_composition(&mut self) -> ViewAction {
1354 self.composition_decision = CompositionDecision::Rejected;
1355 self.step = Step::Model;
1356 ViewAction::None
1357 }
1358
1359 /// Copy note when the chosen role would override an existing roster
1360 /// member of the same id (e.g. "overrides built-in reviewer"). A saved
1361 /// profile shadows lower roster layers rather than adding a new member.
1362 fn roster_override_note(&self) -> Option<String> {
1363 self.override_note_for_scope(self.profile_scope)
1364 }
1365
1366 /// Precedence consequence of saving the selected role into `scope`, given
1367 /// what the roster already contains for that id. Returns `None` when the
1368 /// id is new everywhere.
1369 fn override_note_for_scope(&self, scope: FleetProfileScope) -> Option<String> {
1370 let role = self.selected_role().to_lowercase();
1371 let locale = self.snapshot.locale;
1372 let (id, origin) = self
1373 .snapshot
1374 .roster_members
1375 .iter()
1376 .find(|(id, _)| *id == role)?;
1377 let has_project_copy = self
1378 .snapshot
1379 .roster_details
1380 .iter()
1381 .any(|d| d.id == role && d.scope == FleetProfileScope::Project);
1382 let has_personal_copy = self
1383 .snapshot
1384 .roster_details
1385 .iter()
1386 .any(|d| d.id == role && d.scope == FleetProfileScope::Personal);
1387 Some(match scope {
1388 FleetProfileScope::Personal if has_project_copy => {
1389 tr(locale, MessageId::FleetDestOverridesProject).replace("{id}", id)
1390 }
1391 FleetProfileScope::Project if has_personal_copy => {
1392 tr(locale, MessageId::FleetDestOverridesPersonal).replace("{id}", id)
1393 }
1394 _ => tr(locale, MessageId::FleetDestOverridesBuiltIn)
1395 .replace("{origin}", origin)
1396 .replace("{id}", id),
1397 })
1398 }
1399
1400 /// Localized "This project" / "Personal" label for a scope.
1401 fn scope_label(&self, scope: FleetProfileScope) -> String {
1402 tr(
1403 self.snapshot.locale,
1404 match scope {
1405 FleetProfileScope::Project => MessageId::FleetDestProjectLabel,
1406 FleetProfileScope::Personal => MessageId::FleetDestPersonalLabel,
1407 },
1408 )
1409 .into_owned()
1410 }
1411
1412 fn destination_for(&self, scope: FleetProfileScope) -> Option<&DestinationStatus> {
1413 self.destinations
1414 .as_ref()
1415 .and_then(|all| all.iter().find(|d| d.scope == scope))
1416 }
1417
1418 /// The header chip: where the file will be written, or that the choice is
1419 /// still ahead. Visible on every step so the destination is never a
1420 /// surprise on the last screen.
1421 fn saves_to_line(&self) -> String {
1422 let locale = self.snapshot.locale;
1423 if !self.scope_decided {
1424 return tr(locale, MessageId::FleetSavesToUndecided).into_owned();
1425 }
1426 let path = self
1427 .destination_for(self.profile_scope)
1428 .map(|d| d.target.display().to_string())
1429 .unwrap_or_else(|| self.projected_target(self.profile_scope));
1430 tr(locale, MessageId::FleetSavesToChip)
1431 .replace("{scope}", &self.scope_label(self.profile_scope))
1432 .replace("{path}", &path)
1433 }
1434
1435 /// Best-effort target path without touching the filesystem (used before
1436 /// `refresh_destinations` has run for the current role).
1437 fn projected_target(&self, scope: FleetProfileScope) -> String {
1438 let file = format!("{}.toml", profile_file_stem(&self.selected_role()));
1439 match scope {
1440 FleetProfileScope::Project => self
1441 .snapshot
1442 .workspace
1443 .join(codewhale_engine::fleet::profile::WORKSPACE_AGENT_PROFILE_DIR)
1444 .join(file)
1445 .display()
1446 .to_string(),
1447 FleetProfileScope::Personal => match &self.snapshot.personal_profile_dir {
1448 Ok(dir) => dir.join(file).display().to_string(),
1449 Err(_) => format!("{}/{file}", scope.display_dir()),
1450 },
1451 }
1452 }
1453
1454 /// The label of the primary Review action — it names its effect.
1455 fn save_action_label(&self) -> String {
1456 let locale = self.snapshot.locale;
1457 let exists = self
1458 .destination_for(self.profile_scope)
1459 .is_some_and(|d| d.target_exists);
1460 if exists && self.replace_armed {
1461 let file = self
1462 .destination_for(self.profile_scope)
1463 .and_then(|d| {
1464 d.target
1465 .file_name()
1466 .map(|f| f.to_string_lossy().into_owned())
1467 })
1468 .unwrap_or_default();
1469 return tr(locale, MessageId::FleetActionConfirmReplace).replace("{file}", &file);
1470 }
1471 tr(
1472 locale,
1473 match (self.profile_scope, exists) {
1474 (FleetProfileScope::Project, false) => MessageId::FleetActionSaveProject,
1475 (FleetProfileScope::Personal, false) => MessageId::FleetActionSavePersonal,
1476 (FleetProfileScope::Project, true) => MessageId::FleetActionReplaceProject,
1477 (FleetProfileScope::Personal, true) => MessageId::FleetActionReplacePersonal,
1478 },
1479 )
1480 .into_owned()
1481 }
1482
1483 /// Whether the currently chosen destination can be written.
1484 fn selected_destination_available(&self) -> bool {
1485 self.destination_for(self.profile_scope)
1486 .is_none_or(|d| d.unavailable_reason.is_none())
1487 }
1488
1489 /// The concrete model chosen for this worker, written to the profile
1490 /// `model` field. `None` means `inherit` (reuse the session route).
1491 fn selected_model(&self) -> Option<String> {
1492 self.selected_route().map(|(_, model)| model)
1493 }
1494
1495 /// The concrete `(provider, model)` chosen for this worker — a pinned route
1496 /// independent of the parent/current provider (#4093) — or `None` when
1497 /// `inherit` is selected (reuse the session route).
1498 fn selected_route(&self) -> Option<(String, String)> {
1499 if let Some(assignment) = &self.assignment {
1500 return assignment.provider.clone().zip(assignment.model.clone());
1501 }
1502 let real_idx = self.real_model_idx();
1503 if real_idx == 0 {
1504 return None;
1505 }
1506 self.model_routes.get(real_idx).cloned()
1507 }
1508
1509 /// Indices into `model_choices` visible under the current typed filter
1510 /// (#4639). Empty query shows every row; otherwise substring match over
1511 /// provider id/label and model id.
1512 fn filtered_model_indices(&self) -> Vec<usize> {
1513 (0..self.model_choices.len())
1514 .filter(|idx| {
1515 let (provider, model) = &self.model_routes[*idx];
1516 route_matches_query(&self.model_query, provider, model, *idx == 0)
1517 })
1518 .collect()
1519 }
1520
1521 fn model_filter_changed(&mut self) {
1522 self.model_idx = 0;
1523 if self.composition_decision != CompositionDecision::Pending {
1524 self.composition_decision = CompositionDecision::Edited;
1525 }
1526 }
1527
1528 /// Map the filtered highlight position back to the real `model_choices`
1529 /// index. Selection, persistence, and hitboxes all use the real index.
1530 fn real_model_idx(&self) -> usize {
1531 let filtered = self.filtered_model_indices();
1532 if filtered.is_empty() {
1533 return 0;
1534 }
1535 filtered[self.model_idx.min(filtered.len() - 1)]
1536 }
1537
1538 fn selected_reasoning_effort(&self) -> Option<String> {
1539 if let Some(assignment) = &self.assignment {
1540 return assignment.reasoning.clone();
1541 }
1542 if self.thinking_idx == 0 {
1543 return None;
1544 }
1545 THINKING_CHOICES
1546 .get(self.thinking_idx)
1547 .map(|choice| (*choice).to_string())
1548 }
1549
1550 fn selected_thinking_label(&self) -> String {
1551 self.selected_reasoning_effort().unwrap_or_else(|| {
1552 tr(self.snapshot.locale, MessageId::FleetThinkingInheritLabel)
1553 .replace("{reasoning}", &self.snapshot.reasoning)
1554 })
1555 }
1556
1557 fn scope_preview_header(&self, header: String) -> String {
1558 header.replacen(PROFILE_DIR, self.profile_scope.display_dir(), 1)
1559 }
1560
1561 /// Number of selectable rows on the current step (0 on the review step).
1562 fn step_len(&self) -> usize {
1563 match self.step {
1564 Step::Role => ROLES.len(),
1565 Step::Composition => 0,
1566 Step::Model => self.filtered_model_indices().len(),
1567 Step::Destination => DESTINATION_ORDER.len(),
1568 Step::Review => 0,
1569 }
1570 }
1571
1572 fn move_up(&mut self) {
1573 match self.step {
1574 Step::Role => {
1575 self.role_idx =
1576 codewhale_tui_kit::list_nav::wrap_index(self.role_idx, self.step_len(), -1);
1577 self.discard_model_draft();
1578 self.composition_decision = CompositionDecision::Pending;
1579 }
1580 Step::Composition => {}
1581 Step::Model => {
1582 self.model_idx =
1583 codewhale_tui_kit::list_nav::wrap_index(self.model_idx, self.step_len(), -1);
1584 self.discard_model_draft();
1585 if self.composition_decision != CompositionDecision::Pending {
1586 self.composition_decision = CompositionDecision::Edited;
1587 }
1588 }
1589 Step::Destination => {
1590 self.destination_idx = codewhale_tui_kit::list_nav::wrap_index(
1591 self.destination_idx,
1592 self.step_len(),
1593 -1,
1594 );
1595 }
1596 Step::Review => self.review_scroll = self.review_scroll.saturating_sub(1),
1597 }
1598 }
1599
1600 /// A draft is only valid for the answers it was requested against —
1601 /// including one still in flight.
1602 fn discard_model_draft(&mut self) {
1603 self.model_draft = None;
1604 self.model_draft_preview = None;
1605 self.model_draft_request = None;
1606 }
1607
1608 fn current_draft_request(&self) -> ModelDraftRequest {
1609 ModelDraftRequest {
1610 role: self.selected_role(),
1611 route: self.selected_route(),
1612 reasoning_effort: self.selected_reasoning_effort(),
1613 }
1614 }
1615
1616 fn move_down(&mut self) {
1617 match self.step {
1618 Step::Role => {
1619 self.role_idx =
1620 codewhale_tui_kit::list_nav::wrap_index(self.role_idx, self.step_len(), 1);
1621 self.discard_model_draft();
1622 self.composition_decision = CompositionDecision::Pending;
1623 }
1624 Step::Composition => {}
1625 Step::Model => {
1626 self.model_idx =
1627 codewhale_tui_kit::list_nav::wrap_index(self.model_idx, self.step_len(), 1);
1628 self.discard_model_draft();
1629 if self.composition_decision != CompositionDecision::Pending {
1630 self.composition_decision = CompositionDecision::Edited;
1631 }
1632 }
1633 Step::Destination => {
1634 self.destination_idx = codewhale_tui_kit::list_nav::wrap_index(
1635 self.destination_idx,
1636 self.step_len(),
1637 1,
1638 );
1639 }
1640 Step::Review => self.review_scroll = self.review_scroll.saturating_add(1),
1641 }
1642 }
1643
1644 /// Apply one [`list_nav`](codewhale_tui_kit::list_nav) motion (#6290), returning
1645 /// whether it was consumed. Steps wrap; pages travel [`SETUP_PAGE`] rows
1646 /// and clamp. On the Review step the same keys scroll the proof pane
1647 /// instead — it has no row list — and render clamps the offset. The
1648 /// region axis is declined so Tab/Left/Right keep their explicit wizard
1649 /// arms below.
1650 fn apply_motion(&mut self, motion: codewhale_tui_kit::list_nav::Motion) -> bool {
1651 use codewhale_tui_kit::list_nav::Motion;
1652 match motion {
1653 Motion::Prev => {
1654 self.move_up();
1655 true
1656 }
1657 Motion::Next => {
1658 self.move_down();
1659 true
1660 }
1661 Motion::RegionPrev | Motion::RegionNext => false,
1662 _ => {
1663 if self.step == Step::Review {
1664 match motion {
1665 Motion::PagePrev => {
1666 self.review_scroll =
1667 self.review_scroll.saturating_sub(REVIEW_SCROLL_PAGE);
1668 }
1669 Motion::PageNext => {
1670 self.review_scroll =
1671 self.review_scroll.saturating_add(REVIEW_SCROLL_PAGE);
1672 }
1673 Motion::First => self.review_scroll = 0,
1674 // Render clamps to the content height.
1675 Motion::Last => self.review_scroll = usize::MAX,
1676 _ => return false,
1677 }
1678 return true;
1679 }
1680 let len = self.step_len();
1681 if len == 0 {
1682 return false;
1683 }
1684 let current = match self.step {
1685 Step::Role => self.role_idx,
1686 Step::Model => self.model_idx,
1687 Step::Destination => self.destination_idx,
1688 _ => return false,
1689 };
1690 let Some(next) =
1691 codewhale_tui_kit::list_nav::apply(current, len, SETUP_PAGE, motion)
1692 else {
1693 return false;
1694 };
1695 match self.step {
1696 Step::Role => {
1697 self.role_idx = next;
1698 self.discard_model_draft();
1699 self.composition_decision = CompositionDecision::Pending;
1700 }
1701 Step::Model => {
1702 self.model_idx = next;
1703 self.discard_model_draft();
1704 if self.composition_decision != CompositionDecision::Pending {
1705 self.composition_decision = CompositionDecision::Edited;
1706 }
1707 }
1708 Step::Destination => {
1709 self.destination_idx = next;
1710 }
1711 _ => {}
1712 }
1713 true
1714 }
1715 }
1716 }
1717
1718 /// Re-stat the profile directory. Called on the two transitions that can
1719 /// change the answer — entering Review, and toggling project/user scope —
1720 /// so the Review step never touches the filesystem while painting.
1721 fn refresh_destinations(&mut self) {
1722 let file = self
1723 .model_draft
1724 .as_ref()
1725 .map(|draft| draft.file_name())
1726 .unwrap_or_else(|| format!("{}.toml", profile_file_stem(&self.selected_role())));
1727 let statuses = DESTINATION_ORDER.map(|scope| {
1728 let file = self
1729 .assignment
1730 .as_ref()
1731 .filter(|assignment| {
1732 assignment.source_scope == Some(scope)
1733 || matches!(&assignment.template, RouteTemplate::Markdown(_))
1734 })
1735 .and_then(|assignment| assignment.source.as_ref())
1736 .and_then(|(path, _)| path.file_name())
1737 .and_then(|name| name.to_str())
1738 .unwrap_or(&file);
1739 destination_status(
1740 scope,
1741 &self.snapshot.workspace,
1742 &self.snapshot.personal_profile_dir,
1743 file,
1744 self.snapshot.project_profiles_enabled,
1745 self.snapshot.locale,
1746 )
1747 });
1748 self.destinations = Some(statuses);
1749 self.replace_armed = false;
1750 }
1751
1752 /// Choose a destination explicitly (Destination step or roster preload).
1753 fn choose_destination(&mut self, scope: FleetProfileScope) {
1754 if self.profile_scope != scope {
1755 self.discard_model_draft();
1756 }
1757 self.profile_scope = scope;
1758 self.scope_decided = true;
1759 self.destination_idx = DESTINATION_ORDER
1760 .iter()
1761 .position(|s| *s == scope)
1762 .unwrap_or(0);
1763 self.replace_armed = false;
1764 }
1765
1766 /// starter profile TOML the next save keypress would persist.
1767 fn advance(&mut self) -> ViewAction {
1768 match self.step {
1769 Step::Role => {
1770 self.step = Step::Model;
1771 ViewAction::None
1772 }
1773 Step::Composition => self.accept_composition(),
1774 Step::Model => {
1775 let idx = self.real_model_idx();
1776 match self.model_row_states.get(idx) {
1777 Some(FleetModelRowState::Ready) => {
1778 // Path: role → model → destination → review/save.
1779 // Thinking defaults to inherit; adjust on review with `t`.
1780 self.notice = None;
1781 self.step = Step::Destination;
1782 self.refresh_destinations();
1783 }
1784 Some(FleetModelRowState::NeedsActivation) => {
1785 // Dormant external-consent route: explicit human
1786 // selection must mint the read capability and validate
1787 // only this exact provider/model. Hand off to the host
1788 // so rendering stays I/O-free.
1789 if let Some((provider_id, model)) = self.model_routes.get(idx)
1790 && let Some(provider) =
1791 codewhale_config::ProviderKind::parse(provider_id)
1792 && crate::tui::provider_picker::external_consent_target_for_provider(
1793 provider,
1794 )
1795 .is_some()
1796 {
1797 return ViewAction::Emit(
1798 ViewEvent::FleetSetupExternalConsentActivationRequested {
1799 provider_id: provider_id.clone(),
1800 model: model.clone(),
1801 },
1802 );
1803 }
1804 }
1805 Some(FleetModelRowState::Blocked { reason }) => {
1806 // Stay on the Model step, but say why Enter did nothing
1807 // and where to fix it instead of failing silently.
1808 self.notice = Some(
1809 tr(self.snapshot.locale, MessageId::FleetModelRowBlockedNotice)
1810 .replace("{reason}", reason),
1811 );
1812 }
1813 None => {}
1814 }
1815 ViewAction::None
1816 }
1817 Step::Destination => {
1818 let scope =
1819 DESTINATION_ORDER[self.destination_idx.min(DESTINATION_ORDER.len() - 1)];
1820 let available = self
1821 .destination_for(scope)
1822 .is_none_or(|d| d.unavailable_reason.is_none());
1823 if !available {
1824 // A disabled destination never falls back to the other one.
1825 return ViewAction::None;
1826 }
1827 self.choose_destination(scope);
1828 self.step = Step::Review;
1829 self.review_scroll = 0;
1830 self.review_focus = ReviewFocus::Save;
1831 self.refresh_destinations();
1832 ViewAction::None
1833 }
1834 Step::Review => self.activate_review_focus(),
1835 }
1836 }
1837
1838 /// Enter on the Review step acts on the focused control.
1839 fn activate_review_focus(&mut self) -> ViewAction {
1840 match self.review_focus {
1841 ReviewFocus::Save => self.save_action(),
1842 ReviewFocus::ChangeDestination => {
1843 self.step = Step::Destination;
1844 self.refresh_destinations();
1845 ViewAction::None
1846 }
1847 ReviewFocus::Back => self.back(),
1848 }
1849 }
1850
1851 /// The single save path for both the deterministic starter profile and a
1852 /// model-authored draft. Replacing an existing file requires a second
1853 /// press: the first arms the control and renames it; nothing is written
1854 /// until the second. An unavailable destination never saves.
1855 fn save_action(&mut self) -> ViewAction {
1856 if !self.scope_decided || !self.selected_destination_available() {
1857 return ViewAction::None;
1858 }
1859 let exists = self
1860 .destination_for(self.profile_scope)
1861 .is_some_and(|d| d.target_exists);
1862 if exists && !self.replace_armed {
1863 self.replace_armed = true;
1864 return ViewAction::None;
1865 }
1866 if self.assignment.is_some() {
1867 return ViewAction::Emit(ViewEvent::FleetProfileRouteCommitRequested {
1868 editor_id: self.editor_id,
1869 });
1870 }
1871 match self.model_draft.clone() {
1872 Some(draft) => ViewAction::Emit(ViewEvent::FleetProfileDraftCommitRequested {
1873 editor_id: self.editor_id,
1874 draft,
1875 scope: self.profile_scope,
1876 expected: self
1877 .destination_for(self.profile_scope)
1878 .and_then(|d| d.original.clone()),
1879 }),
1880 None => self.commit_starter_profile_action(),
1881 }
1882 }
1883
1884 /// Step back toward the first screen. Returns `None` at the first step (the
1885 /// host closes the modal via Esc instead).
1886 fn back(&mut self) -> ViewAction {
1887 if self.assignment.is_some() {
1888 return self.route_pick_request();
1889 }
1890 match self.step {
1891 Step::Role => ViewAction::None,
1892 Step::Composition => {
1893 self.step = Step::Model;
1894 ViewAction::None
1895 }
1896 Step::Model => {
1897 self.notice = None;
1898 self.step = Step::Role;
1899 ViewAction::None
1900 }
1901 Step::Destination => {
1902 self.step = Step::Model;
1903 ViewAction::None
1904 }
1905 Step::Review => {
1906 self.replace_armed = false;
1907 self.step = Step::Destination;
1908 self.refresh_destinations();
1909 ViewAction::None
1910 }
1911 }
1912 }
1913
1914 /// Persist the deterministic starter profile directly from the Review
1915 /// summary. Unlike a model-authored draft, every field is derived from the
1916 /// structured choices already visible on this screen, so a second TOML
1917 /// ratification state adds no trust boundary.
1918 fn commit_starter_profile_action(&self) -> ViewAction {
1919 ViewAction::Emit(ViewEvent::FleetProfileDraftCommitRequested {
1920 editor_id: self.editor_id,
1921 draft: self.starter_profile_draft(),
1922 scope: self.profile_scope,
1923 expected: self
1924 .destination_for(self.profile_scope)
1925 .and_then(|d| d.original.clone()),
1926 })
1927 }
1928
1929 /// Build a deterministic starter profile for the current role/model
1930 /// selection. The same save event persists this as model-drafted profiles,
1931 /// so duplicate-id checks and atomic writes stay in one host path.
1932 ///
1933 /// `provider` is seeded from whatever the user actually picked in the
1934 /// Model step (#4093) — a concrete route names its own provider
1935 /// explicitly, so the saved profile is never ambiguously scoped to
1936 /// whatever provider happens to be active at launch time. `inherit`
1937 /// carries no provider, matching its `model: None`.
1938 fn starter_profile_draft(&self) -> Box<codewhale_engine::fleet::profile::FleetProfileDraft> {
1939 let role = &ROLES[self.role_idx.min(ROLES.len() - 1)];
1940 let route = self.selected_route();
1941 Box::new(codewhale_engine::fleet::profile::FleetProfileDraft {
1942 id: profile_file_stem(role.label),
1943 display_name: Some(role.label.to_string()),
1944 description: Some(format!(
1945 "{} - {}",
1946 tr(codewhale_localization::Locale::En, role.summary),
1947 tr(codewhale_localization::Locale::En, role.description)
1948 )),
1949 role_hint: role.label.to_string(),
1950 model_class_hint: None,
1951 model: route.as_ref().map(|(_, model)| model.clone()),
1952 provider: route.map(|(provider, _)| provider),
1953 reasoning_effort: self.selected_reasoning_effort(),
1954 instructions: Some(format!(
1955 "Role: {}. Work only within the assigned Fleet slice. Report concise evidence and stop when the assignment is complete. Do not widen permissions, trust, route configuration, or topology.",
1956 role.label
1957 )),
1958 })
1959 }
1960
1961 /// The action hints for the current step's footer (wrapped by the shared
1962 /// footer renderer so they can never run off the modal edge).
1963 fn footer_hints(&self) -> Vec<ActionHint> {
1964 let locale = self.snapshot.locale;
1965 let mut hints = Vec::new();
1966 match self.step {
1967 Step::Role => {
1968 hints.push(ActionHint::new(
1969 "↑/↓",
1970 tr(locale, MessageId::ProviderExternalActionChoose),
1971 ));
1972 hints.push(ActionHint::new(
1973 "Enter",
1974 tr(locale, MessageId::AutomationNextLabel),
1975 ));
1976 }
1977 Step::Composition => {
1978 hints.push(ActionHint::new(
1979 "a/Enter",
1980 tr(locale, MessageId::FleetSetupActionAccept),
1981 ));
1982 hints.push(ActionHint::new(
1983 "e",
1984 tr(locale, MessageId::FleetSetupActionEdit),
1985 ));
1986 hints.push(ActionHint::new(
1987 "r",
1988 tr(locale, MessageId::FleetSetupActionReject),
1989 ));
1990 hints.push(ActionHint::new("←", tr(locale, MessageId::SetupActionBack)));
1991 }
1992 Step::Model => {
1993 hints.push(ActionHint::new(
1994 "↑/↓",
1995 tr(locale, MessageId::ProviderExternalActionChoose),
1996 ));
1997 hints.push(ActionHint::new(
1998 "/",
1999 tr(locale, MessageId::FleetEditorActionFilter),
2000 ));
2001 if self.has_composition_for_selected_role() {
2002 hints.push(ActionHint::new(
2003 "c",
2004 tr(locale, MessageId::FleetSetupActionSuggest),
2005 ));
2006 }
2007 hints.push(ActionHint::new(
2008 "Enter",
2009 tr(locale, MessageId::AutomationNextLabel),
2010 ));
2011 hints.push(ActionHint::new("←", tr(locale, MessageId::SetupActionBack)));
2012 }
2013 Step::Destination => {
2014 hints.push(ActionHint::new(
2015 "↑/↓",
2016 tr(locale, MessageId::ProviderExternalActionChoose),
2017 ));
2018 hints.push(ActionHint::new(
2019 "Enter/Space",
2020 tr(locale, MessageId::AutomationNextLabel),
2021 ));
2022 hints.push(ActionHint::new("←", tr(locale, MessageId::SetupActionBack)));
2023 }
2024 Step::Review => {
2025 hints.push(ActionHint::new(
2026 "Tab",
2027 tr(locale, MessageId::ExtensionsActionFocus),
2028 ));
2029 hints.push(ActionHint::new(
2030 "Enter",
2031 tr(locale, MessageId::FleetSetupActionActivate),
2032 ));
2033 hints.push(ActionHint::new(
2034 "↑/↓",
2035 tr(locale, MessageId::PagerActionScroll),
2036 ));
2037 hints.push(ActionHint::new("t", tr(locale, MessageId::PhaseReasoning)));
2038 if self.assignment.is_some() {
2039 } else if self.model_draft.is_some() {
2040 hints.push(ActionHint::new(
2041 "m",
2042 tr(locale, MessageId::FleetSetupActionRedraft),
2043 ));
2044 } else if self.snapshot.provider_ready {
2045 hints.push(ActionHint::new(
2046 "m",
2047 tr(locale, MessageId::FleetSetupActionModelDraft),
2048 ));
2049 }
2050 hints.push(ActionHint::new("←", tr(locale, MessageId::SetupActionBack)));
2051 }
2052 }
2053 if self.step == Step::Role {
2054 hints.push(ActionHint::new(
2055 "Esc",
2056 tr(locale, MessageId::SetupActionCancel),
2057 ));
2058 } else {
2059 hints.push(ActionHint::new(
2060 "Esc",
2061 tr(locale, MessageId::SetupActionBack),
2062 ));
2063 }
2064 hints
2065 }
2066 }
2067
2068 impl ModalView for FleetSetupView {
2069 fn kind(&self) -> ModalKind {
2070 ModalKind::FleetSetup
2071 }
2072
2073 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
2074 self
2075 }
2076
2077 fn handle_paste(&mut self, text: &str) -> bool {
2078 if self.step != Step::Model || !self.model_filter_active {
2079 return false;
2080 }
2081 self.model_query.push_str(
2082 &text
2083 .trim_end_matches(['\r', '\n'])
2084 .replace("\r\n", "\n")
2085 .replace(char::is_control, " "),
2086 );
2087 self.model_filter_changed();
2088 true
2089 }
2090
2091 fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction {
2092 match mouse.kind {
2093 MouseEventKind::ScrollUp => self.move_up(),
2094 MouseEventKind::ScrollDown => self.move_down(),
2095 MouseEventKind::Down(MouseButton::Left) => {
2096 let row = self.row_hitboxes.borrow().iter().find_map(|(rect, row)| {
2097 rect.contains(ratatui::layout::Position::new(mouse.column, mouse.row))
2098 .then_some(*row)
2099 });
2100 if let Some(row) = row {
2101 match self.step {
2102 Step::Role => {
2103 self.role_idx = row.min(ROLES.len().saturating_sub(1));
2104 self.composition_decision = CompositionDecision::Pending;
2105 }
2106 Step::Composition => {}
2107 Step::Model => {
2108 self.model_idx = row.min(self.step_len().saturating_sub(1));
2109 if self.composition_decision != CompositionDecision::Pending {
2110 self.composition_decision = CompositionDecision::Edited;
2111 }
2112 }
2113 Step::Destination => {
2114 self.destination_idx = row.min(DESTINATION_ORDER.len() - 1);
2115 return ViewAction::None;
2116 }
2117 Step::Review => {}
2118 }
2119 self.discard_model_draft();
2120 }
2121 }
2122 _ => {}
2123 }
2124 ViewAction::None
2125 }
2126
2127 fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
2128 // Model-step filter input captures keystrokes while active (#4639).
2129 if self.step == Step::Model && self.model_filter_active {
2130 // Typing-safe movement set: pages and edges work while filtering
2131 // without letter aliases eating the query (#6290).
2132 if let Some(motion) = codewhale_tui_kit::list_nav::motion_while_typing(&key)
2133 && self.apply_motion(motion)
2134 {
2135 return ViewAction::None;
2136 }
2137 match key.code {
2138 KeyCode::Enter => {
2139 self.model_filter_active = false;
2140 }
2141 KeyCode::Esc => {
2142 self.model_filter_active = false;
2143 self.model_query.clear();
2144 self.model_idx = 0;
2145 }
2146 KeyCode::Backspace => {
2147 self.model_query.pop();
2148 self.model_filter_changed();
2149 }
2150 KeyCode::Char(ch)
2151 if !key.modifiers.intersects(
2152 KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER,
2153 ) =>
2154 {
2155 self.model_query.push(ch);
2156 self.model_filter_changed();
2157 }
2158 _ => {}
2159 }
2160 return ViewAction::None;
2161 }
2162 // Any navigation key clears a one-shot notice; the notice is re-set
2163 // below when the same blocked action is attempted again.
2164 if !matches!(key.code, KeyCode::Null) {
2165 self.notice = None;
2166 }
2167 // Movement keys come from the shared vocabulary (#6290), j/k aliases
2168 // included; the region axis is declined so Tab/Left/Right keep their
2169 // explicit wizard arms, and letter verbs below are unaffected.
2170 if let Some(motion) = codewhale_tui_kit::list_nav::motion(&key)
2171 && self.apply_motion(motion)
2172 {
2173 return ViewAction::None;
2174 }
2175 if self.assignment.is_some() && matches!(key.code, KeyCode::Char('t')) {
2176 return self.route_pick_request();
2177 }
2178 if self.assignment.is_some() && matches!(key.code, KeyCode::Char('m')) {
2179 return ViewAction::None;
2180 }
2181 match key.code {
2182 KeyCode::Esc if self.step != Step::Role => self.back(),
2183 KeyCode::Esc => ViewAction::Close,
2184 KeyCode::Char('q') if self.step == Step::Role => ViewAction::Close,
2185 // Tab moves focus; it never changes where the file is written.
2186 KeyCode::Tab if self.step == Step::Review => {
2187 self.review_focus = self.review_focus.next();
2188 self.replace_armed = false;
2189 ViewAction::None
2190 }
2191 KeyCode::BackTab if self.step == Step::Review => {
2192 self.review_focus = self.review_focus.prev();
2193 self.replace_armed = false;
2194 ViewAction::None
2195 }
2196 KeyCode::Right | KeyCode::Char('l') if self.step == Step::Review => {
2197 self.review_focus = self.review_focus.next();
2198 self.replace_armed = false;
2199 ViewAction::None
2200 }
2201 KeyCode::Char(' ') if self.step == Step::Destination => self.advance(),
2202 KeyCode::Char(' ') if self.step == Step::Review => self.activate_review_focus(),
2203 KeyCode::Char('a') if self.step == Step::Composition => self.accept_composition(),
2204 KeyCode::Char('e') if self.step == Step::Composition => self.edit_composition(),
2205 KeyCode::Char('r') if self.step == Step::Composition => self.reject_composition(),
2206 KeyCode::Char('c')
2207 if self.step == Step::Model && self.has_composition_for_selected_role() =>
2208 {
2209 self.composition_decision = CompositionDecision::Pending;
2210 self.discard_model_draft();
2211 self.step = Step::Composition;
2212 ViewAction::None
2213 }
2214 KeyCode::Char('/') if self.step == Step::Model => {
2215 self.model_filter_active = true;
2216 ViewAction::None
2217 }
2218 // Secondary accelerator: jump to the Destination step. The primary
2219 // way to change the destination is the focused Review control.
2220 KeyCode::Char('s') if self.step == Step::Review => {
2221 self.replace_armed = false;
2222 self.step = Step::Destination;
2223 self.refresh_destinations();
2224 ViewAction::None
2225 }
2226 KeyCode::Char('t') if self.step == Step::Review => {
2227 self.thinking_idx = (self.thinking_idx + 1) % THINKING_CHOICES.len();
2228 self.discard_model_draft();
2229 ViewAction::None
2230 }
2231 KeyCode::Char('m') if self.step == Step::Review && self.snapshot.provider_ready => {
2232 let route = self.selected_route();
2233 self.model_draft_request = Some(self.current_draft_request());
2234 ViewAction::Emit(ViewEvent::FleetProfileModelDraftRequested {
2235 role: self.selected_role(),
2236 model: route
2237 .as_ref()
2238 .map(|(_, model)| model.clone())
2239 .unwrap_or_else(|| "inherit".to_string()),
2240 // Carry the picked provider so the redrafted profile keeps
2241 // the cross-provider route (#4093). `install_model_draft`
2242 // re-injects it and refuses a draft whose answers changed
2243 // while it was in flight; the event stays self-describing.
2244 provider: route.map(|(provider, _)| provider),
2245 reasoning_effort: self.selected_reasoning_effort(),
2246 locale: self.snapshot.locale,
2247 })
2248 }
2249 KeyCode::Char('g') if self.step == Step::Review => {
2250 self.review_focus = ReviewFocus::Save;
2251 self.save_action()
2252 }
2253 KeyCode::Enter | KeyCode::Right | KeyCode::Char('l') => self.advance(),
2254 KeyCode::Left | KeyCode::Char('h') => self.back(),
2255 _ => ViewAction::None,
2256 }
2257 }
2258
2259 fn render(&self, area: Rect, buf: &mut Buffer) {
2260 self.row_hitboxes.borrow_mut().clear();
2261 // Choice steps have a bounded list/detail body and should not expand
2262 // into a tall empty card on roomy terminals. Review is proof-dense and
2263 // scrollable, so it keeps the extra row budgeted for the footer gutter.
2264 let preferred_height = match self.step {
2265 Step::Role => 22,
2266 Step::Composition => 26,
2267 Step::Model => 23,
2268 Step::Destination => 22,
2269 Step::Review => 32,
2270 };
2271 let popup_area = centered_modal_area(area, 96, preferred_height, 60, 16);
2272
2273 let step_no = match self.step {
2274 Step::Role => 1,
2275 Step::Composition => 2,
2276 Step::Model => 2,
2277 Step::Destination => 3,
2278 Step::Review => 4,
2279 };
2280 let (inner, _) = render_rounded_modal(
2281 area,
2282 popup_area,
2283 buf,
2284 SurfaceFrame::new(tr(self.snapshot.locale, MessageId::FleetSetupModalTitle))
2285 .bottom_right(
2286 tr(self.snapshot.locale, MessageId::FleetSetupStepCounter)
2287 .replace("{step}", &step_no.to_string()),
2288 Style::default().fg(palette::TEXT_MUTED),
2289 )
2290 .padding(Padding::uniform(1)),
2291 );
2292
2293 let hints = self.footer_hints();
2294 let content = render_modal_footer_with_gutter(inner, buf, &hints);
2295
2296 // Header (title + subtitle + "Saves to" chip) above the step body.
2297 // In the Compact tier the subtitle is dropped so the chip survives.
2298 let header_rows = if content.height < 4 {
2299 1
2300 } else if content.height < 12 {
2301 2
2302 } else {
2303 3
2304 };
2305 let chunks = Layout::default()
2306 .direction(Direction::Vertical)
2307 .constraints([Constraint::Length(header_rows), Constraint::Min(1)])
2308 .split(content);
2309 self.render_header(chunks[0], buf);
2310
2311 match self.step {
2312 Step::Role => {
2313 let mut context =
2314 vec![tr(self.snapshot.locale, MessageId::FleetSetupRoleContext).into_owned()];
2315 if let Some(note) = self.roster_override_note() {
2316 context.push(note);
2317 }
2318 let roles: Vec<Choice> = ROLES
2319 .iter()
2320 .map(|role| role.resolve(self.snapshot.locale))
2321 .collect();
2322 render_choice_step(chunks[1], buf, &roles, self.role_idx, &context);
2323 register_choice_hitboxes(chunks[1], ROLES.len(), self.role_idx, &self.row_hitboxes);
2324 }
2325 Step::Destination => {
2326 self.render_destination(chunks[1], buf);
2327 register_choice_hitboxes(
2328 chunks[1],
2329 DESTINATION_ORDER.len(),
2330 self.destination_idx,
2331 &self.row_hitboxes,
2332 );
2333 }
2334 Step::Composition => self.render_composition(chunks[1], buf),
2335 Step::Model => {
2336 let filtered = self.filtered_model_indices();
2337 // Compact tier: the row summary and any notice matter more
2338 // than the long route description, which would push them
2339 // below the fold.
2340 let compact = chunks[1].height < 12;
2341 let filtered_choices: Vec<Choice> = filtered
2342 .iter()
2343 .map(|idx| {
2344 let mut choice = self.model_choices[*idx].clone();
2345 if compact {
2346 choice.description = Cow::Borrowed("");
2347 }
2348 choice
2349 })
2350 .collect();
2351 let selected = self.model_idx.min(filtered.len().saturating_sub(1));
2352 let locale = self.snapshot.locale;
2353 let filter_line = if self.model_filter_active {
2354 tr(locale, MessageId::FleetModelFilterEditing)
2355 .replace("{query}", &self.model_query)
2356 } else if !self.model_query.trim().is_empty() {
2357 tr(locale, MessageId::FleetModelFilterActive)
2358 .replace("{query}", &self.model_query)
2359 .replace("{shown}", &filtered.len().to_string())
2360 .replace("{total}", &self.model_choices.len().to_string())
2361 } else {
2362 tr(locale, MessageId::FleetModelFilterPrompt)
2363 .replace("{count}", &self.model_choices.len().to_string())
2364 };
2365 let mut context = Vec::new();
2366 if let Some(notice) = &self.notice {
2367 context.push(notice.clone());
2368 }
2369 context.push(filter_line);
2370 context.push(
2371 tr(locale, MessageId::FleetModelCurrent)
2372 .replace("{provider}", &self.snapshot.provider)
2373 .replace("{model}", &self.snapshot.model)
2374 .replace("{reasoning}", &self.snapshot.reasoning),
2375 );
2376 context.push(match self.selected_model() {
2377 Some(model) => {
2378 tr(locale, MessageId::FleetModelRunsOn).replace("{model}", &model)
2379 }
2380 None => tr(locale, MessageId::FleetModelInherits).into_owned(),
2381 });
2382 if filtered_choices.is_empty() {
2383 context.push(tr(locale, MessageId::FleetModelNoMatch).into_owned());
2384 }
2385 render_choice_step(chunks[1], buf, &filtered_choices, selected, &context);
2386 register_choice_hitboxes(
2387 chunks[1],
2388 filtered_choices.len(),
2389 selected,
2390 &self.row_hitboxes,
2391 );
2392 }
2393 Step::Review => self.render_review(chunks[1], buf),
2394 }
2395 }
2396 }
2397
2398 impl FleetSetupView {
2399 fn render_header(&self, area: Rect, buf: &mut Buffer) {
2400 let locale = self.snapshot.locale;
2401 let (title, subtitle): (Cow<'static, str>, Cow<'static, str>) = match self.step {
2402 Step::Role => (
2403 tr(locale, MessageId::FleetSetupRoleTitle),
2404 tr(locale, MessageId::FleetSetupRoleSubtitle),
2405 ),
2406 Step::Composition => (
2407 tr(locale, MessageId::FleetSetupCompositionTitle),
2408 tr(locale, MessageId::FleetSetupCompositionSubtitle),
2409 ),
2410 Step::Model => (
2411 tr(locale, MessageId::FleetSetupModelTitle),
2412 tr(locale, MessageId::FleetSetupModelSubtitle),
2413 ),
2414 Step::Destination => (
2415 tr(locale, MessageId::FleetDestStepTitle),
2416 tr(locale, MessageId::FleetDestStepSubtitle),
2417 ),
2418 Step::Review if self.assignment.is_some() => (
2419 Cow::Owned(
2420 tr(locale, MessageId::FleetSetupRoleReviewTitle)
2421 .replace("{role}", &self.selected_role()),
2422 ),
2423 tr(locale, MessageId::FleetSetupRoleReviewSubtitle),
2424 ),
2425 Step::Review if self.model_draft.is_some() => (
2426 tr(locale, MessageId::FleetSetupProfileSaveTitle),
2427 tr(locale, MessageId::FleetSetupProfileSaveSubtitle),
2428 ),
2429 Step::Review => (
2430 tr(locale, MessageId::FleetSetupReviewTitle),
2431 tr(locale, MessageId::FleetSetupReviewSubtitle),
2432 ),
2433 };
2434 let chip_style = Style::default().fg(palette::TEXT_MUTED);
2435 let mut lines = vec![Line::from(Span::styled(
2436 title.into_owned(),
2437 Style::default().fg(palette::WHALE_ACTION).bold(),
2438 ))];
2439 if area.height >= 3 {
2440 lines.push(Line::from(Span::styled(
2441 subtitle.into_owned(),
2442 Style::default().fg(palette::TEXT_MUTED),
2443 )));
2444 }
2445 lines.push(Line::from(Span::styled(
2446 truncate_view_text(&self.saves_to_line(), usize::from(area.width)),
2447 chip_style,
2448 )));
2449 // No wrapping: each header row is one line, so the chip row is
2450 // always the last row and never pushed out by a long subtitle.
2451 Paragraph::new(lines).render(area, buf);
2452 }
2453
2454 /// The Destination step: a focused two-option list (This project /
2455 /// Personal) with the exact resolved file, whether it will be replaced,
2456 /// and the precedence consequence, for the highlighted option.
2457 fn render_destination(&self, area: Rect, buf: &mut Buffer) {
2458 let locale = self.snapshot.locale;
2459 // Compact tier: keep the choice, the file, and the consequence; drop
2460 // the long explanation rather than clip the file line off-screen.
2461 let compact = area.height < 12;
2462 let choices: Vec<Choice> = DESTINATION_ORDER
2463 .iter()
2464 .map(|scope| {
2465 let unavailable = self
2466 .destination_for(*scope)
2467 .and_then(|d| d.unavailable_reason.clone());
2468 let (label, summary, description) = match scope {
2469 FleetProfileScope::Project => (
2470 MessageId::FleetDestProjectLabel,
2471 MessageId::FleetDestProjectSummary,
2472 MessageId::FleetDestProjectDescription,
2473 ),
2474 FleetProfileScope::Personal => (
2475 MessageId::FleetDestPersonalLabel,
2476 MessageId::FleetDestPersonalSummary,
2477 MessageId::FleetDestPersonalDescription,
2478 ),
2479 };
2480 let _ = unavailable;
2481 Choice {
2482 label: Cow::Owned(tr(locale, label).into_owned()),
2483 summary: Cow::Owned(tr(locale, summary).into_owned()),
2484 description: if compact {
2485 Cow::Borrowed("")
2486 } else {
2487 tr(locale, description)
2488 },
2489 }
2490 })
2491 .collect();
2492 let selected = self.destination_idx.min(DESTINATION_ORDER.len() - 1);
2493 let scope = DESTINATION_ORDER[selected];
2494 let mut context = Vec::new();
2495 match self.destination_for(scope) {
2496 Some(status) => {
2497 if let Some(reason) = &status.unavailable_reason {
2498 context.push(
2499 tr(locale, MessageId::FleetDestUnavailable).replace("{reason}", reason),
2500 );
2501 }
2502 context.push(
2503 tr(locale, MessageId::FleetDestPathLine)
2504 .replace("{path}", &status.target.display().to_string()),
2505 );
2506 if status.target_exists {
2507 context.push(
2508 tr(locale, MessageId::FleetDestWillReplace)
2509 .replace("{path}", &status.target.display().to_string()),
2510 );
2511 }
2512 }
2513 None => context.push(
2514 tr(locale, MessageId::FleetDestPathLine)
2515 .replace("{path}", &self.projected_target(scope)),
2516 ),
2517 }
2518 if let Some(note) = self.override_note_for_scope(scope) {
2519 context.push(note);
2520 }
2521 render_choice_step(area, buf, &choices, selected, &context);
2522 }
2523
2524 fn render_composition(&self, area: Rect, buf: &mut Buffer) {
2525 let Some(advisory) = self.composition.as_ref() else {
2526 Paragraph::new("No configured model pool is available. Press e to choose manually.")
2527 .wrap(Wrap { trim: true })
2528 .render(area, buf);
2529 return;
2530 };
2531 let selected_role = self.selected_role();
2532 let mut lines = vec![
2533 Line::from(Span::styled(
2534 format!(
2535 "{} · {}",
2536 advisory.proposal.ratification.as_str().to_ascii_uppercase(),
2537 advisory.proposal.advisory
2538 ),
2539 Style::default().fg(palette::STATUS_WARNING).bold(),
2540 )),
2541 Line::from(""),
2542 ];
2543 for suggestion in &advisory.proposal.suggestions {
2544 let selected = suggestion.role.eq_ignore_ascii_case(&selected_role);
2545 lines.push(Line::from(vec![
2546 Span::styled(
2547 format!(
2548 "{} {}",
2549 codewhale_tui_kit::glyphs::selection_marker(selected),
2550 suggestion.role
2551 ),
2552 if selected {
2553 menu_style::selected_row_style()
2554 } else {
2555 Style::default().fg(palette::TEXT_PRIMARY)
2556 },
2557 ),
2558 Span::styled(
2559 format!(
2560 " → {}/{}",
2561 provider_display_label(&suggestion.provider),
2562 suggestion.model
2563 ),
2564 Style::default().fg(palette::TEXT_MUTED),
2565 ),
2566 ]));
2567 }
2568 lines.extend([
2569 Line::from(""),
2570 Line::from(Span::styled(
2571 format!(
2572 "Accept applies only the {selected_role} suggestion to this unsaved profile. Edit highlights it in the configured model picker; reject keeps your current selection."
2573 ),
2574 Style::default().fg(palette::TEXT_MUTED),
2575 )),
2576 ]);
2577 debug_assert_eq!(
2578 advisory.proposal.ratification,
2579 RatificationState::Unratified
2580 );
2581 Paragraph::new(lines)
2582 .wrap(Wrap { trim: true })
2583 .render(area, buf);
2584 }
2585
2586 fn render_review(&self, area: Rect, buf: &mut Buffer) {
2587 if area.width == 0 || area.height == 0 {
2588 return;
2589 }
2590 // Row 1: the focused action controls. Row 2+: the scrollable summary.
2591 // Keeping the controls out of the scroll region means the save action
2592 // and its label are visible at every scroll offset and every size.
2593 let rows = Layout::default()
2594 .direction(Direction::Vertical)
2595 .constraints([
2596 Constraint::Length(if self.notice.is_some() { 4 } else { 2 }),
2597 Constraint::Min(1),
2598 ])
2599 .split(area);
2600 self.render_review_actions(rows[0], buf);
2601 let body = rows[1];
2602
2603 let locale = self.snapshot.locale;
2604 if let Some(assignment) = &self.assignment {
2605 let follow_session = tr(locale, MessageId::FleetAssignmentFollowSession);
2606 let session_provider = tr(locale, MessageId::FleetAssignmentSessionProvider);
2607 let model = assignment
2608 .model
2609 .as_deref()
2610 .unwrap_or(follow_session.as_ref());
2611 let provider = assignment
2612 .provider
2613 .as_deref()
2614 .unwrap_or(session_provider.as_ref());
2615 let thinking = assignment
2616 .reasoning
2617 .as_deref()
2618 .unwrap_or(follow_session.as_ref());
2619 let text = tr(locale, MessageId::FleetAssignmentReviewBody)
2620 .replace("{role}", &assignment.id)
2621 .replace("{model}", model)
2622 .replace("{provider}", provider)
2623 .replace("{thinking}", thinking)
2624 .replace("{saves_to}", &self.saves_to_line());
2625 render_scrollable_text(body, buf, &text, self.review_scroll);
2626 return;
2627 }
2628
2629 // A ratify-ready draft is on screen: show the exact TOML preview
2630 // inline, scrolled by the same `review_scroll` state, so the save
2631 // control in THIS view ratifies it directly — no separate pager in the
2632 // way to swallow the keypress (#4093).
2633 if let Some(preview) = self.model_draft_preview.as_deref() {
2634 render_scrollable_text(body, buf, preview, self.review_scroll);
2635 return;
2636 }
2637
2638 let role = &ROLES[self.role_idx.min(ROLES.len() - 1)];
2639 let mut lines: Vec<Line> = Vec::new();
2640 let section = |lines: &mut Vec<Line>, label: &str, body: String| {
2641 lines.push(Line::from(Span::styled(
2642 label.to_string(),
2643 Style::default().fg(palette::WHALE_ACTION).bold(),
2644 )));
2645 lines.push(Line::from(Span::styled(
2646 body,
2647 Style::default().fg(palette::TEXT_PRIMARY),
2648 )));
2649 lines.push(Line::from(""));
2650 };
2651
2652 // "Saves to" comes first: it is the decision this screen exists to
2653 // confirm. Exact file, replace/create, precedence consequence.
2654 let mut saves_to = vec![format!(
2655 "{} · {}",
2656 self.scope_label(self.profile_scope),
2657 self.destination_for(self.profile_scope)
2658 .map(|d| d.target.display().to_string())
2659 .unwrap_or_else(|| self.projected_target(self.profile_scope))
2660 )];
2661 if let Some(status) = self.destination_for(self.profile_scope) {
2662 if let Some(reason) = &status.unavailable_reason {
2663 saves_to
2664 .push(tr(locale, MessageId::FleetDestUnavailable).replace("{reason}", reason));
2665 } else if status.target_exists {
2666 saves_to.push(
2667 tr(locale, MessageId::FleetDestWillReplace)
2668 .replace("{path}", &status.target.display().to_string()),
2669 );
2670 }
2671 }
2672 if let Some(note) = self.roster_override_note() {
2673 saves_to.push(note);
2674 }
2675 section(
2676 &mut lines,
2677 &tr(locale, MessageId::FleetReviewSavesTo),
2678 saves_to.join(" · "),
2679 );
2680 section(
2681 &mut lines,
2682 &tr(locale, MessageId::FleetReviewRole),
2683 format!("{} — {}", role.label, tr(locale, role.summary)),
2684 );
2685 let ready_label = tr(locale, MessageId::HotbarSetupStatusReady);
2686 let needs_action_label = tr(locale, MessageId::SetupStatusNeedsAction);
2687 section(
2688 &mut lines,
2689 &tr(locale, MessageId::SettingSubjectModel),
2690 // The picked route's OWN provider, not the parent/current
2691 // session's — a cross-provider pin must never be misreported as
2692 // running on the active provider (#4093).
2693 match self.selected_route() {
2694 Some((provider, model)) => {
2695 let readiness = self
2696 .snapshot
2697 .available_models
2698 .iter()
2699 .find(|(candidate_provider, candidate_model, _)| {
2700 candidate_provider == &provider && candidate_model == &model
2701 })
2702 .map(|(_, _, readiness)| readiness.label().into_owned())
2703 .unwrap_or_else(|| {
2704 if self.snapshot.provider_ready {
2705 ready_label.clone().into_owned()
2706 } else {
2707 needs_action_label.clone().into_owned()
2708 }
2709 });
2710 tr(locale, MessageId::FleetReviewModelPinned)
2711 .replace("{model}", &model)
2712 .replace("{provider}", &provider_display_label(&provider))
2713 .replace("{readiness}", &readiness)
2714 }
2715 None => tr(locale, MessageId::FleetReviewModelInherit)
2716 .replace("{provider}", &self.snapshot.provider)
2717 .replace("{model}", &self.snapshot.model)
2718 .replace(
2719 "{readiness}",
2720 if self.snapshot.provider_ready {
2721 ready_label.as_ref()
2722 } else {
2723 needs_action_label.as_ref()
2724 },
2725 ),
2726 },
2727 );
2728 match self.composition_decision {
2729 CompositionDecision::Accepted => section(
2730 &mut lines,
2731 &tr(locale, MessageId::FleetReviewComposition),
2732 tr(locale, MessageId::FleetReviewCompositionAccepted).into_owned(),
2733 ),
2734 CompositionDecision::Edited => section(
2735 &mut lines,
2736 &tr(locale, MessageId::FleetReviewComposition),
2737 tr(locale, MessageId::FleetReviewCompositionEdited).into_owned(),
2738 ),
2739 CompositionDecision::Rejected => section(
2740 &mut lines,
2741 &tr(locale, MessageId::FleetReviewComposition),
2742 tr(locale, MessageId::FleetReviewCompositionRejected).into_owned(),
2743 ),
2744 CompositionDecision::Pending => {}
2745 }
2746 section(
2747 &mut lines,
2748 &tr(locale, MessageId::SettingSubjectThinking),
2749 self.selected_thinking_label(),
2750 );
2751 section(
2752 &mut lines,
2753 &tr(locale, MessageId::FleetReviewAuthReadiness),
2754 if self.snapshot.provider_ready {
2755 tr(locale, MessageId::FleetReviewAuthReady).into_owned()
2756 } else {
2757 tr(locale, MessageId::FleetReviewAuthNotReady).into_owned()
2758 },
2759 );
2760 section(
2761 &mut lines,
2762 &tr(locale, MessageId::SettingSubjectPermissions),
2763 tr(locale, MessageId::FleetReviewPermissionsBody).into_owned(),
2764 );
2765 section(
2766 &mut lines,
2767 &tr(locale, MessageId::FleetReviewTools),
2768 tr(locale, MessageId::FleetReviewToolsBody).into_owned(),
2769 );
2770 section(
2771 &mut lines,
2772 &tr(locale, MessageId::FleetReviewWorkspaceOrg),
2773 tr(locale, MessageId::FleetReviewWorkspaceLimits)
2774 .replace("{concurrent}", &self.snapshot.max_subagents.to_string())
2775 .replace(
2776 "{launch_slots}",
2777 &self.snapshot.launch_concurrency.to_string(),
2778 )
2779 .replace("{admitted}", &self.snapshot.max_admitted.to_string())
2780 .replace(
2781 "{agent_depth}",
2782 &self.snapshot.subagent_spawn_depth.to_string(),
2783 )
2784 .replace(
2785 "{fleet_depth}",
2786 &self.snapshot.fleet_spawn_depth.to_string(),
2787 )
2788 .replace(
2789 "{ceiling}",
2790 &codewhale_config::MAX_SPAWN_DEPTH_CEILING.to_string(),
2791 )
2792 .replace(
2793 "{enabled}",
2794 &tr(
2795 locale,
2796 if self.snapshot.subagents_enabled {
2797 MessageId::ExtensionsStateEnabled
2798 } else {
2799 MessageId::HotbarSetupStatusDisabled
2800 },
2801 ),
2802 )
2803 .replace(
2804 "{workspace}",
2805 &self.snapshot.workspace.display().to_string(),
2806 ),
2807 );
2808 section(
2809 &mut lines,
2810 &tr(locale, MessageId::FleetReviewPolicyLabel),
2811 self.review_policy_summary(),
2812 );
2813
2814 // `scroll` offsets by *visual* (post-wrap) rows, so the bound must count
2815 // wrapped rows — not logical lines — or the bottom sections become
2816 // unreachable. Estimate each line's wrapped height from its display
2817 // width; an over-estimate is harmless (scroll clamps at the real end).
2818 let wrap_width = usize::from(body.width).max(1);
2819 let visual_rows: usize = lines
2820 .iter()
2821 .map(|line| line.width().div_ceil(wrap_width).max(1))
2822 .sum();
2823 let max_scroll = visual_rows.saturating_sub(usize::from(body.height).max(1));
2824 let scroll = self.review_scroll.min(max_scroll);
2825 Paragraph::new(lines)
2826 .wrap(Wrap { trim: true })
2827 .scroll((scroll as u16, 0))
2828 .render(body, buf);
2829 }
2830
2831 /// The Review step's focused control row: [Save…] [Change destination]
2832 /// [Back]. The focused control is drawn with the canonical selection style
2833 /// and the `▸` marker; a disabled save control (unavailable destination)
2834 /// is dimmed and named with the reason on the "Saves to" line.
2835 fn render_review_actions(&self, area: Rect, buf: &mut Buffer) {
2836 let locale = self.snapshot.locale;
2837 let save_enabled = self.scope_decided && self.selected_destination_available();
2838 let controls: [(ReviewFocus, String, bool); 3] = [
2839 (ReviewFocus::Save, self.save_action_label(), save_enabled),
2840 (
2841 ReviewFocus::ChangeDestination,
2842 tr(locale, MessageId::FleetActionChangeDestination).into_owned(),
2843 true,
2844 ),
2845 (
2846 ReviewFocus::Back,
2847 tr(locale, MessageId::FleetActionBack).into_owned(),
2848 true,
2849 ),
2850 ];
2851 let mut spans: Vec<Span> = Vec::new();
2852 for (focus, label, enabled) in controls {
2853 let focused = focus == self.review_focus;
2854 let text = format!(
2855 "{} {} ",
2856 codewhale_tui_kit::glyphs::selection_marker(focused),
2857 label
2858 );
2859 let style = match (focused, enabled) {
2860 (true, true) => menu_style::selected_row_style(),
2861 (true, false) => menu_style::disabled_selected_row_style(),
2862 (false, true) => Style::default().fg(palette::TEXT_PRIMARY),
2863 (false, false) => Style::default().fg(palette::TEXT_MUTED).dim(),
2864 };
2865 spans.push(Span::styled(text, style));
2866 spans.push(Span::raw(" "));
2867 }
2868 Paragraph::new(vec![
2869 Line::from(spans),
2870 Line::from(Span::styled(
2871 self.notice.as_deref().unwrap_or_default(),
2872 Style::default().fg(palette::TEXT_PRIMARY),
2873 )),
2874 ])
2875 .wrap(Wrap { trim: true })
2876 .render(area, buf);
2877 }
2878
2879 fn review_policy_summary(&self) -> String {
2880 tr(self.snapshot.locale, MessageId::FleetReviewPolicy)
2881 .replace("{api_secs}", &self.snapshot.api_timeout_secs.to_string())
2882 .replace(
2883 "{heartbeat_secs}",
2884 &self.snapshot.heartbeat_timeout_secs.to_string(),
2885 )
2886 }
2887 }
2888
2889 /// Render wrapped, line-scrolled plain text (the ratify-ready draft TOML
2890 /// preview) into `area`, clamping `scroll` to the real wrapped-row bound the
2891 /// same way [`FleetSetupView::render_review`]'s summary does — an
2892 /// over-estimate of wrapped height is harmless (scroll clamps at the end).
2893 fn render_scrollable_text(area: Rect, buf: &mut Buffer, text: &str, scroll: usize) {
2894 let lines: Vec<Line> = text
2895 .lines()
2896 .map(|line| Line::from(line.to_string()))
2897 .collect();
2898 let wrap_width = usize::from(area.width).max(1);
2899 let visual_rows: usize = lines
2900 .iter()
2901 .map(|line| line.width().div_ceil(wrap_width).max(1))
2902 .sum();
2903 let max_scroll = visual_rows.saturating_sub(usize::from(area.height).max(1));
2904 let scroll = scroll.min(max_scroll);
2905 Paragraph::new(lines)
2906 .wrap(Wrap { trim: true })
2907 .scroll((scroll as u16, 0))
2908 .render(area, buf);
2909 }
2910
2911 /// Render a wizard choice step: a list of selectable identifiers on the left and
2912 /// a wrapped detail pane (summary + description + context) on the right. Stacks
2913 /// vertically when the body is too narrow for two columns so nothing truncates.
2914 fn render_choice_step(
2915 area: Rect,
2916 buf: &mut Buffer,
2917 choices: &[Choice],
2918 selected: usize,
2919 context: &[String],
2920 ) {
2921 if area.width == 0 || area.height == 0 {
2922 return;
2923 }
2924
2925 let (list_area, detail_area) = if area.width >= CHOICE_TWO_COLUMN_MIN_WIDTH {
2926 let cols = Layout::default()
2927 .direction(Direction::Horizontal)
2928 .constraints([
2929 Constraint::Length(CHOICE_LIST_WIDTH),
2930 Constraint::Min(CHOICE_DETAIL_MIN_WIDTH),
2931 ])
2932 .split(area);
2933 (cols[0], cols[1])
2934 } else {
2935 let list_height = (choices.len() as u16).min(area.height);
2936 let rows = Layout::default()
2937 .direction(Direction::Vertical)
2938 .constraints([Constraint::Length(list_height), Constraint::Min(0)])
2939 .split(area);
2940 (rows[0], rows[1])
2941 };
2942
2943 // No choices (a type-to-filter query that matches nothing): there is no
2944 // row to point at and no detail to show, so paint the context — the
2945 // caller adds the "no matches" hint — and stop before indexing (#5953).
2946 if choices.is_empty() {
2947 let lines: Vec<Line> = context
2948 .iter()
2949 .map(|entry| {
2950 Line::from(Span::styled(
2951 entry.clone(),
2952 Style::default().fg(palette::TEXT_MUTED),
2953 ))
2954 })
2955 .collect();
2956 Paragraph::new(lines)
2957 .wrap(Wrap { trim: true })
2958 .render(detail_area, buf);
2959 return;
2960 }
2961
2962 // List: labels are identifiers, so a `▸`-marked single line each is safe.
2963 let list_width = usize::from(list_area.width);
2964 let visible = choices.len().min(usize::from(list_area.height));
2965 let row_start = choice_window_start(choices.len(), selected, visible);
2966 let mut list_lines: Vec<Line> = Vec::with_capacity(visible);
2967 let highlight_width = if area.width >= CHOICE_TWO_COLUMN_MIN_WIDTH {
2968 list_area.width.saturating_sub(1)
2969 } else {
2970 list_area.width
2971 };
2972 for (line_offset, (idx, choice)) in choices
2973 .iter()
2974 .enumerate()
2975 .skip(row_start)
2976 .take(visible)
2977 .enumerate()
2978 {
2979 let is_selected = idx == selected;
2980 let pointer = format!(
2981 "{} ",
2982 codewhale_tui_kit::glyphs::selection_marker(is_selected)
2983 );
2984 let style = if is_selected {
2985 menu_style::selected_row_style()
2986 } else {
2987 Style::default().fg(palette::TEXT_PRIMARY)
2988 };
2989 if is_selected && highlight_width > 0 {
2990 buf.set_style(
2991 Rect::new(
2992 list_area.x,
2993 list_area.y.saturating_add(line_offset as u16),
2994 highlight_width,
2995 1,
2996 ),
2997 menu_style::selected_row_bg_style(),
2998 );
2999 }
3000 list_lines.push(Line::from(Span::styled(
3001 truncate_view_text(&format!("{pointer}{}", choice.label), list_width),
3002 style,
3003 )));
3004 }
3005 Paragraph::new(list_lines).render(list_area, buf);
3006
3007 // Detail: summary + wrapped description + wrapped context, all word-wrapped.
3008 let choice = &choices[selected.min(choices.len().saturating_sub(1))];
3009 let mut detail_lines: Vec<Line> = vec![Line::from(Span::styled(
3010 choice.summary.clone(),
3011 Style::default().fg(palette::WHALE_ACTION).bold(),
3012 ))];
3013 // An empty description (compact tiers drop the long explanation so the
3014 // decisive facts stay on screen) leaves no orphan blank rows behind.
3015 if !choice.description.is_empty() {
3016 detail_lines.push(Line::from(""));
3017 detail_lines.push(Line::from(Span::styled(
3018 choice.description.clone(),
3019 Style::default().fg(palette::TEXT_PRIMARY),
3020 )));
3021 }
3022 if !context.is_empty() {
3023 detail_lines.push(Line::from(""));
3024 for entry in context {
3025 detail_lines.push(Line::from(Span::styled(
3026 entry.clone(),
3027 Style::default().fg(palette::TEXT_MUTED),
3028 )));
3029 }
3030 }
3031 Paragraph::new(detail_lines)
3032 .wrap(Wrap { trim: true })
3033 .render(detail_area, buf);
3034 }
3035
3036 /// Register exactly the list column/stack rows painted by
3037 /// [`render_choice_step`]. The detail pane intentionally owns no hitboxes.
3038 fn register_choice_hitboxes(
3039 area: Rect,
3040 choice_count: usize,
3041 selected: usize,
3042 hitboxes: &RefCell<Vec<(Rect, usize)>>,
3043 ) {
3044 if area.width == 0 || area.height == 0 || choice_count == 0 {
3045 return;
3046 }
3047 let list_area = if area.width >= CHOICE_TWO_COLUMN_MIN_WIDTH {
3048 Layout::default()
3049 .direction(Direction::Horizontal)
3050 .constraints([
3051 Constraint::Length(CHOICE_LIST_WIDTH),
3052 Constraint::Min(CHOICE_DETAIL_MIN_WIDTH),
3053 ])
3054 .split(area)[0]
3055 } else {
3056 let list_height = (choice_count as u16).min(area.height);
3057 Layout::default()
3058 .direction(Direction::Vertical)
3059 .constraints([Constraint::Length(list_height), Constraint::Min(0)])
3060 .split(area)[0]
3061 };
3062 let visible = choice_count.min(usize::from(list_area.height));
3063 let row_start = choice_window_start(choice_count, selected, visible);
3064 let mut rows = hitboxes.borrow_mut();
3065 rows.extend((0..visible).map(|visible_idx| {
3066 let choice_idx = row_start + visible_idx;
3067 (
3068 Rect::new(
3069 list_area.x,
3070 list_area.y.saturating_add(visible_idx as u16),
3071 list_area.width,
3072 1,
3073 ),
3074 choice_idx,
3075 )
3076 }));
3077 }
3078
3079 fn choice_window_start(total: usize, selected: usize, visible: usize) -> usize {
3080 if total <= visible || visible == 0 {
3081 return 0;
3082 }
3083 selected
3084 .saturating_add(1)
3085 .saturating_sub(visible)
3086 .min(total.saturating_sub(visible))
3087 }
3088
3089 /// Resolve one save destination off the paint path: the exact target file,
3090 /// whether it already exists, and — when it cannot be written — the localized
3091 /// reason. A disabled destination is never silently swapped for the other.
3092 fn destination_status(
3093 scope: FleetProfileScope,
3094 workspace: &Path,
3095 personal_dir: &Result<PathBuf, String>,
3096 file_name: &str,
3097 project_profiles_enabled: bool,
3098 locale: codewhale_localization::Locale,
3099 ) -> DestinationStatus {
3100 let dir: Result<PathBuf, String> = match scope {
3101 FleetProfileScope::Project => {
3102 Ok(workspace.join(codewhale_engine::fleet::profile::WORKSPACE_AGENT_PROFILE_DIR))
3103 }
3104 FleetProfileScope::Personal => personal_dir.clone(),
3105 };
3106 let (target, mut unavailable_reason) = match dir {
3107 Ok(dir) => (dir.join(file_name), None),
3108 Err(err) => (
3109 PathBuf::from(scope.display_dir()).join(file_name),
3110 Some(tr(locale, MessageId::FleetDestReasonHomeUnavailable).replace("{error}", &err)),
3111 ),
3112 };
3113 if unavailable_reason.is_none() {
3114 match scope {
3115 FleetProfileScope::Project => {
3116 if !project_profiles_enabled {
3117 unavailable_reason =
3118 Some(tr(locale, MessageId::FleetDestReasonNoProjectConfig).into_owned());
3119 } else if !workspace.is_dir() {
3120 unavailable_reason = Some(
3121 tr(locale, MessageId::FleetDestReasonWorkspaceMissing)
3122 .replace("{path}", &workspace.display().to_string()),
3123 );
3124 }
3125 }
3126 FleetProfileScope::Personal => {}
3127 }
3128 }
3129 if unavailable_reason.is_none()
3130 && let Some(parent) = target.parent()
3131 && parent.exists()
3132 && !parent.is_dir()
3133 {
3134 unavailable_reason = Some(
3135 tr(locale, MessageId::FleetDestReasonWorkspaceMissing)
3136 .replace("{path}", &parent.display().to_string()),
3137 );
3138 }
3139 let original = if unavailable_reason.is_none() {
3140 match codewhale_engine::fleet::profile::read_agent_profile_document(
3141 scope, workspace, &target,
3142 ) {
3143 Ok(text) => text,
3144 Err(error) => {
3145 unavailable_reason = Some(
3146 tr(locale, MessageId::FleetProfileIdentityVerifyFailed)
3147 .replace("{error}", &error.to_string()),
3148 );
3149 None
3150 }
3151 }
3152 } else {
3153 None
3154 };
3155 let target_exists = original.is_some();
3156 DestinationStatus {
3157 scope,
3158 unavailable_reason,
3159 target,
3160 target_exists,
3161 original,
3162 }
3163 }
3164
3165 /// Sanitize a planner role label into a safe TOML file stem.
3166 fn profile_file_stem(role: &str) -> String {
3167 let stem: String = role
3168 .chars()
3169 .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
3170 .collect();
3171 let stem = stem.trim_matches('-').to_ascii_lowercase();
3172 if stem.is_empty() {
3173 "custom".to_string()
3174 } else {
3175 stem
3176 }
3177 }
3178
3179 #[cfg(test)]
3180 mod tests {
3181 use super::*;
3182 use crate::tui::views::ViewStack;
3183 use crossterm::event::KeyModifiers;
3184 use unicode_width::UnicodeWidthStr;
3185
3186 const BLOCKER_SIZES: [(u16, u16); 5] = [(80, 24), (89, 50), (100, 30), (120, 32), (160, 40)];
3187
3188 #[test]
3189 fn role_assignment_preserves_profile_fields_and_rejects_stale_source() {
3190 let _env = crate::test_support::lock_test_env();
3191 let workspace = tempfile::tempdir().unwrap();
3192 let directory = workspace
3193 .path()
3194 .join(codewhale_engine::fleet::profile::WORKSPACE_AGENT_PROFILE_DIR);
3195 std::fs::create_dir_all(&directory).unwrap();
3196 let path = directory.join("different-file-name.toml");
3197 let original = r#"id = "custom-reviewer"
3198 display_name = "My reviewer"
3199 description = "Keep this description"
3200 role_hint = "reviewer"
3201 loadout = "inherit"
3202 model = "previous-model"
3203 provider = "deepseek"
3204 [instructions]
3205 text = "Keep these precise instructions"
3206 [tools]
3207 posture = "read-only"
3208 [permissions]
3209 allow_shell = false
3210 trust = false
3211 approval_required = true
3212 "#;
3213 std::fs::write(&path, original).unwrap();
3214 let config = Config::default();
3215 let app = App::new(
3216 crate::tui::test_support::test_tui_options(workspace.path()),
3217 &config,
3218 );
3219 let mut view =
3220 FleetSetupView::new_for_route_assignment(&app, &config, "custom-reviewer").unwrap();
3221 let editor_id = view.editor_id;
3222 assert_eq!(view.selected_role(), "custom-reviewer");
3223 assert_eq!(
3224 view.destination_for(FleetProfileScope::Project)
3225 .unwrap()
3226 .target,
3227 path
3228 );
3229 assert!(view.accept_route(
3230 editor_id,
3231 "deepseek".into(),
3232 "auto".into(),
3233 Some(codewhale_engine::reasoning_preference::ReasoningEffort::High)
3234 ));
3235 assert_eq!(view.step, Step::Review);
3236 assert_eq!(
3237 std::fs::read_to_string(&path).unwrap(),
3238 original,
3239 "picker/review must not write"
3240 );
3241 view.commit_route_assignment(editor_id, &app, &config)
3242 .unwrap();
3243 let before: toml::Table = toml::from_str(original).unwrap();
3244 let after: toml::Table = toml::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
3245 for name in [
3246 "id",
3247 "display_name",
3248 "description",
3249 "role_hint",
3250 "instructions",
3251 "tools",
3252 "permissions",
3253 ] {
3254 assert_eq!(
3255 after.get(name),
3256 before.get(name),
3257 "{name} changed during route assignment"
3258 );
3259 }
3260 assert!(!after.contains_key("model") && !after.contains_key("provider"));
3261 assert_eq!(after["reasoning_effort"].as_str(), Some("high"));
3262 let saved = std::fs::read_to_string(&path).unwrap();
3263 let conflict = codewhale_engine::fleet::profile::save_agent_profile_document(
3264 FleetProfileScope::Project,
3265 workspace.path(),
3266 &path,
3267 Some(original),
3268 "custom-reviewer",
3269 original,
3270 )
3271 .unwrap_err();
3272 assert!(conflict.is::<codewhale_engine::fleet::profile::AgentProfileWriteConflict>());
3273 assert_eq!(std::fs::read_to_string(&path).unwrap(), saved);
3274 let mut stale =
3275 FleetSetupView::new_for_route_assignment(&app, &config, "custom-reviewer").unwrap();
3276 let stale_id = stale.editor_id;
3277 stale.accept_route(stale_id, "deepseek".into(), "auto".into(), None);
3278 let changed = format!(
3279 "{}\n# Another editor changed this file\n",
3280 std::fs::read_to_string(&path).unwrap()
3281 );
3282 std::fs::write(&path, &changed).unwrap();
3283 assert!(
3284 stale
3285 .commit_route_assignment(stale_id, &app, &config)
3286 .is_err()
3287 );
3288 assert_eq!(std::fs::read_to_string(&path).unwrap(), changed);
3289 }
3290
3291 #[test]
3292 fn builtin_role_assignment_requires_destination_and_rejects_new_override() {
3293 let _env = crate::test_support::lock_test_env();
3294 let workspace = tempfile::tempdir().unwrap();
3295 let config = Config::default();
3296 let app = App::new(
3297 crate::tui::test_support::test_tui_options(workspace.path()),
3298 &config,
3299 );
3300 let mut view = FleetSetupView::new_for_route_assignment(&app, &config, "manager").unwrap();
3301 let id = view.editor_id;
3302 view.accept_route(id, "deepseek".into(), "auto".into(), None);
3303 assert_eq!(view.step, Step::Destination);
3304 assert!(!view.scope_decided);
3305 assert!(view.commit_route_assignment(id, &app, &config).is_err());
3306 let directory = workspace
3307 .path()
3308 .join(codewhale_engine::fleet::profile::WORKSPACE_AGENT_PROFILE_DIR);
3309 std::fs::create_dir_all(&directory).unwrap();
3310 std::fs::write(directory.join("manager.toml"), "id = \"manager\"\n").unwrap();
3311 view.choose_destination(FleetProfileScope::Personal);
3312 view.refresh_destinations();
3313 assert!(view.commit_route_assignment(id, &app, &config).is_err());
3314 }
3315
3316 fn snapshot() -> FleetSetupSnapshot {
3317 FleetSetupSnapshot {
3318 workspace: PathBuf::from("/tmp/codewhale-test-workspace"),
3319 locale: codewhale_localization::Locale::En,
3320 provider_ready: true,
3321 provider: "DeepSeek".to_string(),
3322 model: "deepseek-v4-pro".to_string(),
3323 reasoning: "Auto".to_string(),
3324 subagents_enabled: true,
3325 max_subagents: 8,
3326 launch_concurrency: 3,
3327 max_admitted: 20,
3328 subagent_spawn_depth: 3,
3329 fleet_spawn_depth: 3,
3330 api_timeout_secs: 120,
3331 heartbeat_timeout_secs: 300,
3332 roster_members: codewhale_engine::fleet::roster::FleetRoster::built_ins_only()
3333 .members()
3334 .iter()
3335 .map(|member| (member.id.to_lowercase(), member.origin.to_string()))
3336 .collect(),
3337 roster_details: Vec::new(),
3338 project_profiles_enabled: true,
3339 personal_profile_dir: Ok(test_personal_dir()),
3340 available_models: vec![
3341 (
3342 "deepseek".to_string(),
3343 "deepseek-v4-pro".to_string(),
3344 codewhale_engine::provider_readiness::ResolvedProviderReadiness::SavedUnchecked,
3345 ),
3346 (
3347 "deepseek".to_string(),
3348 "deepseek-v4-flash".to_string(),
3349 codewhale_engine::provider_readiness::ResolvedProviderReadiness::SavedUnchecked,
3350 ),
3351 ],
3352 }
3353 }
3354
3355 #[test]
3356 fn setup_target_routes_selected_v2_and_fails_closed_for_stale_selection() {
3357 let _lock = crate::test_support::lock_test_env();
3358 let workspace = tempfile::TempDir::new().expect("workspace");
3359 let personal_home = workspace.path().join("personal-home");
3360 std::fs::create_dir_all(&personal_home).expect("personal home");
3361 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &personal_home);
3362 assert_eq!(
3363 resolve_fleet_setup_edit_target(workspace.path()).expect("no selection"),
3364 FleetSetupEditTarget::LegacyProfiles
3365 );
3366
3367 let fleet = codewhale_engine::fleet::store::FleetFile::new("Launch".to_string(), None)
3368 .expect("valid Fleet");
3369 let fleet_path = codewhale_engine::fleet::store::save_fleet(
3370 &fleet,
3371 codewhale_engine::fleet::store::FleetScope::Workspace,
3372 workspace.path(),
3373 )
3374 .expect("save Fleet");
3375 codewhale_engine::fleet::store::set_selected(
3376 "Launch",
3377 codewhale_engine::fleet::store::FleetScope::Workspace,
3378 workspace.path(),
3379 )
3380 .expect("select Fleet");
3381
3382 assert_eq!(
3383 resolve_fleet_setup_edit_target(workspace.path()).expect("selected Fleet"),
3384 FleetSetupEditTarget::SelectedFleet {
3385 name: "Launch".to_string(),
3386 scope: codewhale_engine::fleet::store::FleetScope::Workspace,
3387 }
3388 );
3389
3390 std::fs::remove_file(fleet_path).expect("make selection stale");
3391 let error = resolve_fleet_setup_edit_target(workspace.path())
3392 .expect_err("a stale selection must not open legacy setup");
3393 assert!(error.contains("Legacy profiles were not opened"), "{error}");
3394 }
3395
3396 fn key(code: KeyCode) -> KeyEvent {
3397 KeyEvent::new(code, KeyModifiers::NONE)
3398 }
3399
3400 /// A hermetic personal profile dir shared by the fixture snapshot, so no
3401 /// test reads the developer's real `$CODEWHALE_HOME/agents`.
3402 fn test_personal_dir() -> PathBuf {
3403 codewhale_engine::fleet::profile::personal_agent_profile_dir()
3404 .expect("hermetic personal profile directory")
3405 }
3406
3407 fn sample_draft() -> Box<codewhale_engine::fleet::profile::FleetProfileDraft> {
3408 let codewhale_engine::fleet::profile::UntrustedProfileParse::Drafted(draft) =
3409 codewhale_engine::fleet::profile::FleetProfileDraft::from_untrusted_json(
3410 r#"{"id":"reviewer","role_hint":"reviewer","description":"Reviews diffs.","instructions":"Read. Report. Stop."}"#,
3411 )
3412 else {
3413 panic!("sample draft should parse");
3414 };
3415 draft
3416 }
3417
3418 /// #5038: the Model step's detail pane carries capability badges for
3419 /// known catalog models and honestly omits them for unknown models, so
3420 /// stale/absent data never blocks selection.
3421 #[test]
3422 fn model_step_detail_shows_capability_badges_for_known_models_only() {
3423 let mut snap = snapshot();
3424 snap.available_models.push((
3425 "deepseek".to_string(),
3426 "totally-made-up-model-xyz".to_string(),
3427 codewhale_engine::provider_readiness::ResolvedProviderReadiness::SavedUnchecked,
3428 ));
3429 let view = FleetSetupView::from_snapshot(snap);
3430
3431 let known = view
3432 .model_choices
3433 .iter()
3434 .find(|choice| choice.label == "deepseek-v4-pro")
3435 .expect("known catalog model row");
3436 assert!(
3437 known.description.contains("Capabilities:"),
3438 "{}",
3439 known.description
3440 );
3441 assert!(
3442 known.description.contains("1.05M ctx"),
3443 "{}",
3444 known.description
3445 );
3446 assert!(
3447 known.description.contains("catalog"),
3448 "catalog-backed rows must name catalog provenance: {}",
3449 known.description
3450 );
3451
3452 let unknown = view.model_choices.last().expect("appended unknown row");
3453 assert_eq!(unknown.label, "totally-made-up-model-xyz");
3454 assert!(
3455 !unknown.description.contains("Capabilities:"),
3456 "{}",
3457 unknown.description
3458 );
3459 // The unknown row stays selectable; absence of data is not a block.
3460 assert_eq!(
3461 view.model_row_states.last(),
3462 Some(&FleetModelRowState::Ready)
3463 );
3464 }
3465
3466 #[test]
3467 fn provider_display_label_preserves_case_colliding_custom_ids() {
3468 assert_eq!(provider_display_label("deepseek"), "DeepSeek");
3469 assert_eq!(provider_display_label("CUSTOM"), "CUSTOM");
3470 assert_eq!(provider_display_label("OPENAI"), "OPENAI");
3471 }
3472
3473 fn to_review(view: &mut FleetSetupView) {
3474 view.handle_key(key(KeyCode::Enter)); // Role -> Model
3475 view.handle_key(key(KeyCode::Enter)); // Model -> Destination
3476 assert_eq!(view.step, Step::Destination);
3477 view.handle_key(key(KeyCode::Enter)); // Destination (Personal) -> Review
3478 assert_eq!(view.step, Step::Review);
3479 }
3480
3481 /// Rendered text with all whitespace and box borders removed, so a phrase
3482 /// or path that wrapped across rows (temp-dir paths vary in length per
3483 /// platform and CI runner) still compares as one token.
3484 fn squashed(text: &str) -> String {
3485 text.chars()
3486 .filter(|c| !c.is_whitespace() && !matches!(c, '│' | '┃' | '┆' | '┊' | '|'))
3487 .collect()
3488 }
3489
3490 fn contains_wrapped(text: &str, needle: &str) -> bool {
3491 squashed(text).contains(&squashed(needle))
3492 }
3493
3494 fn rendered_text(view: &FleetSetupView, w: u16, h: u16) -> String {
3495 let area = Rect::new(0, 0, w, h);
3496 let mut buf = Buffer::empty(area);
3497 view.render(area, &mut buf);
3498 (0..h)
3499 .map(|y| {
3500 (0..w)
3501 .map(|x| buf[(x, y)].symbol().to_string())
3502 .collect::<String>()
3503 })
3504 .collect::<Vec<_>>()
3505 .join("\n")
3506 }
3507
3508 #[test]
3509 fn model_step_context_follows_the_ui_locale() {
3510 let mut view = FleetSetupView::from_snapshot(FleetSetupSnapshot {
3511 locale: codewhale_localization::Locale::Fr,
3512 ..snapshot()
3513 });
3514 view.step = Step::Model;
3515 let text = rendered_text(&view, 120, 40);
3516 assert!(!text.contains("Type / to filter"), "{text}");
3517 assert!(
3518 !text.contains("This member uses your current model"),
3519 "{text}"
3520 );
3521 assert!(!text.contains("Same model as now"), "{text}");
3522 assert!(text.contains("Tapez /"), "{text}");
3523 }
3524
3525 fn workspace_snapshot(workspace: &Path) -> FleetSetupSnapshot {
3526 FleetSetupSnapshot {
3527 workspace: workspace.to_path_buf(),
3528 ..snapshot()
3529 }
3530 }
3531
3532 // ------------------------------------------------------------------
3533 // Save-scope redesign: destination step, review actions, no silent writes.
3534 // ------------------------------------------------------------------
3535
3536 #[test]
3537 fn destination_step_sits_between_model_and_review_and_names_the_exact_file() {
3538 let temp = tempfile::tempdir().expect("temp workspace");
3539 let mut view = FleetSetupView::from_snapshot(workspace_snapshot(temp.path()));
3540 view.handle_key(key(KeyCode::Down)); // explore
3541 view.handle_key(key(KeyCode::Enter)); // -> Model
3542 view.handle_key(key(KeyCode::Enter)); // inherit -> Destination
3543 assert_eq!(view.step, Step::Destination);
3544 assert!(
3545 !view.scope_decided,
3546 "nothing is decided until the user picks"
3547 );
3548 let text = rendered_text(&view, 120, 32);
3549 assert!(text.contains("Where should this profile live?"), "{text}");
3550 assert!(text.contains("This project"), "{text}");
3551 assert!(text.contains("Personal"), "{text}");
3552 assert!(text.contains("Step 3/4"), "{text}");
3553 // The highlighted (Personal) row shows its resolved file.
3554 let personal = test_personal_dir().join("explore.toml");
3555 assert!(
3556 text.contains("File:") && text.contains("agents"),
3557 "resolved file must be visible: {text}"
3558 );
3559 assert_eq!(view.destinations.as_ref().unwrap()[1].target, personal);
3560 // Up -> This project shows the workspace file.
3561 view.handle_key(key(KeyCode::Up));
3562 let text = rendered_text(&view, 120, 32);
3563 let project = temp.path().join(PROFILE_DIR).join("explore.toml");
3564 assert!(!text.contains("Will replace"), "{text}");
3565 assert_eq!(view.destinations.as_ref().unwrap()[0].target, project);
3566 }
3567
3568 #[test]
3569 fn header_chip_says_where_it_saves_on_every_step_once_decided() {
3570 let temp = tempfile::tempdir().expect("temp workspace");
3571 let mut view = FleetSetupView::from_snapshot(workspace_snapshot(temp.path()));
3572 let text = rendered_text(&view, 120, 32);
3573 assert!(text.contains("Saves to: choose in step 3"), "{text}");
3574 view.handle_key(key(KeyCode::Enter));
3575 view.handle_key(key(KeyCode::Enter));
3576 view.handle_key(key(KeyCode::Up)); // This project
3577 view.handle_key(key(KeyCode::Enter)); // -> Review
3578 assert_eq!(view.step, Step::Review);
3579 assert!(view.scope_decided);
3580 assert_eq!(view.profile_scope, FleetProfileScope::Project);
3581 let text = rendered_text(&view, 120, 32);
3582 assert!(text.contains("Saves to: This project"), "{text}");
3583 assert!(text.contains("Save to this project"), "{text}");
3584 // Going back keeps the decided destination visible while revising.
3585 view.handle_key(key(KeyCode::Esc)); // -> Destination
3586 view.handle_key(key(KeyCode::Esc)); // -> Model
3587 assert_eq!(view.step, Step::Model);
3588 let text = rendered_text(&view, 120, 32);
3589 assert!(text.contains("Saves to: This project"), "{text}");
3590 }
3591
3592 #[test]
3593 fn switching_destination_preserves_role_model_and_thinking() {
3594 let temp = tempfile::tempdir().expect("temp workspace");
3595 let mut view = FleetSetupView::from_snapshot(workspace_snapshot(temp.path()));
3596 view.handle_key(key(KeyCode::Down));
3597 view.handle_key(key(KeyCode::Down)); // builder
3598 view.handle_key(key(KeyCode::Enter));
3599 view.handle_key(key(KeyCode::Down)); // deepseek-v4-pro
3600 view.handle_key(key(KeyCode::Enter)); // -> Destination
3601 view.handle_key(key(KeyCode::Up)); // This project
3602 view.handle_key(key(KeyCode::Enter)); // -> Review
3603 view.handle_key(key(KeyCode::Char('t'))); // thinking: off
3604 let role = view.selected_role();
3605 let route = view.selected_route();
3606 let thinking = view.thinking_idx;
3607 assert_eq!(view.profile_scope, FleetProfileScope::Project);
3608 // Change destination via the focused control, pick Personal.
3609 view.handle_key(key(KeyCode::Tab));
3610 assert_eq!(view.review_focus, ReviewFocus::ChangeDestination);
3611 assert_eq!(
3612 view.profile_scope,
3613 FleetProfileScope::Project,
3614 "Tab never changes scope"
3615 );
3616 view.handle_key(key(KeyCode::Enter));
3617 assert_eq!(view.step, Step::Destination);
3618 view.handle_key(key(KeyCode::Down));
3619 view.handle_key(key(KeyCode::Char(' ')));
3620 assert_eq!(view.step, Step::Review);
3621 assert_eq!(view.profile_scope, FleetProfileScope::Personal);
3622 assert_eq!(view.selected_role(), role);
3623 assert_eq!(view.selected_route(), route);
3624 assert_eq!(view.thinking_idx, thinking);
3625 let text = rendered_text(&view, 120, 32);
3626 assert!(text.contains("Save as Personal profile"), "{text}");
3627 }
3628
3629 #[test]
3630 fn existing_target_is_announced_and_needs_a_second_enter_to_replace() {
3631 let temp = tempfile::tempdir().expect("temp workspace");
3632 let dir = temp.path().join(PROFILE_DIR);
3633 std::fs::create_dir_all(&dir).expect("dir");
3634 std::fs::write(dir.join("manager.toml"), "id = \"manager\"\n").expect("existing");
3635 let mut view = FleetSetupView::from_snapshot(workspace_snapshot(temp.path()));
3636 view.handle_key(key(KeyCode::Enter)); // manager
3637 view.handle_key(key(KeyCode::Enter)); // inherit -> Destination
3638 view.handle_key(key(KeyCode::Up)); // This project
3639 let text = rendered_text(&view, 120, 32);
3640 assert!(
3641 contains_wrapped(&text, "Will replace the existing file"),
3642 "{text}"
3643 );
3644 view.handle_key(key(KeyCode::Enter)); // -> Review
3645 let text = rendered_text(&view, 120, 32);
3646 assert!(contains_wrapped(&text, "Replace in this project"), "{text}");
3647 assert!(
3648 contains_wrapped(&text, "Will replace the existing file"),
3649 "{text}"
3650 );
3651 // First Enter arms; nothing is emitted.
3652 let action = view.handle_key(key(KeyCode::Enter));
3653 assert!(
3654 matches!(action, ViewAction::None),
3655 "first Enter must not save"
3656 );
3657 assert!(view.replace_armed);
3658 let text = rendered_text(&view, 120, 32);
3659 assert!(
3660 text.contains("Press Enter again to replace manager.toml"),
3661 "{text}"
3662 );
3663 // Moving focus disarms.
3664 view.handle_key(key(KeyCode::Tab));
3665 assert!(!view.replace_armed);
3666 view.handle_key(key(KeyCode::BackTab));
3667 view.handle_key(key(KeyCode::Enter)); // arm again
3668 let action = view.handle_key(key(KeyCode::Enter)); // confirm
3669 let ViewAction::Emit(ViewEvent::FleetProfileDraftCommitRequested { draft, scope, .. }) =
3670 action
3671 else {
3672 panic!("second Enter saves");
3673 };
3674 assert_eq!(scope, FleetProfileScope::Project);
3675 assert_eq!(draft.id, "manager");
3676 }
3677
3678 #[test]
3679 fn project_destination_is_disabled_with_a_reason_and_never_falls_back() {
3680 let temp = tempfile::tempdir().expect("temp workspace");
3681 let mut view = FleetSetupView::from_snapshot(FleetSetupSnapshot {
3682 project_profiles_enabled: false,
3683 ..workspace_snapshot(temp.path())
3684 });
3685 view.handle_key(key(KeyCode::Enter));
3686 view.handle_key(key(KeyCode::Enter)); // -> Destination
3687 view.handle_key(key(KeyCode::Up)); // This project (disabled)
3688 let text = rendered_text(&view, 120, 32);
3689 assert!(
3690 text.contains("Not available: project profiles are disabled"),
3691 "{text}"
3692 );
3693 let action = view.handle_key(key(KeyCode::Enter));
3694 assert!(matches!(action, ViewAction::None));
3695 assert_eq!(
3696 view.step,
3697 Step::Destination,
3698 "disabled destination does not advance"
3699 );
3700 assert!(!view.scope_decided);
3701 assert_eq!(
3702 view.profile_scope,
3703 FleetProfileScope::Personal,
3704 "no silent fallback either way: the scope is untouched"
3705 );
3706 // Personal still works.
3707 view.handle_key(key(KeyCode::Down));
3708 view.handle_key(key(KeyCode::Enter));
3709 assert_eq!(view.step, Step::Review);
3710 assert_eq!(view.profile_scope, FleetProfileScope::Personal);
3711 }
3712
3713 #[test]
3714 fn precedence_consequences_are_stated_for_both_destinations() {
3715 let temp = tempfile::tempdir().expect("temp workspace");
3716 let project_source = temp.path().join(PROFILE_DIR).join("explore.toml");
3717 let mut snap = workspace_snapshot(temp.path());
3718 snap.roster_members.retain(|(id, _)| id != "explore");
3719 snap.roster_members
3720 .push(("explore".to_string(), "project".to_string()));
3721 snap.roster_details.push(RosterMemberDetail {
3722 id: "explore".to_string(),
3723 scope: FleetProfileScope::Project,
3724 source: project_source,
3725 provider: Some("deepseek".to_string()),
3726 model: Some("deepseek-v4-flash".to_string()),
3727 reasoning_effort: None,
3728 });
3729 let mut view = FleetSetupView::from_snapshot(snap);
3730 view.handle_key(key(KeyCode::Down)); // explore
3731 view.handle_key(key(KeyCode::Enter));
3732 view.handle_key(key(KeyCode::Enter)); // -> Destination (Personal highlighted)
3733 let text = rendered_text(&view, 120, 32);
3734 assert!(text.contains("already has a"), "{text}");
3735 view.handle_key(key(KeyCode::Up)); // This project
3736 let text = rendered_text(&view, 120, 32);
3737 assert!(!text.contains("already has a"), "{text}");
3738 assert!(text.contains("Replaces the project"), "{text}");
3739 }
3740
3741 #[test]
3742 fn reopening_a_saved_member_preloads_its_scope_and_route() {
3743 let temp = tempfile::tempdir().expect("temp workspace");
3744 let mut snap = workspace_snapshot(temp.path());
3745 snap.roster_members.retain(|(id, _)| id != "scout");
3746 snap.roster_members
3747 .push(("scout".to_string(), "project".to_string()));
3748 snap.roster_details.push(RosterMemberDetail {
3749 id: "scout".to_string(),
3750 scope: FleetProfileScope::Project,
3751 source: temp.path().join(PROFILE_DIR).join("scout.toml"),
3752 provider: Some("deepseek".to_string()),
3753 model: Some("deepseek-v4-flash".to_string()),
3754 reasoning_effort: Some("high".to_string()),
3755 });
3756 let view = FleetSetupView::from_snapshot_for_role(snap, "scout");
3757 assert_eq!(view.step, Step::Model);
3758 assert!(view.scope_decided);
3759 assert_eq!(view.profile_scope, FleetProfileScope::Project);
3760 assert_eq!(
3761 view.selected_route(),
3762 Some(("deepseek".to_string(), "deepseek-v4-flash".to_string()))
3763 );
3764 assert_eq!(view.selected_reasoning_effort().as_deref(), Some("high"));
3765 let text = rendered_text(&view, 120, 32);
3766 assert!(text.contains("Saves to: This project"), "{text}");
3767 }
3768
3769 #[test]
3770 fn blocked_model_row_explains_why_enter_did_nothing() {
3771 let mut snap = snapshot();
3772 snap.available_models = vec![(
3773 "xai".to_string(),
3774 "grok-4.5".to_string(),
3775 codewhale_engine::provider_readiness::ResolvedProviderReadiness::MissingKey,
3776 )];
3777 let mut view = FleetSetupView::from_snapshot(snap);
3778 view.handle_key(key(KeyCode::Enter)); // -> Model
3779 view.model_idx = 1;
3780 view.handle_key(key(KeyCode::Enter));
3781 assert_eq!(view.step, Step::Model);
3782 assert!(
3783 view.notice
3784 .as_deref()
3785 .is_some_and(|n| n.contains("Not selectable"))
3786 );
3787 let text = rendered_text(&view, 120, 32);
3788 assert!(text.contains("Not selectable"), "{text}");
3789 view.handle_key(key(KeyCode::Down));
3790 assert!(view.notice.is_none(), "navigation clears the notice");
3791 }
3792
3793 #[test]
3794 fn q_only_cancels_from_the_first_step_and_esc_is_back_elsewhere() {
3795 let mut view = FleetSetupView::from_snapshot(snapshot());
3796 view.handle_key(key(KeyCode::Enter)); // -> Model
3797 assert!(matches!(
3798 view.handle_key(key(KeyCode::Char('q'))),
3799 ViewAction::None
3800 ));
3801 assert_eq!(view.step, Step::Model);
3802 assert!(matches!(
3803 view.handle_key(key(KeyCode::Esc)),
3804 ViewAction::None
3805 ));
3806 assert_eq!(view.step, Step::Role);
3807 assert!(matches!(
3808 view.handle_key(key(KeyCode::Char('q'))),
3809 ViewAction::Close
3810 ));
3811 let hints = view.footer_hints();
3812 assert!(hints.iter().any(|h| h.key == "Esc" && h.label == "cancel"));
3813 }
3814
3815 #[test]
3816 fn destination_and_review_stay_readable_at_60x16_80x24_and_120x32() {
3817 let temp = tempfile::tempdir().expect("temp workspace");
3818 for (w, h) in [(60u16, 16u16), (80, 24), (120, 32)] {
3819 let mut view = FleetSetupView::from_snapshot(workspace_snapshot(temp.path()));
3820 view.handle_key(key(KeyCode::Enter));
3821 view.handle_key(key(KeyCode::Enter)); // -> Destination
3822 let text = rendered_text(&view, w, h);
3823 assert!(text.contains("This project"), "{w}x{h}: {text}");
3824 assert!(text.contains("Personal"), "{w}x{h}: {text}");
3825 assert!(text.contains("File:"), "{w}x{h}: {text}");
3826 assert!(text.contains("Saves to:"), "{w}x{h}: {text}");
3827 view.handle_key(key(KeyCode::Up));
3828 view.handle_key(key(KeyCode::Enter)); // -> Review
3829 let text = rendered_text(&view, w, h);
3830 assert!(text.contains("Save to this project"), "{w}x{h}: {text}");
3831 assert!(text.contains("Saves to: This project"), "{w}x{h}: {text}");
3832 for line in text.lines() {
3833 assert!(
3834 unicode_width::UnicodeWidthStr::width(line) <= usize::from(w),
3835 "{w}x{h}: overflow: {line}"
3836 );
3837 }
3838 }
3839 }
3840
3841 fn open_composition(view: &mut FleetSetupView) {
3842 view.handle_key(key(KeyCode::Enter)); // Role -> Model
3843 assert_eq!(view.step, Step::Model);
3844 view.handle_key(key(KeyCode::Char('c')));
3845 assert_eq!(view.step, Step::Composition);
3846 }
3847
3848 #[test]
3849 fn composition_is_deterministic_unratified_and_pool_bounded() {
3850 let first = FleetSetupView::from_snapshot(snapshot());
3851 let second = FleetSetupView::from_snapshot(snapshot());
3852 let first = first.composition.expect("configured pool advisory");
3853 let second = second.composition.expect("configured pool advisory");
3854
3855 assert_eq!(first.proposal, second.proposal);
3856 assert_eq!(first.proposal.ratification, RatificationState::Unratified);
3857 assert!(!first.proposal.is_actionable());
3858 assert_eq!(
3859 first.request.pool_keys(),
3860 vec![
3861 "deepseek/deepseek-v4-flash".to_string(),
3862 "deepseek/deepseek-v4-pro".to_string(),
3863 ]
3864 );
3865 for suggestion in &first.proposal.suggestions {
3866 assert!(
3867 first
3868 .request
3869 .pool_contains(&suggestion.provider, &suggestion.model),
3870 "{suggestion:?} escaped the configured pool"
3871 );
3872 }
3873
3874 let rendered = render_through_stack(
3875 || {
3876 let mut view = FleetSetupView::from_snapshot(snapshot());
3877 open_composition(&mut view);
3878 view
3879 },
3880 120,
3881 40,
3882 )
3883 .join("\n");
3884 assert!(rendered.contains("UNRATIFIED"), "{rendered}");
3885 assert!(rendered.contains("Suggestion only"), "{rendered}");
3886 assert!(rendered.contains("a/Enter accept"), "{rendered}");
3887 assert!(rendered.contains("e edit"), "{rendered}");
3888 assert!(rendered.contains("r reject"), "{rendered}");
3889 }
3890
3891 #[test]
3892 fn composition_accept_edit_and_reject_keep_the_existing_save_boundary() {
3893 let mut accepted = FleetSetupView::from_snapshot(snapshot());
3894 open_composition(&mut accepted);
3895 let expected = accepted
3896 .validated_composition_route()
3897 .expect("selected role suggestion");
3898 assert!(matches!(
3899 accepted.handle_key(key(KeyCode::Char('a'))),
3900 ViewAction::None
3901 ));
3902 assert_eq!(accepted.step, Step::Destination);
3903 accepted.handle_key(key(KeyCode::Enter)); // Destination -> Review
3904 assert_eq!(accepted.step, Step::Review);
3905 assert_eq!(accepted.composition_decision, CompositionDecision::Accepted);
3906 assert_eq!(accepted.selected_route().as_ref(), Some(&expected));
3907 let ViewAction::Emit(ViewEvent::FleetProfileDraftCommitRequested { draft, .. }) =
3908 accepted.handle_key(key(KeyCode::Enter))
3909 else {
3910 panic!("only the existing review save path may persist an accepted suggestion");
3911 };
3912 assert_eq!(
3913 (draft.provider.as_deref(), draft.model.as_deref()),
3914 (Some(expected.0.as_str()), Some(expected.1.as_str()))
3915 );
3916
3917 let mut edited = FleetSetupView::from_snapshot(snapshot());
3918 open_composition(&mut edited);
3919 let suggested = edited
3920 .validated_composition_route()
3921 .expect("selected role suggestion");
3922 assert!(matches!(
3923 edited.handle_key(key(KeyCode::Char('e'))),
3924 ViewAction::None
3925 ));
3926 assert_eq!(edited.step, Step::Model);
3927 assert_eq!(edited.composition_decision, CompositionDecision::Edited);
3928 assert_eq!(edited.selected_route().as_ref(), Some(&suggested));
3929
3930 let mut rejected = FleetSetupView::from_snapshot(snapshot());
3931 open_composition(&mut rejected);
3932 assert!(rejected.selected_route().is_none());
3933 assert!(matches!(
3934 rejected.handle_key(key(KeyCode::Char('r'))),
3935 ViewAction::None
3936 ));
3937 assert_eq!(rejected.step, Step::Model);
3938 assert_eq!(rejected.composition_decision, CompositionDecision::Rejected);
3939 assert!(rejected.selected_route().is_none());
3940 }
3941
3942 #[test]
3943 fn composition_acceptance_revalidates_and_rejects_an_out_of_pool_route() {
3944 let mut view = FleetSetupView::from_snapshot(snapshot());
3945 open_composition(&mut view);
3946 let advisory = view.composition.as_mut().expect("advisory");
3947 let manager = advisory
3948 .proposal
3949 .suggestions
3950 .iter_mut()
3951 .find(|suggestion| suggestion.role == "manager")
3952 .expect("manager suggestion");
3953 manager.provider = "unconfigured".to_string();
3954 manager.model = "outside-pool".to_string();
3955 assert!(matches!(
3956 advisory.validated_route_for_role("manager"),
3957 Err(CompositionError::ModelOutsidePool { .. })
3958 ));
3959
3960 assert!(matches!(
3961 view.handle_key(key(KeyCode::Char('a'))),
3962 ViewAction::None
3963 ));
3964 assert_eq!(view.step, Step::Composition);
3965 assert_eq!(view.composition_decision, CompositionDecision::Pending);
3966 assert!(view.selected_route().is_none());
3967 }
3968
3969 #[test]
3970 fn composition_does_not_suggest_a_blocked_configured_route() {
3971 let mut snap = snapshot();
3972 snap.available_models.push((
3973 "anthropic".to_string(),
3974 "blocked-model".to_string(),
3975 codewhale_engine::provider_readiness::ResolvedProviderReadiness::SavedLastCheckFailed {
3976 category: codewhale_error_taxonomy::ErrorCategory::Authentication,
3977 message: "auth failed".to_string(),
3978 },
3979 ));
3980 let view = FleetSetupView::from_snapshot(snap);
3981 let advisory = view.composition.expect("ready pool still composes");
3982 assert!(!advisory.request.pool_contains("anthropic", "blocked-model"));
3983 assert!(
3984 advisory
3985 .proposal
3986 .suggestions
3987 .iter()
3988 .all(|suggestion| suggestion.model != "blocked-model")
3989 );
3990 }
3991
3992 #[test]
3993 fn review_step_m_requests_model_draft_with_current_answers() {
3994 let mut view = FleetSetupView::from_snapshot(snapshot());
3995 to_review(&mut view);
3996
3997 let action = view.handle_key(key(KeyCode::Char('m')));
3998 let ViewAction::Emit(ViewEvent::FleetProfileModelDraftRequested {
3999 role,
4000 model,
4001 provider,
4002 reasoning_effort,
4003 locale,
4004 }) = action
4005 else {
4006 panic!("expected model draft request");
4007 };
4008 assert!(!role.is_empty());
4009 assert!(!model.is_empty());
4010 // Default selection is `inherit` (model_idx 0), which carries no
4011 // concrete provider route.
4012 assert_eq!(provider, None);
4013 assert_eq!(reasoning_effort, None);
4014 assert_eq!(locale, codewhale_localization::Locale::En);
4015 }
4016
4017 #[test]
4018 fn m_redraft_preserves_a_cross_provider_pick_regression_4093() {
4019 // #4093 BLOCKER 2 regression: a cross-provider route pick followed by an
4020 // `m` model-assisted redraft must STILL persist the picked provider. A
4021 // model draft comes from `from_untrusted_json`, which hard-sets
4022 // `provider: None` (and can echo any model). Without re-injection the
4023 // ratified profile would carry `model` with no `provider` — the exact
4024 // ambiguous, provider-scoped profile #4093 removes.
4025 //
4026 // The active/session provider is DeepSeek; the picked route is a
4027 // GLM model on Zai — a genuinely different provider than the parent.
4028 let mut snap = snapshot();
4029 snap.provider = "DeepSeek".to_string();
4030 snap.model = "deepseek-v4-pro".to_string();
4031 snap.available_models = vec![(
4032 "zai".to_string(),
4033 "glm-5.2".to_string(),
4034 codewhale_engine::provider_readiness::ResolvedProviderReadiness::SavedUnchecked,
4035 )];
4036 let mut view = FleetSetupView::from_snapshot(snap);
4037
4038 // Role step: keep the first role. Model step: inherit(0), then the one
4039 // cross-provider row (1) -> pick it. Then advance to Review.
4040 view.handle_key(key(KeyCode::Enter)); // Role -> Model
4041 view.handle_key(key(KeyCode::Down)); // -> the zai/glm-5.2 row
4042 assert_eq!(
4043 view.selected_route(),
4044 Some(("zai".to_string(), "glm-5.2".to_string()))
4045 );
4046 view.handle_key(key(KeyCode::Enter)); // Model -> Destination
4047 view.handle_key(key(KeyCode::Enter)); // Destination -> Review
4048 assert_eq!(view.step, Step::Review);
4049 while view.selected_reasoning_effort().as_deref() != Some("max") {
4050 view.handle_key(key(KeyCode::Char('t')));
4051 }
4052
4053 // `m` requests a draft and carries the picked cross-provider route.
4054 let action = view.handle_key(key(KeyCode::Char('m')));
4055 let ViewAction::Emit(ViewEvent::FleetProfileModelDraftRequested {
4056 model,
4057 provider,
4058 reasoning_effort,
4059 ..
4060 }) = action
4061 else {
4062 panic!("expected model draft request");
4063 };
4064 assert_eq!(model, "glm-5.2");
4065 assert_eq!(provider.as_deref(), Some("zai"));
4066 assert_eq!(reasoning_effort.as_deref(), Some("max"));
4067
4068 // The host reconstructs the picked route from the event exactly as
4069 // `handle_fleet_profile_model_draft` does, and carries it to
4070 // `install_model_draft`, which refuses it if the answers changed.
4071 let picked_route = provider.map(|provider| (provider, model.clone()));
4072
4073 // The model returns a draft that (as always) has provider: None — the
4074 // untrusted gate strips any provider a model tries to smuggle.
4075 let drafted = sample_draft();
4076 assert_eq!(drafted.provider, None);
4077
4078 // Installing it re-injects the picked route, so the ratified draft keeps
4079 // BOTH the provider and the model the user actually chose, plus the
4080 // captured thinking tier.
4081 let (_title, content) = view
4082 .install_model_draft(
4083 drafted,
4084 "GLM-5.2".to_string(),
4085 picked_route,
4086 reasoning_effort,
4087 )
4088 .expect("answers unchanged since `m`");
4089 let ratified = view.model_draft.as_deref().expect("draft installed");
4090 assert_eq!(ratified.provider.as_deref(), Some("zai"));
4091 assert_eq!(ratified.model.as_deref(), Some("glm-5.2"));
4092 assert_eq!(ratified.reasoning_effort.as_deref(), Some("max"));
4093
4094 // The rendered TOML the ratify keypress would persist names the provider
4095 // explicitly — never a provider-scoped ambiguity.
4096 assert!(content.contains("provider = \"zai\""), "{content}");
4097 assert!(content.contains("model = \"glm-5.2\""), "{content}");
4098 assert!(content.contains("reasoning_effort = \"max\""), "{content}");
4099
4100 // And ratifying commits exactly that route.
4101 let action = view.handle_key(key(KeyCode::Char('g')));
4102 let ViewAction::Emit(ViewEvent::FleetProfileDraftCommitRequested { draft, scope, .. }) =
4103 action
4104 else {
4105 panic!("expected ratify commit event");
4106 };
4107 assert_eq!(scope, FleetProfileScope::Personal);
4108 assert_eq!(draft.provider.as_deref(), Some("zai"));
4109 assert_eq!(draft.model.as_deref(), Some("glm-5.2"));
4110 assert_eq!(draft.reasoning_effort.as_deref(), Some("max"));
4111 }
4112
4113 #[test]
4114 fn model_step_filter_with_no_matches_renders_a_hint_instead_of_panicking() {
4115 // #5953: a type-to-filter query that matches nothing left
4116 // `render_choice_step` indexing an empty slice.
4117 let snap = snapshot();
4118 let mut view = FleetSetupView::from_snapshot(snap);
4119 view.handle_key(key(KeyCode::Enter));
4120 view.handle_key(key(KeyCode::Char('/')));
4121 for ch in "minimax ".chars() {
4122 view.handle_key(key(KeyCode::Char(ch)));
4123 }
4124 assert!(view.model_filter_active);
4125 assert_eq!(
4126 view.step_len(),
4127 0,
4128 "the query must match nothing for this test"
4129 );
4130 // Every size must render without panicking; the sizes with a detail
4131 // pane must also explain the empty list.
4132 for (w, h, expect_hint) in [(120u16, 40u16, true), (80, 24, true), (60, 12, false)] {
4133 let area = Rect::new(0, 0, w, h);
4134 let mut buf = Buffer::empty(area);
4135 view.render(area, &mut buf);
4136 let text: String = (0..h)
4137 .map(|y| {
4138 (0..w)
4139 .map(|x| buf[(x, y)].symbol().to_string())
4140 .collect::<String>()
4141 })
4142 .collect::<Vec<_>>()
4143 .join("\n");
4144 if expect_hint {
4145 assert!(
4146 text.contains("No routes match"),
4147 "{w}x{h} must explain the empty list:\n{text}"
4148 );
4149 }
4150 }
4151 // Esc clears the filter and the full catalog comes back.
4152 view.handle_key(key(KeyCode::Esc));
4153 assert!(view.step_len() > 0);
4154 }
4155
4156 #[test]
4157 fn model_step_filter_consumes_paste_while_focused() {
4158 let mut snap = snapshot();
4159 snap.available_models.push((
4160 "openrouter".to_string(),
4161 "z-ai/glm-5-turbo".to_string(),
4162 codewhale_engine::provider_readiness::ResolvedProviderReadiness::SavedUnchecked,
4163 ));
4164 let mut stack = crate::tui::views::ViewStack::new();
4165 stack.push(FleetSetupView::from_snapshot(snap));
4166 assert!(!stack.handle_paste("outside model search"));
4167 stack.handle_key(key(KeyCode::Enter));
4168 assert!(!stack.handle_paste("unfocused model search"));
4169
4170 stack.handle_key(key(KeyCode::Char('/')));
4171 stack.handle_key(key(KeyCode::Char('g')));
4172 assert!(stack.handle_paste("lm\r\n"));
4173
4174 let mut modal = stack.pop().unwrap();
4175 let view = modal.as_any_mut().downcast_mut::<FleetSetupView>().unwrap();
4176 assert_eq!(view.model_query, "glm");
4177 assert_eq!(
4178 view.selected_route(),
4179 Some(("openrouter".to_string(), "z-ai/glm-5-turbo".to_string()))
4180 );
4181 }
4182
4183 #[test]
4184 fn model_step_filter_narrows_large_catalogs_by_provider_and_model() {
4185 let mut snap = snapshot();
4186 // Simulate an OpenRouter-scale catalog: many rows from one provider.
4187 for i in 0..120 {
4188 snap.available_models.push((
4189 "openrouter".to_string(),
4190 format!("vendor/model-{i:03}"),
4191 codewhale_engine::provider_readiness::ResolvedProviderReadiness::SavedUnchecked,
4192 ));
4193 }
4194 snap.available_models.push((
4195 "openrouter".to_string(),
4196 "z-ai/glm-5-turbo".to_string(),
4197 codewhale_engine::provider_readiness::ResolvedProviderReadiness::SavedUnchecked,
4198 ));
4199 let mut view = FleetSetupView::from_snapshot(snap);
4200 // Role → Model.
4201 view.handle_key(key(KeyCode::Enter));
4202 let full_len = view.step_len();
4203 assert!(full_len > 120, "unfiltered shows the whole catalog");
4204
4205 // `/` opens the filter; typing narrows by model id substring.
4206 view.handle_key(key(KeyCode::Char('/')));
4207 for ch in "glm".chars() {
4208 view.handle_key(key(KeyCode::Char(ch)));
4209 }
4210 assert_eq!(view.step_len(), 1, "only the glm row survives the filter");
4211 let route = view.selected_route().expect("filtered selection resolves");
4212 assert_eq!(
4213 route,
4214 ("openrouter".to_string(), "z-ai/glm-5-turbo".to_string())
4215 );
4216
4217 // Provider substring filters too.
4218 view.handle_key(key(KeyCode::Esc));
4219 view.handle_key(key(KeyCode::Char('/')));
4220 for ch in "deepseek".chars() {
4221 view.handle_key(key(KeyCode::Char(ch)));
4222 }
4223 // inherit's route IS the active DeepSeek route, so it matches too.
4224 assert_eq!(
4225 view.step_len(),
4226 3,
4227 "deepseek rows plus the inherit (active deepseek route) match"
4228 );
4229
4230 // Enter keeps the filter but releases the input; Esc in filter clears.
4231 view.handle_key(key(KeyCode::Enter));
4232 assert!(!view.model_filter_active);
4233 assert_eq!(view.step_len(), 3);
4234 view.handle_key(key(KeyCode::Char('/')));
4235 view.handle_key(key(KeyCode::Esc));
4236 assert_eq!(
4237 view.step_len(),
4238 full_len,
4239 "clearing restores the full catalog"
4240 );
4241 }
4242
4243 #[test]
4244 fn review_saves_starter_or_ratifies_installed_model_draft() {
4245 let mut view = FleetSetupView::from_snapshot(snapshot());
4246 to_review(&mut view);
4247
4248 // A structured starter draft is save-ready from the summary.
4249 let action = view.handle_key(key(KeyCode::Char('g')));
4250 let ViewAction::Emit(ViewEvent::FleetProfileDraftCommitRequested { draft, scope, .. }) =
4251 action
4252 else {
4253 panic!("expected starter commit event");
4254 };
4255 assert_eq!(scope, FleetProfileScope::Personal);
4256 assert_eq!(draft.id, "manager");
4257
4258 let mut view = FleetSetupView::from_snapshot(snapshot());
4259 to_review(&mut view);
4260 view.handle_key(key(KeyCode::Char('m')));
4261 let (title, content) = view
4262 .install_model_draft(sample_draft(), "GLM-5.2".to_string(), None, None)
4263 .expect("answers unchanged since `m`");
4264 assert!(title.contains("GLM-5.2"));
4265 assert!(content.contains("id = \"reviewer\""), "{content}");
4266 assert!(content.contains("Nothing is saved until"), "{content}");
4267 assert_eq!(
4268 view.destination_for(view.profile_scope)
4269 .unwrap()
4270 .target
4271 .file_name()
4272 .and_then(|name| name.to_str()),
4273 Some("reviewer.toml")
4274 );
4275
4276 let action = view.handle_key(key(KeyCode::Char('g')));
4277 let ViewAction::Emit(ViewEvent::FleetProfileDraftCommitRequested { draft, scope, .. }) =
4278 action
4279 else {
4280 panic!("expected ratify commit event");
4281 };
4282 assert_eq!(scope, FleetProfileScope::Personal);
4283 assert_eq!(draft.id, "reviewer");
4284 let editor_id = view.editor_id;
4285 assert!(view.profile_commit_matches(editor_id));
4286 assert!(!view.profile_commit_matches(uuid::Uuid::new_v4()));
4287 let preview = view.model_draft_preview.clone();
4288 let expected = view
4289 .destination_for(view.profile_scope)
4290 .unwrap()
4291 .original
4292 .clone();
4293 view.profile_save_failed("The profile changed. Review it again before saving.".into());
4294 assert_eq!(view.step, Step::Review);
4295 assert_eq!(view.model_draft.as_ref().unwrap().id, "reviewer");
4296 assert_eq!(view.model_draft_preview, preview);
4297 assert_eq!(
4298 view.destination_for(view.profile_scope).unwrap().original,
4299 expected
4300 );
4301 assert!(!view.replace_armed);
4302 assert!(rendered_text(&view, 120, 32).contains("The profile changed."));
4303 view.handle_key(key(KeyCode::Left));
4304 assert!(!view.profile_commit_matches(editor_id));
4305 }
4306
4307 #[test]
4308 fn changing_answers_discards_a_stale_draft() {
4309 let mut view = FleetSetupView::from_snapshot(snapshot());
4310 to_review(&mut view);
4311 view.handle_key(key(KeyCode::Char('m')));
4312 assert!(
4313 view.install_model_draft(sample_draft(), "GLM-5.2".to_string(), None, None)
4314 .is_some()
4315 );
4316 assert!(view.model_draft.is_some());
4317
4318 // Back to the role step and change the selection: the draft no
4319 // longer matches the answers and must not survive to ratification.
4320 view.handle_key(key(KeyCode::Left)); // Review -> Destination
4321 view.handle_key(key(KeyCode::Left)); // Destination -> Model
4322 view.handle_key(key(KeyCode::Left)); // Model -> Role
4323 assert_eq!(view.step, Step::Role);
4324 view.handle_key(key(KeyCode::Down));
4325 assert!(view.model_draft.is_none());
4326
4327 to_review(&mut view);
4328 let action = view.handle_key(key(KeyCode::Char('g')));
4329 let ViewAction::Emit(ViewEvent::FleetProfileDraftCommitRequested { draft, .. }) = action
4330 else {
4331 panic!("expected fresh deterministic starter");
4332 };
4333 assert_eq!(draft.id, "explore");
4334 }
4335
4336 /// U09-03: the request generation orders `m` presses but cannot see an
4337 /// answer changed after the last one. A draft that lands after the user
4338 /// changed the thinking tier (or role, or route) mid-flight is refused,
4339 /// never installed onto answers it was not written for.
4340 #[test]
4341 fn late_model_draft_is_refused_after_answers_change_in_flight() {
4342 let mut view = FleetSetupView::from_snapshot(snapshot());
4343 to_review(&mut view);
4344 let ViewAction::Emit(ViewEvent::FleetProfileModelDraftRequested {
4345 reasoning_effort, ..
4346 }) = view.handle_key(key(KeyCode::Char('m')))
4347 else {
4348 panic!("expected model draft request");
4349 };
4350 // While the draft is in flight the user cycles the thinking tier.
4351 view.handle_key(key(KeyCode::Char('t')));
4352 assert!(
4353 view.install_model_draft(
4354 sample_draft(),
4355 "GLM-5.2".to_string(),
4356 None,
4357 reasoning_effort.clone()
4358 )
4359 .is_none()
4360 );
4361 assert!(view.model_draft.is_none());
4362 let action = view.handle_key(key(KeyCode::Char('g')));
4363 let ViewAction::Emit(ViewEvent::FleetProfileDraftCommitRequested { draft, .. }) = action
4364 else {
4365 panic!("expected the deterministic starter for the current answers");
4366 };
4367 assert_eq!(draft.id, "manager");
4368
4369 // A draft nobody requested (no `m`) is refused too.
4370 let mut view = FleetSetupView::from_snapshot(snapshot());
4371 to_review(&mut view);
4372 assert!(
4373 view.install_model_draft(sample_draft(), "GLM-5.2".to_string(), None, None)
4374 .is_none()
4375 );
4376 }
4377
4378 #[test]
4379 fn arrows_move_within_step_and_enter_advances() {
4380 let mut view = FleetSetupView::from_snapshot(snapshot());
4381 assert_eq!(view.step, Step::Role);
4382
4383 view.handle_key(key(KeyCode::Down));
4384 assert_eq!(view.role_idx, 1);
4385
4386 view.handle_key(key(KeyCode::Enter));
4387 assert_eq!(view.step, Step::Model);
4388
4389 view.handle_key(key(KeyCode::Down));
4390 assert_eq!(view.model_idx, 1);
4391
4392 view.handle_key(key(KeyCode::Enter));
4393 assert_eq!(view.step, Step::Destination);
4394 view.handle_key(key(KeyCode::Enter));
4395 assert_eq!(view.step, Step::Review);
4396
4397 // `t` cycles thinking on the review step without an extra wizard screen.
4398 view.handle_key(key(KeyCode::Char('t')));
4399 assert_eq!(view.thinking_idx, 1);
4400
4401 // Left steps back through the wizard.
4402 view.handle_key(key(KeyCode::Left));
4403 assert_eq!(view.step, Step::Destination);
4404 view.handle_key(key(KeyCode::Left));
4405 assert_eq!(view.step, Step::Model);
4406 view.handle_key(key(KeyCode::Left));
4407 assert_eq!(view.step, Step::Role);
4408 }
4409
4410 #[test]
4411 fn roster_role_handoff_starts_at_model_and_can_return_to_role() {
4412 let mut via_left = FleetSetupView::from_snapshot_for_role(snapshot(), "consultant");
4413 assert_eq!(via_left.step, Step::Model);
4414 assert_eq!(via_left.selected_role(), "advisor");
4415 assert!(matches!(
4416 via_left.handle_key(key(KeyCode::Left)),
4417 ViewAction::None
4418 ));
4419 assert_eq!(via_left.step, Step::Role);
4420 assert_eq!(via_left.selected_role(), "advisor");
4421
4422 let mut via_esc = FleetSetupView::from_snapshot_for_role(snapshot(), "reviewer");
4423 assert_eq!(via_esc.step, Step::Model);
4424 assert_eq!(via_esc.selected_role(), "reviewer");
4425 assert!(matches!(
4426 via_esc.handle_key(key(KeyCode::Esc)),
4427 ViewAction::None
4428 ));
4429 assert_eq!(via_esc.step, Step::Role);
4430 assert_eq!(via_esc.selected_role(), "reviewer");
4431
4432 let custom = FleetSetupView::from_snapshot_for_role(snapshot(), "domain-expert");
4433 assert_eq!(custom.step, Step::Model);
4434 assert_eq!(custom.selected_role(), "custom");
4435 }
4436
4437 #[test]
4438 fn esc_steps_back_then_cancels_from_role() {
4439 let mut view = FleetSetupView::from_snapshot(snapshot());
4440 view.handle_key(key(KeyCode::Enter)); // -> Model
4441 let action = view.handle_key(key(KeyCode::Esc));
4442 assert!(matches!(action, ViewAction::None));
4443 assert_eq!(view.step, Step::Role);
4444 let action = view.handle_key(key(KeyCode::Esc));
4445 assert!(matches!(action, ViewAction::Close));
4446 }
4447
4448 #[test]
4449 fn mouse_selects_rows_and_wheel_matches_keyboard_navigation() {
4450 let mut view = FleetSetupView::from_snapshot(snapshot());
4451 let area = Rect::new(0, 0, 120, 40);
4452 let mut buf = Buffer::empty(area);
4453 view.render(area, &mut buf);
4454 let (rect, row) = view.row_hitboxes.borrow()[2];
4455
4456 view.handle_mouse(MouseEvent {
4457 kind: MouseEventKind::Down(MouseButton::Left),
4458 column: rect.x,
4459 row: rect.y,
4460 modifiers: KeyModifiers::NONE,
4461 });
4462 assert_eq!(row, 2);
4463 assert_eq!(view.role_idx, 2);
4464
4465 view.handle_mouse(MouseEvent {
4466 kind: MouseEventKind::ScrollDown,
4467 column: rect.x,
4468 row: rect.y,
4469 modifiers: KeyModifiers::NONE,
4470 });
4471 assert_eq!(view.role_idx, 3);
4472 view.handle_mouse(MouseEvent {
4473 kind: MouseEventKind::ScrollUp,
4474 column: rect.x,
4475 row: rect.y,
4476 modifiers: KeyModifiers::NONE,
4477 });
4478 assert_eq!(view.role_idx, 2);
4479 }
4480
4481 #[test]
4482 fn compact_choice_window_keeps_deep_selection_visible_and_clickable() {
4483 let mut view = FleetSetupView::from_snapshot(snapshot());
4484 view.role_idx = ROLES.len() - 1;
4485 let area = Rect::new(0, 0, 80, 16);
4486 let mut buf = Buffer::empty(area);
4487 view.render(area, &mut buf);
4488 let rendered = (0..area.height)
4489 .map(|y| {
4490 (0..area.width)
4491 .map(|x| buf[(x, y)].symbol())
4492 .collect::<String>()
4493 })
4494 .collect::<Vec<_>>()
4495 .join("\n");
4496
4497 assert!(rendered.contains("▸ custom"), "{rendered}");
4498 assert!(
4499 view.row_hitboxes
4500 .borrow()
4501 .iter()
4502 .any(|(_, idx)| *idx == ROLES.len() - 1),
4503 "selected row needs an aligned mouse hitbox"
4504 );
4505 }
4506
4507 /// #3908: destination facts (exists/is_dir) are computed on the
4508 /// transitions that can change them — never per paint.
4509 #[test]
4510 fn review_destinations_are_cached_on_transitions_not_recomputed_per_paint() {
4511 let mut view = FleetSetupView::from_snapshot(snapshot());
4512 assert!(
4513 view.destinations.is_none(),
4514 "nothing is stat-ed before the user reaches the Destination step"
4515 );
4516
4517 view.advance(); // Role -> Model
4518 view.advance(); // Model -> Destination
4519 assert_eq!(view.step, Step::Destination);
4520 let on_entry = view
4521 .destinations
4522 .clone()
4523 .expect("entering Destination must populate the cached statuses");
4524 view.advance(); // Destination -> Review
4525 assert_eq!(view.step, Step::Review);
4526
4527 // Painting repeatedly must not change the cached value — that is the
4528 // whole point — and must not panic on the cached-read path.
4529 let area = Rect::new(0, 0, 80, 24);
4530 for _ in 0..3 {
4531 let mut buf = Buffer::empty(area);
4532 view.render(area, &mut buf);
4533 }
4534 assert_eq!(view.destinations.as_ref(), Some(&on_entry));
4535 }
4536
4537 #[test]
4538 fn destination_status_reports_new_file_replace_and_disabled_reasons() {
4539 let temp = tempfile::tempdir().expect("temp workspace");
4540 let personal = Ok(temp.path().join("home-agents"));
4541 let fresh = destination_status(
4542 FleetProfileScope::Project,
4543 temp.path(),
4544 &personal,
4545 "reviewer.toml",
4546 true,
4547 codewhale_localization::Locale::En,
4548 );
4549 assert_eq!(
4550 fresh.target,
4551 temp.path().join(PROFILE_DIR).join("reviewer.toml")
4552 );
4553 assert!(!fresh.target_exists);
4554 assert!(fresh.unavailable_reason.is_none());
4555
4556 let profile_dir = temp.path().join(PROFILE_DIR);
4557 std::fs::create_dir_all(&profile_dir).expect("profile dir");
4558 std::fs::write(profile_dir.join("reviewer.toml"), "id = \"reviewer\"\n")
4559 .expect("existing profile");
4560 let existing = destination_status(
4561 FleetProfileScope::Project,
4562 temp.path(),
4563 &personal,
4564 "reviewer.toml",
4565 true,
4566 codewhale_localization::Locale::En,
4567 );
4568 assert!(
4569 existing.target_exists,
4570 "the exact target file is detected, not a dir count"
4571 );
4572
4573 let disabled = destination_status(
4574 FleetProfileScope::Project,
4575 temp.path(),
4576 &personal,
4577 "reviewer.toml",
4578 false,
4579 codewhale_localization::Locale::En,
4580 );
4581 assert!(
4582 disabled
4583 .unavailable_reason
4584 .as_deref()
4585 .is_some_and(|r| r.contains("--no-project-config")),
4586 "{disabled:?}"
4587 );
4588
4589 let missing = destination_status(
4590 FleetProfileScope::Project,
4591 &temp.path().join("does-not-exist"),
4592 &personal,
4593 "reviewer.toml",
4594 true,
4595 codewhale_localization::Locale::En,
4596 );
4597 assert!(missing.unavailable_reason.is_some(), "{missing:?}");
4598 }
4599
4600 #[test]
4601 fn one_enter_from_review_saves_starter_profile_for_selection() {
4602 let mut view = FleetSetupView::from_snapshot(snapshot());
4603 // Role: manager(0) scout(1) builder(2) -> builder.
4604 view.handle_key(key(KeyCode::Down));
4605 view.handle_key(key(KeyCode::Down));
4606 view.handle_key(key(KeyCode::Enter)); // -> Model
4607 // Model: inherit(0) deepseek-v4-pro(1) -> deepseek-v4-pro.
4608 view.handle_key(key(KeyCode::Down));
4609 view.handle_key(key(KeyCode::Enter)); // Model -> Destination
4610 view.handle_key(key(KeyCode::Enter)); // Destination -> Review
4611 assert_eq!(view.step, Step::Review);
4612 while view.selected_reasoning_effort().as_deref() != Some("max") {
4613 view.handle_key(key(KeyCode::Char('t')));
4614 }
4615
4616 // The Review summary is already the structured confirmation surface;
4617 // one Enter saves the deterministic starter without another state.
4618 let action = view.handle_key(key(KeyCode::Enter));
4619 let ViewAction::Emit(ViewEvent::FleetProfileDraftCommitRequested { draft, scope, .. }) =
4620 action
4621 else {
4622 panic!("expected one-Enter starter save");
4623 };
4624 let content = draft.render_toml();
4625 assert!(content.contains("id = \"implement\""));
4626 assert!(content.contains("role_hint = \"implement\""));
4627 assert!(content.contains("model = \"deepseek-v4-pro\""));
4628 assert!(content.contains("reasoning_effort = \"max\""));
4629 // A concrete cross-provider route pin names its own provider
4630 // explicitly (#4093) — the saved profile must not be ambiguously
4631 // scoped to whatever provider happens to be active at launch time.
4632 assert!(content.contains("provider = \"deepseek\""), "{content}");
4633 for forbidden in ["base_url", "api_key"] {
4634 assert!(
4635 !content.contains(forbidden),
4636 "starter profile must not carry {forbidden}: {content}"
4637 );
4638 }
4639
4640 assert_eq!(scope, FleetProfileScope::Personal);
4641 assert_eq!(draft.id, "implement");
4642 assert_eq!(draft.role_hint, "implement");
4643 assert_eq!(draft.model.as_deref(), Some("deepseek-v4-pro"));
4644 assert_eq!(draft.provider.as_deref(), Some("deepseek"));
4645 assert_eq!(draft.reasoning_effort.as_deref(), Some("max"));
4646 }
4647
4648 #[test]
4649 fn review_defaults_to_personal_and_can_switch_to_project() {
4650 let temp = tempfile::tempdir().expect("temp workspace");
4651 let mut view = FleetSetupView::from_snapshot(workspace_snapshot(temp.path()));
4652 to_review(&mut view);
4653
4654 assert_eq!(view.profile_scope, FleetProfileScope::Personal);
4655 // `s` is a secondary accelerator back to the Destination step; the
4656 // destination itself is chosen with a focused control, never toggled
4657 // silently.
4658 view.handle_key(key(KeyCode::Char('s')));
4659 assert_eq!(view.step, Step::Destination);
4660 assert_eq!(
4661 view.profile_scope,
4662 FleetProfileScope::Personal,
4663 "s alone changes nothing"
4664 );
4665 view.handle_key(key(KeyCode::Up)); // This project
4666 view.handle_key(key(KeyCode::Enter));
4667 assert_eq!(view.step, Step::Review);
4668 assert_eq!(view.profile_scope, FleetProfileScope::Project);
4669
4670 let action = view.handle_key(key(KeyCode::Enter));
4671 let ViewAction::Emit(ViewEvent::FleetProfileDraftCommitRequested { draft, scope, .. }) =
4672 action
4673 else {
4674 panic!("expected project profile save event");
4675 };
4676 assert_eq!(scope, FleetProfileScope::Project);
4677 let rendered = draft.render_toml();
4678 assert!(rendered.contains("id = \"manager\""), "{rendered}");
4679 }
4680
4681 #[test]
4682 fn inherit_selection_starter_draft_carries_no_provider() {
4683 // `inherit` (no concrete route pin) must never carry a provider —
4684 // there's no explicit route to name (#4093).
4685 let mut view = FleetSetupView::from_snapshot(snapshot());
4686 to_review(&mut view);
4687 let action = view.handle_key(key(KeyCode::Enter));
4688 let ViewAction::Emit(ViewEvent::FleetProfileDraftCommitRequested { draft, .. }) = action
4689 else {
4690 panic!("expected inherit starter save");
4691 };
4692 assert_eq!(draft.model, None);
4693 assert_eq!(draft.provider, None);
4694 assert_eq!(draft.reasoning_effort, None);
4695 let content = draft.render_toml();
4696 assert!(!content.contains("provider"), "{content}");
4697 assert!(!content.contains("reasoning_effort"), "{content}");
4698 }
4699
4700 #[test]
4701 fn role_and_review_steps_note_roster_overrides() {
4702 // "reviewer" collides with the built-in roster member; the
4703 // role step context and review Role section must both say so.
4704 let mut view = FleetSetupView::from_snapshot(snapshot());
4705 for _ in 0..3 {
4706 view.handle_key(key(KeyCode::Down));
4707 }
4708 assert_eq!(view.selected_role(), "reviewer");
4709 assert_eq!(
4710 view.roster_override_note().as_deref(),
4711 Some("Replaces the built-in 'reviewer' role in the Fleet.")
4712 );
4713
4714 let role_step = render_through_stack(
4715 || {
4716 let mut v = FleetSetupView::from_snapshot(snapshot());
4717 for _ in 0..3 {
4718 v.handle_key(key(KeyCode::Down));
4719 }
4720 v
4721 },
4722 120,
4723 40,
4724 )
4725 .join("\n");
4726 assert!(
4727 contains_wrapped(&role_step, "Replaces the built-in 'reviewer'"),
4728 "{role_step}"
4729 );
4730
4731 let review = render_through_stack(
4732 || {
4733 let mut v = FleetSetupView::from_snapshot(snapshot());
4734 for _ in 0..3 {
4735 v.handle_key(key(KeyCode::Down));
4736 }
4737 v.step = Step::Review;
4738 v
4739 },
4740 120,
4741 40,
4742 )
4743 .join("\n");
4744 assert!(
4745 contains_wrapped(&review, "Replaces the built-in 'reviewer'"),
4746 "{review}"
4747 );
4748
4749 // "custom" also matches a built-in roster member.
4750 let mut custom_view = FleetSetupView::from_snapshot(snapshot());
4751 for _ in 0..8 {
4752 custom_view.handle_key(key(KeyCode::Down));
4753 }
4754 assert_eq!(custom_view.selected_role(), "custom");
4755 assert_eq!(
4756 custom_view.roster_override_note().as_deref(),
4757 Some("Replaces the built-in 'custom' role in the Fleet.")
4758 );
4759 }
4760
4761 #[test]
4762 fn default_selection_targets_manager_inherit() {
4763 let view = FleetSetupView::from_snapshot(snapshot());
4764 let draft = view.starter_profile_draft();
4765 assert_eq!(draft.file_name(), "manager.toml");
4766 assert_eq!(draft.role_hint, "manager");
4767 assert!(draft.model.is_none());
4768 assert!(draft.model_class_hint.is_none());
4769 assert!(
4770 draft
4771 .instructions
4772 .as_deref()
4773 .is_some_and(|text| text.contains("assigned Fleet slice"))
4774 );
4775 }
4776
4777 #[test]
4778 fn fleet_model_rows_keep_failed_provider_visible_with_reason() {
4779 let mut snap = snapshot();
4780 snap.available_models = vec![(
4781 "zai".to_string(),
4782 "glm-5.2".to_string(),
4783 codewhale_engine::provider_readiness::ResolvedProviderReadiness::SavedLastCheckFailed {
4784 category: codewhale_error_taxonomy::ErrorCategory::Authentication,
4785 message: "auth failed".to_string(),
4786 },
4787 )];
4788 let mut view = FleetSetupView::from_snapshot(snap);
4789 assert_eq!(view.model_choices.len(), 2);
4790 assert!(
4791 view.model_choices[1]
4792 .summary
4793 .contains("last check failed (authentication)")
4794 );
4795 assert!(view.model_choices[1].summary.contains("auth failed"));
4796 assert_eq!(
4797 view.model_routes[1],
4798 ("zai".to_string(), "glm-5.2".to_string())
4799 );
4800 assert!(matches!(
4801 &view.model_row_states[1],
4802 FleetModelRowState::Blocked { reason } if reason == "auth failed"
4803 ));
4804 view.step = Step::Model;
4805 view.model_idx = 1;
4806 assert!(matches!(
4807 view.handle_key(key(KeyCode::Enter)),
4808 ViewAction::None
4809 ));
4810 assert_eq!(view.step, Step::Model);
4811 }
4812
4813 #[test]
4814 fn fleet_invalid_route_stays_visible_but_cannot_advance() {
4815 let mut snap = snapshot();
4816 snap.available_models = vec![(
4817 "zai".to_string(),
4818 "broken-model".to_string(),
4819 codewhale_engine::provider_readiness::ResolvedProviderReadiness::InvalidRoute,
4820 )];
4821 let mut view = FleetSetupView::from_snapshot(snap);
4822 view.step = Step::Model;
4823 view.model_idx = 1;
4824
4825 assert!(view.model_choices[1].summary.contains("invalid route"));
4826 assert!(matches!(
4827 view.handle_key(key(KeyCode::Enter)),
4828 ViewAction::None
4829 ));
4830 assert_eq!(view.step, Step::Model);
4831 }
4832
4833 #[test]
4834 fn fleet_includes_saved_model_outside_bundled_catalog() {
4835 let providers = codewhale_runtime::config::ProvidersConfig {
4836 openrouter: codewhale_runtime::config::ProviderConfig {
4837 api_key: Some("openrouter-test-key".to_string()),
4838 model: Some("acme/private-preview".to_string()),
4839 ..Default::default()
4840 },
4841 ..Default::default()
4842 };
4843 let config = {
4844 let __cw_config_init_0_0 = Some("openrouter".to_string());
4845 let __cw_config_init_0_1 = Some(providers);
4846 let mut __cw_config_init_0_value: Config = Default::default();
4847 __cw_config_init_0_value.provider = __cw_config_init_0_0;
4848 __cw_config_init_0_value.providers = __cw_config_init_0_1;
4849 __cw_config_init_0_value
4850 };
4851
4852 let routes = cross_provider_model_routes(
4853 &config,
4854 Some(&(config).test_identity_for_kind(codewhale_config::ProviderKind::Openrouter)),
4855 &codewhale_engine::provider_readiness::ProviderReadinessSnapshot::default(),
4856 );
4857
4858 assert!(routes.iter().any(|(provider, model, readiness)| {
4859 provider == "openrouter" && model == "acme/private-preview" && readiness.can_attempt()
4860 }));
4861 assert_eq!(
4862 routes
4863 .iter()
4864 .filter(|(provider, model, _)| {
4865 provider == "openrouter" && model == "acme/private-preview"
4866 })
4867 .count(),
4868 1,
4869 "saved models must not be duplicated when the catalog later learns them"
4870 );
4871 }
4872
4873 #[test]
4874 fn fleet_routes_and_saved_draft_keep_exact_named_custom_provider() {
4875 let mut custom = std::collections::HashMap::new();
4876 for (name, base_url, model) in [
4877 ("custom-a", "http://127.0.0.1:18181/v1", "model-a"),
4878 ("custom-b", "http://127.0.0.1:18182/v1", "model-b"),
4879 ] {
4880 custom.insert(
4881 name.to_string(),
4882 codewhale_runtime::config::ProviderConfig {
4883 kind: Some("openai-compatible".to_string()),
4884 base_url: Some(base_url.to_string()),
4885 model: Some(model.to_string()),
4886 api_key: Some("local-test-key".to_string()),
4887 ..Default::default()
4888 },
4889 );
4890 }
4891 let config = {
4892 let __cw_config_init_1_0 = Some("custom-a".to_string());
4893 let __cw_config_init_1_1 = Some(codewhale_runtime::config::ProvidersConfig {
4894 custom,
4895 ..Default::default()
4896 });
4897 let mut __cw_config_init_1_value: Config = Default::default();
4898 __cw_config_init_1_value.provider = __cw_config_init_1_0;
4899 __cw_config_init_1_value.providers = __cw_config_init_1_1;
4900 __cw_config_init_1_value
4901 };
4902 let routes = cross_provider_model_routes(
4903 &config,
4904 Some(&(config).test_identity_for_kind(codewhale_config::ProviderKind::Custom)),
4905 &codewhale_engine::provider_readiness::ProviderReadinessSnapshot::default(),
4906 );
4907 assert!(
4908 routes
4909 .iter()
4910 .any(|(provider, model, _)| { provider == "custom-a" && model == "model-a" })
4911 );
4912 assert!(
4913 routes
4914 .iter()
4915 .any(|(provider, model, _)| { provider == "custom-b" && model == "model-b" })
4916 );
4917 assert!(!routes.iter().any(|(provider, _, _)| provider == "custom"));
4918
4919 let mut view = FleetSetupView::from_snapshot(FleetSetupSnapshot {
4920 available_models: routes,
4921 provider: "custom-a".to_string(),
4922 model: "model-a".to_string(),
4923 ..snapshot()
4924 });
4925 let route_idx = view
4926 .model_routes
4927 .iter()
4928 .position(|(provider, model)| provider == "custom-b" && model == "model-b")
4929 .expect("custom B route selectable while A is active");
4930 let route = view.model_routes[route_idx].clone();
4931 // Request the draft against the custom B answer, as `m` on Review does.
4932 view.model_idx = route_idx;
4933 view.step = Step::Review;
4934 view.handle_key(key(KeyCode::Char('m')));
4935 let draft = sample_draft();
4936 let (_, rendered) = view
4937 .install_model_draft(draft, "model-b".to_string(), Some(route), None)
4938 .expect("answers unchanged since `m`");
4939 assert!(rendered.contains("provider = \"custom-b\""), "{rendered}");
4940 }
4941
4942 #[test]
4943 fn fleet_routes_keep_legacy_literal_custom_without_named_tables() {
4944 let config = {
4945 let __cw_config_init_2_0 = Some("custom".to_string());
4946 let __cw_config_init_2_1 = Some("legacy-custom-model".to_string());
4947 let mut __cw_config_init_2_value: Config = Default::default();
4948 __cw_config_init_2_value.provider = __cw_config_init_2_0;
4949 __cw_config_init_2_value.default_text_model = __cw_config_init_2_1;
4950 __cw_config_init_2_value
4951 }
4952 .with_legacy_root(
4953 Some("local-test-key".to_string()),
4954 Some("http://127.0.0.1:18080/v1".to_string()),
4955 );
4956
4957 let routes = cross_provider_model_routes(
4958 &config,
4959 Some(&(config).test_identity_for_kind(codewhale_config::ProviderKind::Custom)),
4960 &codewhale_engine::provider_readiness::ProviderReadinessSnapshot::default(),
4961 );
4962
4963 assert!(
4964 routes.iter().any(|(provider, model, readiness)| {
4965 provider == "custom"
4966 && model == "legacy-custom-model"
4967 && matches!(
4968 readiness,
4969 codewhale_engine::provider_readiness::ResolvedProviderReadiness::LocalUnchecked
4970 )
4971 && readiness.can_attempt()
4972 }),
4973 "{routes:?}"
4974 );
4975 }
4976
4977 #[test]
4978 fn role_step_keeps_list_and_detail_separate_at_80_columns() {
4979 let rows = render_through_stack(|| FleetSetupView::from_snapshot(snapshot()), 80, 24);
4980 let text = rows.join("\n");
4981
4982 let manager_row = rows
4983 .iter()
4984 .position(|row| row.contains("▸ manager"))
4985 .expect("manager row should render");
4986 let custom_row = rows
4987 .iter()
4988 .position(|row| row.contains(" custom"))
4989 .expect("custom row should render");
4990 let summary_row = rows
4991 .iter()
4992 .position(|row| row.contains("Plan & split queued work"))
4993 .expect("selected role summary should render");
4994 let description_row = rows
4995 .iter()
4996 .position(|row| row.contains("Coordinates the Fleet run"))
4997 .expect("selected role description should render");
4998
4999 assert!(
5000 manager_row < custom_row,
5001 "expected the full role list before details:\n{text}"
5002 );
5003 assert!(
5004 custom_row < summary_row,
5005 "selected summary must not share a row with role names:\n{text}"
5006 );
5007 assert!(
5008 custom_row < description_row,
5009 "selected description must render below the list:\n{text}"
5010 );
5011 for row in &rows[manager_row..=custom_row] {
5012 assert!(
5013 !row.contains("Plan & split queued work")
5014 && !row.contains("Coordinates the Fleet run")
5015 && !row.contains("Fleet runs agents"),
5016 "role list row contains detail copy at 80 columns: {row:?}\n{text}"
5017 );
5018 }
5019 }
5020
5021 const BLEED_FILL: &str = "\u{e000}";
5022
5023 fn render_through_stack(view_at: impl Fn() -> FleetSetupView, w: u16, h: u16) -> Vec<String> {
5024 let area = Rect::new(0, 0, w, h);
5025 let mut buf = Buffer::empty(area);
5026 for y in 0..h {
5027 for x in 0..w {
5028 // A private-use glyph that no rendered copy or temp path can
5029 // contain, so bleed-through detection cannot false-positive
5030 // on a path like `/Volumes/WorkSSD/...`.
5031 buf[(x, y)].set_symbol(BLEED_FILL);
5032 }
5033 }
5034 let mut stack = ViewStack::new();
5035 stack.push(view_at());
5036 stack.render(area, &mut buf);
5037 (0..h)
5038 .map(|y| {
5039 (0..w)
5040 .map(|x| buf[(x, y)].symbol().to_string())
5041 .collect::<String>()
5042 })
5043 .collect()
5044 }
5045
5046 #[test]
5047 fn fleet_setup_is_usable_and_opaque_at_blocker_sizes() {
5048 // Exercise each step so all three screens are validated at every size.
5049 type Builder = (&'static str, fn() -> FleetSetupView);
5050 let builders: [Builder; 3] = [
5051 ("role", || FleetSetupView::from_snapshot(snapshot())),
5052 ("model", || {
5053 let mut v = FleetSetupView::from_snapshot(snapshot());
5054 v.step = Step::Model;
5055 v
5056 }),
5057 ("review", || {
5058 let mut v = FleetSetupView::from_snapshot(snapshot());
5059 v.step = Step::Review;
5060 v
5061 }),
5062 ];
5063
5064 for (label, make) in builders {
5065 for (w, h) in BLOCKER_SIZES {
5066 let rows = render_through_stack(make, w, h);
5067 let text = rows.join("\n");
5068
5069 // No bleed-through anywhere in the composited frame.
5070 assert!(
5071 !text.contains(BLEED_FILL),
5072 "{label} {w}x{h}: background bleed-through"
5073 );
5074 // Some action label is always visible.
5075 assert!(text.contains("Esc"), "{label} {w}x{h}: missing footer");
5076 // The first impression communicates Fleet = agent team.
5077 assert!(
5078 text.contains("agent team"),
5079 "{label} {w}x{h}: missing framing"
5080 );
5081 // No row overflows the frame width.
5082 for (y, row) in rows.iter().enumerate() {
5083 assert!(
5084 UnicodeWidthStr::width(row.trim_end()) <= w as usize,
5085 "{label} {w}x{h}: row {y} overflows: {row:?}"
5086 );
5087 }
5088 }
5089 }
5090 }
5091
5092 #[test]
5093 fn review_at_cursor_size_keeps_content_and_actions_apart() {
5094 let rows = render_through_stack(
5095 || {
5096 let mut view = FleetSetupView::from_snapshot(snapshot());
5097 view.step = Step::Review;
5098 view
5099 },
5100 89,
5101 50,
5102 );
5103 let popup = centered_modal_area(Rect::new(0, 0, 89, 50), 96, 31, 60, 16);
5104 let review_row = rows
5105 .iter()
5106 .position(|row| row.contains("Review & save"))
5107 .expect("review heading");
5108 let review_col = rows[review_row]
5109 .chars()
5110 .position(|ch| ch == 'R')
5111 .expect("review heading column") as u16;
5112 assert!(
5113 review_col >= popup.x.saturating_add(2),
5114 "body copy must not touch the popup border: {:?}",
5115 rows[review_row]
5116 );
5117
5118 let action_row = rows
5119 .iter()
5120 .rposition(|row| row.contains("Esc"))
5121 .expect("footer Esc action");
5122 let footer_row = rows[..=action_row]
5123 .iter()
5124 .rposition(|row| row.contains("scroll"))
5125 .expect("footer shortcut row");
5126 assert!(footer_row > 0);
5127 let gutter = rows[footer_row - 1]
5128 .chars()
5129 .skip(usize::from(popup.x.saturating_add(1)))
5130 .take(usize::from(popup.width.saturating_sub(2)))
5131 .collect::<String>();
5132 assert!(
5133 gutter.trim().is_empty(),
5134 "review body needs a quiet row before the action rail: {gutter:?}"
5135 );
5136 }
5137
5138 #[test]
5139 fn choice_steps_at_cursor_size_stay_content_sized() {
5140 for (step, expected_height) in [(Step::Role, 22usize), (Step::Model, 23usize)] {
5141 let rows = render_through_stack(
5142 || {
5143 let mut view = FleetSetupView::from_snapshot(snapshot());
5144 view.step = step;
5145 view
5146 },
5147 89,
5148 50,
5149 );
5150 let top = rows
5151 .iter()
5152 .position(|row| row.contains("Fleet setup — your agent team"))
5153 .expect("fleet setup title");
5154 let bottom = rows
5155 .iter()
5156 .rposition(|row| row.contains("Step "))
5157 .expect("fleet setup step receipt");
5158 assert_eq!(
5159 bottom - top + 1,
5160 expected_height,
5161 "choice card should follow its content instead of filling the 89x50 frame"
5162 );
5163 }
5164 }
5165
5166 #[test]
5167 fn review_lists_model_permissions_tools_and_profile_availability() {
5168 // Top of the review: the leading sections are visible without scrolling.
5169 let top = render_through_stack(
5170 || {
5171 let mut v = FleetSetupView::from_snapshot(snapshot());
5172 v.step = Step::Review;
5173 v
5174 },
5175 120,
5176 40,
5177 )
5178 .join("\n");
5179 for section in [
5180 "Saves to",
5181 "Role",
5182 "Model",
5183 "Auth & readiness",
5184 "Permissions",
5185 ] {
5186 assert!(top.contains(section), "review missing section: {section}");
5187 }
5188 // The destination line names the scope and the exact file; the
5189 // permission posture stays governed by the sections below it.
5190 assert!(top.contains("Personal · "), "{top}");
5191 assert!(top.contains("agents"), "{top}");
5192 assert!(
5193 top.contains("can only narrow what the session allows"),
5194 "{top}"
5195 );
5196
5197 // The review is intentionally scrollable; scrolling to the bottom reveals
5198 // the workspace/org execution policy, review policy, and honest save note.
5199 let bottom = render_through_stack(
5200 || {
5201 let mut v = FleetSetupView::from_snapshot(snapshot());
5202 v.step = Step::Review;
5203 v.review_scroll = 999; // clamps to max in render
5204 v
5205 },
5206 120,
5207 40,
5208 )
5209 .join("\n");
5210 for needle in [
5211 "Tools",
5212 "Workspace",
5213 "Review policy",
5214 "Save as Personal profile",
5215 ] {
5216 assert!(bottom.contains(needle), "scrolled review missing: {needle}");
5217 }
5218
5219 let policy = FleetSetupView::from_snapshot(snapshot()).review_policy_summary();
5220 for truth in [
5221 "agents in this session",
5222 "codewhale fleet status",
5223 ".codewhale/fleet.jsonl",
5224 ] {
5225 assert!(policy.contains(truth), "review policy missing: {truth}");
5226 }
5227 assert!(
5228 !policy.contains("inspects the ledger"),
5229 "the interactive status command must not claim to inspect the durable ledger: {policy}"
5230 );
5231 }
5232
5233 #[test]
5234 fn dormant_external_consent_row_requires_activation() {
5235 let mut snap = snapshot();
5236 snap.available_models = vec![(
5237 "openai-codex".to_string(),
5238 "gpt-5.6-sol".to_string(),
5239 codewhale_engine::provider_readiness::ResolvedProviderReadiness::ExternalConsentPendingSelection,
5240 )];
5241 let view = FleetSetupView::from_snapshot(snap);
5242 assert!(
5243 view.model_choices[1]
5244 .summary
5245 .contains("external consent · select to check")
5246 );
5247 assert!(matches!(
5248 view.model_row_states[1],
5249 FleetModelRowState::NeedsActivation
5250 ));
5251 }
5252
5253 #[test]
5254 fn enter_on_dormant_external_consent_emits_activation_event() {
5255 let mut snap = snapshot();
5256 snap.available_models = vec![(
5257 "openai-codex".to_string(),
5258 "gpt-5.6-terra".to_string(),
5259 codewhale_engine::provider_readiness::ResolvedProviderReadiness::ExternalConsentPendingSelection,
5260 )];
5261 let mut view = FleetSetupView::from_snapshot(snap);
5262 view.handle_key(key(KeyCode::Enter)); // Role -> Model
5263 view.handle_key(key(KeyCode::Down)); // inherit -> codex row
5264 assert_eq!(
5265 view.selected_route(),
5266 Some(("openai-codex".to_string(), "gpt-5.6-terra".to_string()))
5267 );
5268 let action = view.handle_key(key(KeyCode::Enter));
5269 let ViewAction::Emit(ViewEvent::FleetSetupExternalConsentActivationRequested {
5270 provider_id,
5271 model,
5272 }) = action
5273 else {
5274 panic!("expected external-consent activation request, got {action:?}");
5275 };
5276 assert_eq!(provider_id, "openai-codex");
5277 assert_eq!(model, "gpt-5.6-terra");
5278 assert_eq!(
5279 view.step,
5280 Step::Model,
5281 "stays on Model step until host validates"
5282 );
5283 }
5284
5285 #[test]
5286 fn refresh_from_snapshot_makes_activated_row_ready() {
5287 let mut snap = snapshot();
5288 snap.available_models = vec![(
5289 "xai".to_string(),
5290 "grok-4.5".to_string(),
5291 codewhale_engine::provider_readiness::ResolvedProviderReadiness::ExternalConsentPendingSelection,
5292 )];
5293 let mut view = FleetSetupView::from_snapshot(snap);
5294 view.handle_key(key(KeyCode::Enter)); // Role -> Model
5295 view.handle_key(key(KeyCode::Down)); // xai row
5296 assert!(matches!(
5297 view.model_row_states[1],
5298 FleetModelRowState::NeedsActivation
5299 ));
5300
5301 // Simulate the host validating the route and rebuilding the snapshot:
5302 // the same row is now Ready.
5303 let mut refreshed = snapshot();
5304 refreshed.available_models = vec![(
5305 "xai".to_string(),
5306 "grok-4.5".to_string(),
5307 codewhale_engine::provider_readiness::ResolvedProviderReadiness::Ready,
5308 )];
5309 view.refresh_from_snapshot(refreshed);
5310
5311 assert!(matches!(
5312 view.model_row_states[1],
5313 FleetModelRowState::Ready
5314 ));
5315 // Selection and step are preserved.
5316 assert_eq!(view.step, Step::Model);
5317 assert_eq!(
5318 view.selected_route(),
5319 Some(("xai".to_string(), "grok-4.5".to_string()))
5320 );
5321 }
5322
5323 #[test]
5324 fn blocked_row_cannot_advance() {
5325 let mut snap = snapshot();
5326 snap.available_models = vec![(
5327 "xai".to_string(),
5328 "grok-4.5".to_string(),
5329 codewhale_engine::provider_readiness::ResolvedProviderReadiness::MissingKey,
5330 )];
5331 let mut view = FleetSetupView::from_snapshot(snap);
5332 view.step = Step::Model;
5333 view.model_idx = 1;
5334 assert!(matches!(
5335 &view.model_row_states[1],
5336 FleetModelRowState::Blocked { reason } if reason == "missing API key"
5337 ));
5338 assert!(matches!(
5339 view.handle_key(key(KeyCode::Enter)),
5340 ViewAction::None
5341 ));
5342 assert_eq!(view.step, Step::Model);
5343 }
5344
5345 #[test]
5346 fn fleet_setup_includes_openai_codex_account_roster_with_dormant_consent() {
5347 let _env = crate::test_support::lock_test_env();
5348 let home = tempfile::tempdir().expect("owned ChatGPT home");
5349 let canonical_home = home
5350 .path()
5351 .canonicalize()
5352 .expect("canonical private fixture home");
5353 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &canonical_home);
5354 let mut config = codewhale_runtime::config::Config::default();
5355 codewhale_runtime::oauth::install_test_chatgpt_registration(&mut config)
5356 .expect("owned ChatGPT registration");
5357 codewhale_runtime::codex_model_roster::install_test_chatgpt_roster(
5358 &config,
5359 &["gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"],
5360 )
5361 .expect("account-scoped roster");
5362
5363 let routes = cross_provider_model_routes(
5364 &config,
5365 Some(&(config).test_identity_for_kind(codewhale_config::ProviderKind::Moonshot)),
5366 &codewhale_engine::provider_readiness::ProviderReadinessSnapshot::default(),
5367 );
5368
5369 for model in ["gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"] {
5370 assert!(
5371 routes.iter().any(|(provider, m, readiness)| {
5372 provider == "openai-codex"
5373 && m == model
5374 && matches!(
5375 readiness,
5376 codewhale_engine::provider_readiness::ResolvedProviderReadiness::SavedUnchecked
5377 )
5378 }),
5379 "missing unchecked owned ChatGPT route for {model}: {routes:?}"
5380 );
5381 }
5382 }
5383
5384 #[test]
5385 fn fleet_setup_includes_xai_grok_routes_with_dormant_consent() {
5386 let _env = crate::test_support::lock_test_env();
5387 let grok_home = tempfile::tempdir().expect("Grok home");
5388 let mut config = codewhale_runtime::config::Config::default();
5389 config.providers = Some(codewhale_runtime::config::ProvidersConfig {
5390 xai: codewhale_runtime::config::ProviderConfig {
5391 auth_mode: Some("oauth".to_string()),
5392 external_credentials: Some(
5393 codewhale_config::ExternalCredentialConsentToml::read_only(
5394 codewhale_config::ProviderKind::Xai,
5395 codewhale_config::ExternalCredentialSource::GrokCli,
5396 grok_home.path().join("grok-auth.json"),
5397 ),
5398 ),
5399 ..Default::default()
5400 },
5401 ..Default::default()
5402 });
5403
5404 let routes = cross_provider_model_routes(
5405 &config,
5406 Some(&(config).test_identity_for_kind(codewhale_config::ProviderKind::Moonshot)),
5407 &codewhale_engine::provider_readiness::ProviderReadinessSnapshot::default(),
5408 );
5409
5410 let xai_rows: Vec<_> = routes
5411 .iter()
5412 .filter(|(provider, _, _)| provider == "xai")
5413 .collect();
5414 assert!(
5415 !xai_rows.is_empty(),
5416 "xAI routes must be offered when Grok CLI consent is configured: {routes:?}"
5417 );
5418 assert!(
5419 xai_rows.iter().all(|(_, _, readiness)| {
5420 matches!(
5421 readiness,
5422 codewhale_engine::provider_readiness::ResolvedProviderReadiness::ExternalConsentPendingSelection
5423 )
5424 }),
5425 "every xAI row must require explicit activation: {xai_rows:?}"
5426 );
5427 }
5428
5429 #[test]
5430 fn fleet_setup_handle_paste_filters_models_only_when_model_filter_active() {
5431 let mut view = FleetSetupView::from_snapshot(snapshot());
5432 assert!(!view.handle_paste("deepseek"));
5433 assert!(view.model_query.is_empty());
5434
5435 view.handle_key(key(KeyCode::Enter));
5436 assert_eq!(view.step, Step::Model);
5437 assert!(!view.handle_paste("deepseek"));
5438 assert!(view.model_query.is_empty());
5439
5440 view.composition_decision = CompositionDecision::Accepted;
5441 view.handle_key(key(KeyCode::Char('/')));
5442 assert!(view.model_filter_active);
5443 view.model_idx = 1;
5444 assert!(view.handle_paste("deep\r\nseek\n"));
5445 assert_eq!(view.model_query, "deep seek");
5446 assert_eq!(view.model_idx, 0);
5447 assert_eq!(view.composition_decision, CompositionDecision::Edited);
5448 }
5449 }
5450
5450 lines RUST