polyc-tui 2026.8.3

Operator cockpit TUI (pc-tui) for the polychrome control plane: fleet, transcript, approvals, and tools panes.
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
//! Questions pane: the `ask_question` inbox — pending clarifying questions
//! surfaced across every conversation in the fleet (`#1660`).
//!
//! The question-pause SIBLING of [`crate::components::approvals::Approvals`],
//! not a reuse of it: `ask_question` is a decision the user makes ("which of
//! these options"), not a danger/permission gate, so it has its own inbox
//! with its own interaction shape — pick one of 2-4 numbered options, or
//! decline — rather than approve/deny/reason.
//!
//! Loaded via `QuestionService.ListPending` and submitted via
//! `QuestionService.Respond` (both `polyc_rpc_client::QuestionDialer`) — no
//! forensics questions projection exists (a follow-up); `ListPending` is
//! already a real, self-sufficient recovery read, mirroring
//! `ApprovalService.ListPending`'s own role for approvals.

use color_eyre::Result;
use ratatui::Frame;
use ratatui::crossterm::event::{KeyCode, KeyEvent};
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, List, ListItem, ListState, Paragraph, Wrap};

use super::Component;
use crate::action::{Action, Pane, QuestionDecision};

/// Maximum options a question offers (mirrors `polyc_tools::ask_question::MAX_OPTIONS`).
/// Duplicated as a plain literal — the TUI doesn't depend on `polyc-tools` for
/// one constant it only needs to bound its own number-key mapping (`'1'..='4'`).
const MAX_OPTIONS: usize = 4;

/// One option a pending question offers, as rendered in the pane.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct QuestionOptionView {
    /// A few words naming this option.
    pub label: String,
    /// The one-sentence consequence of picking this option.
    pub description: String,
    /// Whether this is the model's recommendation (at most one per question).
    pub recommended: bool,
}

/// A pending (or just-decided, this session) `ask_question` question as
/// rendered in the pane. Field names mirror the wire/rpc-client surface:
/// `call_id`/`index` are the question's identity, `header`/`question`/
/// `options` come from `PendingQuestionPrompt`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct QuestionView {
    /// The conversation this question belongs to (required by `QuestionService.Respond`).
    pub conversation_id: String,
    /// Turn that emitted this question occurrence (`#2523`).
    pub turn_id: String,
    /// The `ask_question` call id this question came from.
    pub call_id: String,
    /// This question's position within its call's `questions` array.
    pub index: u32,
    /// The short label (fits a chat-surface button-row heading).
    pub header: String,
    /// The one-sentence question to ask.
    pub question: String,
    /// 2-4 mutually exclusive options.
    pub options: Vec<QuestionOptionView>,
    /// The raw `ask_question` call's full arguments JSON — carried through
    /// but not rendered; kept for parity with the wire type.
    pub args_json: String,
    /// Short-lived signed capability required by `QuestionService.Respond`.
    /// Empty once `response` is populated (nothing left to resolve).
    pub answer_token: String,
    /// The decision recorded THIS session, if the operator has answered it.
    /// `QuestionService.ListPending` only ever returns still-outstanding
    /// questions, so a decided item is never re-confirmed by a later
    /// refresh — it simply stops being replaced, exactly like `Approvals`
    /// keeps a decided item via its own upsert-never-remove shape.
    pub response: Option<QuestionOutcomeView>,
}

/// A decision recorded against a [`QuestionView`], for local display —
/// mirrors `polyc_crypto::question`'s own `ANSWERED_STATE`/`DECLINED_STATE`
/// as plain strings (the TUI doesn't depend on `polyc-crypto` for one
/// constant pair it only needs to render, mirroring
/// `polyc_proto::tool_display`'s own layer-crossing duplication).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct QuestionOutcomeView {
    /// One of `"answered"`/`"declined"` — a cockpit decision is a human
    /// choosing right now, so it is never `"auto_resolved"` (only the
    /// control plane's own timeout sweep produces that state).
    pub state: String,
    /// The chosen option's label; empty for a decline.
    pub selected_label: String,
}

/// The questions component.
#[derive(Default)]
pub(crate) struct Questions {
    /// The most recently selected conversation, shown in the title for
    /// context. The inbox itself is fleet-wide and is NOT filtered to this
    /// id — mirrors `Approvals::conversation_id`'s own role.
    pub conversation_id: Option<String>,
    /// Pending + this-session-decided questions, newest first.
    pub items: Vec<QuestionView>,
    /// Index of the highlighted question, if any.
    pub selected: Option<usize>,
    /// Whether this pane currently has keyboard focus.
    focused: bool,
    /// The last error surfaced while interacting with the inbox, if any.
    last_error: Option<String>,
}

impl Questions {
    /// Insert (or replace) a question, keeping the newest-first ordering and
    /// deduplicating on `(conversation_id, turn_id, call_id, index)`. Returns the
    /// index it landed at. Mirrors `Approvals::upsert`.
    fn upsert(&mut self, view: QuestionView) -> usize {
        if let Some(idx) = self.index_of(
            &view.conversation_id,
            &view.turn_id,
            &view.call_id,
            view.index,
        ) {
            self.items[idx] = view;
            idx
        } else {
            self.items.insert(0, view);
            // Keep the prior selection pointing at the same logical item by
            // nudging it down one slot (a new head shifts everything).
            if let Some(sel) = self.selected.as_mut() {
                *sel += 1;
            }
            0
        }
    }

    /// Find an item's index by its identity.
    fn index_of(
        &self,
        conversation_id: &str,
        turn_id: &str,
        call_id: &str,
        index: u32,
    ) -> Option<usize> {
        self.items.iter().position(|v| {
            v.conversation_id == conversation_id
                && v.turn_id == turn_id
                && v.call_id == call_id
                && v.index == index
        })
    }

    /// The number of questions still awaiting an answer.
    #[must_use]
    pub(crate) fn pending_count(&self) -> usize {
        self.items.iter().filter(|v| v.response.is_none()).count()
    }

    /// Move the selection by `delta`, clamped to the item range.
    fn move_selection(&mut self, delta: isize) {
        self.selected = super::step_selection(self.selected, self.items.len(), delta);
    }

    /// Build the [`QuestionDecision`] for the highlighted item's option
    /// `option_index`, if it is still pending and the index is in range.
    /// `None` (decline) is always in range.
    fn decision_for_selected(&self, selected_index: Option<u32>) -> Option<QuestionDecision> {
        let item = self.items.get(self.selected?)?;
        if item.response.is_some() {
            return None;
        }
        let selected_label = match selected_index {
            Some(i) => item.options.get(i as usize)?.label.clone(),
            None => String::new(),
        };
        Some(QuestionDecision {
            turn_id: item.turn_id.clone(),
            call_id: item.call_id.clone(),
            index: item.index,
            conversation_id: item.conversation_id.clone(),
            selected_index,
            selected_label,
            answer_token: item.answer_token.clone(),
        })
    }

    /// React to a key while focused. Returns a follow-up action (the
    /// decision to submit) when one is produced.
    fn on_key(&mut self, key: KeyEvent) -> Option<Action> {
        match key.code {
            KeyCode::Char('j') | KeyCode::Down => {
                self.move_selection(1);
                None
            }
            KeyCode::Char('k') | KeyCode::Up => {
                self.move_selection(-1);
                None
            }
            // Pick an option by its 1-based number (matches the numbered
            // list the detail pane renders).
            KeyCode::Char(c @ '1'..='9') => {
                let n = c.to_digit(10).unwrap_or(0);
                if n == 0 || n as usize > MAX_OPTIONS {
                    return None;
                }
                self.emit_decision(Some(n - 1))
            }
            // Decline: "use your own judgment" — no option chosen.
            KeyCode::Char('d') => self.emit_decision(None),
            _ => None,
        }
    }

    /// Produce an [`Action::QuestionDecide`] for the current selection and
    /// option, or set a transient error if it cannot be decided.
    fn emit_decision(&mut self, selected_index: Option<u32>) -> Option<Action> {
        if let Some(decision) = self.decision_for_selected(selected_index) {
            self.last_error = None;
            Some(Action::QuestionDecide(decision))
        } else {
            self.last_error = Some(
                "no pending question selected (already answered, or no such option)".to_owned(),
            );
            None
        }
    }
}

impl Component for Questions {
    fn controls(&self) -> Vec<(&'static str, &'static str)> {
        vec![("↑↓/jk", "move"), ("1-4", "pick option"), ("d", "decline")]
    }

    fn handle(&mut self, action: &Action) -> Option<Action> {
        match action {
            // Focus tracking: the loop fans every action to every pane, so
            // the pane must self-gate key handling on the active pane.
            Action::Nav(pane) => {
                self.focused = *pane == Pane::Questions;
                None
            }
            // Track the selected conversation purely for the title; the
            // inbox is intentionally fleet-wide.
            Action::Select(conversation_id) => {
                self.conversation_id = Some(conversation_id.clone());
                None
            }
            // A turn paused on `ask_question` awaiting an answer.
            Action::QuestionPending(view) => {
                let idx = self.upsert(view.clone());
                if self.selected.is_none() {
                    self.selected = Some(idx);
                }
                None
            }
            // The control plane persisted a submitted answer.
            Action::QuestionSubmitted {
                call_id,
                index,
                persisted,
                outcome,
            } => {
                if let Some(idx) = self.items.iter().position(|v| {
                    &v.call_id == call_id && v.index == *index && v.response.is_none()
                }) {
                    if *persisted {
                        if let Some(outcome) = outcome {
                            self.items[idx].response = Some(outcome.clone());
                        }
                        self.last_error = None;
                    } else {
                        self.last_error = Some(format!(
                            "control plane did not persist answer for {call_id}#{index} (already answered or unknown)"
                        ));
                    }
                }
                None
            }
            Action::Error(msg) => {
                self.last_error = Some(msg.clone());
                None
            }
            Action::Key(key) if self.focused => self.on_key(*key),
            _ => None,
        }
    }

    #[allow(clippy::too_many_lines)] // one cohesive ratatui draw: list + detail, mirrors Approvals::draw
    fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> {
        let pending = self.pending_count();
        let title = self.conversation_id.as_ref().map_or_else(
            || format!(" questions — {pending} pending "),
            |id| format!(" questions — {pending} pending (sel conv {id}) "),
        );

        let outer = Block::default().title(title).borders(Borders::ALL);
        let inner = outer.inner(area);
        frame.render_widget(outer, area);

        if self.items.is_empty() {
            let empty = Paragraph::new("no questions — the inbox is clear")
                .style(Style::default().fg(Color::DarkGray));
            frame.render_widget(empty, inner);
            return Ok(());
        }

        // Left: the inbox list. Right: the selected question's full text,
        // numbered options, and decision controls.
        let cols = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Percentage(40), Constraint::Percentage(60)])
            .split(inner);

        // --- list ---
        let list_items: Vec<ListItem> = self
            .items
            .iter()
            .map(|v| {
                let (marker, marker_style) = match &v.response {
                    None => ("", Style::default().fg(Color::Yellow)),
                    Some(_) => ("", Style::default().fg(Color::Green)),
                };
                ListItem::new(Line::from(vec![
                    Span::styled(marker, marker_style),
                    Span::styled(
                        v.header.clone(),
                        Style::default().add_modifier(Modifier::BOLD),
                    ),
                    Span::raw("  "),
                    Span::styled(
                        short(&v.conversation_id),
                        Style::default().fg(Color::DarkGray),
                    ),
                ]))
            })
            .collect();

        let list = List::new(list_items)
            .block(Block::default().borders(Borders::RIGHT))
            .highlight_style(
                Style::default()
                    .bg(Color::Blue)
                    .add_modifier(Modifier::BOLD),
            )
            .highlight_symbol("");
        let mut state = ListState::default();
        state.select(self.selected);
        frame.render_stateful_widget(list, cols[0], &mut state);

        // --- detail ---
        let detail = self.selected.and_then(|s| self.items.get(s));
        let detail_text = detail.map_or_else(
            || Line::from("select a question").into(),
            |v| {
                let mut lines: Vec<Line> = vec![
                    Line::from(vec![Span::styled(
                        polyc_proto::question_prompt_text(&v.header, &v.question),
                        Style::default().add_modifier(Modifier::BOLD),
                    )]),
                    Line::from(vec![
                        Span::styled("call   ", Style::default().fg(Color::DarkGray)),
                        Span::raw(format!("{}#{}", v.call_id, v.index)),
                    ]),
                    Line::from(vec![
                        Span::styled("conv   ", Style::default().fg(Color::DarkGray)),
                        Span::raw(v.conversation_id.clone()),
                    ]),
                    Line::from(""),
                ];
                for (i, opt) in v.options.iter().enumerate() {
                    lines.push(Line::from(vec![
                        Span::styled(format!("[{}] ", i + 1), Style::default().fg(Color::Cyan)),
                        Span::raw(polyc_proto::question_option_line(
                            &opt.label,
                            &opt.description,
                            opt.recommended,
                        )),
                    ]));
                }
                lines.push(Line::from(""));
                if let Some(o) = &v.response {
                    let text = polyc_proto::question_answered_text(
                        &v.header,
                        &o.state,
                        "you",
                        &o.selected_label,
                    );
                    let style = if o.state == "declined" {
                        Style::default().fg(Color::Yellow)
                    } else {
                        Style::default().fg(Color::Green)
                    };
                    lines.push(Line::from(Span::styled(text, style)));
                } else {
                    lines.push(Line::from(Span::styled(
                        "[1-4] pick an option   [d] decline",
                        Style::default().fg(Color::Cyan),
                    )));
                }
                ratatui::text::Text::from(lines)
            },
        );
        let detail_widget = Paragraph::new(detail_text).wrap(Wrap { trim: false });

        if let Some(err) = &self.last_error {
            let rows = Layout::default()
                .direction(Direction::Vertical)
                .constraints([Constraint::Min(1), Constraint::Length(1)])
                .split(cols[1]);
            frame.render_widget(detail_widget, rows[0]);
            frame.render_widget(
                Paragraph::new(err.clone()).style(Style::default().fg(Color::Red)),
                rows[1],
            );
        } else {
            frame.render_widget(detail_widget, cols[1]);
        }

        Ok(())
    }
}

/// Abbreviate a long opaque id for compact display. Counts and slices by
/// `char`, not bytes, so a multi-byte `conversation_id` cannot panic on a
/// UTF-8 boundary. Mirrors `crate::components::approvals::short`.
fn short(s: &str) -> String {
    let count = s.chars().count();
    if count <= 12 {
        s.to_owned()
    } else {
        let head: String = s.chars().take(6).collect();
        let tail: String = s.chars().skip(count - 4).collect();
        format!("{head}{tail}")
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use super::*;
    use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    fn pending(conv: &str, call_id: &str) -> QuestionView {
        QuestionView {
            turn_id: "00000000-0000-0000-0000-000000000001".to_owned(),
            conversation_id: conv.to_owned(),
            call_id: call_id.to_owned(),
            index: 0,
            header: "Deploy target".to_owned(),
            question: "Which environment should this ship to?".to_owned(),
            options: vec![
                QuestionOptionView {
                    label: "Staging".to_owned(),
                    description: "Deploys to staging only.".to_owned(),
                    recommended: false,
                },
                QuestionOptionView {
                    label: "Production".to_owned(),
                    description: "Deploys straight to production.".to_owned(),
                    recommended: true,
                },
            ],
            args_json: r#"{"questions":[]}"#.to_owned(),
            answer_token: "tok".to_owned(),
            response: None,
        }
    }

    fn key(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)
    }

    #[test]
    fn pending_action_inserts_and_selects() {
        let mut pane = Questions::default();
        assert!(
            pane.handle(&Action::QuestionPending(pending("c1", "call-1")))
                .is_none()
        );
        assert_eq!(pane.items.len(), 1);
        assert_eq!(pane.selected, Some(0));
        assert_eq!(pane.pending_count(), 1);
    }

    #[test]
    fn pending_is_deduped_on_identity() {
        let mut pane = Questions::default();
        pane.handle(&Action::QuestionPending(pending("c1", "call-1")));
        pane.handle(&Action::QuestionPending(pending("c1", "call-1")));
        assert_eq!(pane.items.len(), 1);
    }

    #[test]
    fn newest_first_ordering_shifts_selection() {
        let mut pane = Questions::default();
        pane.handle(&Action::QuestionPending(pending("c1", "call-1")));
        pane.handle(&Action::QuestionPending(pending("c1", "call-2")));
        assert_eq!(pane.items[0].call_id, "call-2");
        assert_eq!(pane.selected, Some(1));
    }

    #[test]
    fn number_key_emits_decision_only_when_focused() {
        let mut pane = Questions::default();
        pane.handle(&Action::QuestionPending(pending("c1", "call-1")));
        // not focused: key is ignored
        assert!(pane.handle(&Action::Key(key('1'))).is_none());
        pane.handle(&Action::Nav(Pane::Questions));
        let out = pane.handle(&Action::Key(key('1')));
        match out {
            Some(Action::QuestionDecide(d)) => {
                assert_eq!(d.selected_index, Some(0));
                assert_eq!(d.call_id, "call-1");
                assert_eq!(d.conversation_id, "c1");
            }
            other => panic!("expected QuestionDecide, got {other:?}"),
        }
    }

    #[test]
    fn decline_key_emits_none_selection() {
        let mut pane = Questions::default();
        pane.handle(&Action::QuestionPending(pending("c1", "call-1")));
        pane.handle(&Action::Nav(Pane::Questions));
        let out = pane.handle(&Action::Key(key('d')));
        assert!(matches!(out, Some(Action::QuestionDecide(d)) if d.selected_index.is_none()));
    }

    #[test]
    fn out_of_range_option_number_is_rejected() {
        let mut pane = Questions::default();
        pane.handle(&Action::QuestionPending(pending("c1", "call-1")));
        pane.handle(&Action::Nav(Pane::Questions));
        // Only 2 options exist; '3' is out of range for this question.
        assert!(pane.handle(&Action::Key(key('3'))).is_none());
        assert!(pane.last_error.is_some());
    }

    #[test]
    fn cannot_decide_already_decided_item() {
        let mut pane = Questions::default();
        let mut decided = pending("c1", "call-1");
        decided.response = Some(QuestionOutcomeView {
            state: "answered".to_owned(),
            selected_label: "Production".to_owned(),
        });
        pane.handle(&Action::QuestionPending(decided));
        pane.handle(&Action::Nav(Pane::Questions));
        assert!(pane.handle(&Action::Key(key('1'))).is_none());
        assert!(pane.last_error.is_some());
        assert_eq!(pane.pending_count(), 0);
    }

    #[test]
    fn submitted_not_persisted_sets_error() {
        let mut pane = Questions::default();
        pane.handle(&Action::QuestionPending(pending("c1", "call-1")));
        pane.handle(&Action::QuestionSubmitted {
            call_id: "call-1".to_owned(),
            index: 0,
            persisted: false,
            outcome: None,
        });
        assert!(pane.last_error.is_some());
    }

    #[test]
    fn submitted_persisted_folds_outcome_and_leaves_pending_set() {
        let mut pane = Questions::default();
        pane.handle(&Action::QuestionPending(pending("c1", "call-1")));
        pane.handle(&Action::QuestionSubmitted {
            call_id: "call-1".to_owned(),
            index: 0,
            persisted: true,
            outcome: Some(QuestionOutcomeView {
                state: "answered".to_owned(),
                selected_label: "Production".to_owned(),
            }),
        });
        assert_eq!(pane.pending_count(), 0);
        assert_eq!(
            pane.items[0]
                .response
                .as_ref()
                .map(|o| o.selected_label.as_str()),
            Some("Production")
        );
    }
}