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