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
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
//! Approvals pane: the HITL (human-in-the-loop) inbox — pending tool-call
//! decisions surfaced across every conversation in the fleet.
//!
//! This is the cockpit's differentiator. A pending approval is inferred on the
//! external `AgentService` stream from a trailing tool-call with no matching
//! tool-result before the turn ends; it is also readable from the forensics
//! `/approvals` projection. The pane collects those into one ordered inbox,
//! renders the call arguments as pretty JSON, and lets the operator approve
//! `[a]` / reject `[r]` with an optional typed reason `[e]`.
//!
//! Submitting a decision goes through the THIN path: the component emits an
//! [`Action::ApprovalDecide`]; the loop hands the unsigned
//! [`ApprovalDecision`](crate::action::ApprovalDecision) to
//! [`crate::data::approvals::submit_decision`], which dials
//! `ApprovalService.Respond` and the control plane signs it server-side. The
//! signed outcome comes back as [`Action::ApprovalSubmitted`], which this pane
//! folds onto the matching item.

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, ApprovalDecision, Pane};

/// A pending (or historical) approval as rendered in the pane.
///
/// Field names mirror the wire/forensics surfaces: `request_id` == the
/// tool-call id; `tool_name`/`args_json` come from the `PendingApproval` /
/// forensics `ApprovalEntry`. `response` is populated once a decision exists.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ApprovalView {
    /// Turn that emitted this occurrence of `request_id`.
    pub turn_id: String,
    /// The conversation this approval belongs to (required by `ApprovalService.Respond`).
    pub conversation_id: String,
    /// The pending tool-call id being answered (== `request_id`).
    pub request_id: String,
    /// The tool/function name awaiting approval.
    pub tool_name: String,
    /// The pretty-printed arguments JSON for the call.
    pub args_json: String,
    /// Short-lived signed capability (`#787`) required by
    /// `ApprovalService.Respond`; empty once `response` is populated (nothing
    /// left to resolve).
    pub resolve_token: String,
    /// The recorded decision, if one has been persisted.
    pub response: Option<ApprovalOutcome>,
}

/// A persisted approval decision (mirrors forensics `ApprovalResponseEntry`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ApprovalOutcome {
    /// Whether the call was authorised.
    pub approved: bool,
    /// The rationale recorded with the decision.
    pub reason: String,
    /// Lowercase-hex public key the control plane signed with.
    pub signer_pk_hex: String,
    /// Lowercase-hex ed25519 signature over the canonical decision bytes.
    pub signature_hex: String,
    /// Whether the recorded signature verifies (forensics-reported).
    pub signature_valid: bool,
}

/// Whether the pane is collecting a typed reason, and for which decision.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
enum Editing {
    /// Not editing; `[a]`/`[r]` submit immediately with the default reason.
    #[default]
    Idle,
    /// Typing a reason; on `Enter` the decision is submitted.
    Reason {
        /// `true` if the in-progress decision approves the call.
        approved: bool,
        /// The reason buffer accumulated so far.
        buffer: String,
    },
}

/// The approvals component.
#[derive(Default)]
pub(crate) struct Approvals {
    /// The most recently selected conversation, shown in the title for context.
    /// The inbox itself is fleet-wide and is NOT filtered to this id.
    pub conversation_id: Option<String>,
    /// Pending + historical approvals, newest first.
    pub items: Vec<ApprovalView>,
    /// Index of the highlighted approval, if any.
    pub selected: Option<usize>,
    /// Whether this pane currently has keyboard focus.
    focused: bool,
    /// Reason-entry state machine.
    editing: Editing,
    /// The last error surfaced while interacting with the inbox, if any.
    last_error: Option<String>,
}

impl Approvals {
    /// Insert (or replace) an approval, keeping the newest-first ordering and
    /// deduplicating on `(conversation_id, turn_id, request_id)`. Returns the
    /// index it landed at.
    fn upsert(&mut self, view: ApprovalView) -> usize {
        if let Some(idx) = self.index_of(&view.conversation_id, &view.turn_id, &view.request_id) {
            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, request_id: &str) -> Option<usize> {
        self.items.iter().position(|v| {
            v.conversation_id == conversation_id
                && v.turn_id == turn_id
                && v.request_id == request_id
        })
    }

    /// The number of approvals still awaiting a decision.
    #[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 [`ApprovalDecision`] for the highlighted item, if it is still
    /// pending. Historical (already-decided) items cannot be re-decided.
    fn decision_for_selected(&self, approved: bool, reason: String) -> Option<ApprovalDecision> {
        let item = self.items.get(self.selected?)?;
        if item.response.is_some() {
            return None;
        }
        Some(ApprovalDecision {
            turn_id: item.turn_id.clone(),
            request_id: item.request_id.clone(),
            conversation_id: item.conversation_id.clone(),
            tool_name: item.tool_name.clone(),
            args_json: item.args_json.clone(),
            approved,
            reason,
            resolve_token: item.resolve_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> {
        // Reason-entry sub-mode captures text first.
        if let Editing::Reason { approved, buffer } = &mut self.editing {
            match key.code {
                KeyCode::Char(c) => {
                    buffer.push(c);
                    return None;
                }
                KeyCode::Backspace => {
                    buffer.pop();
                    return None;
                }
                KeyCode::Esc => {
                    self.editing = Editing::Idle;
                    return None;
                }
                KeyCode::Enter => {
                    let approved = *approved;
                    let reason = std::mem::take(buffer);
                    self.editing = Editing::Idle;
                    return self.emit_decision(approved, reason);
                }
                _ => return None,
            }
        }

        match key.code {
            KeyCode::Char('j') | KeyCode::Down => {
                self.move_selection(1);
                None
            }
            KeyCode::Char('k') | KeyCode::Up => {
                self.move_selection(-1);
                None
            }
            // Approve / reject immediately with a default reason.
            KeyCode::Char('a') => self.emit_decision(true, "approved via cockpit".to_owned()),
            KeyCode::Char('r') => self.emit_decision(false, "rejected via cockpit".to_owned()),
            // Begin typing a reason; `Enter` will submit, `Esc` cancels. The
            // capital variants pick the decision sense.
            KeyCode::Char('e' | 'A') => {
                if self.decision_for_selected(true, String::new()).is_some() {
                    self.editing = Editing::Reason {
                        approved: true,
                        buffer: String::new(),
                    };
                }
                None
            }
            KeyCode::Char('R') => {
                if self.decision_for_selected(false, String::new()).is_some() {
                    self.editing = Editing::Reason {
                        approved: false,
                        buffer: String::new(),
                    };
                }
                None
            }
            _ => None,
        }
    }

    /// Produce an [`Action::ApprovalDecide`] for the current selection, or set a
    /// transient error if the selection cannot be decided.
    fn emit_decision(&mut self, approved: bool, reason: String) -> Option<Action> {
        if let Some(decision) = self.decision_for_selected(approved, reason) {
            self.last_error = None;
            Some(Action::ApprovalDecide(decision))
        } else {
            self.last_error = Some("no pending approval selected (already decided?)".to_owned());
            None
        }
    }
}

impl Component for Approvals {
    fn controls(&self) -> Vec<(&'static str, &'static str)> {
        if matches!(self.editing, Editing::Reason { .. }) {
            return vec![("Enter", "submit"), ("Esc", "cancel")];
        }
        vec![
            ("↑↓/jk", "move"),
            ("a", "approve"),
            ("r", "reject"),
            ("e/R", "+reason"),
        ]
    }

    fn capturing_input(&self) -> bool {
        matches!(self.editing, Editing::Reason { .. })
    }

    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::Approvals;
                if !self.focused {
                    // Cancel any half-typed reason when focus leaves.
                    self.editing = Editing::Idle;
                }
                None
            }
            // Track the selected conversation purely for the title; the inbox is
            // intentionally fleet-wide so nothing is hidden behind a selection.
            Action::Select(conversation_id) => {
                self.conversation_id = Some(conversation_id.clone());
                None
            }
            // A turn paused on a tool call awaiting consent.
            Action::ApprovalPending(view) => {
                let idx = self.upsert(view.clone());
                if self.selected.is_none() {
                    self.selected = Some(idx);
                }
                None
            }
            // The control plane persisted (and signed) a decision. Fold the
            // signed outcome onto the matching item so it leaves the pending
            // set immediately (no dependency on a later forensics re-poll).
            Action::ApprovalSubmitted {
                conversation_id,
                turn_id,
                request_id,
                persisted,
                outcome,
            } => {
                if let Some(idx) = self.items.iter().position(|v| {
                    &v.conversation_id == conversation_id
                        && &v.turn_id == turn_id
                        && &v.request_id == request_id
                        && v.response.is_none()
                }) {
                    if *persisted {
                        // Carry the reply's signer pk + signature straight onto
                        // the item; a later forensics refresh, if one arrives,
                        // re-confirms the same outcome via `upsert`.
                        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 decision for {request_id} (already answered or unknown request)"
                        ));
                    }
                }
                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 + editor
    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!(" approvals — {pending} pending "),
            |id| format!(" approvals — {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 approvals — the inbox is clear")
                .style(Style::default().fg(Color::DarkGray));
            frame.render_widget(empty, inner);
            return Ok(());
        }

        // Left: the inbox list. Right: the selected call's pretty-printed args
        // and decision controls. Bottom strip: reason editor / error line.
        let cols = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Percentage(40), Constraint::Percentage(60)])
            .split(inner);

        let rows = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Min(1), Constraint::Length(2)])
            .split(cols[1]);

        // --- 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(o) if o.approved => ("", Style::default().fg(Color::Green)),
                    Some(_) => ("", Style::default().fg(Color::Red)),
                };
                ListItem::new(Line::from(vec![
                    Span::styled(marker, marker_style),
                    Span::styled(
                        v.tool_name.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 an approval").into(),
            |v| {
                let mut lines: Vec<Line> = vec![
                    Line::from(vec![
                        Span::styled("tool   ", Style::default().fg(Color::DarkGray)),
                        Span::styled(
                            v.tool_name.clone(),
                            Style::default().add_modifier(Modifier::BOLD),
                        ),
                    ]),
                    Line::from(vec![
                        Span::styled("call   ", Style::default().fg(Color::DarkGray)),
                        Span::raw(v.request_id.clone()),
                    ]),
                    Line::from(vec![
                        Span::styled("conv   ", Style::default().fg(Color::DarkGray)),
                        Span::raw(v.conversation_id.clone()),
                    ]),
                    Line::from(""),
                ];
                lines.push(Line::from(Span::styled(
                    "args",
                    Style::default().fg(Color::DarkGray),
                )));
                for l in pretty_json(&v.args_json).lines() {
                    lines.push(Line::from(l.to_owned()));
                }
                lines.push(Line::from(""));
                if let Some(o) = &v.response {
                    let verdict = if o.approved { "APPROVED" } else { "REJECTED" };
                    let vstyle = if o.approved {
                        Style::default().fg(Color::Green)
                    } else {
                        Style::default().fg(Color::Red)
                    };
                    lines.push(Line::from(Span::styled(verdict, vstyle)));
                    lines.push(Line::from(format!("reason: {}", o.reason)));
                    lines.push(Line::from(format!("signer: {}", short(&o.signer_pk_hex))));
                    let sig = if o.signature_valid {
                        Span::styled("signature verified", Style::default().fg(Color::Green))
                    } else {
                        Span::styled("signature INVALID", Style::default().fg(Color::Red))
                    };
                    lines.push(Line::from(sig));
                } else {
                    lines.push(Line::from(Span::styled(
                        "[a] approve   [r] reject   [e] approve+reason   [R] reject+reason",
                        Style::default().fg(Color::Cyan),
                    )));
                }
                ratatui::text::Text::from(lines)
            },
        );
        let detail_widget = Paragraph::new(detail_text).wrap(Wrap { trim: false });
        frame.render_widget(detail_widget, rows[0]);

        // --- footer: reason editor or error ---
        let footer = match (&self.editing, &self.last_error) {
            (Editing::Reason { approved, buffer }, _) => {
                let verb = if *approved { "approve" } else { "reject" };
                Paragraph::new(format!(
                    "{verb} reason> {buffer}▏  (Enter submit · Esc cancel)"
                ))
                .style(Style::default().fg(Color::Yellow))
            }
            (Editing::Idle, Some(err)) => {
                Paragraph::new(err.clone()).style(Style::default().fg(Color::Red))
            }
            // Idle with no local error: the global controls footer carries the
            // key hints, so this row stays blank to avoid a duplicate hint line.
            (Editing::Idle, None) => Paragraph::new(""),
        };
        frame.render_widget(footer, rows[1]);

        Ok(())
    }
}

/// Pretty-print a JSON string; fall back to the raw text if it does not parse
/// (the args may legitimately be a non-JSON string or already formatted).
fn pretty_json(raw: &str) -> String {
    serde_json::from_str::<serde_json::Value>(raw)
        .ok()
        .and_then(|v| serde_json::to_string_pretty(&v).ok())
        .unwrap_or_else(|| raw.to_owned())
}

/// Abbreviate a long opaque id/hex string for compact display.
///
/// Counts and slices by `char`, not bytes, so a multi-byte (non-ASCII)
/// `conversation_id` cannot panic on a UTF-8 boundary.
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, req: &str) -> ApprovalView {
        pending_turn(conv, "00000000-0000-0000-0000-000000000001", req)
    }

    fn pending_turn(conv: &str, turn: &str, req: &str) -> ApprovalView {
        ApprovalView {
            conversation_id: conv.to_owned(),
            turn_id: turn.to_owned(),
            request_id: req.to_owned(),
            tool_name: "rm".to_owned(),
            args_json: r#"{"path":"/tmp"}"#.to_owned(),
            resolve_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 = Approvals::default();
        assert!(
            pane.handle(&Action::ApprovalPending(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 = Approvals::default();
        pane.handle(&Action::ApprovalPending(pending("c1", "call-1")));
        pane.handle(&Action::ApprovalPending(pending("c1", "call-1")));
        assert_eq!(pane.items.len(), 1);
    }

    #[test]
    fn reused_request_id_keeps_distinct_turn_occurrences() {
        let mut pane = Approvals::default();
        pane.handle(&Action::ApprovalPending(pending_turn(
            "c1",
            "00000000-0000-0000-0000-000000000001",
            "call-1",
        )));
        pane.handle(&Action::ApprovalPending(pending_turn(
            "c1",
            "00000000-0000-0000-0000-000000000002",
            "call-1",
        )));
        assert_eq!(pane.items.len(), 2);

        pane.handle(&Action::ApprovalSubmitted {
            conversation_id: "c1".to_owned(),
            turn_id: "00000000-0000-0000-0000-000000000001".to_owned(),
            request_id: "call-1".to_owned(),
            persisted: true,
            outcome: Some(ApprovalOutcome {
                approved: true,
                reason: "approved".to_owned(),
                signer_pk_hex: "ab".to_owned(),
                signature_hex: "cd".to_owned(),
                signature_valid: true,
            }),
        });
        assert!(pane.items.iter().any(|item| {
            item.turn_id == "00000000-0000-0000-0000-000000000001" && item.response.is_some()
        }));
        assert!(pane.items.iter().any(|item| {
            item.turn_id == "00000000-0000-0000-0000-000000000002" && item.response.is_none()
        }));
    }

    #[test]
    fn newest_first_ordering_shifts_selection() {
        let mut pane = Approvals::default();
        pane.handle(&Action::ApprovalPending(pending("c1", "call-1")));
        // selection at 0 (call-1)
        pane.handle(&Action::ApprovalPending(pending("c1", "call-2")));
        // call-2 is now head (idx 0); the old selection should track call-1 at 1
        assert_eq!(pane.items[0].request_id, "call-2");
        assert_eq!(pane.selected, Some(1));
    }

    #[test]
    fn approve_key_emits_decision_only_when_focused() {
        let mut pane = Approvals::default();
        pane.handle(&Action::ApprovalPending(pending("c1", "call-1")));
        // not focused: key is ignored
        assert!(pane.handle(&Action::Key(key('a'))).is_none());
        // focus the pane, then approve
        pane.handle(&Action::Nav(Pane::Approvals));
        let out = pane.handle(&Action::Key(key('a')));
        match out {
            Some(Action::ApprovalDecide(d)) => {
                assert!(d.approved);
                assert_eq!(d.request_id, "call-1");
                assert_eq!(d.conversation_id, "c1");
            }
            other => panic!("expected ApprovalDecide, got {other:?}"),
        }
    }

    #[test]
    fn reject_key_emits_negative_decision() {
        let mut pane = Approvals::default();
        pane.handle(&Action::ApprovalPending(pending("c1", "call-1")));
        pane.handle(&Action::Nav(Pane::Approvals));
        let out = pane.handle(&Action::Key(key('r')));
        assert!(matches!(out, Some(Action::ApprovalDecide(d)) if !d.approved));
    }

    #[test]
    fn reason_editing_collects_text_then_submits() {
        let mut pane = Approvals::default();
        pane.handle(&Action::ApprovalPending(pending("c1", "call-1")));
        pane.handle(&Action::Nav(Pane::Approvals));
        // enter approve+reason mode, type "ok", submit
        assert!(pane.handle(&Action::Key(key('e'))).is_none());
        assert!(pane.handle(&Action::Key(key('o'))).is_none());
        assert!(pane.handle(&Action::Key(key('k'))).is_none());
        let out = pane.handle(&Action::Key(KeyEvent::new(
            KeyCode::Enter,
            KeyModifiers::NONE,
        )));
        match out {
            Some(Action::ApprovalDecide(d)) => {
                assert!(d.approved);
                assert_eq!(d.reason, "ok");
            }
            other => panic!("expected ApprovalDecide, got {other:?}"),
        }
    }

    #[test]
    fn cannot_decide_already_decided_item() {
        let mut pane = Approvals::default();
        let mut decided = pending("c1", "call-1");
        decided.response = Some(ApprovalOutcome {
            approved: true,
            reason: "done".to_owned(),
            signer_pk_hex: "ab".to_owned(),
            signature_hex: "cd".to_owned(),
            signature_valid: true,
        });
        pane.handle(&Action::ApprovalPending(decided));
        pane.handle(&Action::Nav(Pane::Approvals));
        assert!(pane.handle(&Action::Key(key('a'))).is_none());
        assert!(pane.last_error.is_some());
        assert_eq!(pane.pending_count(), 0);
    }

    #[test]
    fn submitted_not_persisted_sets_error() {
        let mut pane = Approvals::default();
        pane.handle(&Action::ApprovalPending(pending("c1", "call-1")));
        pane.handle(&Action::ApprovalSubmitted {
            conversation_id: "c1".to_owned(),
            turn_id: "00000000-0000-0000-0000-000000000001".to_owned(),
            request_id: "call-1".to_owned(),
            persisted: false,
            outcome: None,
        });
        assert!(pane.last_error.is_some());
    }

    #[test]
    fn pretty_json_falls_back_on_non_json() {
        assert_eq!(pretty_json("not json"), "not json");
        assert_eq!(pretty_json(r#"{"a":1}"#), "{\n  \"a\": 1\n}");
    }
}