返回 CodeWhale
approval_routing.rs
根目录 / crates / tui / src / tui / ui / approval_routing.rs
1 //! UI-side approval disposition and durable denial receipts.
2
3 use crate::tui::app::{App, StatusToast, StatusToastLevel};
4 use crate::tui::history::HistoryCell;
5 use codewhale_engine::core::engine::EngineHandle;
6 use codewhale_execpolicy::ApprovalMode;
7 use codewhale_localization::MessageId;
8 use codewhale_runtime::audit::log_sensitive_event;
9
10 pub(super) fn is_session_approved_for_tool(
11 app: &App,
12 _tool_name: &str,
13 grouping_key: &str,
14 ) -> bool {
15 // Session grants match the grouping key only (command family / host /
16 // patch paths). A bare tool name is never session-wide: approving one
17 // shell command used to auto-approve the entire shell tool for the
18 // session. The `contains(tool_name)` clause was the escalation (ops R2).
19 app.approval_session_approved.contains(grouping_key)
20 }
21
22 pub(super) fn is_session_denied_for_key(app: &App, approval_key: &str) -> bool {
23 app.approval_session_denied.contains(approval_key)
24 }
25
26 /// A Deny holds for the rest of the user turn it was given in: the model's
27 /// retry loop must not re-prompt for the same call, but the user's next
28 /// message is a new intent and may deserve a different answer.
29 pub(super) fn end_turn_scoped_denials(app: &mut App) {
30 app.approval_session_denied.clear();
31 }
32
33 /// A different conversation (a session switch or resume) inherits neither
34 /// this conversation's denials nor its "approve for session" grants: both
35 /// describe work the user was looking at here. `/new` and `/clear` do the
36 /// same in `reset_conversation_state`.
37 pub(super) fn reset_approval_scope_for_new_conversation(app: &mut App) {
38 app.approval_session_denied.clear();
39 app.approval_session_approved.clear();
40 app.auto_review_blocked_receipts.clear();
41 crate::tui::pending_requests::clear_all(app);
42 }
43
44 pub(super) fn session_denied_notice(app: &App, tool_name: &str) -> String {
45 app.tr(MessageId::ApprovalAutoDeniedSession)
46 .replace("{tool}", tool_name)
47 }
48
49 pub(super) fn surface_session_denied_notice(app: &mut App, tool_name: &str) {
50 let notice = session_denied_notice(app, tool_name);
51 app.push_status_toast(notice.clone(), StatusToastLevel::Warning, Some(12_000));
52
53 // Tool completion and turn completion can replace the one-line status
54 // before the next frame is painted. Keep the recovery path in the
55 // transcript as a settled receipt as well, where it survives that event
56 // ordering and remains available to screen readers and scrollback.
57 let latest_transcript_cell = app
58 .active_cell
59 .as_ref()
60 .and_then(|cell| cell.entries().last())
61 .or_else(|| app.history.last());
62 let already_latest_receipt = matches!(
63 latest_transcript_cell,
64 Some(HistoryCell::System { content }) if content == &notice
65 );
66 if !already_latest_receipt {
67 let receipt = HistoryCell::System { content: notice };
68 if let Some(active_cell) = app.active_cell.as_mut() {
69 // Never grow committed history underneath an active cell: tool
70 // lookup indices address `history ++ active_cell`, so changing
71 // history.len() mid-turn would retarget the pending completion.
72 active_cell.push_untracked(receipt);
73 app.bump_active_cell_revision();
74 } else {
75 app.add_message(receipt);
76 }
77 }
78 }
79
80 pub(super) async fn auto_deny_session_approval(
81 app: &mut App,
82 engine_handle: &EngineHandle,
83 id: &str,
84 tool_name: &str,
85 approval_key: &str,
86 ) {
87 log_sensitive_event(
88 "tool.approval.auto_deny_session",
89 serde_json::json!({
90 "tool_name": tool_name,
91 "approval_key": approval_key,
92 "session_id": app.current_session_id,
93 }),
94 );
95 if let Err(error) = engine_handle
96 .deny_tool_call_by(
97 id.to_string(),
98 codewhale_engine::approval_log::ApprovalDecider::SessionRule,
99 )
100 .await
101 {
102 tracing::warn!(tool_name, %error, "session-rule denial was not accepted by Core");
103 return;
104 }
105 surface_session_denied_notice(app, tool_name);
106 }
107
108 pub(super) fn app_auto_approve_enabled(app: &App) -> bool {
109 app.approval_mode == ApprovalMode::Bypass
110 }
111
112 /// Build the UI-side TurnAuthority for approval disposition (#4412).
113 ///
114 /// Shell/trust bits do not affect disposition; mode + approval_mode + the
115 /// full-access shape (Bypass) are what the shared resolver consults.
116 fn app_turn_authority_for_approvals(app: &App) -> codewhale_engine::core::authority::TurnAuthority {
117 codewhale_engine::core::authority::TurnAuthority::for_tui_surface(
118 app.mode,
119 true,
120 false,
121 app_auto_approve_enabled(app),
122 app.approval_mode,
123 )
124 }
125
126 /// Who answered an `AutoApprove` disposition: the posture when it allows the
127 /// call on its own, otherwise the remembered session rule that did.
128 pub(super) fn auto_approval_decider(
129 app: &App,
130 approval_force_prompt: bool,
131 ) -> codewhale_engine::approval_log::ApprovalDecider {
132 use codewhale_engine::core::authority::ApprovalRequestDisposition;
133 match codewhale_engine::core::authority::resolve_approval_request_disposition(
134 &app_turn_authority_for_approvals(app),
135 false,
136 false,
137 approval_force_prompt,
138 "",
139 ) {
140 ApprovalRequestDisposition::AutoApprove => {
141 codewhale_engine::approval_log::ApprovalDecider::Posture
142 }
143 _ => codewhale_engine::approval_log::ApprovalDecider::SessionRule,
144 }
145 }
146
147 pub(super) fn resolve_ui_approval_disposition(
148 app: &App,
149 tool_name: &str,
150 grouping_key: &str,
151 approval_key: &str,
152 approval_force_prompt: bool,
153 ) -> codewhale_engine::core::authority::ApprovalRequestDisposition {
154 let disposition = codewhale_engine::core::authority::resolve_approval_request_disposition(
155 &app_turn_authority_for_approvals(app),
156 is_session_approved_for_tool(app, tool_name, grouping_key),
157 is_session_denied_for_key(app, approval_key),
158 approval_force_prompt,
159 approval_key,
160 );
161 // Full Access holds a required prompt only because a programme with no
162 // person at the card must not be stranded by one. This surface always has
163 // that person, and a Computer Use consent or script exists for no other
164 // reason than to carry their answer, so ask instead of denying.
165 if disposition
166 == codewhale_engine::core::authority::ApprovalRequestDisposition::AutoDenyFullAccessPolicyHold
167 && codewhale_engine::tools::approval_cache::computer_use_human_decision_tool(tool_name)
168 {
169 return codewhale_engine::core::authority::ApprovalRequestDisposition::Prompt;
170 }
171 disposition
172 }
173
174 fn report_stale_resolution<E: std::fmt::Display>(
175 event_prefix: &str,
176 mut details: serde_json::Value,
177 tool_id: &str,
178 outcome: Result<(), E>,
179 app: &mut App,
180 ) {
181 match outcome {
182 Ok(()) => log_sensitive_event(&format!("{event_prefix}_resolved"), details),
183 Err(error) => {
184 tracing::warn!(%error, tool_id = %tool_id, "stale-request resolution op rejected");
185 let error = error.to_string();
186 let message = app
187 .tr(MessageId::StaleRequestResolutionFailed)
188 .replace("{error}", &error);
189 details["error"] = serde_json::Value::String(error);
190 log_sensitive_event(&format!("{event_prefix}_resolution_failed"), details);
191 app.add_message(HistoryCell::Error {
192 message: message.clone(),
193 severity: codewhale_error_taxonomy::ErrorSeverity::Error,
194 code: None,
195 });
196 app.push_status_toast_record(
197 StatusToast::new(message, StatusToastLevel::Error, Some(12_000))
198 .for_event(format!("stale-resolution:{tool_id}")),
199 );
200 }
201 }
202 }
203
204 /// Answer, explicitly, a request that must not open a card here, so nothing
205 /// waits on a card that never shows (approvals C1):
206 ///
207 /// - a child agent's approval from another conversation (the agent is known
208 /// to belong elsewhere) is answered `unavailable`;
209 /// - while the parent is idle or its turn was cancelled locally, a request
210 /// the parent owns can only be stale: an approval or sandbox elevation is
211 /// answered `unavailable`, a question is cancelled. Neither is recorded
212 /// as the person's denial.
213 ///
214 /// A child agent's request from this conversation is never stale on the
215 /// idle/cancel basis: the child is still running and waiting on the person,
216 /// so it falls through to the normal handler. Returns `true` when the event
217 /// was consumed here.
218 pub(super) async fn resolve_stale_parent_request(
219 app: &mut App,
220 engine_handle: &EngineHandle,
221 event: &codewhale_engine::core::events::Event,
222 ) -> bool {
223 use codewhale_engine::core::events::Event;
224 if let Event::ApprovalRequired { id, tool_name, .. } = event
225 && crate::tui::pending_requests::is_foreign_child_request(app, id)
226 {
227 let outcome = engine_handle.deny_tool_call_unavailable(id.clone()).await;
228 report_stale_resolution(
229 "tool.approval.foreign_session_child",
230 serde_json::json!({
231 "tool_name": tool_name,
232 "session_id": app.current_session_id,
233 }),
234 id,
235 outcome,
236 app,
237 );
238 return true;
239 }
240 if !(app.suppress_stream_events_until_turn_complete || !app.is_loading) {
241 return false;
242 }
243 match event {
244 Event::ApprovalRequired { id, tool_name, .. }
245 if !codewhale_engine::tools::subagent::SubAgentManager::is_child_approval_id(id) =>
246 {
247 let outcome = engine_handle.deny_tool_call_unavailable(id.clone()).await;
248 report_stale_resolution(
249 "tool.approval.stale_parent",
250 serde_json::json!({
251 "tool_name": tool_name,
252 "session_id": app.current_session_id,
253 }),
254 id,
255 outcome,
256 app,
257 );
258 true
259 }
260 Event::ElevationRequired {
261 tool_id, tool_name, ..
262 } => {
263 let outcome = engine_handle
264 .deny_tool_call_unavailable(tool_id.clone())
265 .await;
266 report_stale_resolution(
267 "tool.sandbox.stale_elevation",
268 serde_json::json!({
269 "tool_name": tool_name,
270 "session_id": app.current_session_id,
271 }),
272 tool_id,
273 outcome,
274 app,
275 );
276 true
277 }
278 Event::UserInputRequired { id, .. }
279 if !codewhale_engine::tools::subagent::SubAgentManager::is_child_approval_id(id) =>
280 {
281 let outcome = engine_handle.cancel_user_input(id.clone()).await;
282 report_stale_resolution(
283 "tool.user_input.stale_parent",
284 serde_json::json!({
285 "tool_id": id,
286 "session_id": app.current_session_id,
287 }),
288 id,
289 outcome,
290 app,
291 );
292 true
293 }
294 _ => false,
295 }
296 }
297
297 lines RUST