Skip to main content

agent86_core/
approval.rs

1//! The human-in-the-loop approval gate, ported from Python's
2//! `guardrails/policy.py`, and the terminal prompt from `ui/repl.py`.
3//!
4//! Read-only tools always pass. Side-effecting tools pass under `auto`, are
5//! blocked under `deny`, and are put to the user under `ask`. With no prompt
6//! (piped stdin, CI, cron), `ask` declines: running unattended requires an
7//! explicit `--yes` or `approval = "auto"`.
8
9use crate::pyjson::python_json_dumps;
10use crate::tools::{Tool, ToolContext};
11use crate::types::{ApprovalMode, ToolCall};
12use serde_json::Value;
13use std::io::{BufRead, IsTerminal, Write};
14use std::sync::{Mutex, PoisonError};
15
16/// The one-line argument summary is capped at this many characters.
17pub const SUMMARY_LIMIT: usize = 300;
18/// The prompt shows at most this many lines of a tool's preview.
19pub const APPROVAL_DETAIL_LINES: usize = 40;
20
21/// What the user is asked to approve.
22#[derive(Debug, Clone, PartialEq)]
23pub struct ApprovalPreview {
24    /// The arguments as `json.dumps`, capped at [`SUMMARY_LIMIT`].
25    pub summary: String,
26    /// The tool's own description of the effect, such as a unified diff.
27    pub detail: Option<String>,
28    /// What `detail` is written in (`diff`, `bash`, `python`), as Python's `lexer`.
29    pub lexer: Option<&'static str>,
30    /// Beyond Python: a caution shown above the detail, for a write into agent86's
31    /// own configuration or skills ([`guarded_warning`]).
32    pub warning: Option<String>,
33    /// Beyond Python: show the whole detail, never capped, because what is approved
34    /// is all of it (a project specialty's file, whose every line becomes prompt text).
35    pub full: bool,
36    /// Beyond Python: the specialist sub-agent asking (or, for a project specialty's
37    /// own approval, its name), so a surface can say who asks.
38    pub agent: Option<String>,
39    /// Beyond Python: the file text the call would change, before and after, for
40    /// a surface that shows a reviewable diff (an editor over ACP). Built from the
41    /// expanded call, then redacted, as `detail` is.
42    pub change: Option<crate::tools::FileChange>,
43    /// Beyond Python: the sub-agent the call comes from, with its card, worktree, and
44    /// spend so far, for a surface that shows who asks (an editor's approval inbox).
45    /// `None` for the main agent's calls.
46    pub asker: Option<Box<Asker>>,
47}
48
49/// The sub-agent a question comes from (beyond Python), as it stood when the
50/// question was built: an editor shows it beside the question, so the user knows
51/// which of several sub-agents running at once asks, where it works, and what it
52/// has cost.
53#[derive(Debug, Clone, PartialEq)]
54pub struct Asker {
55    /// The provider id of the card it reports on (its top-level delegation's call,
56    /// or `/agent`'s synthetic one), when the surface observes sub-agents.
57    pub card: Option<String>,
58    /// Its per-spawn number, as sub-agent events and the trace carry it.
59    pub run: u64,
60    /// The specialty or role it runs as.
61    pub agent: String,
62    pub depth: u32,
63    /// The git worktree it is jailed to: the worktree's directory and its branch.
64    pub worktree: Option<(String, String)>,
65    /// Model calls it has made so far.
66    pub steps: u32,
67    /// What it and anything it delegated have spent so far.
68    pub cost_usd: f64,
69}
70
71impl Asker {
72    /// The sub-agent `ctx` belongs to, or `None` for the main agent's context.
73    pub fn of(ctx: &ToolContext) -> Option<Self> {
74        let run = ctx.subagent.as_ref()?;
75        let (steps, cost_usd) = run.progress();
76        Some(Self {
77            card: ctx.card.as_ref().map(|card| card.id.clone()),
78            run: run.run,
79            agent: run.name.clone(),
80            depth: run.depth,
81            worktree: ctx.worktree.as_ref().map(|worktree| {
82                (
83                    crate::tools::display_path(&worktree.path),
84                    worktree.branch.clone(),
85                )
86            }),
87            steps,
88            cost_usd,
89        })
90    }
91}
92
93/// What a queued question is (beyond Python).
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum QuestionKind {
96    /// May a tool call run?
97    Approval,
98    /// May a project specialty run?
99    Specialty,
100    /// Raise a spent limit?
101    Limit,
102    /// Enter a secret.
103    Secret,
104    /// Answer a surface a `render_ui` call waits on (beyond Python; ADR 0005).
105    Ui,
106}
107
108impl QuestionKind {
109    pub fn as_str(self) -> &'static str {
110        match self {
111            Self::Approval => "approval",
112            Self::Specialty => "specialty",
113            Self::Limit => "limit",
114            Self::Secret => "secret",
115            Self::Ui => "ui",
116        }
117    }
118}
119
120/// A question in the [`PromptQueue`], described for a surface that lists the
121/// questions waiting (beyond Python). It names who asks and about what, never the
122/// arguments or a secret's name.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct Question {
125    pub kind: QuestionKind,
126    /// The tool an approval is for.
127    pub tool: Option<String>,
128    /// The call it belongs to, by the id the gate sees (`<card>/<n>` for a
129    /// sub-agent's call).
130    pub call: Option<String>,
131    /// The sub-agent asking, when one is.
132    pub agent: Option<String>,
133    /// The provider id of the asking sub-agent's card.
134    pub card: Option<String>,
135    /// What is asked about beyond the tool: the project specialty to run, or the
136    /// limit to raise.
137    pub subject: Option<String>,
138}
139
140impl Question {
141    pub fn new(kind: QuestionKind) -> Self {
142        Self {
143            kind,
144            tool: None,
145            call: None,
146            agent: None,
147            card: None,
148            subject: None,
149        }
150    }
151
152    /// The question about `call`, whose prompt shows `preview`.
153    pub fn about(
154        kind: QuestionKind,
155        tool: &str,
156        call: &ToolCall,
157        preview: &ApprovalPreview,
158    ) -> Self {
159        let asker = preview.asker.as_ref();
160        Self {
161            tool: Some(tool.to_owned()),
162            call: Some(call.id.clone()),
163            agent: asker.map(|asker| asker.agent.clone()),
164            card: asker.and_then(|asker| asker.card.clone()),
165            ..Self::new(kind)
166        }
167    }
168}
169
170/// Told the question being asked, if any, and those waiting behind it in the order
171/// they will be asked, whenever either changes. Called with the queue locked, so it
172/// must not block or ask anything itself.
173pub type QueueWatcher = std::sync::Arc<dyn Fn(Option<&Question>, &[Question]) + Send + Sync>;
174
175/// The caution for a write into agent86's own configuration or skills.
176pub fn guarded_warning(path: &str) -> String {
177    format!(
178        "This writes agent86's own configuration or skills ({}), which changes what \
179         agent86 runs or is told from now on. Asked even in auto mode.",
180        crate::escape::show_controls(path)
181    )
182}
183
184/// Asks whether one side-effecting call may run: `(tool name, preview) -> approved`.
185pub type ApprovalPrompt = Box<dyn Fn(&str, &ApprovalPreview) -> bool + Send + Sync>;
186
187/// [`ApprovalPrompt`] for a surface that has to say which call it asks about
188/// (beyond Python): the ACP server names the call's id in its permission request, so
189/// the editor can match the question to the tool call it already showed.
190pub type CallApprovalPrompt = Box<dyn Fn(&ToolCall, &ApprovalPreview) -> bool + Send + Sync>;
191
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
193pub struct ApprovalDecision {
194    pub approved: bool,
195    pub reason: &'static str,
196}
197
198/// One question at a time (beyond Python): approval, limit, and secret prompts all
199/// pass through one queue, because sub-agents running in parallel can each reach a
200/// prompt, and a terminal or an editor answers one at a time. Questions are asked
201/// in the order they arrived, and a watcher can be told which are waiting
202/// ([`PromptQueue::set_watcher`]), so an editor can list them. A waiter that gets
203/// its turn after the turn was cancelled declines without asking, so a cancel is
204/// not followed by each queued question in turn. Clones share the queue.
205#[derive(Clone, Default)]
206pub struct PromptQueue {
207    inner: std::sync::Arc<QueueInner>,
208}
209
210#[derive(Default)]
211struct QueueInner {
212    state: Mutex<QueueState>,
213    /// Signalled whenever the question being asked ends or a waiter gives up its
214    /// turn, so the next in line can go.
215    turn_over: std::sync::Condvar,
216    cancel: Mutex<Option<crate::agent::CancelToken>>,
217    watcher: Mutex<Option<QueueWatcher>>,
218}
219
220#[derive(Default)]
221struct QueueState {
222    next: u64,
223    asking: Option<Question>,
224    /// By ticket, in arrival order.
225    waiting: std::collections::VecDeque<(u64, Question)>,
226}
227
228/// Ends the question being asked, even if its prompt panics.
229struct Asked<'a>(&'a PromptQueue);
230
231impl Drop for Asked<'_> {
232    fn drop(&mut self) {
233        let mut state = self.0.lock();
234        state.asking = None;
235        // With a question waiting, its turn reports next (asked, or given up), so
236        // a watcher never sees the gap between the two.
237        if state.waiting.is_empty() {
238            self.0.report(&state);
239        }
240        self.0.inner.turn_over.notify_all();
241    }
242}
243
244impl std::fmt::Debug for PromptQueue {
245    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246        formatter.write_str("PromptQueue")
247    }
248}
249
250impl PromptQueue {
251    /// Decline queued questions once `token` (the turn's) is cancelled.
252    pub fn watch(&self, token: crate::agent::CancelToken) {
253        *self
254            .inner
255            .cancel
256            .lock()
257            .unwrap_or_else(PoisonError::into_inner) = Some(token);
258    }
259
260    /// Tell `watcher` (or, with `None`, nobody) what is asked and waiting from now on.
261    pub fn set_watcher(&self, watcher: Option<QueueWatcher>) {
262        *self
263            .inner
264            .watcher
265            .lock()
266            .unwrap_or_else(PoisonError::into_inner) = watcher;
267    }
268
269    /// Ask `question` with `ask` once every question that arrived before it has
270    /// been asked, or `None` when the turn was cancelled while it waited.
271    pub fn ask<T>(&self, question: Question, ask: impl FnOnce() -> T) -> Option<T> {
272        let mut state = self.lock();
273        let waited = state.asking.is_some() || !state.waiting.is_empty();
274        let question = if waited {
275            let ticket = state.next;
276            state.next += 1;
277            state.waiting.push_back((ticket, question));
278            self.report(&state);
279            while state.asking.is_some()
280                || state.waiting.front().map(|(first, _)| *first) != Some(ticket)
281            {
282                state = self
283                    .inner
284                    .turn_over
285                    .wait(state)
286                    .unwrap_or_else(PoisonError::into_inner);
287            }
288            state
289                .waiting
290                .pop_front()
291                .map_or_else(|| unreachable!("first in line"), |(_, question)| question)
292        } else {
293            question
294        };
295        if self.cancelled() {
296            if waited {
297                self.report(&state);
298                self.inner.turn_over.notify_all();
299            }
300            return None;
301        }
302        state.asking = Some(question);
303        self.report(&state);
304        drop(state);
305        let _asked = Asked(self);
306        Some(ask())
307    }
308
309    fn lock(&self) -> std::sync::MutexGuard<'_, QueueState> {
310        self.inner
311            .state
312            .lock()
313            .unwrap_or_else(PoisonError::into_inner)
314    }
315
316    fn cancelled(&self) -> bool {
317        self.inner
318            .cancel
319            .lock()
320            .unwrap_or_else(PoisonError::into_inner)
321            .as_ref()
322            .is_some_and(crate::agent::CancelToken::is_cancelled)
323    }
324
325    /// Tell the watcher, if there is one, about `state`.
326    fn report(&self, state: &QueueState) {
327        let watcher = self
328            .inner
329            .watcher
330            .lock()
331            .unwrap_or_else(PoisonError::into_inner)
332            .clone();
333        if let Some(watcher) = watcher {
334            let waiting: Vec<Question> = state
335                .waiting
336                .iter()
337                .map(|(_, question)| question.clone())
338                .collect();
339            watcher(state.asking.as_ref(), &waiting);
340        }
341    }
342}
343
344/// Decides whether a call may run, asking a human when the mode says so.
345pub struct ApprovalGate {
346    /// Behind a lock, so the interactive interface can switch it (Shift+Tab) while a
347    /// turn holds the harness; the next call is decided under the new mode, as in Python.
348    mode: Mutex<ApprovalMode>,
349    pub prompt: Option<ApprovalPrompt>,
350    /// Asked in place of `prompt` when set.
351    pub call_prompt: Option<CallApprovalPrompt>,
352    /// Every question goes through it, one at a time (beyond Python).
353    pub queue: PromptQueue,
354    /// Asked in place of the others about a project specialty's file (beyond
355    /// Python): an editor offers one remembering option for it, which a call's
356    /// prompt cannot.
357    pub specialty_prompt: Option<CallApprovalPrompt>,
358}
359
360impl ApprovalGate {
361    pub fn new(mode: ApprovalMode, prompt: Option<ApprovalPrompt>) -> Self {
362        Self {
363            mode: Mutex::new(mode),
364            prompt,
365            call_prompt: None,
366            queue: PromptQueue::default(),
367            specialty_prompt: None,
368        }
369    }
370
371    /// Ask `preview` of whichever prompt is installed, or `None` when nobody can be
372    /// asked.
373    fn ask(&self, tool: &dyn Tool, call: &ToolCall, preview: &ApprovalPreview) -> Option<bool> {
374        self.ask_about(tool.name(), call, preview)
375    }
376
377    pub fn mode(&self) -> ApprovalMode {
378        *self.mode.lock().unwrap_or_else(PoisonError::into_inner)
379    }
380
381    pub fn set_mode(&self, mode: ApprovalMode) {
382        *self.mode.lock().unwrap_or_else(PoisonError::into_inner) = mode;
383    }
384
385    pub fn decide(&self, tool: &dyn Tool, call: &ToolCall, ctx: &ToolContext) -> ApprovalDecision {
386        let decision = |approved, reason| ApprovalDecision { approved, reason };
387        let scope = ctx.scope.as_deref();
388        // Beyond Python: a specialist sub-agent's list comes before anything else,
389        // so nobody is asked about a call that would then be refused.
390        if !ctx.scope_allows(tool.name()) {
391            return decision(false, "not permitted for this sub-agent");
392        }
393        // Its approval mode applies only when stricter than the session's, read
394        // for each call so a switch mid-turn still counts.
395        let mode = crate::tools::stricter(Some(self.mode()), scope.and_then(|s| s.approval))
396            .unwrap_or(ApprovalMode::Ask);
397        // Beyond Python: a specialty's `confirm` tools are asked about in every mode
398        // but `deny`, read-only ones included.
399        if let Some(scope) = scope.filter(|s| s.confirm.iter().any(|t| t == tool.name())) {
400            if mode == ApprovalMode::Deny {
401                return decision(false, "blocked by approval policy (deny)");
402            }
403            if !self.can_ask() {
404                return decision(
405                    false,
406                    "this sub-agent's calls to this tool need approval, and no prompt is available",
407                );
408            }
409            let mut preview = build_preview(tool, call, ctx);
410            preview.warning = Some(format!(
411                "The '{}' sub-agent always asks before running {}.",
412                scope.label,
413                tool.name()
414            ));
415            preview.agent = Some(scope.label.clone());
416            return if self.ask(tool, call, &preview) == Some(true) {
417                decision(true, "approved by user")
418            } else {
419                decision(false, "declined by user")
420            };
421        }
422        if !tool.side_effecting() {
423            return decision(true, "read-only");
424        }
425        // Beyond Python: agent86's own files are asked about whatever the mode,
426        // except that `deny` still denies.
427        if let Some(path) = tool.guarded_target(&call.arguments, ctx) {
428            if mode == ApprovalMode::Deny {
429                return decision(false, "blocked by approval policy (deny)");
430            }
431            if !self.can_ask() {
432                return decision(
433                    false,
434                    "writing agent86's own configuration or skills needs approval, and no \
435                     prompt is available",
436                );
437            }
438            let mut preview = build_preview(tool, call, ctx);
439            preview.warning = Some(guarded_warning(&path));
440            preview.agent = scope.map(|scope| scope.label.clone());
441            return if self.ask(tool, call, &preview) == Some(true) {
442                decision(true, "approved by user")
443            } else {
444                decision(false, "declined by user")
445            };
446        }
447        match mode {
448            ApprovalMode::Auto => decision(true, "auto-approved"),
449            ApprovalMode::Deny => decision(false, "blocked by approval policy (deny)"),
450            ApprovalMode::Ask => {
451                if !self.can_ask() {
452                    return decision(false, "approval required but no prompt available");
453                }
454                let mut preview = build_preview(tool, call, ctx);
455                // Beyond Python: the user is told which sub-agent asks.
456                if let Some(scope) = scope {
457                    preview.warning = Some(format!("Asked by the '{}' sub-agent.", scope.label));
458                    preview.agent = Some(scope.label.clone());
459                }
460                if self.ask(tool, call, &preview) == Some(true) {
461                    decision(true, "approved by user")
462                } else {
463                    decision(false, "declined by user")
464                }
465            }
466        }
467    }
468
469    /// Ask about a project specialty's file: the specialty hook when one is
470    /// installed, else the call prompts. `None` when nobody can be asked.
471    pub fn ask_specialty(&self, call: &ToolCall, preview: &ApprovalPreview) -> Option<bool> {
472        match &self.specialty_prompt {
473            Some(prompt) => {
474                let mut question =
475                    Question::about(QuestionKind::Specialty, "delegate", call, preview);
476                question.subject = preview.agent.clone();
477                Some(
478                    self.queue
479                        .ask(question, || prompt(call, preview))
480                        .unwrap_or(false),
481                )
482            }
483            None => self.ask_about("delegate", call, preview),
484        }
485    }
486
487    /// Whether anybody can be asked.
488    pub fn can_ask(&self) -> bool {
489        self.prompt.is_some() || self.call_prompt.is_some()
490    }
491
492    /// Put a question that is not a tool's own to whichever prompt is installed (a
493    /// project specialty's approval). `call` is the call it belongs to, for a surface
494    /// that has to say which; `name` is what the plain prompt shows. `None` when
495    /// nobody can be asked.
496    pub fn ask_about(
497        &self,
498        name: &str,
499        call: &ToolCall,
500        preview: &ApprovalPreview,
501    ) -> Option<bool> {
502        if !self.can_ask() {
503            return None;
504        }
505        // A question that waited past a cancel is declined without being put.
506        Some(
507            self.queue
508                .ask(
509                    Question::about(QuestionKind::Approval, name, call, preview),
510                    || match &self.call_prompt {
511                        Some(prompt) => prompt(call, preview),
512                        None => self
513                            .prompt
514                            .as_ref()
515                            .is_some_and(|prompt| prompt(name, preview)),
516                    },
517                )
518                .unwrap_or(false),
519        )
520    }
521}
522
523/// The approval payload: a one-line argument summary plus the tool's own detail.
524///
525/// A tool that expands `${secret:NAME}` previews what it will really do (so a file
526/// that already holds the value shows no change on that line), and the detail is
527/// then redacted, so the user approves the placeholder, never reads the value.
528pub fn build_preview(tool: &dyn Tool, call: &ToolCall, ctx: &ToolContext) -> ApprovalPreview {
529    let text = python_json_dumps(&Value::Object(call.arguments.clone()), false);
530    let summary = if text.chars().count() <= SUMMARY_LIMIT {
531        text
532    } else {
533        format!(
534            "{} ...",
535            text.chars().take(SUMMARY_LIMIT).collect::<String>()
536        )
537    };
538    let expanded = crate::tools::with_secrets(tool, call, ctx)
539        .map_or_else(|_| call.arguments.clone(), |call| call.arguments.clone());
540    ApprovalPreview {
541        summary,
542        detail: tool
543            .preview(&expanded, ctx)
544            .map(|detail| ctx.secrets.redact(&detail))
545            .filter(|detail| !detail.is_empty()),
546        lexer: tool.preview_lexer(),
547        warning: None,
548        full: false,
549        agent: None,
550        change: tool
551            .change(&expanded, ctx)
552            .map(|change| change.redacted(&ctx.secrets)),
553        asker: Asker::of(ctx).map(Box::new),
554    }
555}
556
557/// The prompt to install for `agent86 run`: one that asks at the terminal when
558/// stdin is a terminal, and none otherwise (so `ask` declines).
559pub fn terminal_prompt_if_interactive() -> Option<ApprovalPrompt> {
560    std::io::stdin()
561        .is_terminal()
562        .then(|| Box::new(terminal_prompt) as ApprovalPrompt)
563}
564
565/// Ask at the terminal whether one side-effecting call may run. Default: no.
566///
567/// The preview is printed above the question, because approving a write
568/// sight-unseen is what this prompt exists to prevent. Python prints the prompt
569/// on stdout; it goes to stderr here so `run --json` output stays one object.
570pub fn terminal_prompt(tool_name: &str, preview: &ApprovalPreview) -> bool {
571    let color = std::io::stderr().is_terminal() && color_allowed();
572    ask(&mut std::io::stderr(), color, tool_name, preview)
573}
574
575/// [`terminal_prompt`] on stdout, as Python's REPL asks; the REPL has no JSON
576/// output to protect.
577pub fn stdout_prompt(tool_name: &str, preview: &ApprovalPreview) -> bool {
578    let color = std::io::stdout().is_terminal() && color_allowed();
579    ask(&mut std::io::stdout(), color, tool_name, preview)
580}
581
582fn color_allowed() -> bool {
583    std::env::var_os("NO_COLOR").is_none_or(|value| value.is_empty())
584}
585
586/// What the terminal prompt prints before reading the answer.
587///
588/// Beyond Python: the detail, the summary it falls back to, and the tool's name
589/// come from the model (an MCP server names its own tools), so their control
590/// characters are shown, not sent ([`crate::escape::show_controls`]). Otherwise a
591/// `\r` or an escape sequence could draw a harmless command over the one that runs.
592pub fn prompt_text(color: bool, tool_name: &str, preview: &ApprovalPreview) -> String {
593    use crate::escape::show_controls;
594    let detail = preview.detail.as_deref().unwrap_or(&preview.summary);
595    let tool_name = show_controls(tool_name);
596    let mut text = String::from("\n");
597    if let Some(warning) = &preview.warning {
598        let warning = show_controls(warning);
599        text.push_str(&if color {
600            format!("\x1b[1;33mwarning:\x1b[0m {warning}\n")
601        } else {
602            format!("warning: {warning}\n")
603        });
604    }
605    text.push_str(&show_controls(&if preview.full {
606        detail.to_owned()
607    } else {
608        cap_lines(detail, APPROVAL_DETAIL_LINES)
609    }));
610    text.push('\n');
611    text.push_str(&if color {
612        format!("\x1b[1;33mapprove \x1b[0m\x1b[1m{tool_name}?\x1b[0m\n")
613    } else {
614        format!("approve {tool_name}?\n")
615    });
616    text.push_str("  [y/N] ");
617    text
618}
619
620fn ask(out: &mut dyn Write, color: bool, tool_name: &str, preview: &ApprovalPreview) -> bool {
621    let _ = write!(out, "{}", prompt_text(color, tool_name, preview));
622    let _ = out.flush();
623
624    let mut answer = String::new();
625    match std::io::stdin().lock().read_line(&mut answer) {
626        Ok(0) | Err(_) => {
627            // Nobody is there to answer: decline, the safe default.
628            let _ = writeln!(out, "declined");
629            false
630        }
631        Ok(_) => matches!(answer.trim().to_lowercase().as_str(), "y" | "yes"),
632    }
633}
634
635/// At most `limit` lines of `text`, saying how many were dropped.
636pub fn cap_lines(text: &str, limit: usize) -> String {
637    let lines = crate::difflib::splitlines(text);
638    if lines.len() <= limit {
639        return text.to_owned();
640    }
641    format!(
642        "{}\n… truncated ({} more lines)",
643        lines[..limit].join("\n"),
644        lines.len() - limit
645    )
646}
647
648#[cfg(test)]
649mod tests {
650    use super::*;
651
652    #[test]
653    fn long_previews_are_capped() {
654        let text: Vec<String> = (0..45).map(|i| format!("line {i}")).collect();
655        let capped = cap_lines(&text.join("\n"), 40);
656        assert!(
657            capped.ends_with("line 39\n… truncated (5 more lines)"),
658            "{capped}"
659        );
660        assert_eq!(cap_lines("short", 40), "short");
661    }
662
663    fn preview(summary: &str, detail: Option<&str>) -> ApprovalPreview {
664        ApprovalPreview {
665            summary: summary.to_owned(),
666            detail: detail.map(str::to_owned),
667            lexer: None,
668            warning: None,
669            full: false,
670            agent: None,
671            change: None,
672            asker: None,
673        }
674    }
675
676    #[test]
677    fn the_prompt_shows_control_characters_instead_of_obeying_them() {
678        // `\r` would return the cursor and draw `echo hi` over `rm -rf x`.
679        let text = prompt_text(
680            false,
681            "run_command",
682            &preview("{}", Some("rm -rf x\recho hi")),
683        );
684        assert_eq!(text, "\nrm -rf x␍echo hi\napprove run_command?\n  [y/N] ");
685
686        // The summary it falls back to, an escape sequence, and a bidi override.
687        let text = prompt_text(
688            false,
689            "mcp\u{1b}[8m_tool",
690            &preview("{\"path\": \"a\u{202e}txt.sh\"}\u{1b}[2K", None),
691        );
692        assert_eq!(
693            text,
694            "\n{\"path\": \"a<U+202E>txt.sh\"}␛[2K\napprove mcp␛[8m_tool?\n  [y/N] "
695        );
696        assert!(!text.contains('\u{1b}') && !text.contains('\u{202e}'));
697    }
698
699    type Views = std::sync::Arc<Mutex<Vec<(Option<String>, Vec<String>)>>>;
700
701    /// A queue whose watcher keeps every view it is shown, by each question's call.
702    fn watched_queue() -> (PromptQueue, Views) {
703        let queue = PromptQueue::default();
704        let views: Views = std::sync::Arc::default();
705        let seen = std::sync::Arc::clone(&views);
706        queue.set_watcher(Some(std::sync::Arc::new(
707            move |asking: Option<&Question>, waiting: &[Question]| {
708                let call = |question: &Question| question.call.clone().unwrap_or_default();
709                seen.lock()
710                    .unwrap()
711                    .push((asking.map(call), waiting.iter().map(call).collect()));
712            },
713        )));
714        (queue, views)
715    }
716
717    fn question(call: &str) -> Question {
718        Question {
719            call: Some(call.to_owned()),
720            ..Question::new(QuestionKind::Approval)
721        }
722    }
723
724    /// Wait until the queue has shown `waiting` questions behind the one asked.
725    fn until_waiting(views: &Views, waiting: usize) {
726        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
727        while views
728            .lock()
729            .unwrap()
730            .last()
731            .is_none_or(|(_, queued)| queued.len() != waiting)
732        {
733            assert!(
734                std::time::Instant::now() < deadline,
735                "{:?}",
736                views.lock().unwrap()
737            );
738            std::thread::sleep(std::time::Duration::from_millis(5));
739        }
740    }
741
742    #[test]
743    fn questions_are_asked_in_arrival_order_and_the_watcher_sees_who_waits() {
744        let (queue, views) = watched_queue();
745        let asked = std::sync::Arc::new(Mutex::new(Vec::new()));
746        let (release, hold) = std::sync::mpsc::channel::<()>();
747        std::thread::scope(|scope| {
748            let first = scope.spawn(|| {
749                let hold = hold;
750                queue.ask(question("a"), || {
751                    asked.lock().unwrap().push("a");
752                    hold.recv().unwrap();
753                })
754            });
755            until_waiting(&views, 0);
756            let mut rest = Vec::new();
757            for (call, behind) in [("b", 1), ("c", 2)] {
758                let (queue, asked) = (&queue, &asked);
759                rest.push(
760                    scope.spawn(move || {
761                        queue.ask(question(call), || asked.lock().unwrap().push(call))
762                    }),
763                );
764                until_waiting(&views, behind);
765            }
766            release.send(()).unwrap();
767            assert!(first.join().unwrap().is_some());
768            for waiter in rest {
769                assert!(waiter.join().unwrap().is_some());
770            }
771        });
772        assert_eq!(*asked.lock().unwrap(), ["a", "b", "c"]);
773        let view = |asking: Option<&str>, waiting: &[&str]| {
774            (
775                asking.map(str::to_owned),
776                waiting
777                    .iter()
778                    .map(|call| (*call).to_owned())
779                    .collect::<Vec<_>>(),
780            )
781        };
782        assert_eq!(
783            *views.lock().unwrap(),
784            [
785                view(Some("a"), &[]),
786                view(Some("a"), &["b"]),
787                view(Some("a"), &["b", "c"]),
788                view(Some("b"), &["c"]),
789                view(Some("c"), &[]),
790                view(None, &[]),
791            ]
792        );
793    }
794
795    #[test]
796    fn questions_waiting_past_a_cancel_are_declined_without_being_asked() {
797        let (queue, views) = watched_queue();
798        let token = crate::agent::CancelToken::default();
799        queue.watch(token.clone());
800        let (release, hold) = std::sync::mpsc::channel::<()>();
801        std::thread::scope(|scope| {
802            let first = scope.spawn(|| {
803                let hold = hold;
804                queue.ask(question("a"), || hold.recv().unwrap())
805            });
806            until_waiting(&views, 0);
807            let second =
808                scope.spawn(|| queue.ask(question("b"), || panic!("asked after a cancel")));
809            until_waiting(&views, 1);
810            token.cancel();
811            release.send(()).unwrap();
812            assert!(first.join().unwrap().is_some());
813            assert!(second.join().unwrap().is_none());
814        });
815        assert_eq!(
816            views.lock().unwrap().last(),
817            Some(&(None, Vec::new())),
818            "the declined question left the queue empty"
819        );
820        // A question arriving after the cancel is declined at once.
821        assert!(queue.ask(question("c"), || ()).is_none());
822    }
823
824    #[test]
825    fn a_sub_agents_call_is_previewed_with_who_asks() {
826        let dir = std::env::temp_dir().join(format!("agent86-asker-{}", std::process::id()));
827        std::fs::create_dir_all(&dir).unwrap();
828        let mut ctx = ToolContext::new(&dir).unwrap();
829        assert_eq!(Asker::of(&ctx), None);
830        let run = std::sync::Arc::new(crate::subagent::SubagentRun::new(7, "writer", 2));
831        ctx.subagent = Some(run);
832        ctx.card = Some(std::sync::Arc::new(crate::subagent::Card::new(
833            "call_9", true,
834        )));
835        let asker = Asker::of(&ctx).unwrap();
836        assert_eq!(
837            asker,
838            Asker {
839                card: Some("call_9".into()),
840                run: 7,
841                agent: "writer".into(),
842                depth: 2,
843                worktree: None,
844                steps: 0,
845                cost_usd: 0.0,
846            }
847        );
848        let call = ToolCall {
849            id: "call_9/3".into(),
850            name: "write_file".into(),
851            arguments: serde_json::Map::new(),
852        };
853        let shown = ApprovalPreview {
854            asker: Some(Box::new(asker)),
855            ..preview("{}", None)
856        };
857        let question = Question::about(QuestionKind::Approval, "write_file", &call, &shown);
858        assert_eq!(question.call.as_deref(), Some("call_9/3"));
859        assert_eq!(question.agent.as_deref(), Some("writer"));
860        assert_eq!(question.card.as_deref(), Some("call_9"));
861        let _ = std::fs::remove_dir_all(&dir);
862    }
863
864    #[test]
865    fn the_prompts_own_colours_survive() {
866        let mut shown = preview("{}", Some("ls"));
867        shown.warning = Some("careful".to_owned());
868        let text = prompt_text(true, "run_command", &shown);
869        assert_eq!(
870            text,
871            "\n\u{1b}[1;33mwarning:\u{1b}[0m careful\nls\n\
872             \u{1b}[1;33mapprove \u{1b}[0m\u{1b}[1mrun_command?\u{1b}[0m\n  [y/N] "
873        );
874    }
875}