返回 CodeWhale
redaction_gate.rs
根目录 / crates / tui / src / tui / redaction_gate.rs
1 //! Startup gate for the `[redaction] model_bound = "disabled"` opt-out.
2 //!
3 //! Setting `[redaction] model_bound = "disabled"` in `config.toml` only
4 //! records a request. Lowering the model-bound masking boundary is a security
5 //! decision, so the interactive TUI shows this full-screen gate on the next
6 //! launch and only applies the opt-out after the user confirms it here (see
7 //! [`codewhale_config::redaction`] for the effective-mode contract).
8 //!
9 //! The gate follows the onboarding visual grammar — one Underwater surface,
10 //! one bottom action rail — but it is **not** an onboarding step: returning
11 //! users see it, and answering it never touches the `.onboarded` marker. The
12 //! three actions mirror the workspace-trust screen's explicit-key discipline:
13 //! Enter never confirms by reflex, and each choice advertises its own key.
14
15 use ratatui::{
16 Frame,
17 layout::Rect,
18 style::Style,
19 text::{Line, Span},
20 widgets::Paragraph,
21 };
22
23 use crate::tui::app::{App, RedactionGateNotice, StatusToastKind};
24 use crate::tui::onboarding::wrap_words;
25 use crate::tui::shell_key_routing::{ShellBindingId, binding};
26 use crate::tui::views::{ActionHint, render_modal_footer, render_underwater_surface};
27 use codewhale_localization::MessageId;
28 use codewhale_palette as palette;
29
30 /// Render the gate. Callers (the frame compositor) invoke this only while
31 /// `app.redaction_gate` is set. The gate has two stages: the first stage
32 /// explains the opt-out and its risk; pressing the confirm key moves to the
33 /// second, final-confirmation stage (`app.redaction_gate_confirming`), which
34 /// repeats the red warning and requires a second explicit confirm before the
35 /// opt-out is recorded.
36 pub fn render(f: &mut Frame, area: Rect, app: &App) {
37 let title = if app.redaction_gate_confirming {
38 app.tr(MessageId::RedactionGateConfirmTitle).into_owned()
39 } else {
40 app.tr(MessageId::RedactionGateTitle).into_owned()
41 };
42 let mut hints = action_hints(app);
43 hints.push(ActionHint::new(
44 binding(ShellBindingId::RedactionGateScroll).footer_chord,
45 app.tr(MessageId::SetupActionScrollBody).to_string(),
46 ));
47 let buf = f.buffer_mut();
48 let inner = render_underwater_surface(area, buf, &title);
49 let content = render_modal_footer(inner, buf, &hints);
50 let lines = screen_lines(app, usize::from(content.width), usize::from(content.height));
51 if lines.is_empty() {
52 return;
53 }
54 let body = center_vertically(content, lines.len());
55 f.render_widget(Paragraph::new(lines), body);
56 }
57
58 fn center_vertically(area: Rect, rows: usize) -> Rect {
59 let pad = (area
60 .height
61 .saturating_sub(u16::try_from(rows).unwrap_or(area.height)))
62 / 2;
63 Rect {
64 y: area.y.saturating_add(pad),
65 height: area.height.saturating_sub(pad),
66 ..area
67 }
68 }
69
70 fn action_hints(app: &App) -> Vec<ActionHint> {
71 [
72 (
73 ShellBindingId::RedactionGateConfirm,
74 MessageId::RedactionGateActionConfirm,
75 ),
76 (
77 ShellBindingId::RedactionGateKeepOrBack,
78 if app.redaction_gate_confirming {
79 MessageId::RedactionGateActionBack
80 } else {
81 MessageId::RedactionGateActionKeep
82 },
83 ),
84 (
85 ShellBindingId::RedactionGateQuit,
86 MessageId::RedactionGateActionQuit,
87 ),
88 ]
89 .into_iter()
90 .map(|(id, label)| ActionHint::new(binding(id).footer_chord, app.tr(label).to_string()))
91 .collect()
92 }
93
94 fn screen_lines(app: &App, width: usize, height: usize) -> Vec<Line<'static>> {
95 let mut out = Vec::new();
96 let now = std::time::Instant::now();
97 if let Some(toast) = [
98 RedactionGateNotice::WriteFailure,
99 RedactionGateNotice::EnterGuidance,
100 ]
101 .into_iter()
102 .find_map(|notice| {
103 app.status_toasts.iter().rev().find(|toast| {
104 toast.kind == StatusToastKind::RedactionGate(notice) && !toast.is_expired(now)
105 })
106 }) {
107 for line in wrap_words(&toast.text, width) {
108 out.push(Line::from(Span::styled(
109 line,
110 Style::default().fg(toast.level.ink().color(&app.ui_theme)),
111 )));
112 }
113 out.push(Line::from(""));
114 }
115 // Put the consequence first even when the rest needs scrolling.
116 wrap_body_danger(&mut out, app, MessageId::RedactionGateDangerNotice, width);
117 out.push(Line::from(""));
118 if app.redaction_gate_confirming {
119 wrap_body(
120 &mut out,
121 app,
122 MessageId::RedactionGateConfirmQuestion,
123 width,
124 );
125 } else {
126 wrap_body(&mut out, app, MessageId::RedactionGateQuestion, width);
127 out.push(Line::from(""));
128 wrap_body_muted(&mut out, app, MessageId::RedactionGateRisk, width);
129 wrap_body_muted(&mut out, app, MessageId::RedactionGateEffect, width);
130 wrap_body_muted(&mut out, app, MessageId::RedactionGateRollbackHint, width);
131 }
132 let scroll = app
133 .redaction_gate_scroll
134 .get()
135 .min(out.len().saturating_sub(height));
136 app.redaction_gate_scroll.set(scroll);
137 out.into_iter().skip(scroll).take(height).collect()
138 }
139
140 /// Body sentence in the primary lane.
141 fn wrap_body(lines: &mut Vec<Line<'static>>, app: &App, id: MessageId, width: usize) {
142 let text = app.tr(id);
143 for segment in wrap_words(&text, width) {
144 lines.push(Line::from(Span::styled(
145 segment,
146 Style::default().fg(palette::TEXT_PRIMARY),
147 )));
148 }
149 }
150
151 /// The red, bold warning shown on both gate stages. Wrap on display width
152 /// exactly like the other lanes so no locale clips mid-word.
153 fn wrap_body_danger(lines: &mut Vec<Line<'static>>, app: &App, id: MessageId, width: usize) {
154 let text = app.tr(id);
155 for segment in wrap_words(&text, width) {
156 lines.push(Line::from(Span::styled(
157 segment,
158 Style::default()
159 .fg(palette::STATUS_ERROR)
160 .add_modifier(ratatui::style::Modifier::BOLD),
161 )));
162 }
163 }
164
165 /// Supporting hint in the muted lane.
166 fn wrap_body_muted(lines: &mut Vec<Line<'static>>, app: &App, id: MessageId, width: usize) {
167 let text = app.tr(id);
168 for segment in wrap_words(&text, width) {
169 lines.push(Line::from(Span::styled(
170 segment,
171 Style::default().fg(palette::TEXT_MUTED),
172 )));
173 }
174 }
175
176 // The "keep masking" answer persists nothing and rewrites no file: the
177 // current launch stays on the safe default, and because the config field
178 // still requests `"disabled"`, the gate asks again on the next launch until
179 // the user confirms or edits the field back to `"enabled"`. The event loop
180 // implements this inline (it only clears the gate flag); this module-level
181 // contract comment is where the semantics live.
182
183 #[cfg(test)]
184 mod tests {
185 use super::*;
186 use crate::tui::app::TuiOptions;
187 use crate::tui::views::action_footer_lines;
188 use codewhale_runtime::config::Config;
189 use std::path::PathBuf;
190
191 fn app_fixture() -> App {
192 let options = TuiOptions {
193 model: "test-model".to_string(),
194 ..crate::tui::test_support::test_tui_options(PathBuf::from("workspace-fixture"))
195 };
196 let mut app = App::new(options, &Config::default());
197 app.ui_locale = codewhale_localization::Locale::En;
198 app.redaction_gate = true;
199 app
200 }
201
202 #[test]
203 fn gate_names_the_boundary_and_the_three_explicit_actions() {
204 let app = app_fixture();
205 let body = screen_lines(&app, 70, 24)
206 .into_iter()
207 .flat_map(|line| line.spans.into_iter().map(|span| span.content.to_string()))
208 .collect::<Vec<_>>()
209 .join("\n");
210 let flat = body.split_whitespace().collect::<Vec<_>>().join(" ");
211 assert!(flat.contains("model-bound"), "{body}");
212 assert!(flat.contains("API keys"), "{body}");
213
214 let rail = action_hints(&app)
215 .iter()
216 .flat_map(|hint| action_footer_lines(std::slice::from_ref(hint), 60))
217 .flat_map(|line| {
218 line.spans
219 .into_iter()
220 .map(|span| span.content.to_string())
221 .collect::<Vec<_>>()
222 })
223 .collect::<Vec<_>>()
224 .join(" ");
225 for expected in ["1/Y", "2/U", "3/N"] {
226 assert!(
227 rail.contains(expected),
228 "missing {expected} in rail: {rail}"
229 );
230 }
231 assert!(rail.contains("confirm"), "{rail}");
232 assert!(rail.contains("keep"), "{rail}");
233 assert!(rail.contains("quit"), "{rail}");
234 }
235
236 #[test]
237 fn gate_renders_without_panicking_on_short_screens() {
238 // The gate must survive very narrow terminals without clipping the
239 // question (see the trust screen's narrow-terminal discipline).
240 for width in [40usize, 60, 80, 120] {
241 for locale in [
242 codewhale_localization::Locale::En,
243 codewhale_localization::Locale::ZhHans,
244 ] {
245 let mut app = app_fixture();
246 app.ui_locale = locale;
247 let _ = screen_lines(&app, width, 24);
248 // Both stages must survive the same narrow lanes.
249 app.redaction_gate_confirming = true;
250 let _ = screen_lines(&app, width, 24);
251 }
252 }
253 }
254
255 #[test]
256 fn gate_scroll_reaches_every_body_line_with_actions_visible_in_all_locales() {
257 use ratatui::{
258 Terminal,
259 backend::TestBackend,
260 buffer::{Buffer, CellWidth},
261 };
262 use std::collections::HashSet;
263 let visible_row = |buffer: &Buffer, area: Rect, y| {
264 let mut row = String::new();
265 let mut x = area.x;
266 while x < area.right() {
267 let cell = &buffer[(x, y)];
268 row.push_str(cell.symbol());
269 // TestBackend retains hidden cells beneath wide characters
270 // between draws. Read the terminal-visible graphemes only.
271 x += cell.cell_width().max(1);
272 }
273 row
274 };
275 let compact = |text: &str| {
276 text.chars()
277 .filter(|ch| !ch.is_whitespace())
278 .collect::<String>()
279 };
280 for &(width, height) in &[(40, 12), (60, 16), (80, 24)] {
281 for &locale in codewhale_localization::Locale::shipped() {
282 for confirming in [false, true] {
283 let mut app = app_fixture();
284 app.ui_locale = locale;
285 app.redaction_gate_confirming = confirming;
286 let area = Rect::new(0, 0, width, height);
287 let mut buffer = Buffer::empty(area);
288 let inner = render_underwater_surface(area, &mut buffer, "");
289 let mut hints = action_hints(&app);
290 hints.push(ActionHint::new(
291 "↑/↓",
292 app.tr(MessageId::SetupActionScrollBody).to_string(),
293 ));
294 let content = render_modal_footer(inner, &mut buffer, &hints);
295 assert!(
296 content.height > 0,
297 "no reading space at {width}x{height}, {locale:?}"
298 );
299 let expected = screen_lines(&app, content.width as usize, usize::MAX);
300 let mut seen = HashSet::new();
301 let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
302 for scroll in 0..=expected.len() {
303 app.redaction_gate_scroll.set(scroll);
304 let rendered = terminal.draw(|frame| render(frame, area, &app)).unwrap();
305 let buffer = rendered.buffer;
306 let mut whole = String::new();
307 for y in 0..height {
308 let row = visible_row(buffer, area, y);
309 whole.push_str(&row);
310 }
311 for key in ["1/Y", "2/U", "3/N", "↑/↓"] {
312 assert!(
313 whole.contains(key),
314 "missing action {key} at {width}x{height}, {locale:?}"
315 );
316 }
317 for y in content.y..content.y + content.height {
318 let row = visible_row(buffer, content, y);
319 seen.insert(compact(&row));
320 }
321 }
322 for line in expected {
323 let text = line
324 .spans
325 .iter()
326 .map(|span| span.content.as_ref())
327 .collect::<String>();
328 assert!(
329 unicode_width::UnicodeWidthStr::width(text.as_str())
330 <= usize::from(content.width),
331 "overflow at {width}x{height}, {locale:?}: {text}"
332 );
333 assert!(
334 seen.contains(&compact(&text)),
335 "unreachable or clipped body at {width}x{height}, {locale:?}, stage {confirming}: {text}"
336 );
337 }
338 }
339 }
340 }
341 }
342
343 #[test]
344 fn gate_notice_survives_unrelated_status_refresh_and_receipt_failure_keeps_masking() {
345 let temp = tempfile::tempdir().unwrap();
346 let path = temp.path().join("selected.toml");
347 std::fs::write(&path, "[redaction]\nmodel_bound = \"disabled\"\n").unwrap();
348 let config = codewhale_plugins::providers::load_config(Some(path.clone()), None).unwrap();
349 // An existing directory makes the write fail on every supported OS.
350 std::fs::create_dir(codewhale_config::redaction::model_bound_state_path(&path)).unwrap();
351 assert!(config.record_redaction_confirmation().is_err());
352 assert!(config.redaction_confirmation_required());
353 let mut app = app_fixture();
354 let notice = app.tr(MessageId::RedactionGateSaveFailed).into_owned();
355 app.push_status_toast_record(
356 crate::tui::app::StatusToast::new(
357 notice.clone(),
358 crate::tui::app::StatusToastLevel::Error,
359 None,
360 )
361 .for_redaction_gate(RedactionGateNotice::WriteFailure),
362 );
363 let hint = app.tr(MessageId::RedactionGateEnterHint).into_owned();
364 app.push_status_toast_record(
365 crate::tui::app::StatusToast::new(
366 hint.clone(),
367 crate::tui::app::StatusToastLevel::Info,
368 Some(12_000),
369 )
370 .for_redaction_gate(RedactionGateNotice::EnterGuidance),
371 );
372 app.push_status_toast(
373 "Unrelated runtime error",
374 crate::tui::app::StatusToastLevel::Error,
375 None,
376 );
377 app.show_event_notice(
378 "Unrelated runtime status",
379 crate::tui::app::StatusToastLevel::Info,
380 );
381 let lines = screen_lines(&app, 38, 6)
382 .into_iter()
383 .map(|line| line.to_string())
384 .collect::<Vec<_>>()
385 .join(" ");
386 assert!(lines.contains("Could not save confirmation"));
387 assert!(!lines.contains("Unrelated runtime status"));
388 assert!(!lines.contains("Unrelated runtime error"));
389 assert!(!lines.contains(&hint));
390 assert_eq!(
391 screen_lines(&app, 38, 6)[0].spans[0].style.fg,
392 Some(app.ui_theme.error_fg)
393 );
394 assert!(app.redaction_gate);
395 assert_eq!(
396 codewhale_config::redaction::effective_masking(
397 config.model_bound_redaction(),
398 config.loaded_config_path.as_deref()
399 ),
400 codewhale_config::redaction::ModelBoundMasking::Enabled
401 );
402 app.retire_redaction_gate_notice(RedactionGateNotice::EnterGuidance);
403 assert!(screen_lines(&app, 100, 24)[0].to_string().contains(&notice));
404 app.retire_redaction_gate_notice(RedactionGateNotice::WriteFailure);
405 let remaining = screen_lines(&app, 100, 24)
406 .into_iter()
407 .map(|line| line.to_string())
408 .collect::<Vec<_>>()
409 .join(" ");
410 assert!(!remaining.contains(&notice));
411 assert!(!remaining.contains("Unrelated runtime error"));
412 assert_eq!(
413 app.status_toasts
414 .iter()
415 .map(|notice| notice.text.as_str())
416 .collect::<Vec<_>>(),
417 ["Unrelated runtime error", "Unrelated runtime status"]
418 );
419 }
420
421 /// The red warning is part of both stages, and the second stage swaps the
422 /// "keep" action for a "back" action: you can only move forward with an
423 /// explicit second confirm.
424 #[test]
425 fn both_stages_show_the_danger_warning_and_second_stage_offers_back() {
426 let first = app_fixture();
427 let first_body = screen_lines(&first, 70, 24)
428 .into_iter()
429 .flat_map(|line| line.spans.into_iter().map(|span| span.content.to_string()))
430 .collect::<Vec<_>>()
431 .join("\n");
432 assert!(first_body.contains("Caution"), "{first_body}");
433
434 let mut confirming = app_fixture();
435 confirming.redaction_gate_confirming = true;
436 let confirm_body = screen_lines(&confirming, 70, 24)
437 .into_iter()
438 .flat_map(|line| line.spans.into_iter().map(|span| span.content.to_string()))
439 .collect::<Vec<_>>()
440 .join("\n");
441 assert!(confirm_body.contains("really sure"), "{confirm_body}");
442 assert!(confirm_body.contains("Caution"), "{confirm_body}");
443
444 let rail = action_hints(&confirming)
445 .iter()
446 .flat_map(|hint| action_footer_lines(std::slice::from_ref(hint), 60))
447 .flat_map(|line| {
448 line.spans
449 .into_iter()
450 .map(|span| span.content.to_string())
451 .collect::<Vec<_>>()
452 })
453 .collect::<Vec<_>>()
454 .join(" ");
455 assert!(rail.contains("back"), "{rail}");
456 assert!(
457 !rail.contains("keep"),
458 "second stage must not offer keep: {rail}"
459 );
460 assert!(rail.contains("quit"), "{rail}");
461 }
462 }
463
463 lines RUST