Skip to main content

eclipse_web/
verb.rs

1//! The composer's verbs, executed on the server (`#254`).
2//!
3//! A line the table serves for `Front::Web` never reaches the model. `chat()` parses it first and
4//! this module answers it: one row in the transcript, no turn, no tokens, and nothing written to
5//! the session store except the one column a verb names (`/archive`'s flag).
6//!
7//! Three rules hold it together. **One implementation.** A verb that changes something calls the
8//! same `apply_*` function its API route calls — `/model` and the picker are one function, so a
9//! pick in one shows in the other. **The table decides what exists.** Nothing here names a command
10//! that `COMMANDS` does not mark `Web`; a word this module has no arm for is a bug the table's own
11//! test cannot see, so the `other` arm says so instead of guessing. **A refusal is a row too.**
12//! `/resume` in the browser says where it lives rather than becoming a question about resuming.
13
14use crate::app::{apply_model, apply_reasoning, apply_setting, AppState};
15use eclipse_core::commands::{self, Command, Front};
16
17/// What a served command answers with: the row, whether it is a refusal, and whether the page
18/// should forget the session it is holding (only `/new` does).
19#[derive(Debug, Clone)]
20pub struct Answer {
21    pub text: String,
22    pub refused: bool,
23    pub clear_session: bool,
24    /// `Some` when the answer changed `/yolo`, so the page can paint the state the server is in
25    /// rather than remembering what was typed (#285). `None` is "nothing to say about it".
26    pub yolo: Option<bool>,
27}
28
29impl Answer {
30    fn said(text: impl Into<String>) -> Self {
31        Self {
32            text: text.into(),
33            refused: false,
34            clear_session: false,
35            yolo: None,
36        }
37    }
38
39    pub(crate) fn refused(text: impl Into<String>) -> Self {
40        Self {
41            text: text.into(),
42            refused: true,
43            clear_session: false,
44            yolo: None,
45        }
46    }
47}
48
49/// The composer's `!` lines, refused (`#283`).
50///
51/// **The decision, taken on the issue and not to be re-opened by a patch: there is no `!command` in
52/// the browser.** `bang::Surface` has no `Web` variant for this reason — a bang exists on the
53/// promise that a person is typing *and watching*, and this surface is one shared token, one
54/// machine, and whoever holds the token. So the line is not run.
55///
56/// It is not forwarded either, which is what an unhandled line does today. Forwarding quietly
57/// redefines the keystroke: `!ls` would become a prompt the model may answer by calling `shell`,
58/// so the person would be approving a command they thought they had already typed. Refusing says
59/// what happened, in one row, and runs nothing.
60///
61/// The rule is `bang::parse`'s: a leading `!` after indentation. `!!x` is a bang too — the terminal
62/// hands `!x` to the shell, because `!!` is history expansion and the extra bang is what the typist
63/// meant. Anything else (`fix it!`, `a ! b`) is prose and reaches the model as it always did.
64pub fn bang_refusal(line: &str) -> Option<Answer> {
65    if !line.trim_start().starts_with('!') {
66        return None;
67    }
68    Some(Answer::refused(
69        "`!command` runs a shell in a terminal and nowhere else — nothing was run here. A `!` line \
70         is refused rather than sent on, because sending it would turn \"run this\" into \"ask the \
71         model about this\". Type it in the terminal, or send it without the `!` to ask about it.",
72    ))
73}
74
75/// Run one command and answer it. `arg` is the text after the word, trimmed, exactly as `parse`
76/// gives it; `session` is the session the composer is holding, if any.
77pub async fn serve(st: &AppState, command: &Command, arg: &str, session: Option<&str>) -> Answer {
78    let arg = arg.trim();
79    match command.name {
80        // The table's own words, for this front: no `!command` line, because the dashboard has no
81        // bang.
82        "/help" => Answer::said(commands::help(Front::Web)),
83        // The dashboard has no session until a message arrives, so this is a promise rather than a
84        // switch: the page drops the id it holds and the next turn opens a new one.
85        "/new" => Answer {
86            text: "a new session starts with the next message".to_string(),
87            refused: false,
88            clear_session: true,
89            yolo: None,
90        },
91        "/id" => Answer::said(match session.filter(|s| !s.is_empty()) {
92            Some(id) => id.to_string(),
93            None => "(none yet — the next message opens one)".to_string(),
94        }),
95        // No provider is not "no model": the read-out says why, in the refusal colour, the way
96        // `/reasoning` does — a dashboard started without a config is exactly when someone is
97        // looking for what is missing.
98        "/model" if st.agent.is_none() => Answer::refused(crate::app::unconfigured(st)),
99        "/model" => match arg.is_empty() {
100            true => Answer::said(model_readout(st)),
101            false => match apply_model(st, Some(arg.to_string())).await {
102                Ok(answer) => Answer::said(format!(
103                    "model: {} (the next turn uses it; config.toml is not touched)",
104                    answer["model"].as_str().unwrap_or("?")
105                )),
106                Err((_, why)) => Answer::refused(why),
107            },
108        },
109        // `#172`: a goal is a row the runtime judges at the end of every turn, so the gateway can
110        // carry it with the tab closed — the sweeper starts the next turn when the row says
111        // another one is owed.
112        "/goal" => match session.filter(|s| !s.is_empty()) {
113            Some(id) => {
114                let now = eclipse_core::session::now_ms() as i64;
115                match eclipse_core::goals::manage(&st.store, id, arg, now) {
116                    Ok(said) => Answer::said(said),
117                    Err(why) => Answer::refused(format!("{why:#}")),
118                }
119            }
120            None => Answer::said(
121                "no session yet — send a message first, then `/goal <text>` sets a standing goal \
122                 for it",
123            ),
124        },
125        // `#173`: the gateway owns this timer, and the row says so — a loop started here keeps
126        // ticking with the tab closed, which is the opposite of the terminal's rule.
127        "/loop" => match crate::loops_gateway::manage(st, session, arg) {
128            Ok(said) => Answer::said(said),
129            Err(why) => Answer::refused(why),
130        },
131        "/reasoning" => match arg.is_empty() {
132            true => Answer::said(reasoning_readout(st)),
133            false => {
134                let level = if arg == "default" {
135                    None
136                } else {
137                    Some(arg.to_string())
138                };
139                match apply_reasoning(st, level).await {
140                    Ok(answer) => Answer::said(reasoning_line(&answer)),
141                    Err((_, why)) => Answer::refused(why),
142                }
143            }
144        },
145        // `#285`: the dashboard owns the switch now, and the answer is `Yolo::apply`'s sentence —
146        // the same words the terminal prints, because the wording lives in `eclipse-core` where
147        // both fronts read it. The page paints from the flag, not from what was typed.
148        "/yolo" => match st.yolo.apply(arg) {
149            Ok(mut said) => {
150                // The state sentence stays `Yolo::apply`'s, word for word. The count is the extra
151                // fact a browser owes the person who was not looking at every card (#285).
152                let unasked = st.unasked.load(std::sync::atomic::Ordering::Relaxed);
153                if unasked > 0 {
154                    said.push_str(&format!(
155                        "\n\n{} tool call(s) have run in this dashboard without a card.",
156                        unasked
157                    ));
158                }
159                Answer {
160                    yolo: Some(st.yolo.on()),
161                    ..Answer::said(said)
162                }
163            }
164            Err(why) => Answer::refused(why),
165        },
166        "/status" => Answer::said(status_readout(st, session)),
167        "/settings" => Answer::said(settings_readout(st)),
168        "/set" => {
169            let Some((key, value)) = split_set(arg) else {
170                return Answer::refused("usage: /set <key> <value> — the keys are in /settings");
171            };
172            match apply_setting(st, key, Some(value)).await {
173                Ok(setting) => Answer::said(format!(
174                    "{} = {} — written; the next run uses it",
175                    setting["key"].as_str().unwrap_or(key),
176                    setting["value"].as_str().unwrap_or(value)
177                )),
178                Err((_, why)) => Answer::refused(why),
179            }
180        }
181        "/cron" => Answer::said(cron_readout(st)),
182        // The dashboard has no `/bg`, no registry of its own and no composer to return to: the
183        // table refuses it before this module is asked. This arm is what `/compress` is for.
184        "/compress" => match st.agent.clone() {
185            Some(agent) => {
186                agent.compress_now();
187                Answer::said(
188                    "compacting: the older turns are replaced with the handoff on the next request",
189                )
190            }
191            None => Answer::refused(crate::app::unconfigured(st)),
192        },
193        // `#240`: the open session out of the list, `list` for the ones already filed, `off` to
194        // put this one back. The store call is the CLI's `set_archived`, and the sentence names
195        // what did *not* change — the messages, the search — because that is the difference
196        // between this and the `delete` three pixels below it in the menu.
197        "/archive" => {
198            let store = st.store.clone();
199            match arg {
200                "list" => match store.list_with_archived() {
201                    // A store that cannot answer is not an empty archive. `unwrap_or_default()`
202                    // would turn a locked database into "nothing is archived: every session is in
203                    // the list" — a claim about the archive made from no data, and the one person
204                    // who could tell it was wrong is the one who filed something.
205                    Err(e) => Answer::refused(format!("cannot read the archive: {e}")),
206                    Ok(listed) => {
207                        let filed: Vec<_> = listed.iter().filter(|s| s.archived).collect();
208                        if filed.is_empty() {
209                            Answer::said("nothing is archived: every session is in the list")
210                        } else {
211                            let mut out = format!(
212                                "{} archived session(s) — out of the list, still in the find box:",
213                                filed.len()
214                            );
215                            for s in filed {
216                                out.push_str(&format!("\n{} · {}", s.id, s.label()));
217                            }
218                            Answer::said(out)
219                        }
220                    }
221                },
222                "off" => match session.filter(|id| !id.is_empty()) {
223                    None => Answer::refused("no session is open yet: there is nothing to put back"),
224                    Some(id) => match store.set_archived(id, false) {
225                        Ok(()) => Answer::said(format!(
226                            "{id} is back in the list, and a prune may take it again"
227                        )),
228                        Err(e) => Answer::refused(e.to_string()),
229                    },
230                },
231                "" => match session.filter(|id| !id.is_empty()) {
232                    None => Answer::refused("no session is open yet: the next message opens one"),
233                    Some(id) => match store.set_archived(id, true) {
234                        Ok(()) => Answer::said(format!(
235                            "{id} is out of the list and still in the find box — `/archive off` \
236                             puts it back"
237                        )),
238                        Err(e) => Answer::refused(e.to_string()),
239                    },
240                },
241                other => Answer::refused(format!("/archive takes `list` or `off`, not {other:?}")),
242            }
243        }
244        // Unreachable while the table and this module agree: `Front::Web` is only marked on names
245        // with an arm above. Said plainly rather than invented, because a silent no is what this
246        // change exists to remove.
247        other => Answer::refused(format!(
248            "{other} has no implementation in the dashboard — that is a bug, not a refusal"
249        )),
250    }
251}
252
253/// `/set <key> <value>`: the key, then everything after it. Split at the first space, not the last,
254/// because a value may contain one (`/set provider.system_prompt be brief`).
255fn split_set(arg: &str) -> Option<(&str, &str)> {
256    let (key, value) = arg.split_once(char::is_whitespace)?;
257    let value = value.trim();
258    (!key.is_empty() && !value.is_empty()).then_some((key, value))
259}
260
261fn model_readout(st: &AppState) -> String {
262    let current = st.current_model().unwrap_or_else(|| "(none)".into());
263    let configured = st.configured_model().unwrap_or_else(|| "(none)".into());
264    format!(
265        "model: {current} (configured: {configured}) — the picker in the stats row lists what the \
266         endpoint serves"
267    )
268}
269
270/// One line for the dial, in the words the submenu and `/reasoning` in a terminal already use.
271fn reasoning_line(answer: &serde_json::Value) -> String {
272    let effort = answer["effort"].as_str().unwrap_or("?");
273    let detail = answer["effort_detail"].as_str().unwrap_or("");
274    format!("effort: {effort} — {detail}")
275}
276
277fn reasoning_readout(st: &AppState) -> String {
278    let Some(agent) = st.agent.as_ref() else {
279        return crate::app::unconfigured(st);
280    };
281    let report = agent.reasoning_report();
282    let mut out = format!("effort: {} — {}", report.label, report.sentence());
283    match agent.reasoning_control() {
284        Some(eclipse_core::provider::Reasoning::Policy(policy)) => {
285            let words = policy.vocabulary();
286            if !words.is_empty() {
287                out.push_str(&format!("\nthis route takes: {}", words.join(" · ")));
288            }
289        }
290        Some(eclipse_core::provider::Reasoning::Off) => {
291            out.push_str("\nno reasoning control on this model");
292        }
293        Some(eclipse_core::provider::Reasoning::Undeclared) => {
294            out.push_str("\nthis backend declares no reasoning control");
295        }
296        None => {}
297    }
298    out
299}
300
301/// The numbers a person asks `/status` for, from what this process knows outside a turn: the ones
302/// a *turn* reports (tokens, cache, wall) belong to the run, and the strip under the composer
303/// already carries them.
304fn status_readout(st: &AppState, session: Option<&str>) -> String {
305    let model = st.current_model().unwrap_or_else(|| "(none)".into());
306    let window = st.agent.as_ref().map(|a| a.context_window()).unwrap_or(0);
307    let mut out = format!(
308        "model: {model}\ncontext window: {}",
309        match window {
310            0 => "not stated by the endpoint".to_string(),
311            n => format!("{n} tokens"),
312        }
313    );
314    if let Some(agent) = st.agent.as_ref() {
315        out.push_str(&format!(
316            "\neffort: {} — {}",
317            agent.reasoning_report().label,
318            agent.reasoning_report().sentence()
319        ));
320        out.push_str(&format!("\nmax iterations: {}", agent.max_iterations()));
321    }
322    out.push_str(&format!(
323        "\nsession: {}",
324        session.filter(|s| !s.is_empty()).unwrap_or("(none yet)")
325    ));
326    out
327}
328
329/// `/settings`: every key, its value and whether it is the default — the same rows
330/// `GET /api/settings` serves, in the shape `eclipse config keys` prints.
331fn settings_readout(st: &AppState) -> String {
332    let cfg = match st.reload_config() {
333        Ok(cfg) => cfg,
334        Err(why) => return why,
335    };
336    let mut out = format!(
337        "{} key(s), profile {}\n",
338        cfg.settings().len(),
339        cfg.profile_name()
340    );
341    for s in cfg.settings() {
342        let shown = if s.secret {
343            if s.value.is_some() {
344                "(set)".to_string()
345            } else {
346                "(not set)".to_string()
347            }
348        } else {
349            s.rendered()
350        };
351        out.push_str(&format!(
352            "{} = {}{}\n",
353            s.path(),
354            shown,
355            if s.is_default() { "  (default)" } else { "" }
356        ));
357    }
358    out.push_str("\n/set <key> <value> writes one");
359    out
360}
361
362/// `/cron`: the jobs the pane lists, in the shape `eclipse cron list` prints — name, schedule, next
363/// fire, and how the last run ended.
364///
365/// The clock face comes from `cron::local_parts`, the same call the terminal's table makes; the
366/// relative "in 3h 10m" the terminal adds is left out rather than reimplemented here, because a
367/// second humaniser is a second thing that can say a different time.
368fn cron_readout(st: &AppState) -> String {
369    let Some(root) = st.cron_root.as_ref() else {
370        return "this dashboard was started without an install root, so it has no cron state"
371            .to_string();
372    };
373    let now = eclipse_core::session::now_ms() as i64;
374    let jobs = match eclipse_core::cron::views(root, now) {
375        Ok(jobs) => jobs,
376        Err(e) => {
377            return format!(
378                "{} could not be read: {e}",
379                eclipse_core::cron::jobs_path(root).display()
380            )
381        }
382    };
383    if jobs.is_empty() {
384        return format!(
385            "nothing scheduled — {} holds no jobs",
386            eclipse_core::cron::jobs_path(root).display()
387        );
388    }
389    let width = jobs.iter().map(|j| j.name.len()).max().unwrap_or(4).max(4);
390    let mut out = format!("{:<width$}  {:<18}  next", "job", "schedule");
391    for job in &jobs {
392        let next = match (job.enabled, job.next_ms) {
393            (false, _) => "— (disabled)".to_string(),
394            (true, Some(ms)) => {
395                let (_, _, _, h, m) = eclipse_core::cron::local_parts(ms);
396                format!("{h:02}:{m:02}")
397            }
398            (true, None) => "—".to_string(),
399        };
400        out.push_str(&format!(
401            "\n{:<width$}  {:<18}  {next}",
402            job.name, job.schedule
403        ));
404        if let Some(outcome) = &job.last_outcome {
405            out.push_str(&format!(", last {outcome}"));
406        }
407    }
408    out.push_str("\nthe cron pane runs, edits and removes them");
409    out
410}