quorum-rs 0.7.0

Rust SDK and CLI for multi-agent deliberation systems — ships the `quorum` binary (run / status / trace / tui / init) plus the underlying agent, LLM, tool, prompt, and worker library.
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
use std::collections::HashMap;

use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Cell, Paragraph, Row, Table, Wrap};

use super::common::{ListState, fill_cell, render_error, render_key_hints, truncate};
use super::{FetchRequest, View, ViewAction};
use crate::cli::remote::DiscoveredRoom;
use crate::cli::tui::event::{self, AppEvent, DataEvent, PolicyInfo};
use crate::cli::workspace::RoomConfig;

/// Main menu — rooms table as the primary screen.
///
/// Enter = start deliberation (task input), d = detail, Tab = settings menu.
pub struct MainMenuView {
    rooms: Vec<(String, RoomConfig)>,
    default_room: Option<String>,
    /// Config-free remote rooms (`GET /rooms`), used when no local
    /// `nsed.yaml` rooms are configured. A room carrying a `policy` is
    /// submittable directly from this screen.
    remote_rooms: Vec<DiscoveredRoom>,
    /// Policies discovered from the orchestrator (`GET /policies`), used to
    /// render a room's bound policy by its human NAME instead of the raw
    /// policy id (a long hex hash) that nsed.yaml / the wizard stores.
    remote_policies: Vec<PolicyInfo>,
    /// Orchestrator name to fetch remote rooms / submit against in
    /// config-free mode (the synthetic `"default"`).
    orchestrator: String,
    list_state: ListState,
    task_input_active: bool,
    task_text: String,
    detail_visible: bool,
    /// Convergence threshold (`effort`) the operator wants for the
    /// deliberation. Stored as a string while the user types so
    /// partial input (`"0."`) doesn't get rounded away. Parsed on
    /// submit. Defaults to `"0.7"` — the same number every
    /// generated `workspace.yaml` ships with.
    pub threshold_text: String,
    /// `true` when Tab has moved focus from the task input to the
    /// threshold field. Keystrokes route to `threshold_text` instead
    /// of `task_text`.
    pub threshold_input_active: bool,
}

impl MainMenuView {
    /// Build the main menu. `rooms` are local config rooms; when empty the
    /// view runs config-free and fetches submittable rooms from `orchestrator`.
    pub fn new(
        rooms: HashMap<String, RoomConfig>,
        default_room: Option<String>,
        orchestrator: String,
    ) -> Self {
        let mut sorted: Vec<_> = rooms.into_iter().collect();
        sorted.sort_by(|a, b| a.0.cmp(&b.0));
        let count = sorted.len();
        Self {
            rooms: sorted,
            default_room,
            remote_rooms: Vec::new(),
            remote_policies: Vec::new(),
            orchestrator,
            list_state: ListState::new(count),
            task_input_active: false,
            task_text: String::new(),
            detail_visible: false,
            threshold_text: String::from("0.7"),
            threshold_input_active: false,
        }
    }

    /// `true` when there are no rooms to show at all — neither local config
    /// rooms nor remote (orchestrator) ones.
    fn is_empty(&self) -> bool {
        self.rooms.is_empty() && self.remote_rooms.is_empty()
    }

    /// Total selectable rooms: local config rooms first, then remote ones.
    fn shown_count(&self) -> usize {
        self.rooms.len() + self.remote_rooms.len()
    }

    /// Resolve the current selection to a local or remote room. The flat
    /// selection index runs over local rooms first, then remote.
    fn selected_kind(&self) -> Option<Sel> {
        let sel = self.list_state.selected;
        if sel < self.rooms.len() {
            Some(Sel::Local(sel))
        } else if sel < self.shown_count() {
            Some(Sel::Remote(sel - self.rooms.len()))
        } else {
            None
        }
    }

    /// Parse the threshold field. Returns `None` (use policy default)
    /// when the field is empty or unparseable; clamped to `[0.0, 1.0]`
    /// when valid.
    fn parsed_threshold(&self) -> Option<f32> {
        let trimmed = self.threshold_text.trim();
        if trimmed.is_empty() {
            return None;
        }
        trimmed.parse::<f32>().ok().map(|v| v.clamp(0.0, 1.0))
    }

    /// Render a room's bound policy for display: resolve a policy id to its
    /// human name via the discovered policies; pass a name through unchanged;
    /// fall back to the raw value when policies haven't loaded or don't match.
    fn policy_label(&self, policy: &str) -> String {
        self.remote_policies
            .iter()
            .find(|p| p.policy_id == policy || p.name == policy)
            .map(|p| p.name.clone())
            .unwrap_or_else(|| policy.to_string())
    }

    /// The selected LOCAL room, if the selection lands in the local section.
    /// Remote rooms have no local detail panel.
    fn selected_room(&self) -> Option<&(String, RoomConfig)> {
        match self.selected_kind() {
            Some(Sel::Local(i)) => self.rooms.get(i),
            _ => None,
        }
    }
}

/// Where the flat room selection points: a local config room or a remote one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Sel {
    Local(usize),
    Remote(usize),
}

impl View for MainMenuView {
    fn captures_input(&self) -> bool {
        self.task_input_active
    }

    fn on_enter(&mut self) -> Vec<ViewAction> {
        // Pull remote rooms (Remote section) AND policies (to render a room's
        // bound policy by name instead of its raw id).
        vec![
            ViewAction::Fetch(FetchRequest::Rooms {
                orchestrator: self.orchestrator.clone(),
            }),
            ViewAction::Fetch(FetchRequest::Policies {
                orchestrator: self.orchestrator.clone(),
                tag: None,
            }),
        ]
    }

    fn update(&mut self, app_event: &AppEvent) -> Option<ViewAction> {
        if let AppEvent::Data(DataEvent::RoomsLoaded {
            orchestrator,
            rooms,
        }) = app_event
            && *orchestrator == self.orchestrator
        {
            self.remote_rooms = rooms.clone();
            self.list_state.set_count(self.shown_count());
            return None;
        }
        if let AppEvent::Data(DataEvent::PoliciesLoaded {
            orchestrator,
            policies,
        }) = app_event
            && *orchestrator == self.orchestrator
        {
            self.remote_policies = policies.clone();
            return None;
        }
        // Surface fetch/submit failures instead of silently swallowing them —
        // an empty remote list or a reset-to-list after submit otherwise looks
        // like nothing happened.
        if let AppEvent::Data(DataEvent::FetchError { context, error }) = app_event {
            return Some(ViewAction::SetStatus(
                format!("{context} failed: {error}"),
                super::StatusLevel::Error,
            ));
        }
        let AppEvent::Terminal(event) = app_event else {
            return None;
        };

        // Task input mode
        if self.task_input_active {
            return self.update_task_input(event);
        }

        // Detail mode
        if self.detail_visible {
            if event::is_escape(event) || event::is_key(event, 'q') {
                self.detail_visible = false;
                return None;
            }
            if event::is_up(event) {
                self.list_state.up();
            }
            if event::is_down(event) {
                self.list_state.down();
            }
            if event::is_enter(event) && self.shown_count() > 0 {
                self.detail_visible = false;
                self.task_input_active = true;
                self.task_text.clear();
            }
            return None;
        }

        // Normal mode
        if event::is_key(event, 'q') || event::is_escape(event) {
            return Some(ViewAction::Quit);
        }
        // `n` opens room admin (create / delete) — folded in from the old
        // Rooms tab so the top bar stays a single Room tab.
        if event::is_key(event, 'n') {
            return Some(ViewAction::Push(super::ViewId::Rooms));
        }
        if event::is_up(event) {
            self.list_state.up();
        }
        if event::is_down(event) {
            self.list_state.down();
        }
        // Enter = start deliberation
        if event::is_enter(event) && self.shown_count() > 0 {
            self.task_input_active = true;
            self.task_text.clear();
            return None;
        }
        // d = detail panel
        if event::is_key(event, 'd') && self.selected_room().is_some() {
            self.detail_visible = true;
            return None;
        }
        None
    }

    fn draw(&mut self, frame: &mut Frame, area: Rect) {
        // Compute dynamic input height: wrap text to available width,
        // capped so title (2), key hints (1), and at least 1 table row remain visible.
        let input_height = if self.task_input_active {
            let inner_width = area.width.saturating_sub(2).max(1) as usize; // minus borders
            let char_count = self.task_text.chars().count().max(1);
            let wrapped_lines = char_count.div_ceil(inner_width);
            let reserved = 2 + 1 + 1; // title + key hints + min 1 table row
            let max_lines = area.height.saturating_sub(reserved + 2) as usize; // -2 for own borders
            let max_lines = max_lines.max(1); // always show at least 1 line
            (wrapped_lines.min(max_lines) as u16) + 2
        } else {
            0
        };

        // Single-line threshold input below the task input. Visible
        // whenever the task input is active.
        let threshold_height = if self.task_input_active { 3 } else { 0 };

        let chunks = Layout::vertical([
            Constraint::Length(2),                // title
            Constraint::Length(input_height),     // task input
            Constraint::Length(threshold_height), // threshold input
            Constraint::Min(0),                   // rooms table
            Constraint::Length(1),                // key hints
        ])
        .split(area);

        // Title
        let title = Paragraph::new(Line::from(vec![
            Span::styled(
                " NSED ",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw("— Multi-Agent Deliberation"),
        ]))
        .block(
            Block::default()
                .borders(Borders::BOTTOM)
                .border_type(BorderType::Plain),
        );
        frame.render_widget(title, chunks[0]);

        // Task input
        if self.task_input_active {
            let room_name = self
                .rooms
                .get(self.list_state.selected)
                .map(|(n, _)| n.as_str())
                .unwrap_or("?");
            let task_focused = !self.threshold_input_active;
            let task_style = if task_focused {
                Style::default().fg(Color::Yellow)
            } else {
                Style::default().fg(Color::DarkGray)
            };
            let task_border = if task_focused {
                Style::default().fg(Color::Yellow)
            } else {
                Style::default().fg(Color::DarkGray)
            };
            let input = Paragraph::new(self.task_text.as_str())
                .style(task_style)
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_style(task_border)
                        .title(format!(" Task for '{room_name}' (Tab → threshold) ")),
                )
                .wrap(Wrap { trim: false });
            frame.render_widget(input, chunks[1]);

            // Threshold input (always shown while in task mode).
            let threshold_focused = self.threshold_input_active;
            let threshold_style = if threshold_focused {
                Style::default().fg(Color::Yellow)
            } else {
                Style::default().fg(Color::DarkGray)
            };
            let threshold_border = if threshold_focused {
                Style::default().fg(Color::Yellow)
            } else {
                Style::default().fg(Color::DarkGray)
            };
            let threshold_paragraph = Paragraph::new(self.threshold_text.as_str())
                .style(threshold_style)
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_style(threshold_border)
                        .title(" Convergence threshold (0.0–1.0, default 0.7) "),
                );
            frame.render_widget(threshold_paragraph, chunks[2]);
        }

        // Rooms: Local (nsed.yaml) section above Remote (orchestrator).
        if self.is_empty() {
            render_error(
                frame,
                chunks[3],
                "No rooms yet — create one in Settings → Rooms (set a policy to submit here)",
            );
        } else {
            let local_sel = match self.selected_kind() {
                Some(Sel::Local(i)) => Some(i),
                _ => None,
            };
            let remote_sel = match self.selected_kind() {
                Some(Sel::Remote(i)) => Some(i),
                _ => None,
            };
            // Split vertically only when both sections have content.
            let (local_area, remote_area) = if self.rooms.is_empty() {
                (None, Some(chunks[3]))
            } else if self.remote_rooms.is_empty() {
                (Some(chunks[3]), None)
            } else {
                let local_h = ((self.rooms.len() as u16 + 3).min(chunks[3].height / 2)).max(4);
                let split = Layout::vertical([Constraint::Length(local_h), Constraint::Min(0)])
                    .split(chunks[3]);
                (Some(split[0]), Some(split[1]))
            };
            if let Some(la) = local_area {
                // Detail panel only applies to a selected local room.
                if self.detail_visible && local_sel.is_some() {
                    let h = Layout::horizontal([
                        Constraint::Percentage(45),
                        Constraint::Percentage(55),
                    ])
                    .split(la);
                    self.draw_table(frame, h[0], local_sel);
                    if let Some((name, config)) = self.selected_room() {
                        draw_room_detail(frame, h[1], name, config, self.default_room.as_deref());
                    }
                } else {
                    self.draw_table(frame, la, local_sel);
                }
            }
            if let Some(ra) = remote_area {
                self.draw_remote_table(frame, ra, remote_sel);
            }
        }

        // Key hints
        let hints = if self.task_input_active {
            vec![
                ("Enter", "Start"),
                ("Tab", "Task↔Threshold"),
                ("Esc", "Cancel"),
            ]
        } else if self.detail_visible {
            vec![
                ("↑↓", "Navigate"),
                ("Enter", "Deliberate"),
                ("Esc", "Close"),
            ]
        } else {
            vec![
                ("↑↓", "Navigate"),
                ("Enter", "Deliberate"),
                ("d", "Detail"),
                ("1-5/Tab", "Switch tab"),
                ("q", "Quit"),
            ]
        };
        render_key_hints(frame, chunks[4], &hints);
    }
}

impl MainMenuView {
    /// Render the remote (orchestrator) rooms table. A room with no policy
    /// shows `— (no policy)` so the operator knows it can't be submitted to
    /// until one is set. `selected_row` highlights the row when the union
    /// selection points into this section.
    fn draw_remote_table(&self, frame: &mut Frame, area: Rect, selected_row: Option<usize>) {
        let header = Row::new(vec![
            Cell::from("Room"),
            Cell::from("Policy"),
            Cell::from("Tags"),
            Cell::from("Fill"),
        ])
        .style(
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        );
        let visible = area.height.saturating_sub(3) as usize;
        let rows: Vec<Row> = self
            .remote_rooms
            .iter()
            .enumerate()
            .take(visible.max(1))
            .map(|(i, room)| {
                let style = if Some(i) == selected_row {
                    Style::default().add_modifier(Modifier::REVERSED)
                } else {
                    Style::default()
                };
                let policy = match room.policy.as_deref() {
                    Some(p) => self.policy_label(p),
                    None => "— (no policy)".to_string(),
                };
                Row::new(vec![
                    Cell::from(truncate(&room.id, 24)),
                    Cell::from(truncate(&policy, 20)),
                    Cell::from(truncate(&room.tags.join(", "), 26)),
                    fill_cell(room.eligible_agent_count, room.desired_agents),
                ])
                .style(style)
            })
            .collect();
        let table = Table::new(
            rows,
            [
                Constraint::Length(26),
                Constraint::Length(22),
                Constraint::Min(18),
                Constraint::Length(8),
            ],
        )
        .header(header)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .title(format!(
                    " Remote (orchestrator) ({}) ",
                    self.remote_rooms.len()
                )),
        );
        frame.render_widget(table, area);
    }

    fn update_task_input(&mut self, event: &crossterm::event::Event) -> Option<ViewAction> {
        if event::is_escape(event) {
            self.task_input_active = false;
            self.threshold_input_active = false;
            return None;
        }
        // Tab toggles focus between the task field and the threshold
        // field. Threshold field auto-selects all on focus so retyping
        // is easy (clear is achieved with Backspace once focused).
        if event::is_tab(event) {
            self.threshold_input_active = !self.threshold_input_active;
            return None;
        }
        if event::is_enter(event) && !self.task_text.is_empty() {
            self.task_input_active = false;
            self.threshold_input_active = false;
            let effort_override = self.parsed_threshold();

            return match self.selected_kind() {
                // Remote room: submit using the policy bound to it (resolved
                // server-side at dispatch).
                Some(Sel::Remote(i)) => {
                    let room = &self.remote_rooms[i];
                    let Some(policy) = room.policy.clone() else {
                        return Some(ViewAction::SetStatus(
                            format!(
                                "Room '{}' has no policy bound — set one when creating it \
                                 (Settings → Rooms → New room → policy)",
                                room.id
                            ),
                            super::StatusLevel::Error,
                        ));
                    };
                    Some(ViewAction::LaunchJob {
                        orchestrator: self.orchestrator.clone(),
                        task: self.task_text.clone(),
                        room: Some(room.id.clone()),
                        policy: Some(policy),
                        effort_override,
                    })
                }
                // Local room: submit via the orchestrator pinned in nsed.yaml.
                Some(Sel::Local(i)) => {
                    let (room_name, room_config) = &self.rooms[i];
                    let orchestrator = match &room_config.orchestrator {
                        Some(o) => o.clone(),
                        None => {
                            return Some(ViewAction::SetStatus(
                                format!("Room '{room_name}' has no orchestrator configured"),
                                super::StatusLevel::Error,
                            ));
                        }
                    };
                    Some(ViewAction::LaunchJob {
                        orchestrator,
                        task: self.task_text.clone(),
                        room: Some(room_name.clone()),
                        policy: None,
                        effort_override,
                    })
                }
                None => Some(ViewAction::SetStatus(
                    "No rooms available".into(),
                    super::StatusLevel::Error,
                )),
            };
        }
        if let crossterm::event::Event::Key(key) = event
            && key.kind == crossterm::event::KeyEventKind::Press
        {
            // Route printable / backspace keystrokes into whichever
            // field is currently focused.
            let target: &mut String = if self.threshold_input_active {
                &mut self.threshold_text
            } else {
                &mut self.task_text
            };
            match key.code {
                crossterm::event::KeyCode::Char(c) => {
                    target.push(c);
                    return None;
                }
                crossterm::event::KeyCode::Backspace => {
                    target.pop();
                    return None;
                }
                _ => {}
            }
        }
        None
    }

    /// Render the local (nsed.yaml) room table. `selected_row` is the row to
    /// highlight when the union selection points into this section.
    fn draw_table(&self, frame: &mut Frame, area: Rect, selected_row: Option<usize>) {
        let header = Row::new(vec![
            Cell::from(""),
            Cell::from("Room"),
            Cell::from("Policy"),
            Cell::from("Orchestrator"),
        ])
        .style(
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        );

        let visible_height = area.height.saturating_sub(3) as usize;
        let rows: Vec<Row> = self
            .rooms
            .iter()
            .enumerate()
            .take(visible_height.max(1))
            .map(|(i, (name, config))| {
                let style = if Some(i) == selected_row {
                    Style::default().add_modifier(Modifier::REVERSED)
                } else {
                    Style::default()
                };

                let is_default = self.default_room.as_deref() == Some(name.as_str());
                let marker = if is_default { "" } else { " " };

                Row::new(vec![
                    Cell::from(Span::styled(marker, Style::default().fg(Color::Yellow))),
                    Cell::from(name.as_str()),
                    Cell::from(truncate(&self.policy_label(&config.policy), 25)),
                    Cell::from(config.orchestrator.as_deref().unwrap_or("default")),
                ])
                .style(style)
            })
            .collect();

        let table = Table::new(
            rows,
            [
                Constraint::Length(3),
                Constraint::Length(20),
                Constraint::Length(27),
                Constraint::Min(20),
            ],
        )
        .header(header)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(format!(" Local (nsed.yaml) ({}) ", self.rooms.len())),
        );

        frame.render_widget(table, area);
    }
}

/// Render a detail panel for a single room.
fn draw_room_detail(
    frame: &mut Frame,
    area: Rect,
    name: &str,
    config: &RoomConfig,
    default_room: Option<&str>,
) {
    let is_default = default_room == Some(name);

    let mut lines = vec![
        Line::from(vec![
            Span::styled("Policy: ", Style::default().fg(Color::Cyan)),
            Span::raw(&config.policy),
        ]),
        Line::from(vec![
            Span::styled("Orchestrator: ", Style::default().fg(Color::Cyan)),
            Span::raw(config.orchestrator.as_deref().unwrap_or("(default)")),
        ]),
        Line::from(vec![
            Span::styled("Default: ", Style::default().fg(Color::Cyan)),
            if is_default {
                Span::styled("★ Yes", Style::default().fg(Color::Yellow))
            } else {
                Span::raw("No")
            },
        ]),
    ];

    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "Press Enter to start a deliberation",
        Style::default().fg(Color::DarkGray),
    )));

    let detail = Paragraph::new(lines)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(format!(" Room: {name} ")),
        )
        .wrap(Wrap { trim: false });

    frame.render_widget(detail, area);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::tui::views::StatusLevel;
    use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};

    fn make_key(code: KeyCode) -> AppEvent {
        AppEvent::Terminal(Event::Key(KeyEvent {
            code,
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        }))
    }

    fn sample_rooms() -> HashMap<String, RoomConfig> {
        let mut map = HashMap::new();
        map.insert(
            "local".into(),
            RoomConfig {
                policy: "review".into(),
                orchestrator: Some("local-orch".into()),
            },
        );
        map.insert(
            "remote".into(),
            RoomConfig {
                policy: "brainstorm".into(),
                orchestrator: Some("peeramid".into()),
            },
        );
        map
    }

    #[test]
    fn new_sorts_by_name() {
        let view = MainMenuView::new(sample_rooms(), Some("local".into()), "orch".into());
        assert_eq!(view.rooms[0].0, "local");
        assert_eq!(view.rooms[1].0, "remote");
    }

    #[test]
    fn q_quits() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        let action = view.update(&make_key(KeyCode::Char('q')));
        assert_eq!(action, Some(ViewAction::Quit));
    }

    #[test]
    fn escape_quits() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        let action = view.update(&make_key(KeyCode::Esc));
        assert_eq!(action, Some(ViewAction::Quit));
    }

    #[test]
    fn enter_activates_task_input() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        let action = view.update(&make_key(KeyCode::Enter));
        assert!(action.is_none());
        assert!(view.task_input_active);
    }

    #[test]
    fn d_opens_detail_panel() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        let action = view.update(&make_key(KeyCode::Char('d')));
        assert!(action.is_none());
        assert!(view.detail_visible);
    }

    #[test]
    fn tab_in_list_mode_is_ignored_by_view() {
        // The shell owns Tab (tab switching); the view must not consume it.
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        let action = view.update(&make_key(KeyCode::Tab));
        assert!(action.is_none());
    }

    #[test]
    fn captures_input_only_while_task_input_active() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        assert!(!view.captures_input());
        view.task_input_active = true;
        assert!(view.captures_input());
    }

    #[test]
    fn escape_in_detail_closes_detail() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        view.detail_visible = true;

        let action = view.update(&make_key(KeyCode::Esc));
        assert!(action.is_none()); // Does NOT quit
        assert!(!view.detail_visible);
    }

    #[test]
    fn enter_in_detail_opens_task_input() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        view.detail_visible = true;

        let action = view.update(&make_key(KeyCode::Enter));
        assert!(action.is_none());
        assert!(view.task_input_active);
        assert!(!view.detail_visible);
    }

    #[test]
    fn task_input_enter_launches_job() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        view.task_input_active = true;
        view.task_text = "Review my code".into();

        let action = view.update(&make_key(KeyCode::Enter));
        assert_eq!(
            action,
            Some(ViewAction::LaunchJob {
                orchestrator: "local-orch".into(),
                task: "Review my code".into(),
                room: Some("local".into()),
                policy: None,
                effort_override: Some(0.7),
            })
        );
        assert!(!view.task_input_active);
    }

    #[test]
    fn task_input_threshold_parsed_into_effort_override() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        view.task_input_active = true;
        view.task_text = "spicy debate".into();
        view.threshold_text = "0.42".into();

        let action = view.update(&make_key(KeyCode::Enter));
        match action {
            Some(ViewAction::LaunchJob {
                effort_override, ..
            }) => assert_eq!(effort_override, Some(0.42)),
            other => panic!("expected LaunchJob, got {other:?}"),
        }
    }

    #[test]
    fn threshold_parse_empty_yields_none() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        view.threshold_text.clear();
        assert!(view.parsed_threshold().is_none());
    }

    #[test]
    fn threshold_parse_clamps_above_one() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        view.threshold_text = "1.5".into();
        assert_eq!(view.parsed_threshold(), Some(1.0));
    }

    #[test]
    fn threshold_parse_clamps_negative() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        view.threshold_text = "-0.5".into();
        assert_eq!(view.parsed_threshold(), Some(0.0));
    }

    #[test]
    fn tab_in_task_input_toggles_threshold_focus() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        view.task_input_active = true;
        assert!(!view.threshold_input_active);
        view.update(&make_key(KeyCode::Tab));
        assert!(view.threshold_input_active);
        view.update(&make_key(KeyCode::Tab));
        assert!(!view.threshold_input_active);
    }

    #[test]
    fn keystrokes_in_threshold_focus_edit_threshold_text() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        view.task_input_active = true;
        view.threshold_input_active = true;
        view.threshold_text.clear();
        view.update(&make_key(KeyCode::Char('0')));
        view.update(&make_key(KeyCode::Char('.')));
        view.update(&make_key(KeyCode::Char('9')));
        assert_eq!(view.threshold_text, "0.9");
        // The task field shouldn't have been touched.
        assert_eq!(view.task_text, "");
    }

    #[test]
    fn task_input_empty_enter_ignored() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        view.task_input_active = true;
        view.task_text.clear();

        let action = view.update(&make_key(KeyCode::Enter));
        assert!(action.is_none());
    }

    #[test]
    fn task_input_escape_cancels() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        view.task_input_active = true;
        view.task_text = "some text".into();

        let action = view.update(&make_key(KeyCode::Esc));
        assert!(action.is_none());
        assert!(!view.task_input_active);
    }

    #[test]
    fn task_input_no_orchestrator_returns_error() {
        let mut rooms = HashMap::new();
        rooms.insert(
            "no-orch".into(),
            RoomConfig {
                policy: "review".into(),
                orchestrator: None,
            },
        );
        let mut view = MainMenuView::new(rooms, None, "orch".into());
        view.task_input_active = true;
        view.task_text = "do something".into();

        let action = view.update(&make_key(KeyCode::Enter));
        assert!(matches!(
            action,
            Some(ViewAction::SetStatus(msg, StatusLevel::Error))
            if msg.contains("no orchestrator")
        ));
    }

    #[test]
    fn empty_rooms_no_crash() {
        let view = MainMenuView::new(HashMap::new(), None, "orch".into());
        assert!(view.rooms.is_empty());
    }

    fn remote_room(id: &str, policy: Option<&str>) -> DiscoveredRoom {
        DiscoveredRoom {
            id: id.into(),
            tags: vec!["team".into()],
            visibility: "public".into(),
            eligible_agent_count: 2,
            eligible_agent_ids: vec!["a1".into(), "a2".into()],
            policy: policy.map(Into::into),
            desired_agents: None,
        }
    }

    #[test]
    fn is_empty_when_no_local_or_remote_rooms() {
        let view = MainMenuView::new(HashMap::new(), None, "orch".into());
        assert!(view.is_empty());
        // Local rooms alone make it non-empty.
        let view = MainMenuView::new(sample_rooms(), None, "orch".into());
        assert!(!view.is_empty());
    }

    #[test]
    fn on_enter_always_fetches_remote() {
        // Both config-free and local-config views fetch remote rooms AND
        // policies (the latter to resolve a room's policy id to its name).
        let mut view = MainMenuView::new(HashMap::new(), None, "orch".into());
        assert_eq!(
            view.on_enter(),
            vec![
                ViewAction::Fetch(FetchRequest::Rooms {
                    orchestrator: "orch".into(),
                }),
                ViewAction::Fetch(FetchRequest::Policies {
                    orchestrator: "orch".into(),
                    tag: None,
                }),
            ]
        );
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        assert_eq!(view.on_enter().len(), 2);
    }

    #[test]
    fn selection_spans_local_then_remote() {
        // 2 local (sample_rooms: local, remote) + 1 remote = 3 selectable.
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        view.update(&AppEvent::Data(DataEvent::RoomsLoaded {
            orchestrator: "orch".into(),
            rooms: vec![remote_room("rmt", Some("p"))],
        }));
        assert_eq!(view.shown_count(), 3);
        assert_eq!(view.selected_kind(), Some(Sel::Local(0)));
        view.list_state.selected = 2;
        assert_eq!(view.selected_kind(), Some(Sel::Remote(0)));
    }

    #[test]
    fn fetch_error_surfaces_as_status() {
        let mut view = MainMenuView::new(HashMap::new(), None, "orch".into());
        let action = view.update(&AppEvent::Data(DataEvent::FetchError {
            context: "rooms".into(),
            error: "boom".into(),
        }));
        match action {
            Some(ViewAction::SetStatus(msg, super::super::StatusLevel::Error)) => {
                assert!(msg.contains("rooms") && msg.contains("boom"), "{msg}");
            }
            other => panic!("expected SetStatus error, got {other:?}"),
        }
    }

    #[test]
    fn policy_label_resolves_id_to_name() {
        let mut view = MainMenuView::new(HashMap::new(), None, "orch".into());
        view.update(&AppEvent::Data(DataEvent::PoliciesLoaded {
            orchestrator: "orch".into(),
            policies: vec![PolicyInfo {
                policy_id: "e032deadbeef".into(),
                name: "noosphera:0v1".into(),
                tags: vec![],
                max_rounds: 3,
                effort: 0.7,
                is_role_based: false,
            }],
        }));
        // id resolves to name; a name passes through; unknown falls back to raw.
        assert_eq!(view.policy_label("e032deadbeef"), "noosphera:0v1");
        assert_eq!(view.policy_label("noosphera:0v1"), "noosphera:0v1");
        assert_eq!(view.policy_label("nope"), "nope");
    }

    #[test]
    fn rooms_loaded_populates_remote_rooms() {
        let mut view = MainMenuView::new(HashMap::new(), None, "orch".into());
        let action = view.update(&AppEvent::Data(DataEvent::RoomsLoaded {
            orchestrator: "orch".into(),
            rooms: vec![remote_room("alpha", Some("review"))],
        }));
        assert!(action.is_none());
        assert_eq!(view.remote_rooms.len(), 1);
        assert_eq!(view.list_state.count, 1);
    }

    #[test]
    fn rooms_loaded_for_other_orchestrator_ignored() {
        let mut view = MainMenuView::new(HashMap::new(), None, "orch".into());
        view.update(&AppEvent::Data(DataEvent::RoomsLoaded {
            orchestrator: "elsewhere".into(),
            rooms: vec![remote_room("alpha", Some("review"))],
        }));
        assert!(view.remote_rooms.is_empty());
    }

    #[test]
    fn config_free_submit_launches_with_bound_policy() {
        let mut view = MainMenuView::new(HashMap::new(), None, "peeramid".into());
        view.remote_rooms = vec![remote_room("alpha", Some("review"))];
        view.list_state.set_count(1);
        view.task_input_active = true;
        view.task_text = "ship it".into();

        let action = view.update(&make_key(KeyCode::Enter));
        assert_eq!(
            action,
            Some(ViewAction::LaunchJob {
                orchestrator: "peeramid".into(),
                task: "ship it".into(),
                room: Some("alpha".into()),
                policy: Some("review".into()),
                effort_override: Some(0.7),
            })
        );
    }

    #[test]
    fn config_free_submit_without_policy_errors() {
        let mut view = MainMenuView::new(HashMap::new(), None, "peeramid".into());
        view.remote_rooms = vec![remote_room("alpha", None)];
        view.list_state.set_count(1);
        view.task_input_active = true;
        view.task_text = "ship it".into();

        let action = view.update(&make_key(KeyCode::Enter));
        assert!(matches!(
            action,
            Some(ViewAction::SetStatus(msg, StatusLevel::Error))
            if msg.contains("no policy bound")
        ));
    }

    #[test]
    fn config_free_submit_no_rooms_errors() {
        let mut view = MainMenuView::new(HashMap::new(), None, "peeramid".into());
        view.task_input_active = true;
        view.task_text = "ship it".into();

        let action = view.update(&make_key(KeyCode::Enter));
        assert!(matches!(
            action,
            Some(ViewAction::SetStatus(msg, StatusLevel::Error))
            if msg.contains("No rooms available")
        ));
    }

    #[test]
    fn task_input_typing_appends_characters() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        view.task_input_active = true;

        view.update(&make_key(KeyCode::Char('H')));
        view.update(&make_key(KeyCode::Char('i')));
        assert_eq!(view.task_text, "Hi");
    }

    #[test]
    fn task_input_backspace_removes_last_char() {
        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        view.task_input_active = true;
        view.task_text = "Hello".into();

        view.update(&make_key(KeyCode::Backspace));
        assert_eq!(view.task_text, "Hell");
    }

    /// Long text wraps without panic: dynamic layout accepts multi-line input.
    #[test]
    fn task_input_draw_does_not_panic_on_long_text() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let mut view = MainMenuView::new(sample_rooms(), None, "orch".into());
        view.task_input_active = true;
        // 200 chars on an 80-col terminal → 3 wrapped lines → height 5 (3 + 2 borders)
        view.task_text = "a".repeat(200);

        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|frame| {
                let area = frame.area();
                view.draw(frame, area);
            })
            .unwrap();

        // Verify the input area got more than the old fixed 3 rows.
        // With 200 chars / 78 inner width ≈ 3 lines → height = 5 (3 lines + 2 borders).
        // The test passes if draw() doesn't panic — the layout accepted dynamic height.
    }
}