eclipse-web 0.13.2

Local web dashboard for eclipse
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! The composer's verbs, executed on the server (`#254`).
//!
//! A line the table serves for `Front::Web` never reaches the model. `chat()` parses it first and
//! this module answers it: one row in the transcript, no turn, no tokens, and nothing written to
//! the session store except the one column a verb names (`/archive`'s flag).
//!
//! Three rules hold it together. **One implementation.** A verb that changes something calls the
//! same `apply_*` function its API route calls — `/model` and the picker are one function, so a
//! pick in one shows in the other. **The table decides what exists.** Nothing here names a command
//! that `COMMANDS` does not mark `Web`; a word this module has no arm for is a bug the table's own
//! test cannot see, so the `other` arm says so instead of guessing. **A refusal is a row too.**
//! `/resume` in the browser says where it lives rather than becoming a question about resuming.

use crate::app::{apply_model, apply_reasoning, apply_setting, AppState};
use eclipse_core::commands::{self, Command, Front};

/// What a served command answers with: the row, whether it is a refusal, and whether the page
/// should forget the session it is holding (only `/new` does).
#[derive(Debug, Clone)]
pub struct Answer {
    pub text: String,
    pub refused: bool,
    pub clear_session: bool,
    /// `Some` when the answer changed `/yolo`, so the page can paint the state the server is in
    /// rather than remembering what was typed (#285). `None` is "nothing to say about it".
    pub yolo: Option<bool>,
}

impl Answer {
    fn said(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            refused: false,
            clear_session: false,
            yolo: None,
        }
    }

    pub(crate) fn refused(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            refused: true,
            clear_session: false,
            yolo: None,
        }
    }
}

/// The composer's `!` lines, refused (`#283`).
///
/// **The decision, taken on the issue and not to be re-opened by a patch: there is no `!command` in
/// the browser.** `bang::Surface` has no `Web` variant for this reason — a bang exists on the
/// promise that a person is typing *and watching*, and this surface is one shared token, one
/// machine, and whoever holds the token. So the line is not run.
///
/// It is not forwarded either, which is what an unhandled line does today. Forwarding quietly
/// redefines the keystroke: `!ls` would become a prompt the model may answer by calling `shell`,
/// so the person would be approving a command they thought they had already typed. Refusing says
/// what happened, in one row, and runs nothing.
///
/// The rule is `bang::parse`'s: a leading `!` after indentation. `!!x` is a bang too — the terminal
/// hands `!x` to the shell, because `!!` is history expansion and the extra bang is what the typist
/// meant. Anything else (`fix it!`, `a ! b`) is prose and reaches the model as it always did.
pub fn bang_refusal(line: &str) -> Option<Answer> {
    if !line.trim_start().starts_with('!') {
        return None;
    }
    Some(Answer::refused(
        "`!command` runs a shell in a terminal and nowhere else — nothing was run here. A `!` line \
         is refused rather than sent on, because sending it would turn \"run this\" into \"ask the \
         model about this\". Type it in the terminal, or send it without the `!` to ask about it.",
    ))
}

/// Run one command and answer it. `arg` is the text after the word, trimmed, exactly as `parse`
/// gives it; `session` is the session the composer is holding, if any.
pub async fn serve(st: &AppState, command: &Command, arg: &str, session: Option<&str>) -> Answer {
    let arg = arg.trim();
    match command.name {
        // The table's own words, for this front: no `!command` line, because the dashboard has no
        // bang.
        "/help" => Answer::said(commands::help(Front::Web)),
        // The dashboard has no session until a message arrives, so this is a promise rather than a
        // switch: the page drops the id it holds and the next turn opens a new one.
        "/new" => Answer {
            text: "a new session starts with the next message".to_string(),
            refused: false,
            clear_session: true,
            yolo: None,
        },
        "/id" => Answer::said(match session.filter(|s| !s.is_empty()) {
            Some(id) => id.to_string(),
            None => "(none yet — the next message opens one)".to_string(),
        }),
        // No provider is not "no model": the read-out says why, in the refusal colour, the way
        // `/reasoning` does — a dashboard started without a config is exactly when someone is
        // looking for what is missing.
        "/model" if st.agent.is_none() => Answer::refused(crate::app::unconfigured(st)),
        "/model" => match arg.is_empty() {
            true => Answer::said(model_readout(st)),
            false => match apply_model(st, Some(arg.to_string())).await {
                Ok(answer) => Answer::said(format!(
                    "model: {} (the next turn uses it; config.toml is not touched)",
                    answer["model"].as_str().unwrap_or("?")
                )),
                Err((_, why)) => Answer::refused(why),
            },
        },
        // `#172`: a goal is a row the runtime judges at the end of every turn, so the gateway can
        // carry it with the tab closed — the sweeper starts the next turn when the row says
        // another one is owed.
        "/goal" => match session.filter(|s| !s.is_empty()) {
            Some(id) => {
                let now = eclipse_core::session::now_ms() as i64;
                match eclipse_core::goals::manage(&st.store, id, arg, now) {
                    Ok(said) => Answer::said(said),
                    Err(why) => Answer::refused(format!("{why:#}")),
                }
            }
            None => Answer::said(
                "no session yet — send a message first, then `/goal <text>` sets a standing goal \
                 for it",
            ),
        },
        // `#173`: the gateway owns this timer, and the row says so — a loop started here keeps
        // ticking with the tab closed, which is the opposite of the terminal's rule.
        "/loop" => match crate::loops_gateway::manage(st, session, arg) {
            Ok(said) => Answer::said(said),
            Err(why) => Answer::refused(why),
        },
        "/reasoning" => match arg.is_empty() {
            true => Answer::said(reasoning_readout(st)),
            false => {
                let level = if arg == "default" {
                    None
                } else {
                    Some(arg.to_string())
                };
                match apply_reasoning(st, level).await {
                    Ok(answer) => Answer::said(reasoning_line(&answer)),
                    Err((_, why)) => Answer::refused(why),
                }
            }
        },
        // `#285`: the dashboard owns the switch now, and the answer is `Yolo::apply`'s sentence —
        // the same words the terminal prints, because the wording lives in `eclipse-core` where
        // both fronts read it. The page paints from the flag, not from what was typed.
        "/yolo" => match st.yolo.apply(arg) {
            Ok(mut said) => {
                // The state sentence stays `Yolo::apply`'s, word for word. The count is the extra
                // fact a browser owes the person who was not looking at every card (#285).
                let unasked = st.unasked.load(std::sync::atomic::Ordering::Relaxed);
                if unasked > 0 {
                    said.push_str(&format!(
                        "\n\n{} tool call(s) have run in this dashboard without a card.",
                        unasked
                    ));
                }
                Answer {
                    yolo: Some(st.yolo.on()),
                    ..Answer::said(said)
                }
            }
            Err(why) => Answer::refused(why),
        },
        "/status" => Answer::said(status_readout(st, session)),
        "/settings" => Answer::said(settings_readout(st)),
        "/set" => {
            let Some((key, value)) = split_set(arg) else {
                return Answer::refused("usage: /set <key> <value> — the keys are in /settings");
            };
            match apply_setting(st, key, Some(value)).await {
                Ok(setting) => Answer::said(format!(
                    "{} = {} — written; the next run uses it",
                    setting["key"].as_str().unwrap_or(key),
                    setting["value"].as_str().unwrap_or(value)
                )),
                Err((_, why)) => Answer::refused(why),
            }
        }
        "/cron" => Answer::said(cron_readout(st)),
        // The dashboard has no `/bg`, no registry of its own and no composer to return to: the
        // table refuses it before this module is asked. This arm is what `/compress` is for.
        "/compress" => match st.agent.clone() {
            Some(agent) => {
                agent.compress_now();
                Answer::said(
                    "compacting: the older turns are replaced with the handoff on the next request",
                )
            }
            None => Answer::refused(crate::app::unconfigured(st)),
        },
        // `#240`: the open session out of the list, `list` for the ones already filed, `off` to
        // put this one back. The store call is the CLI's `set_archived`, and the sentence names
        // what did *not* change — the messages, the search — because that is the difference
        // between this and the `delete` three pixels below it in the menu.
        "/archive" => {
            let store = st.store.clone();
            match arg {
                "list" => match store.list_with_archived() {
                    // A store that cannot answer is not an empty archive. `unwrap_or_default()`
                    // would turn a locked database into "nothing is archived: every session is in
                    // the list" — a claim about the archive made from no data, and the one person
                    // who could tell it was wrong is the one who filed something.
                    Err(e) => Answer::refused(format!("cannot read the archive: {e}")),
                    Ok(listed) => {
                        let filed: Vec<_> = listed.iter().filter(|s| s.archived).collect();
                        if filed.is_empty() {
                            Answer::said("nothing is archived: every session is in the list")
                        } else {
                            let mut out = format!(
                                "{} archived session(s) — out of the list, still in the find box:",
                                filed.len()
                            );
                            for s in filed {
                                out.push_str(&format!("\n{} · {}", s.id, s.label()));
                            }
                            Answer::said(out)
                        }
                    }
                },
                "off" => match session.filter(|id| !id.is_empty()) {
                    None => Answer::refused("no session is open yet: there is nothing to put back"),
                    Some(id) => match store.set_archived(id, false) {
                        Ok(()) => Answer::said(format!(
                            "{id} is back in the list, and a prune may take it again"
                        )),
                        Err(e) => Answer::refused(e.to_string()),
                    },
                },
                "" => match session.filter(|id| !id.is_empty()) {
                    None => Answer::refused("no session is open yet: the next message opens one"),
                    Some(id) => match store.set_archived(id, true) {
                        Ok(()) => Answer::said(format!(
                            "{id} is out of the list and still in the find box — `/archive off` \
                             puts it back"
                        )),
                        Err(e) => Answer::refused(e.to_string()),
                    },
                },
                other => Answer::refused(format!("/archive takes `list` or `off`, not {other:?}")),
            }
        }
        // Unreachable while the table and this module agree: `Front::Web` is only marked on names
        // with an arm above. Said plainly rather than invented, because a silent no is what this
        // change exists to remove.
        other => Answer::refused(format!(
            "{other} has no implementation in the dashboard — that is a bug, not a refusal"
        )),
    }
}

/// `/set <key> <value>`: the key, then everything after it. Split at the first space, not the last,
/// because a value may contain one (`/set provider.system_prompt be brief`).
fn split_set(arg: &str) -> Option<(&str, &str)> {
    let (key, value) = arg.split_once(char::is_whitespace)?;
    let value = value.trim();
    (!key.is_empty() && !value.is_empty()).then_some((key, value))
}

fn model_readout(st: &AppState) -> String {
    let current = st.current_model().unwrap_or_else(|| "(none)".into());
    let configured = st.configured_model().unwrap_or_else(|| "(none)".into());
    format!(
        "model: {current} (configured: {configured}) — the picker in the stats row lists what the \
         endpoint serves"
    )
}

/// One line for the dial, in the words the submenu and `/reasoning` in a terminal already use.
fn reasoning_line(answer: &serde_json::Value) -> String {
    let effort = answer["effort"].as_str().unwrap_or("?");
    let detail = answer["effort_detail"].as_str().unwrap_or("");
    format!("effort: {effort} — {detail}")
}

fn reasoning_readout(st: &AppState) -> String {
    let Some(agent) = st.agent.as_ref() else {
        return crate::app::unconfigured(st);
    };
    let report = agent.reasoning_report();
    let mut out = format!("effort: {} — {}", report.label, report.sentence());
    match agent.reasoning_control() {
        Some(eclipse_core::provider::Reasoning::Policy(policy)) => {
            let words = policy.vocabulary();
            if !words.is_empty() {
                out.push_str(&format!("\nthis route takes: {}", words.join(" · ")));
            }
        }
        Some(eclipse_core::provider::Reasoning::Off) => {
            out.push_str("\nno reasoning control on this model");
        }
        Some(eclipse_core::provider::Reasoning::Undeclared) => {
            out.push_str("\nthis backend declares no reasoning control");
        }
        None => {}
    }
    out
}

/// The numbers a person asks `/status` for, from what this process knows outside a turn: the ones
/// a *turn* reports (tokens, cache, wall) belong to the run, and the strip under the composer
/// already carries them.
fn status_readout(st: &AppState, session: Option<&str>) -> String {
    let model = st.current_model().unwrap_or_else(|| "(none)".into());
    let window = st.agent.as_ref().map(|a| a.context_window()).unwrap_or(0);
    let mut out = format!(
        "model: {model}\ncontext window: {}",
        match window {
            0 => "not stated by the endpoint".to_string(),
            n => format!("{n} tokens"),
        }
    );
    if let Some(agent) = st.agent.as_ref() {
        out.push_str(&format!(
            "\neffort: {} — {}",
            agent.reasoning_report().label,
            agent.reasoning_report().sentence()
        ));
        out.push_str(&format!("\nmax iterations: {}", agent.max_iterations()));
    }
    out.push_str(&format!(
        "\nsession: {}",
        session.filter(|s| !s.is_empty()).unwrap_or("(none yet)")
    ));
    out
}

/// `/settings`: every key, its value and whether it is the default — the same rows
/// `GET /api/settings` serves, in the shape `eclipse config keys` prints.
fn settings_readout(st: &AppState) -> String {
    let cfg = match st.reload_config() {
        Ok(cfg) => cfg,
        Err(why) => return why,
    };
    let mut out = format!(
        "{} key(s), profile {}\n",
        cfg.settings().len(),
        cfg.profile_name()
    );
    for s in cfg.settings() {
        let shown = if s.secret {
            if s.value.is_some() {
                "(set)".to_string()
            } else {
                "(not set)".to_string()
            }
        } else {
            s.rendered()
        };
        out.push_str(&format!(
            "{} = {}{}\n",
            s.path(),
            shown,
            if s.is_default() { "  (default)" } else { "" }
        ));
    }
    out.push_str("\n/set <key> <value> writes one");
    out
}

/// `/cron`: the jobs the pane lists, in the shape `eclipse cron list` prints — name, schedule, next
/// fire, and how the last run ended.
///
/// The clock face comes from `cron::local_parts`, the same call the terminal's table makes; the
/// relative "in 3h 10m" the terminal adds is left out rather than reimplemented here, because a
/// second humaniser is a second thing that can say a different time.
fn cron_readout(st: &AppState) -> String {
    let Some(root) = st.cron_root.as_ref() else {
        return "this dashboard was started without an install root, so it has no cron state"
            .to_string();
    };
    let now = eclipse_core::session::now_ms() as i64;
    let jobs = match eclipse_core::cron::views(root, now) {
        Ok(jobs) => jobs,
        Err(e) => {
            return format!(
                "{} could not be read: {e}",
                eclipse_core::cron::jobs_path(root).display()
            )
        }
    };
    if jobs.is_empty() {
        return format!(
            "nothing scheduled — {} holds no jobs",
            eclipse_core::cron::jobs_path(root).display()
        );
    }
    let width = jobs.iter().map(|j| j.name.len()).max().unwrap_or(4).max(4);
    let mut out = format!("{:<width$}  {:<18}  next", "job", "schedule");
    for job in &jobs {
        let next = match (job.enabled, job.next_ms) {
            (false, _) => "— (disabled)".to_string(),
            (true, Some(ms)) => {
                let (_, _, _, h, m) = eclipse_core::cron::local_parts(ms);
                format!("{h:02}:{m:02}")
            }
            (true, None) => "—".to_string(),
        };
        out.push_str(&format!(
            "\n{:<width$}  {:<18}  {next}",
            job.name, job.schedule
        ));
        if let Some(outcome) = &job.last_outcome {
            out.push_str(&format!(", last {outcome}"));
        }
    }
    out.push_str("\nthe cron pane runs, edits and removes them");
    out
}