Files
codex/codex-rs/tui/src/bottom_pane/hooks_browser_view.rs
T
andrewgu-oai c483edf177 Include environment hooks in thread hook listings (#56553)
## Why

Listing hooks by working directory alone omits hooks supplied by a thread's selected execution environments, including hooks that can block a turn.

## What changed

- Add `threadId` to `hooks/list` to return a loaded thread's current hook inventory, including selected, ready environments. Reject requests that also specify `cwds`.
- Expose `environmentId` in hook metadata and have the TUI hooks browser query the current thread and label environment-owned hooks. Keep working-directory lookup for startup review.
- Represent environment hook source paths with `PathUri` and use `LegacyAppPathString` in hook run summaries to preserve native path conventions.

## Testing

Add coverage for listing a blocking environment hook and removing it after environment failure, delivering prompt input and reporting exit status in PowerShell and Bash, and running `PreToolUse` hooks only on the command's owning executor. Extend remote network tests to verify that environment hooks use the command's network policy while retaining their filesystem access.

GitOrigin-RevId: 97229e22793df51f4bd502c1f9e19f0c52fb2305
2026-10-23 18:39:28 +00:00

1697 lines
58 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use codex_app_server_protocol::HookEventName;
use codex_app_server_protocol::HookHandlerMetadata;
use codex_app_server_protocol::HookMetadata;
use codex_app_server_protocol::HookSource;
use codex_app_server_protocol::HookTrustStatus;
use codex_app_server_protocol::HooksListEntry;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
use ratatui::buffer::Buffer;
use ratatui::layout::Constraint;
use ratatui::layout::Layout;
use ratatui::layout::Rect;
use ratatui::style::Styled;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::text::Span;
use ratatui::widgets::Paragraph;
use ratatui::widgets::Widget;
use strum::IntoEnumIterator;
use self::render::detail_line;
use self::render::detail_wrapped_lines;
use super::CancellationEvent;
use super::bottom_pane_view::BottomPaneView;
use super::picker_style::selection_style;
use super::popup_consts::MAX_POPUP_ROWS;
use super::scroll_state::ScrollState;
use super::selection_popup_common::render_menu_surface;
use crate::app_event::AppEvent;
use crate::app_event_sender::AppEventSender;
use crate::hooks_rpc::HookTrustUpdate;
use crate::hooks_rpc::hook_needs_review;
use crate::key_hint;
use crate::key_hint::KeyBindingListExt;
use crate::keymap::ListAction;
use crate::keymap::ListKeymap;
use crate::line_truncation::truncate_line_with_ellipsis_if_overflow;
use crate::render::renderable::Renderable;
use crate::status::format_directory_display;
const EVENT_COLUMN_WIDTH: usize = 22;
const COUNT_COLUMN_WIDTH: usize = 12;
const MAX_COMMAND_DETAIL_LINES: usize = 3;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HooksBrowserPage {
Events,
Handlers(HookEventName),
}
pub(crate) struct HooksBrowserView {
entry: HooksListEntry,
page: HooksBrowserPage,
state: ScrollState,
complete: bool,
app_event_tx: AppEventSender,
keymap: ListKeymap,
}
impl HooksBrowserView {
#[cfg(test)]
pub(crate) fn new(
hooks: Vec<HookMetadata>,
warnings: Vec<String>,
errors: Vec<codex_app_server_protocol::HookErrorInfo>,
app_event_tx: AppEventSender,
) -> Self {
Self::from_entry(
HooksListEntry {
cwd: std::path::PathBuf::new(),
hooks,
warnings,
errors,
},
app_event_tx,
crate::keymap::RuntimeKeymap::defaults().list,
)
}
pub(crate) fn from_entry(
mut entry: HooksListEntry,
app_event_tx: AppEventSender,
keymap: ListKeymap,
) -> Self {
entry.hooks.sort_by_key(|hook| hook.display_order);
let mut view = Self {
entry,
page: HooksBrowserPage::Events,
state: ScrollState::new(),
complete: false,
app_event_tx,
keymap,
};
if view.page_len() > 0 {
view.state.selected_idx = Some(
view.event_rows()
.iter()
.position(|row| row.needs_review > 0)
.unwrap_or(0),
);
}
view
}
fn event_rows(&self) -> Vec<EventRow> {
codex_protocol::protocol::HookEventName::iter()
.map(|event_name| {
let event_name: HookEventName = event_name.into();
let installed = self
.entry
.hooks
.iter()
.filter(|hook| hook.event_name == event_name)
.count();
let active = self
.entry
.hooks
.iter()
.filter(|hook| hook.event_name == event_name && hook_is_active(hook))
.count();
let needs_review = self
.entry
.hooks
.iter()
.filter(|hook| hook.event_name == event_name && hook_needs_review(hook))
.count();
EventRow {
event_name,
installed,
active,
needs_review,
}
})
.collect()
}
fn handlers_for_event(&self, event_name: HookEventName) -> impl Iterator<Item = &HookMetadata> {
self.entry
.hooks
.iter()
.filter(move |hook| hook.event_name == event_name)
}
fn selected_event(&self) -> Option<HookEventName> {
self.state
.selected_idx
.and_then(|idx| codex_protocol::protocol::HookEventName::iter().nth(idx))
.map(Into::into)
}
fn selected_hook_index(&self, event_name: HookEventName) -> Option<usize> {
let selected_visible_idx = self.state.selected_idx?;
self.entry
.hooks
.iter()
.enumerate()
.filter(|(_, hook)| hook.event_name == event_name)
.nth(selected_visible_idx)
.map(|(idx, _)| idx)
}
fn selected_hook(&self, event_name: HookEventName) -> Option<&HookMetadata> {
self.selected_hook_index(event_name)
.and_then(|idx| self.entry.hooks.get(idx))
}
fn page_len(&self) -> usize {
match self.page {
HooksBrowserPage::Events => codex_protocol::protocol::HookEventName::iter().count(),
HooksBrowserPage::Handlers(event_name) => self.handlers_for_event(event_name).count(),
}
}
fn open_selected_event(&mut self) {
let Some(event_name) = self.selected_event() else {
return;
};
self.page = HooksBrowserPage::Handlers(event_name);
self.state = ScrollState::new();
if self.page_len() > 0 {
self.state.selected_idx = Some(0);
}
}
fn toggle_selected_hook(&mut self, event_name: HookEventName) {
let Some(idx) = self.selected_hook_index(event_name) else {
return;
};
let Some(hook) = self.entry.hooks.get_mut(idx) else {
return;
};
if hook.is_managed {
return;
}
if hook_needs_review(hook) {
return;
}
hook.enabled = !hook.enabled;
self.app_event_tx.send(AppEvent::SetHookEnabled {
key: hook.key.clone(),
enabled: hook.enabled,
});
}
fn trust_selected_hook(&mut self, event_name: HookEventName) {
let Some(idx) = self.selected_hook_index(event_name) else {
return;
};
let Some(hook) = self.entry.hooks.get_mut(idx) else {
return;
};
if !hook_needs_review(hook) {
return;
}
hook.trust_status = HookTrustStatus::Trusted;
self.app_event_tx.send(AppEvent::TrustHook {
key: hook.key.clone(),
current_hash: hook.current_hash.clone(),
});
}
fn trust_all_hooks(&mut self) {
let mut updates = Vec::new();
for hook in &mut self.entry.hooks {
if !hook_needs_review(hook) {
continue;
}
hook.trust_status = HookTrustStatus::Trusted;
updates.push(HookTrustUpdate {
key: hook.key.clone(),
current_hash: hook.current_hash.clone(),
});
}
if !updates.is_empty() {
self.app_event_tx.send(AppEvent::TrustHooks { updates });
}
}
fn close(&mut self) {
self.complete = true;
}
fn return_to_events(&mut self) {
let selected_event_name = match self.page {
HooksBrowserPage::Events => None,
HooksBrowserPage::Handlers(event_name) => Some(event_name),
};
self.page = HooksBrowserPage::Events;
self.state = ScrollState::new();
self.state.selected_idx = selected_event_name
.and_then(|event_name| {
codex_protocol::protocol::HookEventName::iter()
.position(|candidate| HookEventName::from(candidate) == event_name)
})
.or_else(|| (self.page_len() > 0).then_some(0));
}
fn event_header_lines() -> Vec<Line<'static>> {
vec![
"Hooks".bold().into(),
"Lifecycle hooks from config and enabled plugins."
.dim()
.into(),
]
}
fn review_needed_total_count(&self) -> usize {
self.entry
.hooks
.iter()
.filter(|hook| hook_needs_review(hook))
.count()
}
#[allow(clippy::disallowed_methods)]
fn handler_header_lines(
event_name: HookEventName,
review_needed_count: usize,
) -> Vec<Line<'static>> {
let mut lines = vec![format!("{} hooks", event_label(event_name)).bold().into()];
match review_needed_message(review_needed_count) {
None => lines.push(
"Turn hooks on or off. Your changes are saved automatically."
.dim()
.into(),
),
Some(message) => lines.push(message.yellow().into()),
}
lines
}
fn review_needed_count(&self, event_name: HookEventName) -> usize {
self.handlers_for_event(event_name)
.filter(|hook| hook_needs_review(hook))
.count()
}
#[allow(clippy::disallowed_methods)]
fn event_table_lines(&self) -> Vec<Line<'static>> {
let rows = self.event_rows();
let show_review = rows.iter().any(|row| row.needs_review > 0);
let mut lines = Vec::new();
let mut header = vec![
format!("{:<EVENT_COLUMN_WIDTH$}", "Event").into(),
format!("{:<COUNT_COLUMN_WIDTH$}", "Installed").into(),
format!("{:<COUNT_COLUMN_WIDTH$}", "Active").into(),
];
if show_review {
header.push(format!("{:<COUNT_COLUMN_WIDTH$}", "Review").into());
}
header.push("Description".into());
lines.push(Line::from(header));
for (idx, row) in rows.into_iter().enumerate() {
let selected = self.state.selected_idx == Some(idx);
let needs_review = row.needs_review > 0;
let mut row_line = vec![
Span::from(format!(
"{:<EVENT_COLUMN_WIDTH$}",
event_label(row.event_name)
)),
Span::from(format!("{:<COUNT_COLUMN_WIDTH$}", row.installed)),
Span::from(format!("{:<COUNT_COLUMN_WIDTH$}", row.active)),
];
if show_review {
let review_count = Span::from(format!("{:<COUNT_COLUMN_WIDTH$}", row.needs_review));
row_line.push(if needs_review {
review_count.yellow()
} else {
review_count
});
}
row_line.push(Span::from(event_description(row.event_name)));
if selected {
let style = selection_style();
for span in &mut row_line {
*span = span.clone().set_style(style);
}
} else {
row_line[1] = row_line[1].clone().dim();
row_line[2] = row_line[2].clone().dim();
if show_review && !needs_review {
row_line[3] = row_line[3].clone().dim();
}
let description_idx = row_line.len() - 1;
row_line[description_idx] = row_line[description_idx].clone().dim();
}
lines.push(if selected {
Line::from(row_line).style(selection_style())
} else {
Line::from(row_line)
});
}
lines
}
fn event_issue_lines(&self) -> Vec<Line<'static>> {
let mut lines = Vec::new();
if self.entry.warnings.is_empty() && self.entry.errors.is_empty() {
return lines;
}
lines.push("Issues".bold().into());
lines.extend(
self.entry
.warnings
.iter()
.map(|warning| format!("⚠ {warning}").into()),
);
lines.extend(self.entry.errors.iter().map(|error| {
format!("■ {}: {}", error.path.display(), error.message)
.red()
.into()
}));
lines
}
#[allow(clippy::disallowed_methods)]
fn event_page_lines(&self) -> Vec<Line<'static>> {
let mut lines = Self::event_header_lines();
lines.push(Line::default());
if let Some(message) = review_needed_message(self.review_needed_total_count()) {
lines.push(format!("⚠ {message}").yellow().into());
lines.push(Line::default());
}
let issue_lines = self.event_issue_lines();
if !issue_lines.is_empty() {
lines.extend(issue_lines);
lines.push(Line::default());
}
lines.extend(self.event_table_lines());
lines
}
#[allow(clippy::disallowed_methods)]
fn handler_row_lines(&self, event_name: HookEventName, width: usize) -> Vec<Line<'static>> {
let index_width = self
.handlers_for_event(event_name)
.count()
.to_string()
.len()
.max(2);
self.handlers_for_event(event_name)
.enumerate()
.map(|(idx, hook)| {
let marker = if hook_needs_review(hook) {
'!'
} else if hook_is_active(hook) {
'x'
} else {
' '
};
let title = hook
.status_message
.as_deref()
.map(str::trim)
.filter(|title| !title.is_empty())
.unwrap_or("Unnamed hook");
let trust_suffix = match hook.trust_status {
HookTrustStatus::Modified => " · modified",
HookTrustStatus::Untrusted => " · new",
HookTrustStatus::Managed | HookTrustStatus::Trusted => "",
};
let prefix = if self.state.selected_idx == Some(idx) {
"› "
} else {
" "
};
let mut line = Line::from(vec![
format!("{prefix}[{marker}] ").into(),
format!("{:>index_width$}", idx + 1).dim(),
format!(" {title}{trust_suffix}").into(),
]);
line = truncate_line_with_ellipsis_if_overflow(line, width);
let needs_review = hook_needs_review(hook);
if self.state.selected_idx == Some(idx) {
line = line.patch_style(selection_style());
} else if needs_review {
line = line.yellow();
} else if hook.is_managed {
line = line.dim();
}
line
})
.collect()
}
fn detail_lines(
&self,
event_name: HookEventName,
width: usize,
) -> Vec<crate::terminal_hyperlinks::HyperlinkLine> {
let Some(hook) = self.selected_hook(event_name) else {
return crate::terminal_hyperlinks::plain_hyperlink_lines(vec![
"No hooks installed for this event.".dim().into(),
]);
};
let mut lines = vec![detail_line("Event", event_label(event_name))];
if let Some(matcher) = hook.matcher.as_deref() {
lines.extend(detail_wrapped_lines(
"Matcher", matcher, width, /*max_lines*/ None,
));
}
lines.extend(detail_wrapped_lines(
"Source",
&detail_source_value(hook),
width,
/*max_lines*/ None,
));
match &hook.handler {
HookHandlerMetadata::Command { command, r#async } => {
lines.extend(detail_wrapped_lines(
"Command",
command,
width,
Some(MAX_COMMAND_DETAIL_LINES),
));
lines.push(detail_line("Mode", if *r#async { "Async" } else { "Sync" }));
}
HookHandlerMetadata::McpTool { server, tool } => {
lines.extend(detail_wrapped_lines(
"MCP Server",
server,
width,
/*max_lines*/ None,
));
lines.extend(detail_wrapped_lines(
"MCP Tool", tool, width, /*max_lines*/ None,
));
}
HookHandlerMetadata::Prompt {} => {
lines.push(detail_line("Handler", "Prompt"));
}
HookHandlerMetadata::Agent {} => {
lines.push(detail_line("Handler", "Agent"));
}
}
lines.push(detail_line("Timeout", &format!("{}s", hook.timeout_sec)));
if let Some(limit) = hook.additional_context_limit {
let value = if limit == 0 {
"unlimited".to_string()
} else {
format!("limit: {limit} approximate tokens")
};
lines.push(detail_line("Context", &value));
}
lines.push(detail_line("Trust", hook_trust_label(hook.trust_status)));
lines
}
fn render_footer(&self, area: Rect, buf: &mut Buffer) {
let hint_area = Rect {
x: area.x + 2,
y: area.y,
width: area.width.saturating_sub(2),
height: area.height,
};
let accept = self.keymap.primary_hint(ListAction::Accept);
let cancel = self
.keymap
.primary_hint(ListAction::Cancel)
.unwrap_or_else(|| key_hint::plain(KeyCode::Esc).into());
let mut spans = Vec::new();
match self.page {
HooksBrowserPage::Events => {
if self.review_needed_total_count() > 0 {
spans.extend(key_hint::plain(KeyCode::Char('t')).spans());
spans.push(" trust all · ".dim());
if let Some(accept) = accept {
spans.extend(accept.spans());
spans.push(" review · ".dim());
}
} else if let Some(accept) = accept {
spans.extend(accept.spans());
spans.push(" details · ".dim());
}
spans.extend(cancel.spans());
spans.push(" close".dim());
}
HooksBrowserPage::Handlers(event_name) => {
if let Some(hook) = self.selected_hook(event_name) {
if hook.is_managed {
spans.push("Managed (always on) · ".dim());
} else if hook_needs_review(hook) {
spans.extend(key_hint::plain(KeyCode::Char('t')).spans());
spans.push(" trust · ".dim());
} else {
let mut toggle = key_hint::plain(KeyCode::Char(' ')).display_label();
if let Some(accept) = accept {
toggle.push('/');
toggle.push_str(&accept.display_label());
}
spans.extend(key_hint::key_label_spans(&toggle));
spans.push(" toggle · ".dim());
}
}
spans.extend(cancel.spans());
spans.push(" back".dim());
}
}
let footer = Line::from(spans);
footer.dim().render(hint_area, buf);
}
}
impl BottomPaneView for HooksBrowserView {
fn keymap_contexts(&self) -> crate::keymap::KeymapContextSet {
crate::keymap::KeymapContextSet::new(crate::keymap::KeymapContext::List)
}
fn handle_key_event(&mut self, key_event: KeyEvent) {
if let Some(action) = self.keymap.vertical_action_for(key_event) {
let len = self.page_len();
self.state
.apply_vertical_action(action, len, MAX_POPUP_ROWS.min(len.max(1)));
return;
}
match key_event {
_ if self.keymap.accept.is_pressed(key_event)
&& self.page == HooksBrowserPage::Events =>
{
self.open_selected_event()
}
_ if self.keymap.accept.is_pressed(key_event) => {
if let HooksBrowserPage::Handlers(event_name) = self.page {
self.toggle_selected_hook(event_name);
}
}
KeyEvent {
code: KeyCode::Char(' '),
modifiers: KeyModifiers::NONE,
..
} => {
if let HooksBrowserPage::Handlers(event_name) = self.page {
self.toggle_selected_hook(event_name);
}
}
KeyEvent {
code: KeyCode::Char('t'),
modifiers: KeyModifiers::NONE,
..
} => match self.page {
HooksBrowserPage::Events => self.trust_all_hooks(),
HooksBrowserPage::Handlers(event_name) => self.trust_selected_hook(event_name),
},
_ if self.keymap.cancel.is_pressed(key_event) => match self.page {
HooksBrowserPage::Events => self.close(),
HooksBrowserPage::Handlers(_) => self.return_to_events(),
},
_ => {}
}
}
fn is_complete(&self) -> bool {
self.complete
}
fn on_ctrl_c(&mut self) -> CancellationEvent {
self.close();
CancellationEvent::Handled
}
fn prefer_esc_to_handle_key_event(&self) -> bool {
true
}
}
#[path = "hooks_browser_render.rs"]
mod render;
fn hook_is_active(hook: &HookMetadata) -> bool {
hook.enabled
&& matches!(
hook.trust_status,
HookTrustStatus::Managed | HookTrustStatus::Trusted
)
}
fn review_needed_message(count: usize) -> Option<String> {
match count {
0 => None,
1 => Some("1 hook needs review before it can run.".to_string()),
count => Some(format!("{count} hooks need review before they can run.")),
}
}
struct EventRow {
event_name: HookEventName,
installed: usize,
active: usize,
needs_review: usize,
}
fn hook_trust_label(status: HookTrustStatus) -> &'static str {
match status {
HookTrustStatus::Managed => "Managed",
HookTrustStatus::Trusted => "Trusted",
HookTrustStatus::Untrusted => "New hook - review required",
HookTrustStatus::Modified => "Modified since last trusted - review required",
}
}
fn event_label(event_name: HookEventName) -> &'static str {
match event_name {
HookEventName::PreToolUse => "PreToolUse",
HookEventName::PermissionRequest => "PermissionRequest",
HookEventName::PostToolUse => "PostToolUse",
HookEventName::PreCompact => "PreCompact",
HookEventName::PostCompact => "PostCompact",
HookEventName::PreModelRequest => "PreModelRequest",
HookEventName::PostModelRequest => "PostModelRequest",
HookEventName::SessionStart => "SessionStart",
HookEventName::SessionEnd => "SessionEnd",
HookEventName::UserPromptSubmit => "UserPromptSubmit",
HookEventName::SubagentStart => "SubagentStart",
HookEventName::SubagentStop => "SubagentStop",
HookEventName::Stop => "Stop",
HookEventName::Interrupt => "Interrupt",
}
}
fn event_description(event_name: HookEventName) -> &'static str {
match event_name {
HookEventName::PreToolUse => "Before a tool executes",
HookEventName::PermissionRequest => "When permission is requested",
HookEventName::PostToolUse => "After a tool executes",
HookEventName::PreCompact => "Before context compaction",
HookEventName::PostCompact => "After context compaction",
HookEventName::PreModelRequest => "Before a model request",
HookEventName::PostModelRequest => "After a model request, including failures",
HookEventName::SessionStart => "When a new session starts",
HookEventName::SessionEnd => "Right before a session ends",
HookEventName::UserPromptSubmit => "When the user submits a prompt",
HookEventName::SubagentStart => "When a subagent is created",
HookEventName::SubagentStop => "Right before a subagent ends its turn",
HookEventName::Stop => "Right before Codex ends its turn",
HookEventName::Interrupt => "Right before an interrupted turn is aborted",
}
}
fn hook_source_summary(hook: &HookMetadata) -> String {
if let Some(id) = &hook.environment_id {
return format!("Environment - {id}");
}
match hook.source {
HookSource::Plugin => hook
.plugin_id
.as_deref()
.map(|plugin_id| format!("Plugin - {plugin_id}"))
.unwrap_or_else(|| "Plugin".to_string()),
_ => config_source_label(hook.source).to_string(),
}
}
fn detail_source_value(hook: &HookMetadata) -> String {
if hook.environment_id.is_some() {
return hook_source_summary(hook);
}
match hook.source {
HookSource::Plugin => hook_source_summary(hook),
HookSource::System
| HookSource::Mdm
| HookSource::CloudRequirements
| HookSource::CloudManagedConfig
| HookSource::LegacyManagedConfigFile
| HookSource::LegacyManagedConfigMdm => config_source_label(hook.source).to_string(),
_ => format!(
"{} - {}",
config_source_label(hook.source),
format_directory_display(&hook.source_path, /*max_width*/ None)
),
}
}
fn config_source_label(source: HookSource) -> &'static str {
match source {
HookSource::System => "Admin config",
HookSource::User => "User config",
HookSource::Project => "Project config",
HookSource::Mdm => "Admin config",
HookSource::SessionFlags => "Session flags",
HookSource::Plugin => unreachable!("plugin hooks are handled by summary_source"),
HookSource::CloudRequirements => "Admin config",
HookSource::CloudManagedConfig => "Cloud-managed config",
HookSource::LegacyManagedConfigFile => "Admin config",
HookSource::LegacyManagedConfigMdm => "Admin config",
HookSource::Unknown => "Unknown source",
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::app_event::AppEvent;
use crate::app_event_sender::AppEventSender;
use crate::bottom_pane::bottom_pane_view::BottomPaneView;
use crate::render::renderable::Renderable;
use crate::test_support::PathBufExt;
use crate::test_support::test_path_buf;
use crate::test_support::test_path_display;
use codex_app_server_protocol::HookErrorInfo;
use codex_app_server_protocol::HookEventName;
use codex_app_server_protocol::HookHandlerMetadata;
use codex_app_server_protocol::HookMetadata;
use codex_app_server_protocol::HookSource;
use codex_app_server_protocol::HookTrustStatus;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use insta::assert_snapshot;
use pretty_assertions::assert_eq;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Color;
use ratatui::style::Modifier;
use tokio::sync::mpsc::unbounded_channel;
pub(super) fn render_lines(view: &HooksBrowserView, width: u16) -> String {
let height = view.desired_height(width);
let area = Rect::new(0, 0, width, height);
let mut buf = Buffer::empty(area);
view.render(area, &mut buf);
(0..area.height)
.map(|row| {
let rendered = (0..area.width)
.map(|col| {
let symbol = buf[(area.x + col, area.y + row)].symbol();
if symbol.is_empty() {
" ".to_string()
} else {
crate::terminal_hyperlinks::strip_osc8(symbol)
}
})
.collect::<String>();
let normalized = rendered
.replace(&test_path_display("/tmp/hooks.json"), "/tmp/hooks.json")
.replace(&test_path_display("/tmp/h.json"), "/tmp/h.json");
format!("{normalized:width$}", width = area.width as usize)
})
.collect::<Vec<_>>()
.join("\n")
}
pub(super) fn render_buffer(view: &HooksBrowserView, width: u16) -> Buffer {
let height = view.desired_height(width);
let area = Rect::new(0, 0, width, height);
let mut buf = Buffer::empty(area);
view.render(area, &mut buf);
buf
}
#[allow(clippy::too_many_arguments)]
pub(super) fn hook(
key: &str,
event_name: HookEventName,
source: HookSource,
plugin_id: Option<&str>,
command: &str,
enabled: bool,
is_managed: bool,
display_order: i64,
) -> HookMetadata {
let current_hash = "sha256:current".to_string();
HookMetadata {
key: key.to_string(),
event_name,
handler: HookHandlerMetadata::Command {
command: command.to_string(),
r#async: false,
},
is_managed,
matcher: Some("Bash".to_string()),
timeout_sec: 30,
status_message: None,
additional_context_limit: None,
source_path: test_path_buf("/tmp/hooks.json").abs(),
source,
plugin_id: plugin_id.map(str::to_string),
environment_id: None,
display_order,
enabled,
current_hash,
trust_status: if is_managed {
HookTrustStatus::Managed
} else {
HookTrustStatus::Trusted
},
}
}
fn view() -> HooksBrowserView {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
HooksBrowserView::new(
vec![
hook(
"plugin:superpowers",
HookEventName::PreToolUse,
HookSource::Plugin,
Some("superpowers@openai-curated"),
"${CODEX_PLUGIN_ROOT}/hooks/pre-tool-use-check.sh",
/*enabled*/ true,
/*is_managed*/ false,
/*display_order*/ 0,
),
hook(
"path:user-config",
HookEventName::PreToolUse,
HookSource::User,
/*plugin_id*/ None,
"~/bin/check-shell-with-a-command-that-is-way-too-long-for-the-summary-column.sh",
/*enabled*/ false,
/*is_managed*/ false,
/*display_order*/ 1,
),
hook(
"path:managed",
HookEventName::PermissionRequest,
HookSource::System,
/*plugin_id*/ None,
"/enterprise/hooks/permission-check.sh",
/*enabled*/ true,
/*is_managed*/ true,
/*display_order*/ 2,
),
],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
)
}
#[test]
fn renders_event_browser() {
let mut view = view();
assert_snapshot!("hooks_browser_events", render_lines(&view, /*width*/ 112));
view.state.selected_idx = Some(view.event_rows().len() - 1);
assert_snapshot!(
"hooks_browser_model_requests",
render_lines(&view, /*width*/ 112),
);
view.keymap.accept.clear();
assert!(!render_lines(&view, /*width*/ 112).contains("enter details"));
}
#[test]
fn compact_hooks_keep_the_last_event_and_selection_visible() {
let mut view = view();
view.state.selected_idx = Some(view.event_rows().len() - 1);
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 40, /*height*/ 16,
);
let mut buf = Buffer::empty(area);
view.render(area, &mut buf);
let text = (0..area.height)
.map(|y| {
(0..area.width)
.map(|x| buf[(x, y)].symbol())
.collect::<String>()
.trim_end()
.to_owned()
})
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(text);
let selected_y = text
.lines()
.position(|line| line.starts_with("› "))
.unwrap() as u16;
assert_eq!(buf[(0, selected_y)].bg, selection_style().bg.unwrap());
assert_eq!(buf[(39, selected_y)].bg, selection_style().bg.unwrap());
assert!(text.contains("Interrupt"));
assert!(text.contains("Active/Installed"));
}
#[test]
fn selected_event_rows_use_the_shared_selection_style() {
let view = view();
let buf = render_buffer(&view, /*width*/ 112);
let expected = selection_style();
let selected_cell = buf
.content
.iter()
.find(|cell| {
let style = cell.style();
cell.symbol() == "P"
&& style.fg == expected.fg
&& style.add_modifier.contains(Modifier::BOLD)
})
.expect("selected event row should use the shared accent style");
assert_eq!(selected_cell.style().fg, expected.fg);
}
#[test]
fn renders_event_browser_with_review_column_when_needed() {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
let mut untrusted_hook = hook(
"path:untrusted",
HookEventName::PreToolUse,
HookSource::User,
/*plugin_id*/ None,
"/tmp/pre-tool-use-check.sh",
/*enabled*/ false,
/*is_managed*/ false,
/*display_order*/ 0,
);
untrusted_hook.trust_status = HookTrustStatus::Untrusted;
let view = HooksBrowserView::new(
vec![untrusted_hook],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
assert_snapshot!(
"hooks_browser_events_with_review_column",
render_lines(&view, /*width*/ 112)
);
assert_eq!(
view.event_table_lines()[1].spans[3].style.fg,
selection_style().fg
);
assert!(
view.event_table_lines()[1].spans[3]
.style
.add_modifier
.contains(ratatui::style::Modifier::BOLD)
);
}
#[test]
fn renders_event_browser_with_issues() {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
let view = HooksBrowserView::new(
Vec::new(),
vec!["skipped invalid matcher for PreToolUse".to_string()],
vec![HookErrorInfo {
path: test_path_buf("/tmp/hooks.json"),
message: "failed to parse hooks config".to_string(),
}],
AppEventSender::new(tx_raw),
);
assert_snapshot!(
"hooks_browser_events_with_issues",
render_lines(&view, /*width*/ 112)
);
}
#[test]
fn renders_handler_browser_with_details() {
let mut view = view();
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert_snapshot!("hooks_browser_handlers", render_lines(&view, /*width*/ 112));
}
#[test]
fn renders_handler_status_messages_with_blank_fallback() {
let mut view = view();
view.entry.hooks[0].status_message = Some(" 检查 🦀 shell commands ".to_string());
view.entry.hooks[1].status_message = Some(" \t\n ".to_string());
view.entry.hooks[2].event_name = HookEventName::PreToolUse;
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert_snapshot!(
"hooks_browser_status_messages",
render_lines(&view, /*width*/ 112)
);
for (fg, bg) in [
((230, 230, 230), (18, 20, 30)),
((32, 32, 32), (255, 255, 255)),
] {
crate::terminal_palette::with_test_default_colors(
crate::terminal_probe::DefaultColors { fg, bg },
|| {
let buf = render_buffer(&view, /*width*/ 112);
let selected_y = (0..buf.area.height)
.find(|&y| buf[(0, y)].symbol() == "›")
.expect("selected hook row");
for y in [selected_y, selected_y + 1] {
assert!(buf[(7, y)].modifier.contains(Modifier::DIM));
assert!(!buf[(10, y)].modifier.contains(Modifier::DIM));
}
assert_eq!(buf[(10, selected_y)].symbol(), "检");
assert_eq!(buf[(10, selected_y)].fg, selection_style().fg.unwrap());
assert_eq!(
(0..buf.area.width)
.map(|x| buf[(x, selected_y)].bg)
.collect::<Vec<_>>(),
vec![selection_style().bg.unwrap(); usize::from(buf.area.width)]
);
},
);
}
}
#[test]
fn renders_mcp_tool_handler_with_server_and_tool_details() {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
let mut configured_hook = hook(
"plugin:security-scanner",
HookEventName::PreToolUse,
HookSource::Plugin,
Some("security-tools@openai-curated"),
"",
/*enabled*/ true,
/*is_managed*/ false,
/*display_order*/ 0,
);
configured_hook.handler = HookHandlerMetadata::McpTool {
server: "scanner".to_string(),
tool: "scan_file".to_string(),
};
let mut view = HooksBrowserView::new(
vec![configured_hook],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert_snapshot!(
"hooks_browser_mcp_tool_handler",
render_lines(&view, /*width*/ 112)
);
}
#[test]
fn renders_handler_additional_context_limit() {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
let mut configured_hook = hook(
"path:context-limit",
HookEventName::PreToolUse,
HookSource::User,
/*plugin_id*/ None,
"/tmp/pre-tool-use.sh",
/*enabled*/ true,
/*is_managed*/ false,
/*display_order*/ 0,
);
configured_hook.additional_context_limit = Some(0);
let mut view = HooksBrowserView::new(
vec![configured_hook],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert_snapshot!(
"hooks_browser_additional_context_limit",
render_lines(&view, /*width*/ 112)
);
}
#[test]
fn renders_untrusted_enabled_handler_as_inactive() {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
let mut untrusted_hook = hook(
"path:untrusted",
HookEventName::PreToolUse,
HookSource::User,
/*plugin_id*/ None,
"~/bin/untrusted.sh",
/*enabled*/ true,
/*is_managed*/ false,
/*display_order*/ 0,
);
untrusted_hook.trust_status = HookTrustStatus::Untrusted;
let HookHandlerMetadata::Command { r#async, .. } = &mut untrusted_hook.handler else {
panic!("expected command hook");
};
*r#async = true;
let mut view = HooksBrowserView::new(
vec![untrusted_hook],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert_snapshot!(
"hooks_browser_untrusted_enabled_handler",
render_lines(&view, /*width*/ 112)
);
}
#[test]
fn review_needed_handler_rows_use_warning_color() {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
let mut untrusted_hook = hook(
"path:untrusted",
HookEventName::PreToolUse,
HookSource::User,
/*plugin_id*/ None,
"~/bin/untrusted.sh",
/*enabled*/ false,
/*is_managed*/ false,
/*display_order*/ 1,
);
untrusted_hook.trust_status = HookTrustStatus::Untrusted;
let mut view = HooksBrowserView::new(
vec![
hook(
"path:trusted",
HookEventName::PreToolUse,
HookSource::User,
/*plugin_id*/ None,
"~/bin/trusted.sh",
/*enabled*/ true,
/*is_managed*/ false,
/*display_order*/ 0,
),
untrusted_hook,
],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert_eq!(
view.handler_row_lines(HookEventName::PreToolUse, /*width*/ 112)[1]
.style
.fg,
Some(Color::Yellow)
);
}
#[test]
fn review_needed_handler_header_uses_warning_color() {
assert_eq!(
HooksBrowserView::handler_header_lines(
HookEventName::PreToolUse,
/*review_needed_count*/ 1,
)[1]
.spans[0]
.style
.fg,
Some(Color::Yellow)
);
}
#[test]
fn renders_managed_handler_without_toggle_hint() {
let mut view = view();
view.handle_key_event(KeyEvent::from(KeyCode::Down));
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert_snapshot!(
"hooks_browser_managed_handler",
render_lines(&view, /*width*/ 112)
);
}
#[test]
fn renders_selected_managed_handler() {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
let mut view = HooksBrowserView::new(
vec![
hook(
"path:managed-1",
HookEventName::PreToolUse,
HookSource::System,
/*plugin_id*/ None,
"/enterprise/hooks/pre-tool-use-1.sh",
/*enabled*/ true,
/*is_managed*/ true,
/*display_order*/ 0,
),
hook(
"path:managed-2",
HookEventName::PreToolUse,
HookSource::System,
/*plugin_id*/ None,
"/enterprise/hooks/pre-tool-use-2.sh",
/*enabled*/ true,
/*is_managed*/ true,
/*display_order*/ 1,
),
],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
view.handle_key_event(KeyEvent::from(KeyCode::Down));
assert_snapshot!(
"hooks_browser_selected_managed_handler",
render_lines(&view, /*width*/ 112)
);
}
#[test]
fn renders_scrolled_handler_window() {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
let hooks = (0..MAX_POPUP_ROWS + 3)
.map(|idx| {
let mut hook = hook(
&format!("path:hook-{idx}"),
HookEventName::PreToolUse,
HookSource::User,
/*plugin_id*/ None,
&format!("/tmp/hook-{idx}.sh"),
/*enabled*/ true,
/*is_managed*/ false,
idx as i64,
);
if idx % 2 == 0 {
hook.status_message = Some(format!("Check tool {}", idx + 1));
}
hook
})
.collect();
let mut view =
HooksBrowserView::new(hooks, Vec::new(), Vec::new(), AppEventSender::new(tx_raw));
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
for _ in 0..MAX_POPUP_ROWS + 1 {
view.handle_key_event(KeyEvent::from(KeyCode::Down));
}
assert_snapshot!(
"hooks_browser_scrolled_handlers",
render_lines(&view, /*width*/ 112)
);
assert_eq!(
view.selected_hook(HookEventName::PreToolUse)
.map(|hook| hook.key.as_str()),
Some("path:hook-9")
);
}
#[test]
fn renders_command_details_with_three_line_cap() {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
let mut capped_command_hook = hook(
"path:long-command",
HookEventName::PreToolUse,
HookSource::User,
/*plugin_id*/ None,
"one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty",
/*enabled*/ true,
/*is_managed*/ false,
/*display_order*/ 0,
);
capped_command_hook.source_path = test_path_buf("/tmp/h.json").abs();
capped_command_hook.status_message =
Some("Check shell commands before allowing them to execute".to_string());
let mut view = HooksBrowserView::new(
vec![capped_command_hook],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert_snapshot!(
"hooks_browser_capped_command_details",
render_lines(&view, /*width*/ 44)
);
}
#[test]
fn renders_empty_handler_browser_message() {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
let mut view = HooksBrowserView::new(
Vec::new(),
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
view.handle_key_event(KeyEvent::from(KeyCode::Down));
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert_snapshot!(
"hooks_browser_empty_handlers",
render_lines(&view, /*width*/ 112)
);
}
#[test]
fn managed_hooks_count_as_active() {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
let view = HooksBrowserView::new(
vec![hook(
"path:managed",
HookEventName::PreToolUse,
HookSource::System,
/*plugin_id*/ None,
"/enterprise/hooks/pre-tool-use-check.sh",
/*enabled*/ true,
/*is_managed*/ true,
/*display_order*/ 0,
)],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
let rows = view.event_rows();
let pre_tool_use = rows
.into_iter()
.find(|row| row.event_name == HookEventName::PreToolUse)
.expect("pre tool use row");
assert_eq!(pre_tool_use.installed, 1);
assert_eq!(pre_tool_use.active, 1);
}
#[test]
fn review_needed_hooks_are_not_active() {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
let mut untrusted_hook = hook(
"path:untrusted",
HookEventName::PreToolUse,
HookSource::User,
/*plugin_id*/ None,
"/tmp/pre-tool-use-check.sh",
/*enabled*/ true,
/*is_managed*/ false,
/*display_order*/ 0,
);
untrusted_hook.trust_status = HookTrustStatus::Untrusted;
let view = HooksBrowserView::new(
vec![untrusted_hook],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
let rows = view.event_rows();
let pre_tool_use = rows
.into_iter()
.find(|row| row.event_name == HookEventName::PreToolUse)
.expect("pre tool use row");
assert_eq!(pre_tool_use.installed, 1);
assert_eq!(pre_tool_use.active, 0);
assert_eq!(pre_tool_use.needs_review, 1);
}
#[test]
fn review_needed_event_is_selected_by_default() {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
let mut untrusted_hook = hook(
"path:untrusted",
HookEventName::PermissionRequest,
HookSource::User,
/*plugin_id*/ None,
"/tmp/permission-request-check.sh",
/*enabled*/ false,
/*is_managed*/ false,
/*display_order*/ 0,
);
untrusted_hook.trust_status = HookTrustStatus::Untrusted;
let view = HooksBrowserView::new(
vec![untrusted_hook],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
assert_eq!(
view.selected_event(),
Some(HookEventName::PermissionRequest)
);
}
#[test]
fn renders_review_needed_handler() {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
let mut untrusted_hook = hook(
"path:untrusted",
HookEventName::PreToolUse,
HookSource::User,
/*plugin_id*/ None,
"/tmp/pre-tool-use-check.sh",
/*enabled*/ false,
/*is_managed*/ false,
/*display_order*/ 0,
);
untrusted_hook.trust_status = HookTrustStatus::Untrusted;
let mut view = HooksBrowserView::new(
vec![untrusted_hook],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert_snapshot!(
"hooks_browser_review_needed_handler",
render_lines(&view, /*width*/ 112)
);
}
fn assert_unmanaged_toggle_key(key_code: KeyCode) {
let (tx_raw, mut rx) = unbounded_channel::<AppEvent>();
let mut view = HooksBrowserView::new(
vec![hook(
"plugin:superpowers",
HookEventName::PreToolUse,
HookSource::Plugin,
Some("superpowers@openai-curated"),
"hooks/pre-tool-use-check.sh",
/*enabled*/ true,
/*is_managed*/ false,
/*display_order*/ 0,
)],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
view.handle_key_event(KeyEvent::from(key_code));
match rx.try_recv().expect("toggle event") {
AppEvent::SetHookEnabled { key, enabled } => {
assert_eq!(key, "plugin:superpowers");
assert!(!enabled);
}
other => panic!("expected hook toggle event, got {other:?}"),
}
}
#[test]
fn toggle_keys_toggle_unmanaged_handler() {
for key_code in [KeyCode::Char(' '), KeyCode::Enter] {
assert_unmanaged_toggle_key(key_code);
}
}
#[test]
fn space_does_not_toggle_managed_handler() {
let (tx_raw, mut rx) = unbounded_channel::<AppEvent>();
let mut view = HooksBrowserView::new(
vec![hook(
"path:managed",
HookEventName::PreToolUse,
HookSource::System,
/*plugin_id*/ None,
"/enterprise/hooks/pre-tool-use-check.sh",
/*enabled*/ true,
/*is_managed*/ true,
/*display_order*/ 0,
)],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
view.handle_key_event(KeyEvent::from(KeyCode::Char(' ')));
assert!(rx.try_recv().is_err());
}
#[test]
fn trust_key_trusts_review_needed_handler_without_changing_enablement() {
let (tx_raw, mut rx) = unbounded_channel::<AppEvent>();
let mut untrusted_hook = hook(
"path:untrusted",
HookEventName::PreToolUse,
HookSource::User,
/*plugin_id*/ None,
"/tmp/pre-tool-use-check.sh",
/*enabled*/ false,
/*is_managed*/ false,
/*display_order*/ 0,
);
untrusted_hook.trust_status = HookTrustStatus::Untrusted;
let current_hash = untrusted_hook.current_hash.clone();
let mut view = HooksBrowserView::new(
vec![untrusted_hook],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
view.handle_key_event(KeyEvent::from(KeyCode::Char('t')));
match rx.try_recv().expect("trust event") {
AppEvent::TrustHook {
key,
current_hash: hash_to_trust,
} => {
assert_eq!(key, "path:untrusted");
assert_eq!(hash_to_trust, current_hash);
}
other => panic!("expected hook trust event, got {other:?}"),
}
}
#[test]
fn trust_key_preserves_disabled_modified_handler() {
let (tx_raw, mut rx) = unbounded_channel::<AppEvent>();
let mut modified_hook = hook(
"path:modified",
HookEventName::PreToolUse,
HookSource::User,
/*plugin_id*/ None,
"/tmp/pre-tool-use-check.sh",
/*enabled*/ false,
/*is_managed*/ false,
/*display_order*/ 0,
);
modified_hook.trust_status = HookTrustStatus::Modified;
let current_hash = modified_hook.current_hash.clone();
let mut view = HooksBrowserView::new(
vec![modified_hook],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
view.handle_key_event(KeyEvent::from(KeyCode::Char('t')));
let hook = view.entry.hooks.first().expect("trusted hook");
assert!(!hook.enabled);
assert_eq!(hook.trust_status, HookTrustStatus::Trusted);
match rx.try_recv().expect("trust event") {
AppEvent::TrustHook {
key,
current_hash: hash_to_trust,
} => {
assert_eq!(key, "path:modified");
assert_eq!(hash_to_trust, current_hash);
}
other => panic!("expected hook trust event, got {other:?}"),
}
}
#[test]
fn trust_key_on_event_page_trusts_all_review_needed_hooks() {
let (tx_raw, mut rx) = unbounded_channel::<AppEvent>();
let mut untrusted_hook = hook(
"path:untrusted",
HookEventName::PreToolUse,
HookSource::User,
/*plugin_id*/ None,
"/tmp/pre-tool-use-check.sh",
/*enabled*/ false,
/*is_managed*/ false,
/*display_order*/ 0,
);
untrusted_hook.trust_status = HookTrustStatus::Untrusted;
let mut modified_hook = hook(
"path:modified",
HookEventName::Stop,
HookSource::User,
/*plugin_id*/ None,
"/tmp/stop-check.sh",
/*enabled*/ false,
/*is_managed*/ false,
/*display_order*/ 1,
);
modified_hook.trust_status = HookTrustStatus::Modified;
let mut view = HooksBrowserView::new(
vec![
untrusted_hook,
modified_hook,
hook(
"path:trusted",
HookEventName::PreToolUse,
HookSource::User,
/*plugin_id*/ None,
"/tmp/trusted.sh",
/*enabled*/ true,
/*is_managed*/ false,
/*display_order*/ 2,
),
],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
view.handle_key_event(KeyEvent::from(KeyCode::Char('t')));
assert_eq!(
view.entry
.hooks
.iter()
.map(|hook| hook.trust_status)
.collect::<Vec<_>>(),
vec![
HookTrustStatus::Trusted,
HookTrustStatus::Trusted,
HookTrustStatus::Trusted,
]
);
match rx.try_recv().expect("trust event") {
AppEvent::TrustHooks { updates } => assert_eq!(
updates,
vec![
HookTrustUpdate {
key: "path:untrusted".to_string(),
current_hash: "sha256:current".to_string(),
},
HookTrustUpdate {
key: "path:modified".to_string(),
current_hash: "sha256:current".to_string(),
},
]
),
other => panic!("expected hook trust event, got {other:?}"),
}
assert!(rx.try_recv().is_err());
}
#[test]
fn escape_returns_to_the_selected_event() {
let mut view = view();
view.handle_key_event(KeyEvent::from(KeyCode::Down));
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
view.handle_key_event(KeyEvent::from(KeyCode::Esc));
assert_eq!(view.page, HooksBrowserPage::Events);
assert_eq!(
view.selected_event(),
Some(HookEventName::PermissionRequest)
);
}
#[test]
fn esc_routes_through_the_view() {
assert!(view().prefer_esc_to_handle_key_event());
}
}