Skip to content

Commit 4330d98

Browse files
committed
feat(tui): approve-all confirmation modal and CTF cleanup
Add [A] confirmation popup that snapshots pending chunks, shows a scrollable list, and approves each chunk individually on confirm. This prevents approving chunks that arrived after the modal opened. Remove transient issue #205 reference from CTF victory banner.
1 parent 4c32351 commit 4330d98

5 files changed

Lines changed: 200 additions & 41 deletions

File tree

‎crates/navigator-tui/src/app.rs‎

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,11 @@ pub struct App {
372372
pub pending_draft_approve: bool,
373373
pub pending_draft_reject: bool,
374374
pub pending_draft_approve_all: bool,
375+
376+
/// When true, the approve-all confirmation modal is shown.
377+
pub approve_all_confirm_open: bool,
378+
/// Snapshot of pending chunks captured when `[A]` was pressed.
379+
pub approve_all_confirm_chunks: Vec<navigator_core::proto::PolicyChunk>,
375380
}
376381

377382
impl App {
@@ -445,6 +450,8 @@ impl App {
445450
pending_draft_approve: false,
446451
pending_draft_reject: false,
447452
pending_draft_approve_all: false,
453+
approve_all_confirm_open: false,
454+
approve_all_confirm_chunks: Vec::new(),
448455
}
449456
}
450457

@@ -706,6 +713,24 @@ impl App {
706713
}
707714

708715
fn handle_draft_key(&mut self, key: KeyEvent) {
716+
// Approve-all confirmation modal intercepts all keys when open.
717+
if self.approve_all_confirm_open {
718+
match key.code {
719+
KeyCode::Char('y') | KeyCode::Enter => {
720+
self.pending_draft_approve_all = true;
721+
self.approve_all_confirm_open = false;
722+
// Don't clear chunks here — the event loop takes them
723+
// via std::mem::take when it processes the flag.
724+
}
725+
KeyCode::Esc | KeyCode::Char('n') => {
726+
self.approve_all_confirm_open = false;
727+
self.approve_all_confirm_chunks.clear();
728+
}
729+
_ => {}
730+
}
731+
return;
732+
}
733+
709734
// Detail popup intercepts most keys when open.
710735
if self.draft_detail_open {
711736
match key.code {
@@ -811,10 +836,17 @@ impl App {
811836
}
812837
}
813838
}
814-
// Approve all pending chunks.
839+
// Approve all pending chunks — show confirmation modal.
815840
KeyCode::Char('A') => {
816-
if self.draft_chunks.iter().any(|c| c.status == "pending") {
817-
self.pending_draft_approve_all = true;
841+
let pending: Vec<_> = self
842+
.draft_chunks
843+
.iter()
844+
.filter(|c| c.status == "pending")
845+
.cloned()
846+
.collect();
847+
if !pending.is_empty() {
848+
self.approve_all_confirm_chunks = pending;
849+
self.approve_all_confirm_open = true;
818850
}
819851
}
820852
KeyCode::Char('q') => self.running = false,

‎crates/navigator-tui/src/lib.rs‎

Lines changed: 43 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,8 @@ pub async fn run(channel: Channel, gateway_name: &str, endpoint: &str) -> Result
111111
}
112112
if app.pending_draft_approve_all {
113113
app.pending_draft_approve_all = false;
114-
spawn_draft_approve_all(&app, events.sender());
114+
let snapshot = std::mem::take(&mut app.approve_all_confirm_chunks);
115+
spawn_draft_approve_all(&app, snapshot, events.sender());
115116
}
116117
}
117118
Some(Event::LogLines(lines)) => {
@@ -1661,46 +1662,57 @@ fn spawn_draft_reject(app: &App, tx: mpsc::UnboundedSender<Event>) {
16611662
});
16621663
}
16631664

1664-
/// Approve all pending draft chunks.
1665-
fn spawn_draft_approve_all(app: &App, tx: mpsc::UnboundedSender<Event>) {
1665+
/// Approve the snapshotted draft chunks one by one.
1666+
///
1667+
/// Only the chunks captured when `[A]` was pressed are approved — any new
1668+
/// chunks that arrived while the confirmation modal was open are skipped.
1669+
fn spawn_draft_approve_all(
1670+
app: &App,
1671+
snapshot: Vec<navigator_core::proto::PolicyChunk>,
1672+
tx: mpsc::UnboundedSender<Event>,
1673+
) {
16661674
let mut client = app.client.clone();
16671675
let name = match app.selected_sandbox_name() {
16681676
Some(n) => n.to_string(),
16691677
None => return,
16701678
};
16711679

16721680
tokio::spawn(async move {
1673-
let req = navigator_core::proto::ApproveAllDraftChunksRequest {
1674-
name,
1675-
include_security_flagged: false,
1676-
};
1677-
match tokio::time::timeout(
1678-
Duration::from_secs(10),
1679-
client.approve_all_draft_chunks(req),
1680-
)
1681-
.await
1682-
{
1683-
Ok(Ok(resp)) => {
1684-
let inner = resp.into_inner();
1685-
let mut msg = format!(
1686-
"Approved {} chunks -> policy v{}",
1687-
inner.chunks_approved, inner.policy_version
1688-
);
1689-
if inner.chunks_skipped > 0 {
1690-
use std::fmt::Write;
1691-
let _ = write!(msg, " ({} security-flagged skipped)", inner.chunks_skipped);
1681+
let total = snapshot.len();
1682+
let mut approved = 0u32;
1683+
let mut last_version = 0u32;
1684+
let mut errors: Vec<String> = Vec::new();
1685+
1686+
for chunk in &snapshot {
1687+
let req = navigator_core::proto::ApproveDraftChunkRequest {
1688+
name: name.clone(),
1689+
chunk_id: chunk.id.clone(),
1690+
};
1691+
match tokio::time::timeout(Duration::from_secs(5), client.approve_draft_chunk(req))
1692+
.await
1693+
{
1694+
Ok(Ok(resp)) => {
1695+
approved += 1;
1696+
last_version = resp.into_inner().policy_version;
1697+
}
1698+
Ok(Err(e)) => {
1699+
errors.push(format!("{}: {}", chunk.rule_name, e.message()));
1700+
}
1701+
Err(_) => {
1702+
errors.push(format!("{}: timed out", chunk.rule_name));
16921703
}
1693-
let _ = tx.send(Event::DraftActionResult(Ok(msg)));
1694-
}
1695-
Ok(Err(e)) => {
1696-
let _ = tx.send(Event::DraftActionResult(Err(e.message().to_string())));
1697-
}
1698-
Err(_) => {
1699-
let _ = tx.send(Event::DraftActionResult(Err(
1700-
"approve-all timed out".to_string()
1701-
)));
17021704
}
17031705
}
1706+
1707+
let msg = if errors.is_empty() {
1708+
format!("Approved {approved}/{total} chunks -> policy v{last_version}")
1709+
} else {
1710+
format!(
1711+
"Approved {approved}/{total} chunks (errors: {})",
1712+
errors.join("; ")
1713+
)
1714+
};
1715+
let _ = tx.send(Event::DraftActionResult(Ok(msg)));
17041716
});
17051717
}
17061718

‎crates/navigator-tui/src/ui/mod.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,11 @@ fn draw_sandbox_screen(frame: &mut Frame<'_>, app: &mut App, area: Rect) {
101101
sandbox_draft::draw_detail_popup(frame, chunk, frame.size());
102102
}
103103
}
104+
105+
// Approve-all confirmation popup renders over everything.
106+
if app.approve_all_confirm_open && !app.approve_all_confirm_chunks.is_empty() {
107+
sandbox_draft::draw_approve_all_popup(frame, &app.approve_all_confirm_chunks, frame.size());
108+
}
104109
}
105110

106111
// ---------------------------------------------------------------------------

‎crates/navigator-tui/src/ui/sandbox_draft.rs‎

Lines changed: 113 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@
66
use crate::app::App;
77
use crate::theme::styles;
88
use navigator_core::proto::PolicyChunk;
9-
use ratatui::Frame;
109
use ratatui::layout::{Constraint, Direction, Layout, Rect};
1110
use ratatui::style::{Color, Modifier, Style};
1211
use ratatui::text::{Line, Span};
1312
use ratatui::widgets::{Block, Borders, Clear, Padding, Paragraph, Wrap};
13+
use ratatui::Frame;
1414

1515
/// Draw the draft recommendations panel (list view with highlight bar).
1616
pub fn draw(frame: &mut Frame<'_>, app: &mut App, area: Rect) {
@@ -267,6 +267,118 @@ pub fn draw_detail_popup(frame: &mut Frame<'_>, chunk: &PolicyChunk, area: Rect)
267267
);
268268
}
269269

270+
// ---------------------------------------------------------------------------
271+
// Approve-all confirmation popup ([A] key)
272+
// ---------------------------------------------------------------------------
273+
274+
pub fn draw_approve_all_popup(frame: &mut Frame<'_>, chunks: &[PolicyChunk], area: Rect) {
275+
let count = chunks.len();
276+
// Height: header(1) + blank(1) + chunks(count, capped at 12) + blank(1) + hints(1) + borders(2) + padding(1)
277+
let list_lines = count.min(12);
278+
let popup_height = (7 + list_lines) as u16;
279+
let popup_height = popup_height.min(area.height.saturating_sub(4));
280+
let popup_width = (area.width * 4 / 5).min(area.width.saturating_sub(4));
281+
let popup_area = centered_rect(popup_width, popup_height, area);
282+
283+
frame.render_widget(Clear, popup_area);
284+
285+
let block = Block::default()
286+
.title(Span::styled(
287+
" Approve All ",
288+
Style::default()
289+
.fg(Color::Yellow)
290+
.add_modifier(Modifier::BOLD),
291+
))
292+
.borders(Borders::ALL)
293+
.border_style(styles::ACCENT)
294+
.padding(Padding::new(1, 1, 0, 0));
295+
296+
// Usable width inside borders + padding.
297+
let inner_width = popup_width.saturating_sub(4) as usize;
298+
299+
let mut lines: Vec<Line<'_>> = Vec::new();
300+
301+
lines.push(Line::from(vec![
302+
Span::styled("Approve ", styles::TEXT),
303+
Span::styled(
304+
format!("{count}"),
305+
Style::default()
306+
.fg(Color::Yellow)
307+
.add_modifier(Modifier::BOLD),
308+
),
309+
Span::styled(
310+
format!(
311+
" pending policy request{}?",
312+
if count == 1 { "" } else { "s" }
313+
),
314+
styles::TEXT,
315+
),
316+
]));
317+
lines.push(Line::from(""));
318+
319+
for (i, chunk) in chunks.iter().enumerate() {
320+
if i >= 12 {
321+
lines.push(Line::from(Span::styled(
322+
format!(" ... and {} more", count - 12),
323+
styles::MUTED,
324+
)));
325+
break;
326+
}
327+
let endpoint_str = chunk
328+
.proposed_rule
329+
.as_ref()
330+
.and_then(|r| r.endpoints.first())
331+
.map(|ep| format!("{}:{}", ep.host, ep.port))
332+
.unwrap_or_default();
333+
334+
// Truncate to fit within the popup width.
335+
// " -> " (5) + rule_name + " " (2) + endpoint
336+
let prefix_len = 5;
337+
let sep_len = 2;
338+
let budget = inner_width.saturating_sub(prefix_len + sep_len);
339+
let (name_str, ep_str) = if chunk.rule_name.len() + endpoint_str.len() > budget {
340+
let ep_budget = endpoint_str.len().min(budget / 2);
341+
let name_budget = budget.saturating_sub(ep_budget);
342+
(
343+
truncate_str(&chunk.rule_name, name_budget),
344+
truncate_str(&endpoint_str, ep_budget),
345+
)
346+
} else {
347+
(chunk.rule_name.clone(), endpoint_str)
348+
};
349+
350+
lines.push(Line::from(vec![
351+
Span::styled(" -> ", styles::MUTED),
352+
Span::styled(name_str, styles::TEXT),
353+
Span::styled(" ", styles::MUTED),
354+
Span::styled(ep_str, styles::ACCENT),
355+
]));
356+
}
357+
358+
lines.push(Line::from(""));
359+
lines.push(Line::from(vec![
360+
Span::styled("[y/Enter]", styles::KEY_HINT),
361+
Span::styled(" Approve all ", styles::TEXT),
362+
Span::styled("[n/Esc]", styles::KEY_HINT),
363+
Span::styled(" Cancel", styles::TEXT),
364+
]));
365+
366+
frame.render_widget(Paragraph::new(lines).block(block), popup_area);
367+
}
368+
369+
/// Truncate a string to `max_len` chars, appending "..." if truncated.
370+
fn truncate_str(s: &str, max_len: usize) -> String {
371+
if s.len() <= max_len {
372+
s.to_string()
373+
} else if max_len <= 3 {
374+
s.chars().take(max_len).collect()
375+
} else {
376+
let mut out: String = s.chars().take(max_len - 3).collect();
377+
out.push_str("...");
378+
out
379+
}
380+
}
381+
270382
fn format_short_time(epoch_ms: i64) -> String {
271383
if epoch_ms <= 0 {
272384
return String::from("--:--:--");

‎examples/policy-advisor/ctf.py‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -236,12 +236,10 @@ def attempt_gate(gate: dict) -> tuple[str, str]:
236236
| |
237237
| Each denied connection was detected by the sandbox |
238238
| proxy, aggregated into a denial summary, transported |
239-
| to the gateway, and mapped into a NetworkPolicyRule |
240-
| for your approval. |
241-
| |
242-
| Next up: AI-assisted mode (issue #205). |
243-
| |
244-
+============================================================+\
239+
| to the gateway, and mapped into a NetworkPolicyRule |
240+
| for your approval. |
241+
| |
242+
+============================================================+\
245243
{RESET}
246244
"""
247245

0 commit comments

Comments
 (0)