codewhale-tui 0.8.67

Terminal UI for open-source and open-weight coding models
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
//! `/fleet setup` — a progressive "set up your agent team" flow.
//!
//! Replaces the old six-column config matrix (#3791). Fleet is presented as an
//! agent team: the user makes one focused choice at a time (a role, then a model
//! class) and then reviews the full posture — model/route, permissions, tools,
//! workspace/org scope, and review policy — before starting. "Start" previews a
//! deterministic starter TOML profile; nothing is written until the user
//! explicitly ratifies the exact rendered bytes.
//!
//! NOTE (audit #7 / #3167): the role/model taxonomy and copy below are
//! intentionally English for now; #3167 reworks this into an interactive
//! provider/model picker that will churn most of this text. The command entry
//! (`CmdFleetDescription`) is already localized.

use std::path::{Path, PathBuf};

use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{
    buffer::Buffer,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Padding, Paragraph, Widget, Wrap},
};

use crate::config::Config;
use crate::palette;
use crate::tui::app::App;
use crate::tui::views::{
    ActionHint, ModalKind, ModalView, ViewAction, ViewEvent, centered_modal_area,
    render_modal_footer, render_modal_surface, truncate_view_text,
};

const PROFILE_DIR: &str = ".codewhale/agents";

/// A selectable choice in a wizard step: a short identifier `label`, a one-line
/// `summary`, and a longer `description` shown (wrapped) in the detail pane.
struct Choice {
    label: &'static str,
    summary: &'static str,
    description: &'static str,
}

const CHOICE_LIST_WIDTH: u16 = 22;
const CHOICE_DETAIL_MIN_WIDTH: u16 = 58;
const CHOICE_TWO_COLUMN_MIN_WIDTH: u16 = CHOICE_LIST_WIDTH + CHOICE_DETAIL_MIN_WIDTH;

/// Agent-team roles. `label` doubles as the profile `role_hint` and file stem,
/// so these strings are part of the generated-profile contract.
const ROLES: [Choice; 8] = [
    Choice {
        label: "manager",
        summary: "Plan & split queued work",
        description: "Coordinates the Fleet run: plans the work, splits it into bounded tasks, and dispatches workers.",
    },
    Choice {
        label: "scout",
        summary: "Read-first research",
        description: "Research and repo reconnaissance. Reads and summarizes before anything is written.",
    },
    Choice {
        label: "builder",
        summary: "Implements bounded changes",
        description: "Implements changes strictly inside its assigned task scope; writes only what the slice needs.",
    },
    Choice {
        label: "reviewer",
        summary: "Read-only review",
        description: "Checks regressions, tests, and diffs. Read-only — it never writes.",
    },
    Choice {
        label: "verifier",
        summary: "Runs focused validation",
        description: "Runs targeted validation and reports receipts back to the orchestrator.",
    },
    Choice {
        label: "synthesizer",
        summary: "Reduce receipts to handoff",
        description: "Turns worker receipts into bounded handoff state instead of raw transcript replay.",
    },
    Choice {
        label: "general",
        summary: "General-purpose worker",
        description: "A flexible worker with no specialized posture — use it when the task doesn't fit a named role.",
    },
    Choice {
        label: "custom",
        summary: "Author a profile by hand",
        description: "Define the posture yourself in a workspace agent TOML profile under .codewhale/agents/.",
    },
];

/// The `inherit` row shown first in the Model step (#3167). Concrete provider
/// models follow it, built per-run from the active provider's catalog, so the
/// user picks a real model instead of an abstract class.
const MODEL_INHERIT: Choice = Choice {
    label: "inherit",
    summary: "Same model as now",
    description: "Reuse the active provider, model, and reasoning for this worker — the operator's route. Recommended default.",
};

#[derive(Debug, Clone)]
pub struct FleetSetupSnapshot {
    workspace: PathBuf,
    locale: crate::localization::Locale,
    /// Whether the active provider has a key or local runtime — gates the
    /// model-draft offer, mirroring the constitution card's `provider_ready`.
    provider_ready: bool,
    provider: String,
    model: String,
    reasoning: String,
    subagents_enabled: bool,
    max_subagents: usize,
    launch_concurrency: usize,
    max_admitted: usize,
    subagent_spawn_depth: u32,
    fleet_spawn_depth: u32,
    token_budget: Option<u64>,
    api_timeout_secs: u64,
    heartbeat_timeout_secs: u64,
    /// Lowercased roster member ids with their origin labels (built-in /
    /// config / project), so the wizard can say when a chosen role would
    /// override an existing roster member.
    roster_members: Vec<(String, String)>,
    /// Concrete model ids selectable for a worker on the active provider,
    /// shown after `inherit` in the Model step.
    available_models: Vec<&'static str>,
}

impl FleetSetupSnapshot {
    #[must_use]
    pub fn from_app(app: &App, config: &Config) -> Self {
        let provider = app.api_provider.display_name().to_string();
        let model = if app.auto_model {
            app.last_effective_model
                .as_deref()
                .map(|effective| format!("auto -> {effective}"))
                .unwrap_or_else(|| "auto".to_string())
        } else {
            app.model.clone()
        };
        let fleet_spawn_depth = config
            .fleet
            .as_ref()
            .map(|fleet| fleet.exec.max_spawn_depth)
            .unwrap_or_else(|| codewhale_config::FleetExecConfig::default().max_spawn_depth)
            .min(codewhale_config::MAX_SPAWN_DEPTH_CEILING);
        let roster_members =
            crate::fleet::roster::FleetRoster::load(&config.fleet_config(), &app.workspace)
                .members()
                .iter()
                .map(|member| (member.id.to_lowercase(), member.origin.to_string()))
                .collect();

        Self {
            workspace: app.workspace.clone(),
            locale: app.ui_locale,
            provider_ready: crate::config::has_api_key_for(config, app.api_provider),
            provider,
            model,
            reasoning: app.reasoning_effort_display_label(),
            subagents_enabled: config.subagents_enabled_for_provider(app.api_provider),
            max_subagents: config.max_subagents_for_provider(app.api_provider),
            launch_concurrency: config.launch_concurrency_for_provider(app.api_provider),
            max_admitted: config.max_admitted_subagents_for_provider(app.api_provider),
            subagent_spawn_depth: config.subagent_max_spawn_depth_for_provider(app.api_provider),
            fleet_spawn_depth,
            token_budget: config.subagent_token_budget_for_provider(app.api_provider),
            api_timeout_secs: config.subagent_api_timeout_secs_for_provider(app.api_provider),
            heartbeat_timeout_secs: config
                .subagent_heartbeat_timeout_secs_for_provider(app.api_provider),
            roster_members,
            available_models: crate::config::model_completion_names_for_provider(app.api_provider),
        }
    }
}

/// Which focused screen of the wizard is showing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Step {
    /// Pick the team role.
    Role,
    /// Pick the model-routing class.
    Model,
    /// Review the full posture and start.
    Review,
}

pub struct FleetSetupView {
    snapshot: FleetSetupSnapshot,
    step: Step,
    role_idx: usize,
    model_idx: usize,
    review_scroll: usize,
    /// A model-drafted profile awaiting ratification (already sanitized and
    /// bounded by the untrusted gate). Cleared when the selection changes so
    /// a stale draft can never be ratified against fresh answers.
    model_draft: Option<Box<crate::fleet::profile::FleetProfileDraft>>,
    /// Display label of the model that authored `model_draft`.
    model_draft_label: Option<String>,
    /// Model-step rows: `inherit` followed by the active provider's models.
    model_choices: Vec<Choice>,
}

impl FleetSetupView {
    #[must_use]
    pub fn new(app: &App, config: &Config) -> Self {
        Self::from_snapshot(FleetSetupSnapshot::from_app(app, config))
    }

    fn from_snapshot(snapshot: FleetSetupSnapshot) -> Self {
        let mut model_choices = vec![MODEL_INHERIT];
        for &name in &snapshot.available_models {
            model_choices.push(Choice {
                label: name,
                summary: "Pin this model",
                description: "Route this worker to this specific model on the active provider instead of inheriting the session route.",
            });
        }
        Self {
            snapshot,
            step: Step::Role,
            role_idx: 0,
            model_idx: 0,
            review_scroll: 0,
            model_draft: None,
            model_draft_label: None,
            model_choices,
        }
    }

    /// Install a sanitized, bounded model draft and return the preview the
    /// host must open in the same breath — that preview is the exact TOML the
    /// ratify keypress would persist.
    pub fn install_model_draft(
        &mut self,
        draft: Box<crate::fleet::profile::FleetProfileDraft>,
        model_label: String,
    ) -> (String, String) {
        let (title, header) = match self.snapshot.locale {
            crate::localization::Locale::ZhHans => (
                format!("Fleet 配置 — 由 {model_label} 起草(按 g 批准)"),
                format!(
                    "# .codewhale/agents/{}\n# 由 {model_label} 起草,并由 CodeWhale 校验与限界。\n# 权限保持在 Fleet 底线:无 shell、无 trust、需审批。\n# 在向导中按 g 之前不会保存任何内容。\n\n",
                    draft.file_name()
                ),
            ),
            _ => (
                format!("Fleet profile — draft by {model_label} (g ratifies)"),
                format!(
                    "# .codewhale/agents/{}\n# Drafted by {model_label}, validated and bounded by CodeWhale.\n# Permissions stay at the fleet floor: no shell, no trust, approval required.\n# Nothing is saved until you press g in the wizard.\n\n",
                    draft.file_name()
                ),
            ),
        };
        let content = format!("{header}{}", draft.render_toml());
        self.model_draft = Some(draft);
        self.model_draft_label = Some(model_label);
        (title, content)
    }

    /// The planner role chosen (drives the profile file name and `role_hint`).
    fn selected_role(&self) -> &'static str {
        ROLES[self.role_idx.min(ROLES.len() - 1)].label
    }

    /// Copy note when the chosen role would override an existing roster
    /// member of the same id (e.g. "overrides built-in reviewer"). A saved
    /// profile shadows lower roster layers rather than adding a new member.
    fn roster_override_note(&self) -> Option<String> {
        let role = self.selected_role().to_lowercase();
        self.snapshot
            .roster_members
            .iter()
            .find(|(id, _)| *id == role)
            .map(|(id, origin)| format!("Overrides the {origin} '{id}' roster member."))
    }

    /// The concrete model chosen for this worker, or `None` for `inherit`
    /// (reuse the session route). Written to the profile `model` field.
    fn selected_model(&self) -> Option<String> {
        match self.model_choices.get(self.model_idx) {
            Some(choice) if choice.label != "inherit" => Some(choice.label.to_string()),
            _ => None,
        }
    }

    /// Number of selectable rows on the current step (0 on the review step).
    fn step_len(&self) -> usize {
        match self.step {
            Step::Role => ROLES.len(),
            Step::Model => self.model_choices.len(),
            Step::Review => 0,
        }
    }

    fn move_up(&mut self) {
        match self.step {
            Step::Role => {
                self.role_idx = self.role_idx.saturating_sub(1);
                self.discard_model_draft();
            }
            Step::Model => {
                self.model_idx = self.model_idx.saturating_sub(1);
                self.discard_model_draft();
            }
            Step::Review => self.review_scroll = self.review_scroll.saturating_sub(1),
        }
    }

    /// A draft is only valid for the answers it was requested against.
    fn discard_model_draft(&mut self) {
        self.model_draft = None;
        self.model_draft_label = None;
    }

    fn move_down(&mut self) {
        match self.step {
            Step::Role => {
                self.role_idx = (self.role_idx + 1).min(self.step_len().saturating_sub(1));
                self.discard_model_draft();
            }
            Step::Model => {
                self.model_idx = (self.model_idx + 1).min(self.step_len().saturating_sub(1));
                self.discard_model_draft();
            }
            Step::Review => self.review_scroll = self.review_scroll.saturating_add(1),
        }
    }

    /// Advance to the next step, or — on the review step — preview the exact
    /// starter profile TOML the next ratify keypress would persist.
    fn advance(&mut self) -> ViewAction {
        match self.step {
            Step::Role => {
                self.step = Step::Model;
                ViewAction::None
            }
            Step::Model => {
                self.step = Step::Review;
                self.review_scroll = 0;
                ViewAction::None
            }
            Step::Review => self.preview_starter_profile_action(),
        }
    }

    /// Step back toward the first screen. Returns `None` at the first step (the
    /// host closes the modal via Esc instead).
    fn back(&mut self) -> ViewAction {
        match self.step {
            Step::Role => ViewAction::None,
            Step::Model => {
                self.step = Step::Role;
                ViewAction::None
            }
            Step::Review => {
                self.step = Step::Model;
                ViewAction::None
            }
        }
    }

    fn preview_starter_profile_action(&mut self) -> ViewAction {
        let draft = self.starter_profile_draft();
        let (title, header) = match self.snapshot.locale {
            crate::localization::Locale::ZhHans => (
                "Fleet 配置 — 起始草案(Enter/g 批准)".to_string(),
                format!(
                    "# .codewhale/agents/{}\n# CodeWhale 根据当前角色和模型选择确定性渲染。\n# 权限保持在 Fleet 底线:无 shell、无 trust、需审批。\n# 在向导中按 Enter 或 g 之前不会保存任何内容。\n\n",
                    draft.file_name()
                ),
            ),
            _ => (
                "Fleet profile — starter draft (Enter/g ratifies)".to_string(),
                format!(
                    "# .codewhale/agents/{}\n# Deterministic starter profile rendered by CodeWhale from your role/model choices.\n# Permissions stay at the fleet floor: no shell, no trust, approval required.\n# Nothing is saved until you press Enter or g in the wizard.\n\n",
                    draft.file_name()
                ),
            ),
        };
        let content = format!("{header}{}", draft.render_toml());
        self.model_draft = Some(draft);
        self.model_draft_label = Some("CodeWhale starter".to_string());
        ViewAction::Emit(ViewEvent::OpenTextPager { title, content })
    }

    /// Build a deterministic starter profile for the current role/model
    /// selection. The same ratify event persists this as model-drafted profiles,
    /// so duplicate-id checks and atomic writes stay in one host path.
    fn starter_profile_draft(&self) -> Box<crate::fleet::profile::FleetProfileDraft> {
        let role = &ROLES[self.role_idx.min(ROLES.len() - 1)];
        Box::new(crate::fleet::profile::FleetProfileDraft {
            id: profile_file_stem(role.label),
            display_name: Some(role.label.to_string()),
            description: Some(format!("{} - {}", role.summary, role.description)),
            role_hint: role.label.to_string(),
            model_class_hint: None,
            model: self.selected_model(),
            instructions: Some(format!(
                "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.",
                role.label
            )),
        })
    }

    /// The action hints for the current step's footer (wrapped by the shared
    /// footer renderer so they can never run off the modal edge).
    fn footer_hints(&self) -> Vec<ActionHint> {
        let mut hints = Vec::new();
        match self.step {
            Step::Role => {
                hints.push(ActionHint::new("↑/↓", "choose"));
                hints.push(ActionHint::new("Enter", "next"));
            }
            Step::Model => {
                hints.push(ActionHint::new("↑/↓", "choose"));
                hints.push(ActionHint::new("Enter", "next"));
                hints.push(ActionHint::new("", "back"));
            }
            Step::Review => {
                hints.push(ActionHint::new("↑/↓", "scroll"));
                if self.model_draft.is_some() {
                    hints.push(ActionHint::new("Enter", "ratify"));
                    hints.push(ActionHint::new("g", "ratify draft"));
                    hints.push(ActionHint::new("m", "redraft"));
                } else if self.snapshot.provider_ready {
                    hints.push(ActionHint::new("Enter", "preview"));
                    hints.push(ActionHint::new("m", "model draft"));
                } else {
                    hints.push(ActionHint::new("Enter", "preview"));
                }
                hints.push(ActionHint::new("", "back"));
            }
        }
        hints.push(ActionHint::new("Esc", "cancel"));
        hints
    }
}

impl ModalView for FleetSetupView {
    fn kind(&self) -> ModalKind {
        ModalKind::FleetSetup
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }

    fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
        match key.code {
            KeyCode::Esc | KeyCode::Char('q') => ViewAction::Close,
            KeyCode::Up | KeyCode::Char('k') => {
                self.move_up();
                ViewAction::None
            }
            KeyCode::Down | KeyCode::Char('j') => {
                self.move_down();
                ViewAction::None
            }
            KeyCode::Char('m') if self.step == Step::Review && self.snapshot.provider_ready => {
                ViewAction::Emit(ViewEvent::FleetProfileModelDraftRequested {
                    role: self.selected_role().to_string(),
                    model: self
                        .selected_model()
                        .unwrap_or_else(|| "inherit".to_string()),
                    locale: self.snapshot.locale,
                })
            }
            KeyCode::Char('g') if self.step == Step::Review => match self.model_draft.clone() {
                Some(draft) => {
                    ViewAction::EmitAndClose(ViewEvent::FleetProfileDraftCommitRequested { draft })
                }
                None => ViewAction::None,
            },
            KeyCode::Enter | KeyCode::Right | KeyCode::Char('l')
                if self.step == Step::Review && self.model_draft.is_some() =>
            {
                // A ratify-ready draft is on screen; Enter should ratify it,
                // not silently start the manual profile-prompt flow and drop
                // the draft.
                match self.model_draft.clone() {
                    Some(draft) => {
                        ViewAction::EmitAndClose(ViewEvent::FleetProfileDraftCommitRequested {
                            draft,
                        })
                    }
                    None => ViewAction::None,
                }
            }
            KeyCode::Enter | KeyCode::Right | KeyCode::Char('l') => self.advance(),
            KeyCode::Left | KeyCode::Char('h') => self.back(),
            KeyCode::Home => {
                self.review_scroll = 0;
                ViewAction::None
            }
            KeyCode::PageUp => {
                self.review_scroll = self.review_scroll.saturating_sub(8);
                ViewAction::None
            }
            KeyCode::PageDown => {
                self.review_scroll = self.review_scroll.saturating_add(8);
                ViewAction::None
            }
            _ => ViewAction::None,
        }
    }

    fn render(&self, area: Rect, buf: &mut Buffer) {
        let popup_area = centered_modal_area(area, 96, 30, 60, 16);
        render_modal_surface(area, popup_area, buf);

        let step_no = match self.step {
            Step::Role => 1,
            Step::Model => 2,
            Step::Review => 3,
        };
        let block = Block::default()
            .title(Line::from(Span::styled(
                " Fleet setup — your agent team ",
                Style::default()
                    .fg(palette::WHALE_ACCENT_PRIMARY)
                    .add_modifier(Modifier::BOLD),
            )))
            .title_bottom(
                Line::from(Span::styled(
                    format!(" Step {step_no}/3 "),
                    Style::default().fg(palette::TEXT_MUTED),
                ))
                .alignment(ratatui::layout::Alignment::Right),
            )
            .borders(Borders::ALL)
            .border_style(Style::default().fg(palette::BORDER_COLOR))
            .style(Style::default().bg(palette::DEEPSEEK_INK))
            .padding(Padding::uniform(1));

        let inner = block.inner(popup_area);
        block.render(popup_area, buf);

        let hints = self.footer_hints();
        let content = render_modal_footer(inner, buf, &hints);

        // Header (intro + breadcrumb) above the step body.
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(3), Constraint::Min(1)])
            .split(content);
        self.render_header(chunks[0], buf);

        match self.step {
            Step::Role => {
                let mut context = vec![
                    "Fleet runs sub-agents that delegate work. Pick the role this".to_string(),
                    "team member should play. It becomes the profile role_hint.".to_string(),
                ];
                if let Some(note) = self.roster_override_note() {
                    context.push(note);
                }
                render_choice_step(chunks[1], buf, &ROLES, self.role_idx, &context)
            }
            Step::Model => render_choice_step(
                chunks[1],
                buf,
                &self.model_choices,
                self.model_idx,
                &[
                    format!(
                        "Current route: {} / {}  ·  reasoning {}",
                        self.snapshot.provider, self.snapshot.model, self.snapshot.reasoning
                    ),
                    match self.selected_model() {
                        Some(model) => format!("This worker will run on {model}."),
                        None => "This worker inherits your current route.".to_string(),
                    },
                ],
            ),
            Step::Review => self.render_review(chunks[1], buf),
        }
    }
}

impl FleetSetupView {
    fn render_header(&self, area: Rect, buf: &mut Buffer) {
        let (title, subtitle) = match self.step {
            Step::Role => (
                "Choose a team role",
                "Each Fleet member plays one role in the delegation.",
            ),
            Step::Model => (
                "Choose a model",
                "Pick this worker's model, or inherit your current route.",
            ),
            Step::Review => (
                "Review & start",
                "Confirm the posture below, preview exact TOML, then ratify to save.",
            ),
        };
        let lines = vec![
            Line::from(Span::styled(
                title,
                Style::default().fg(palette::DEEPSEEK_SKY).bold(),
            )),
            Line::from(Span::styled(
                subtitle,
                Style::default().fg(palette::TEXT_MUTED),
            )),
        ];
        Paragraph::new(lines)
            .wrap(Wrap { trim: true })
            .render(area, buf);
    }

    fn render_review(&self, area: Rect, buf: &mut Buffer) {
        let role = &ROLES[self.role_idx.min(ROLES.len() - 1)];
        let (profile_value, _) = profile_file_status(&self.snapshot.workspace);
        let file_stem = profile_file_stem(role.label);
        let token_budget = self
            .snapshot
            .token_budget
            .map(|budget| format!("{budget} tokens"))
            .unwrap_or_else(|| "unbounded".to_string());

        let mut lines: Vec<Line> = Vec::new();
        let section = |lines: &mut Vec<Line>, label: &str, body: String| {
            lines.push(Line::from(Span::styled(
                label.to_string(),
                Style::default().fg(palette::DEEPSEEK_SKY).bold(),
            )));
            lines.push(Line::from(Span::styled(
                body,
                Style::default().fg(palette::TEXT_PRIMARY),
            )));
            lines.push(Line::from(""));
        };

        section(
            &mut lines,
            "Role",
            match self.roster_override_note() {
                Some(note) => format!("{}{} · {note}", role.label, role.summary),
                None => format!("{}{}", role.label, role.summary),
            },
        );
        section(
            &mut lines,
            "Model",
            match self.selected_model() {
                Some(model) => format!("{model}  ·  provider {}", self.snapshot.provider),
                None => format!(
                    "inherit  ·  route {} / {}, reasoning {}",
                    self.snapshot.provider, self.snapshot.model, self.snapshot.reasoning
                ),
            },
        );
        section(
            &mut lines,
            "Permissions",
            "Inherit the parent envelope and narrow only. Children cannot widen approval, trust, or secrets, and required approvals stay on.".to_string(),
        );
        section(
            &mut lines,
            "Tools",
            "Read tools by default; write tools for builders within scope; shell stays policy-gated; artifacts and receipts stay inspectable.".to_string(),
        );
        section(
            &mut lines,
            "Workspace & org",
            format!(
                "{} · sub-agents {} ({} concurrent, {} launch slots, {} admitted) · recursion agent {} / fleet {} (ceiling {})",
                self.snapshot.workspace.display(),
                if self.snapshot.subagents_enabled {
                    "enabled"
                } else {
                    "disabled"
                },
                self.snapshot.max_subagents,
                self.snapshot.launch_concurrency,
                self.snapshot.max_admitted,
                self.snapshot.subagent_spawn_depth,
                self.snapshot.fleet_spawn_depth,
                codewhale_config::MAX_SPAWN_DEPTH_CEILING,
            ),
        );
        section(
            &mut lines,
            "Review policy",
            format!(
                "Budget {token_budget} · {}s api, {}s heartbeat. Fleet -> exec runs the workers; /fleet status (or /subagents) inspects the ledger.",
                self.snapshot.api_timeout_secs, self.snapshot.heartbeat_timeout_secs
            ),
        );
        section(
            &mut lines,
            "Profile",
            format!(
                "{PROFILE_DIR}/{file_stem}.toml  ·  {profile_value} present. Start previews a deterministic starter profile; nothing is written to disk until ratification.",
            ),
        );

        // `scroll` offsets by *visual* (post-wrap) rows, so the bound must count
        // wrapped rows — not logical lines — or the bottom sections become
        // unreachable. Estimate each line's wrapped height from its display
        // width; an over-estimate is harmless (scroll clamps at the real end).
        let wrap_width = usize::from(area.width).max(1);
        let visual_rows: usize = lines
            .iter()
            .map(|line| line.width().div_ceil(wrap_width).max(1))
            .sum();
        let max_scroll = visual_rows.saturating_sub(usize::from(area.height).max(1));
        let scroll = self.review_scroll.min(max_scroll);
        Paragraph::new(lines)
            .wrap(Wrap { trim: true })
            .scroll((scroll as u16, 0))
            .render(area, buf);
    }
}

/// Render a wizard choice step: a list of selectable identifiers on the left and
/// a wrapped detail pane (summary + description + context) on the right. Stacks
/// vertically when the body is too narrow for two columns so nothing truncates.
fn render_choice_step(
    area: Rect,
    buf: &mut Buffer,
    choices: &[Choice],
    selected: usize,
    context: &[String],
) {
    if area.width == 0 || area.height == 0 {
        return;
    }

    let (list_area, detail_area) = if area.width >= CHOICE_TWO_COLUMN_MIN_WIDTH {
        let cols = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Length(CHOICE_LIST_WIDTH),
                Constraint::Min(CHOICE_DETAIL_MIN_WIDTH),
            ])
            .split(area);
        (cols[0], cols[1])
    } else {
        let list_height = (choices.len() as u16 + 1).min(area.height.saturating_sub(1).max(1));
        let rows = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(list_height), Constraint::Min(1)])
            .split(area);
        (rows[0], rows[1])
    };

    // List: labels are identifiers, so a `>`-marked single line each is safe.
    let list_width = usize::from(list_area.width);
    let mut list_lines: Vec<Line> = Vec::with_capacity(choices.len());
    for (idx, choice) in choices.iter().enumerate() {
        let is_selected = idx == selected;
        let pointer = if is_selected { "> " } else { "  " };
        let style = if is_selected {
            Style::default()
                .fg(palette::SELECTION_TEXT)
                .bg(palette::SELECTION_BG)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(palette::TEXT_PRIMARY)
        };
        list_lines.push(Line::from(Span::styled(
            truncate_view_text(&format!("{pointer}{}", choice.label), list_width),
            style,
        )));
    }
    Paragraph::new(list_lines).render(list_area, buf);

    // Detail: summary + wrapped description + wrapped context, all word-wrapped.
    let choice = &choices[selected.min(choices.len().saturating_sub(1))];
    let mut detail_lines: Vec<Line> = vec![
        Line::from(Span::styled(
            choice.summary,
            Style::default().fg(palette::WHALE_ACCENT_PRIMARY).bold(),
        )),
        Line::from(""),
        Line::from(Span::styled(
            choice.description,
            Style::default().fg(palette::TEXT_PRIMARY),
        )),
    ];
    if !context.is_empty() {
        detail_lines.push(Line::from(""));
        for entry in context {
            detail_lines.push(Line::from(Span::styled(
                entry.clone(),
                Style::default().fg(palette::TEXT_MUTED),
            )));
        }
    }
    Paragraph::new(detail_lines)
        .wrap(Wrap { trim: true })
        .render(detail_area, buf);
}

fn profile_file_status(workspace: &Path) -> (String, String) {
    let dir = workspace.join(PROFILE_DIR);
    if !dir.exists() {
        return (
            "0 files".to_string(),
            format!("create {PROFILE_DIR}/*.toml"),
        );
    }
    if !dir.is_dir() {
        return (
            "blocked".to_string(),
            format!("{} is not a dir", dir.display()),
        );
    }

    let count = std::fs::read_dir(&dir)
        .ok()
        .into_iter()
        .flat_map(|entries| entries.flatten())
        .filter(|entry| entry.path().extension().and_then(|value| value.to_str()) == Some("toml"))
        .count();

    if count == 1 {
        ("1 file".to_string(), PROFILE_DIR.to_string())
    } else {
        (format!("{count} files"), PROFILE_DIR.to_string())
    }
}

/// Sanitize a planner role label into a safe TOML file stem.
fn profile_file_stem(role: &str) -> String {
    let stem: String = role
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
        .collect();
    let stem = stem.trim_matches('-').to_ascii_lowercase();
    if stem.is_empty() {
        "custom".to_string()
    } else {
        stem
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tui::views::ViewStack;
    use crossterm::event::KeyModifiers;
    use unicode_width::UnicodeWidthStr;

    const BLOCKER_SIZES: [(u16, u16); 4] = [(80, 24), (100, 30), (120, 32), (160, 40)];

    fn snapshot() -> FleetSetupSnapshot {
        FleetSetupSnapshot {
            workspace: PathBuf::from("/tmp/codewhale-test-workspace"),
            locale: crate::localization::Locale::En,
            provider_ready: true,
            provider: "DeepSeek".to_string(),
            model: "deepseek-v4-pro".to_string(),
            reasoning: "Auto".to_string(),
            subagents_enabled: true,
            max_subagents: 8,
            launch_concurrency: 3,
            max_admitted: 20,
            subagent_spawn_depth: 3,
            fleet_spawn_depth: 3,
            token_budget: Some(100_000),
            api_timeout_secs: 120,
            heartbeat_timeout_secs: 300,
            roster_members: crate::fleet::roster::FleetRoster::built_ins_only()
                .members()
                .iter()
                .map(|member| (member.id.to_lowercase(), member.origin.to_string()))
                .collect(),
            available_models: vec!["deepseek-v4-pro", "deepseek-v4-flash"],
        }
    }

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    fn sample_draft() -> Box<crate::fleet::profile::FleetProfileDraft> {
        let crate::fleet::profile::UntrustedProfileParse::Drafted(draft) =
            crate::fleet::profile::FleetProfileDraft::from_untrusted_json(
                r#"{"id":"reviewer","role_hint":"reviewer","description":"Reviews diffs.","instructions":"Read. Report. Stop."}"#,
            )
        else {
            panic!("sample draft should parse");
        };
        draft
    }

    fn to_review(view: &mut FleetSetupView) {
        view.handle_key(key(KeyCode::Enter));
        view.handle_key(key(KeyCode::Enter));
        assert_eq!(view.step, Step::Review);
    }

    #[test]
    fn review_step_m_requests_model_draft_with_current_answers() {
        let mut view = FleetSetupView::from_snapshot(snapshot());
        to_review(&mut view);

        let action = view.handle_key(key(KeyCode::Char('m')));
        let ViewAction::Emit(ViewEvent::FleetProfileModelDraftRequested {
            role,
            model,
            locale,
        }) = action
        else {
            panic!("expected model draft request");
        };
        assert!(!role.is_empty());
        assert!(!model.is_empty());
        assert_eq!(locale, crate::localization::Locale::En);
    }

    #[test]
    fn ratify_is_inert_without_a_draft_and_commits_with_one() {
        let mut view = FleetSetupView::from_snapshot(snapshot());
        to_review(&mut view);

        // No draft installed: g does nothing, m is the offered action.
        assert!(matches!(
            view.handle_key(key(KeyCode::Char('g'))),
            ViewAction::None
        ));

        let (title, content) = view.install_model_draft(sample_draft(), "GLM-5.2".to_string());
        assert!(title.contains("GLM-5.2"));
        assert!(content.contains("id = \"reviewer\""), "{content}");
        assert!(content.contains("Nothing is saved until"), "{content}");

        let action = view.handle_key(key(KeyCode::Char('g')));
        let ViewAction::EmitAndClose(ViewEvent::FleetProfileDraftCommitRequested { draft }) =
            action
        else {
            panic!("expected ratify commit event");
        };
        assert_eq!(draft.id, "reviewer");
    }

    #[test]
    fn changing_answers_discards_a_stale_draft() {
        let mut view = FleetSetupView::from_snapshot(snapshot());
        to_review(&mut view);
        let _ = view.install_model_draft(sample_draft(), "GLM-5.2".to_string());
        assert!(view.model_draft.is_some());

        // Back to the role step and change the selection: the draft no
        // longer matches the answers and must not survive to ratification.
        view.handle_key(key(KeyCode::Left));
        view.handle_key(key(KeyCode::Left));
        assert_eq!(view.step, Step::Role);
        view.handle_key(key(KeyCode::Down));
        assert!(view.model_draft.is_none());

        to_review(&mut view);
        assert!(matches!(
            view.handle_key(key(KeyCode::Char('g'))),
            ViewAction::None
        ));
    }

    #[test]
    fn arrows_move_within_step_and_enter_advances() {
        let mut view = FleetSetupView::from_snapshot(snapshot());
        assert_eq!(view.step, Step::Role);

        view.handle_key(key(KeyCode::Down));
        assert_eq!(view.role_idx, 1);

        view.handle_key(key(KeyCode::Enter));
        assert_eq!(view.step, Step::Model);

        view.handle_key(key(KeyCode::Down));
        assert_eq!(view.model_idx, 1);

        view.handle_key(key(KeyCode::Enter));
        assert_eq!(view.step, Step::Review);

        // Left steps back through the wizard.
        view.handle_key(key(KeyCode::Left));
        assert_eq!(view.step, Step::Model);
        view.handle_key(key(KeyCode::Left));
        assert_eq!(view.step, Step::Role);
    }

    #[test]
    fn esc_cancels_from_any_step() {
        let mut view = FleetSetupView::from_snapshot(snapshot());
        view.handle_key(key(KeyCode::Enter)); // -> Model
        let action = view.handle_key(key(KeyCode::Esc));
        assert!(matches!(action, ViewAction::Close));
    }

    #[test]
    fn start_on_review_previews_and_ratifies_starter_profile_for_selection() {
        let mut view = FleetSetupView::from_snapshot(snapshot());
        // Role: manager(0) scout(1) builder(2) -> builder.
        view.handle_key(key(KeyCode::Down));
        view.handle_key(key(KeyCode::Down));
        view.handle_key(key(KeyCode::Enter)); // -> Model
        // Model: inherit(0) deepseek-v4-pro(1) -> deepseek-v4-pro.
        view.handle_key(key(KeyCode::Down));
        view.handle_key(key(KeyCode::Enter)); // -> Review

        let action = view.handle_key(key(KeyCode::Enter)); // Start
        match action {
            ViewAction::Emit(ViewEvent::OpenTextPager { title, content }) => {
                assert!(title.contains("starter draft"));
                assert!(content.contains("# .codewhale/agents/builder.toml"));
                assert!(content.contains("id = \"builder\""));
                assert!(content.contains("role_hint = \"builder\""));
                assert!(content.contains("model = \"deepseek-v4-pro\""));
                assert!(content.contains("Nothing is saved until"));
                for forbidden in ["provider", "base_url", "api_key"] {
                    assert!(
                        !content.contains(forbidden),
                        "starter profile must not carry {forbidden}: {content}"
                    );
                }
            }
            other => panic!("expected starter profile preview, got {other:?}"),
        }
        assert!(view.model_draft.is_some());

        let action = view.handle_key(key(KeyCode::Enter)); // ratify previewed draft
        let ViewAction::EmitAndClose(ViewEvent::FleetProfileDraftCommitRequested { draft }) =
            action
        else {
            panic!("expected ratified starter draft");
        };
        assert_eq!(draft.id, "builder");
        assert_eq!(draft.role_hint, "builder");
        assert_eq!(draft.model.as_deref(), Some("deepseek-v4-pro"));
    }

    #[test]
    fn role_and_review_steps_note_roster_overrides() {
        // "reviewer" (index 4) collides with the built-in roster member; the
        // role step context and review Role section must both say so.
        let mut view = FleetSetupView::from_snapshot(snapshot());
        for _ in 0..3 {
            view.handle_key(key(KeyCode::Down));
        }
        assert_eq!(view.selected_role(), "reviewer");
        assert_eq!(
            view.roster_override_note().as_deref(),
            Some("Overrides the built-in 'reviewer' roster member.")
        );

        let role_step = render_through_stack(
            || {
                let mut v = FleetSetupView::from_snapshot(snapshot());
                for _ in 0..3 {
                    v.handle_key(key(KeyCode::Down));
                }
                v
            },
            120,
            40,
        )
        .join("\n");
        assert!(
            role_step.contains("Overrides the built-in 'reviewer'"),
            "{role_step}"
        );

        let review = render_through_stack(
            || {
                let mut v = FleetSetupView::from_snapshot(snapshot());
                for _ in 0..3 {
                    v.handle_key(key(KeyCode::Down));
                }
                v.step = Step::Review;
                v
            },
            120,
            40,
        )
        .join("\n");
        assert!(
            review.contains("Overrides the built-in 'reviewer'"),
            "{review}"
        );

        // "custom" matches no roster member: no override note anywhere.
        let mut custom_view = FleetSetupView::from_snapshot(snapshot());
        for _ in 0..7 {
            custom_view.handle_key(key(KeyCode::Down));
        }
        assert_eq!(custom_view.selected_role(), "custom");
        assert!(custom_view.roster_override_note().is_none());
    }

    #[test]
    fn default_selection_targets_manager_inherit() {
        let view = FleetSetupView::from_snapshot(snapshot());
        let draft = view.starter_profile_draft();
        assert_eq!(draft.file_name(), "manager.toml");
        assert_eq!(draft.role_hint, "manager");
        assert!(draft.model.is_none());
        assert!(draft.model_class_hint.is_none());
        assert!(
            draft
                .instructions
                .as_deref()
                .is_some_and(|text| text.contains("assigned Fleet slice"))
        );
    }

    #[test]
    fn role_step_keeps_list_and_detail_separate_at_80_columns() {
        let rows = render_through_stack(|| FleetSetupView::from_snapshot(snapshot()), 80, 24);
        let text = rows.join("\n");

        let manager_row = rows
            .iter()
            .position(|row| row.contains("> manager"))
            .expect("manager row should render");
        let custom_row = rows
            .iter()
            .position(|row| row.contains("  custom"))
            .expect("custom row should render");
        let summary_row = rows
            .iter()
            .position(|row| row.contains("Plan & split queued work"))
            .expect("selected role summary should render");
        let description_row = rows
            .iter()
            .position(|row| row.contains("Coordinates the Fleet run"))
            .expect("selected role description should render");

        assert!(
            manager_row < custom_row,
            "expected the full role list before details:\n{text}"
        );
        assert!(
            custom_row < summary_row,
            "selected summary must not share a row with role names:\n{text}"
        );
        assert!(
            custom_row < description_row,
            "selected description must render below the list:\n{text}"
        );
        for row in &rows[manager_row..=custom_row] {
            assert!(
                !row.contains("Plan & split queued work")
                    && !row.contains("Coordinates the Fleet run")
                    && !row.contains("Fleet runs sub-agents"),
                "role list row contains detail copy at 80 columns: {row:?}\n{text}"
            );
        }
    }

    fn render_through_stack(view_at: impl Fn() -> FleetSetupView, w: u16, h: u16) -> Vec<String> {
        let area = Rect::new(0, 0, w, h);
        let mut buf = Buffer::empty(area);
        for y in 0..h {
            for x in 0..w {
                buf[(x, y)].set_symbol("X");
            }
        }
        let mut stack = ViewStack::new();
        stack.push(view_at());
        stack.render(area, &mut buf);
        (0..h)
            .map(|y| {
                (0..w)
                    .map(|x| buf[(x, y)].symbol().to_string())
                    .collect::<String>()
            })
            .collect()
    }

    #[test]
    fn fleet_setup_is_usable_and_opaque_at_blocker_sizes() {
        // Exercise each step so all three screens are validated at every size.
        type Builder = (&'static str, fn() -> FleetSetupView);
        let builders: [Builder; 3] = [
            ("role", || FleetSetupView::from_snapshot(snapshot())),
            ("model", || {
                let mut v = FleetSetupView::from_snapshot(snapshot());
                v.step = Step::Model;
                v
            }),
            ("review", || {
                let mut v = FleetSetupView::from_snapshot(snapshot());
                v.step = Step::Review;
                v
            }),
        ];

        for (label, make) in builders {
            for (w, h) in BLOCKER_SIZES {
                let rows = render_through_stack(make, w, h);
                let text = rows.join("\n");

                // No bleed-through anywhere in the composited frame.
                assert!(
                    !text.contains('X'),
                    "{label} {w}x{h}: background bleed-through"
                );
                // Some action label is always visible.
                assert!(text.contains("cancel"), "{label} {w}x{h}: missing footer");
                // The first impression communicates Fleet = agent team.
                assert!(
                    text.contains("agent team"),
                    "{label} {w}x{h}: missing framing"
                );
                // No row overflows the frame width.
                for (y, row) in rows.iter().enumerate() {
                    assert!(
                        UnicodeWidthStr::width(row.trim_end()) <= w as usize,
                        "{label} {w}x{h}: row {y} overflows: {row:?}"
                    );
                }
            }
        }
    }

    #[test]
    fn review_lists_model_permissions_tools_and_scope() {
        // Top of the review: the leading sections are visible without scrolling.
        let top = render_through_stack(
            || {
                let mut v = FleetSetupView::from_snapshot(snapshot());
                v.step = Step::Review;
                v
            },
            120,
            40,
        )
        .join("\n");
        for section in ["Role", "Model", "Permissions", "Tools"] {
            assert!(top.contains(section), "review missing section: {section}");
        }

        // The review is intentionally scrollable; scrolling to the bottom reveals
        // the workspace/org scope, review policy, and the honest ratification
        // note on the Start action.
        let bottom = render_through_stack(
            || {
                let mut v = FleetSetupView::from_snapshot(snapshot());
                v.step = Step::Review;
                v.review_scroll = 999; // clamps to max in render
                v
            },
            120,
            40,
        )
        .join("\n");
        for needle in ["Workspace", "Review policy", "until ratification"] {
            assert!(bottom.contains(needle), "scrolled review missing: {needle}");
        }
    }
}