Skip to main content

eclipse_core/
yolo.rs

1//! `/yolo`: approvals off for this session, visibly.
2//!
3//! Two ways to run without being asked already existed — `--yes` on the command line and
4//! `[cli] approval = "auto"` in the config — and both are decided before the session starts, are
5//! invisible afterwards, and cannot be undone without starting another one. This is the third
6//! way, and the only one that is a *process setting*: it starts at whatever the other two decided,
7//! `/yolo` flips it, and nothing is ever written to `config.toml`. A mode you forgot about must not
8//! become what the next session starts with.
9//!
10//! The flag is shared between the front ends — the terminal, the plain REPL and the dashboard, which
11//! reads it once per run when it builds its approver — and read per turn, which is the whole
12//! difference from the startup value: `Gate` is chosen at the top of a turn, so a toggle applies to
13//! the next turn rather than to the next process.
14//!
15//! It lives in `eclipse-core` rather than in the CLI for one reason: `/yolo` answers in one
16//! sentence on every surface, and a sentence worded in two crates is a sentence that eventually
17//! says two different things.
18
19use std::sync::atomic::{AtomicBool, Ordering};
20use std::sync::Arc;
21
22/// The words `/yolo` accepts, in the order the refusal lists them.
23pub const WORDS: &[&str] = &["on", "off"];
24
25/// Whether tools may run without asking, for as long as this process lives.
26///
27/// Cloned into both front ends and read per turn; the atomic is the whole point, because the
28/// toggle is handled in the same `match` that answers a turn, several frames below the loop that
29/// chose the policy.
30#[derive(Clone, Debug)]
31pub struct Yolo(Arc<AtomicBool>);
32
33impl Yolo {
34    pub fn new(on: bool) -> Self {
35        Self(Arc::new(AtomicBool::new(on)))
36    }
37
38    /// Whether the next turn may answer every tool call itself.
39    pub fn on(&self) -> bool {
40        self.0.load(Ordering::Relaxed)
41    }
42
43    pub fn set(&self, on: bool) {
44        self.0.store(on, Ordering::Relaxed);
45    }
46
47    /// `/yolo` with no argument toggles; `on` and `off` set. `Err` is what the caller shows for a
48    /// word that is not one of them, and nothing was changed.
49    ///
50    /// The `Ok` text names the state that is now in force rather than the transition, because a
51    /// toggle's answer has to be readable without knowing what it was before.
52    pub fn apply(&self, arg: &str) -> Result<String, String> {
53        match arg.trim() {
54            "" => {
55                let on = !self.on();
56                self.set(on);
57                Ok(announce(on))
58            }
59            "on" => {
60                self.set(true);
61                Ok(announce(true))
62            }
63            "off" => {
64                self.set(false);
65                Ok(announce(false))
66            }
67            other => Err(format!(
68                "`/yolo` is a switch, not a setting: `{other}` is not one of {}. Nothing changed — it is {}.",
69                quoted(),
70                state(self.on())
71            )),
72        }
73    }
74}
75
76/// The readout's word for the state: what the next turn will do with a call that needs a person.
77pub fn state(on: bool) -> &'static str {
78    if on {
79        "auto"
80    } else {
81        "ask"
82    }
83}
84
85/// The sentence an answer prints, in both fronts, so the two cannot word one mode differently.
86pub fn announce(on: bool) -> String {
87    if on {
88        "approvals: auto — a tool that needs permission runs instead of parking, until `/yolo off` \
89         or this session ends. Nothing was written to `config.toml`."
90            .to_string()
91    } else {
92        "approvals: ask — a tool that needs permission parks again, as the session started. \
93         Nothing was written to `config.toml`."
94            .to_string()
95    }
96}
97
98/// `on`, `off`, or the words for a refusal, in one place so a message cannot list a verb that does
99/// not work.
100pub fn quoted() -> String {
101    WORDS
102        .iter()
103        .map(|w| format!("`{w}`"))
104        .collect::<Vec<_>>()
105        .join(" or ")
106}
107
108/// Why `/yolo` is not a thing on `surface`.
109///
110/// A job or a platform request that starts with every approval pre-answered is a mode nobody can
111/// see and nobody can undo: there is no composer to type `/yolo off` into, and no screen that says
112/// it is on. Those two doors decide their policy up front instead.
113pub fn refusal(surface: &str) -> String {
114    format!(
115        "`/yolo` turns every approval off for the session that typed it, and {surface} has no \
116         session to turn it back on in — the line was not run. A run's policy is decided before it \
117         starts: `--yes`, or `[cli] approval = \"auto\"`."
118    )
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    #[test]
126    fn no_argument_toggles_and_on_off_set() {
127        let yolo = Yolo::new(false);
128        assert!(!yolo.on());
129        assert!(yolo.apply("").unwrap().contains("approvals: auto"));
130        assert!(yolo.on(), "a bare `/yolo` turns it on");
131        assert!(yolo.apply("").unwrap().contains("approvals: ask"));
132        assert!(!yolo.on(), "and the next one turns it off again");
133
134        yolo.apply("on").unwrap();
135        assert!(yolo.on());
136        yolo.apply("on").unwrap();
137        assert!(yolo.on(), "`on` when it is already on is not an error");
138
139        yolo.apply("off").unwrap();
140        assert!(!yolo.on());
141        yolo.apply("off").unwrap();
142        assert!(!yolo.on());
143    }
144
145    #[test]
146    fn the_answer_names_what_is_in_force_not_what_changed() {
147        let yolo = Yolo::new(false);
148        // A toggle's answer has to be readable without knowing what it was: this one says `auto`
149        // and no earlier state is mentioned.
150        let said = yolo.apply("").unwrap();
151        assert!(said.contains("approvals: auto"), "{said}");
152        assert!(!said.contains("approvals: ask"), "{said}");
153    }
154
155    #[test]
156    fn a_word_that_is_not_a_switch_is_refused_and_changes_nothing() {
157        let yolo = Yolo::new(true);
158        let why = yolo.apply("high").unwrap_err();
159        assert!(why.contains("`high`"), "{why}");
160        assert!(why.contains("`on` or `off`"), "{why}");
161        assert!(yolo.on(), "the mode it was in is the mode it is in");
162    }
163
164    #[test]
165    fn it_starts_at_whatever_the_startup_flags_decided() {
166        assert!(Yolo::new(true).on(), "`--yes` is the initial value");
167        assert!(!Yolo::new(false).on());
168        // And the clone sees the same switch: one flag for both front ends.
169        let a = Yolo::new(false);
170        let b = a.clone();
171        a.set(true);
172        assert!(
173            b.on(),
174            "the clone is the same flag, not a copy of its value"
175        );
176    }
177
178    #[test]
179    fn the_refusal_says_where_a_policy_does_come_from() {
180        let said = refusal("a cron job");
181        assert!(said.contains("`/yolo`"), "{said}");
182        assert!(said.contains("a cron job"), "{said}");
183        assert!(said.contains("--yes"), "{said}");
184        assert!(said.contains("[cli] approval"), "{said}");
185    }
186
187    #[test]
188    fn both_states_have_one_word_and_one_sentence() {
189        assert_eq!(state(true), "auto");
190        assert_eq!(state(false), "ask");
191        assert_eq!(quoted(), "`on` or `off`");
192        assert_ne!(announce(true), announce(false));
193        for on in [true, false] {
194            assert!(
195                announce(on).contains("config.toml"),
196                "the promise that nothing is written belongs in the answer"
197            );
198        }
199    }
200}