Skip to main content

eclipse_web/
app.rs

1//! HTTP routes for the local dashboard.
2
3use crate::calls;
4use crate::verb::{self, Answer};
5use async_trait::async_trait;
6use axum::extract::{DefaultBodyLimit, Path, Query, Request, State};
7use axum::http::{header, HeaderMap, HeaderValue, Method, StatusCode};
8use axum::middleware::{self, Next};
9use axum::response::sse::{Event, KeepAlive, Sse};
10use axum::response::{Html, IntoResponse, Response};
11use axum::routing::{get, post, put};
12use axum::{Form, Json, Router};
13use eclipse_core::cancel::Cancel;
14use eclipse_core::commands::{Front, Parsed};
15use eclipse_core::contextbar::Reading;
16use eclipse_core::runtime::{Agent, AgentEvent, RunOptions};
17use eclipse_core::session::{FlareJobRow, FlareRunRow};
18use eclipse_core::tools::Approver;
19use futures_util::stream::{self, Stream};
20use futures_util::StreamExt;
21use serde::Deserialize;
22use serde_json::json;
23use std::collections::HashMap;
24use std::convert::Infallible;
25use std::sync::atomic::{AtomicU64, Ordering};
26use std::sync::{Arc, Mutex};
27use std::time::{Duration, Instant};
28use tokio::sync::{mpsc, oneshot, Semaphore};
29
30const INDEX_HTML: &str = include_str!("index.html");
31
32/// `#509`: the Bots pane, written into the page only when `[bots]` declared something.
33///
34/// A config with no bots renders the sidebar and the main column it rendered before there were
35/// bots — the placeholder is replaced with an empty string — so the promise "the Sessions tab is
36/// byte-identical for someone with no bots" is kept by the server, not by a CSS rule that would
37/// have to be remembered.
38const BOTS_PANE: &str = r#"  <section id="botspane" hidden aria-label="bots">
39    <header>
40      <h2>bots</h2>
41      <small id="botsfile"></small>
42      <span class="grow"></span>
43      <button id="botsrefresh" type="button">refresh</button>
44    </header>
45    <div id="botsmsg"></div>
46    <table id="botstable">
47      <thead><tr><th>bot</th><th>lane</th><th>last</th><th>said</th><th></th></tr></thead>
48      <tbody id="botsrows"></tbody>
49    </table>
50    <div id="botsprompt" hidden></div>
51  </section>
52"#;
53
54/// `#171`: the Flares pane, spliced into the page only when the run ledger holds a run.
55///
56/// The same promise as [`BOTS_PANE`], and for a sharper reason: a flare run belongs to a session,
57/// so a person who has never fanned one out must get the dashboard they had before the feature
58/// existed. The placeholder becomes an empty string and the pane, its styles and its sidebar
59/// button are simply not in the document.
60const FLARES_PANE: &str = r#"  <section id="flarespane" hidden aria-label="flare runs">
61    <header>
62      <h2>flare runs</h2>
63      <small id="flaresfile"></small>
64      <span class="grow"></span>
65      <button id="flaresrefresh" type="button">refresh</button>
66    </header>
67    <div id="flaresmsg"></div>
68    <table id="flaretable">
69      <thead><tr><th>run</th><th>state</th><th>age</th><th>routes</th><th>jobs</th><th>cost</th><th></th></tr></thead>
70      <tbody id="flarerows"></tbody>
71    </table>
72  </section>
73"#;
74
75/// The most one chat message may weigh. A paste over this is refused by name rather than by
76/// axum's own 413, which says nothing a person can act on.
77///
78/// Derived from the attachment rules, because the two used to disagree: the cap was 4 MiB while
79/// `MAX_ATTACHMENTS × MAX_PICTURE_BYTES` promised 8 × 2 MiB, and base64 inflates a picture by 4/3.
80/// **Two** 2 MiB pictures are 5.6 MB of data URL, so they were refused with the advice "write it
81/// to a file and send the path" — advice no one can follow with a picture. The text allowance is
82/// `MAX_ATTACHED_CHARS` on top of the pictures' own room.
83pub const CHAT_BODY_LIMIT: usize = MAX_ATTACHMENTS
84    * (eclipse_core::message::MAX_PICTURE_BYTES / 3 * 4 + 1024)
85    + MAX_ATTACHED_CHARS;
86
87/// The logo's geometry, as committed. Its colours are *not* the ones served: `mark_svg` replaces
88/// them with the palette, so the brand is written down in one place (`eclipse_core::palette`) and
89/// the file keeps the radii, the filters and the layering that make it an eclipse.
90///
91/// Both assets are reached through `static/`, which holds symlinks to the single copies at the
92/// repository root. `cargo package` only ships files *inside* the crate directory, so the old
93/// `../../../assets/...` paths compiled in the workspace and then failed the publish of `eclipse-web`
94/// itself: the tarball carried no assets, and verification died on `couldn't read` before upload
95/// ('#'241). Symlinks are dereferenced into the tarball, so the packed copies stay byte-identical to
96/// the root ones — the same rule `LICENSE` follows.
97const MARK_SVG: &str = include_str!("../static/eclipse-mark.svg");
98
99/// The multi-size icon, byte for byte — the geometry of the same mark, already rasterised.
100const FAVICON_ICO: &[u8] = include_bytes!("../static/eclipse.ico");
101
102/// `GET /logo.svg`: the mark in this build's colours.
103///
104/// The source SVG names its own four colours (`#FF8A2B` halo, `#FFB45E` bloom, `#FFF7E8` ring,
105/// `#05060D` disc). Serving it verbatim would make the dashboard a second definition of the brand —
106/// the terminal draws the same mark from `palette::ACCENT`, and the two would drift the first time
107/// either moved. So the geometry is the file's and the colours are the table's: each literal is
108/// substituted below, and a test asserts the served bytes carry the palette's numbers.
109fn mark_svg() -> String {
110    use eclipse_core::palette as p;
111    let hex = |c: (u8, u8, u8)| format!("#{:02X}{:02X}{:02X}", c.0, c.1, c.2);
112    MARK_SVG
113        // The halo and the bloom are the accent, at two opacities.
114        .replace("#FF8A2B", &hex(p::ACCENT))
115        .replace("#FFB45E", &hex(p::ACCENT))
116        // The ring is the wordmark's hot end; the disc is the page's own background.
117        .replace("#FFF7E8", &hex(p::WORDMARK_TOP))
118        .replace("#05060D", &hex(p::BG))
119}
120const LOGIN_HTML: &str = include_str!("login.html");
121
122const SESSION_COOKIE: &str = "eclipse_session";
123
124/// How many logins are remembered at once; the oldest is dropped to make room. The default
125/// login lifetime lives in `eclipse_core::config` so the server and the docs cannot drift.
126const MAX_LOGINS: usize = 32;
127
128/// Agent runs allowed in flight at once; further chat requests get HTTP 429. One semaphore for
129/// every route that can start a run: the dashboard and the gateway must not each believe they
130/// are the only caller.
131pub const MAX_CONCURRENT_CHATS: usize = 4;
132
133/// How long a tool approval may stay unanswered before it counts as declined.
134const APPROVAL_TIMEOUT: Duration = Duration::from_secs(120);
135
136struct Pending {
137    run: u64,
138    decide: oneshot::Sender<bool>,
139}
140
141/// Approval requests waiting for a click. Each belongs to one agent run and is removed
142/// when it is answered, times out, or its run ends, so nothing outlives the run.
143#[derive(Default)]
144struct Approvals {
145    pending: Mutex<HashMap<String, Pending>>,
146    next_run: AtomicU64,
147}
148
149impl Approvals {
150    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, Pending>> {
151        self.pending.lock().unwrap_or_else(|e| e.into_inner())
152    }
153
154    /// Deliver a decision. `false` if the id is unknown, already answered or expired.
155    fn resolve(&self, id: &str, approved: bool) -> bool {
156        match self.lock().remove(id) {
157            Some(p) => {
158                let _ = p.decide.send(approved);
159                true
160            }
161            None => false,
162        }
163    }
164
165    #[cfg(test)]
166    fn len(&self) -> usize {
167        self.lock().len()
168    }
169}
170
171/// Drops every approval still pending for a run, and the run's cancel handle, when the
172/// run's task ends.
173struct RunScope {
174    state: Shared,
175    run: u64,
176    token: String,
177}
178
179impl Drop for RunScope {
180    fn drop(&mut self) {
181        self.state.approvals.lock().retain(|_, p| p.run != self.run);
182        self.state
183            .cancels
184            .lock()
185            .unwrap_or_else(|e| e.into_inner())
186            .remove(&self.token);
187    }
188}
189
190/// Cancels a run when the browser connection that started it goes away. Only a cancel
191/// token is held: if the run already finished, setting it does nothing.
192struct DisconnectGuard {
193    cancel: Cancel,
194}
195
196impl Drop for DisconnectGuard {
197    fn drop(&mut self) {
198        self.cancel.cancel();
199    }
200}
201
202#[derive(Clone, Copy, PartialEq, Eq)]
203enum Verdict {
204    Approved,
205    Denied,
206    TimedOut,
207    Cancelled,
208}
209
210impl Verdict {
211    fn as_str(self) -> &'static str {
212        match self {
213            Verdict::Approved => "approved",
214            Verdict::Denied => "denied",
215            Verdict::TimedOut => "timeout",
216            Verdict::Cancelled => "cancelled",
217        }
218    }
219}
220
221/// Asks the browser: emits an `approval_request` SSE event and waits for the decision
222/// POSTed to `/api/approvals/:id`. Anything but an explicit approval declines the tool.
223struct WebApprover {
224    state: Shared,
225    run: u64,
226    events: mpsc::UnboundedSender<Out>,
227}
228
229#[async_trait]
230impl Approver for WebApprover {
231    async fn decide(
232        &self,
233        call: &eclipse_core::approvals::Pending,
234    ) -> eclipse_core::approvals::Decision {
235        use eclipse_core::approvals::Decision;
236        let (tool, summary) = (call.tool.as_str(), call.summary.as_str());
237        let Ok(id) = eclipse_core::token::random_hex(16) else {
238            return Decision::Defer;
239        };
240        // `#285`: `/yolo` is on, so this call runs and nobody is asked. Counted, because "approvals
241        // are off" is a claim about a run that has already done things — the page shows the number.
242        if self.state.yolo.on() {
243            self.state
244                .unasked
245                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
246            return Decision::Allow;
247        }
248        let (decide, answer) = oneshot::channel();
249        // Registered before the event goes out so the answer can never beat it.
250        self.state.approvals.lock().insert(
251            id.clone(),
252            Pending {
253                run: self.run,
254                decide,
255            },
256        );
257        let request = Out::ApprovalRequest {
258            id: id.clone(),
259            tool: tool.to_string(),
260            summary: summary.to_string(),
261            timeout_secs: self.state.approval_timeout.as_secs(),
262        };
263        let verdict = if self.events.send(request).is_err() {
264            Verdict::Cancelled
265        } else {
266            tokio::select! {
267                r = answer => match r {
268                    Ok(true) => Verdict::Approved,
269                    Ok(false) => Verdict::Denied,
270                    Err(_) => Verdict::Cancelled,
271                },
272                _ = tokio::time::sleep(self.state.approval_timeout) => Verdict::TimedOut,
273                // The browser went away; nobody is left to answer.
274                _ = self.events.closed() => Verdict::Cancelled,
275            }
276        };
277        self.state.approvals.lock().remove(&id);
278        let _ = self.events.send(Out::ApprovalResolved { id, verdict });
279        match verdict {
280            Verdict::Approved => Decision::Allow,
281            // A prompt somebody had in front of them and let lapse is a "no" — fail-closed, and the
282            // model reads it as one. The browser going away is different: nobody saw the question,
283            // so the call stays on record and the panel shows it waiting when someone returns.
284            Verdict::TimedOut => Decision::Deny("the approval request timed out".to_string()),
285            Verdict::Cancelled => Decision::Defer,
286            Verdict::Denied => Decision::Deny("declined in the panel".to_string()),
287        }
288    }
289}
290
291/// One logged-in browser. The cookie carries a random id minted at login, never the
292/// token itself; ids live in memory only, so a restart logs everyone out.
293struct Session {
294    expires: Instant,
295    /// Minted with the session id, written into the page as a meta tag, and echoed in
296    /// `X-Eclipse-CSRF` on every request that changes something. It is the second lock: a browser
297    /// that reports an opaque origin — `Origin: null`, which an embedded pane, a sandboxed frame,
298    /// a `file://` page or a header-rewriting extension all produce — still has to prove it read
299    /// this page, and a page on another site cannot read it. Without this, the origin check was
300    /// the only thing standing between a session cookie and a cross-site post.
301    csrf: String,
302}
303
304struct Logins {
305    sessions: Mutex<HashMap<String, Session>>,
306    /// How long a login lasts. Carried here rather than read from the constant at each use,
307    /// so `[web] session_ttl_hours` is one decision made once.
308    ttl: Duration,
309}
310
311impl Logins {
312    fn new(ttl: Duration) -> Self {
313        Self {
314            sessions: Mutex::default(),
315            ttl,
316        }
317    }
318
319    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, Session>> {
320        self.sessions.lock().unwrap_or_else(|e| e.into_inner())
321    }
322
323    /// Starts a session, returning `(id, csrf)`: the id goes in the cookie, the csrf into the page.
324    fn create(&self) -> Option<(String, String)> {
325        let id = eclipse_core::token::random_hex(32).ok()?;
326        let csrf = eclipse_core::token::random_hex(32).ok()?;
327        let now = Instant::now();
328        let mut map = self.lock();
329        map.retain(|_, s| s.expires > now);
330        while map.len() >= MAX_LOGINS {
331            let oldest = map
332                .iter()
333                .min_by_key(|(_, s)| s.expires)
334                .map(|(k, _)| k.clone())?;
335            map.remove(&oldest);
336        }
337        map.insert(
338            id.clone(),
339            Session {
340                expires: now + self.ttl,
341                csrf: csrf.clone(),
342            },
343        );
344        Some((id, csrf))
345    }
346
347    fn is_valid(&self, id: &str) -> bool {
348        let mut map = self.lock();
349        match map.get(id) {
350            Some(s) if s.expires > Instant::now() => true,
351            Some(_) => {
352                map.remove(id);
353                false
354            }
355            None => false,
356        }
357    }
358
359    /// The session's CSRF token, if the session is still alive.
360    fn csrf_for(&self, id: &str) -> Option<String> {
361        let now = Instant::now();
362        self.lock()
363            .get(id)
364            .filter(|s| s.expires > now)
365            .map(|s| s.csrf.clone())
366    }
367
368    /// Whether `presented` is this session's token. Compared in constant time: a token that
369    /// arrives by guess should not be narrowed by how long the comparison took.
370    fn csrf_ok(&self, id: &str, presented: &str) -> bool {
371        self.csrf_for(id)
372            .is_some_and(|want| eclipse_core::token::constant_time_eq(presented, &want))
373    }
374
375    fn remove(&self, id: &str) {
376        self.lock().remove(id);
377    }
378}
379
380pub struct AppState {
381    /// `None` when the provider is not configured; the dashboard still starts.
382    pub agent: Option<Arc<Agent>>,
383    pub store: eclipse_core::session::SessionStore,
384    pub model: String,
385    pub config_error: Option<String>,
386    chat_slots: Arc<Semaphore>,
387    approvals: Approvals,
388    /// Running chats by run id, so `POST /api/runs/:id/cancel` (or a closed browser
389    /// connection) can stop one. Removed when the run ends.
390    cancels: Mutex<HashMap<String, Cancel>>,
391    approval_timeout: Duration,
392    /// `#285`: `/yolo` for this dashboard process. One server, many tabs — so the switch is the
393    /// server's, read per run when the approver decides, and every tab sees the same state after a
394    /// reload. That is the opposite of the terminal's rule, and the reason is in the sentence the
395    /// module already wrote down: a mode nobody can see must not be reachable. Here the page *can*
396    /// show it (the stats row), so it can survive a reload — a mode that vanished on F5 would be
397    /// exactly the invisible one.
398    pub yolo: eclipse_core::yolo::Yolo,
399    /// Tool calls this dashboard has run without a card, since the process started. The honest
400    /// minimum the issue asked for: an approval-off state has to say how much has already gone by.
401    pub unasked: std::sync::atomic::AtomicUsize,
402    auth_token: String,
403    /// What a *human* sign-in is checked against: a username and a password hash from `.env`, or
404    /// — on an install that predates the password form — the shared token. The token above stays
405    /// whatever this says: `/v1`'s `Authorization: Bearer` is a machine credential and the
406    /// dashboard's human door does not replace it.
407    auth: eclipse_core::auth::Credentials,
408    /// How long a login lasts. The cookie's max-age and the server-side expiry must agree,
409    /// or the browser holds a cookie the server has already forgotten.
410    login_ttl: Duration,
411    logins: Logins,
412    /// Wrong tokens get slower. See [`LoginThrottle`].
413    throttle: LoginThrottle,
414    /// The config file this process was started with, and the profile overlay in force. The
415    /// settings endpoints read and write that file rather than a copy in memory: what the next
416    /// run loads is the file, so what a page shows has to be the file too.
417    pub config_path: Option<std::path::PathBuf>,
418    pub profile: Option<String>,
419    /// Whether `config_path` came from `--config` rather than from `$ECLIPSE_CONFIG`. It decides
420    /// one thing: an explicit file is the file a write lands in, exactly as `config set` treats it
421    /// (`config::write_target`). A path the process merely defaulted to is not explicit, so a
422    /// served profile's overlay is where its writes go (`#571`).
423    pub config_explicit: bool,
424    /// Where `profiles/` lives — `[`eclipse_core::config::home_root`], the directory the config
425    /// layout hangs off. The served profile's overlay is under it, and so is the file a dashboard
426    /// write lands in (`#571`). `None` when this process has no home, and then there is nowhere to
427    /// write but the file it was started with.
428    pub profiles_root: Option<std::path::PathBuf>,
429    /// The install root whose cron state is probed by /healthz. `None` in unit tests.
430    pub cron_root: Option<std::path::PathBuf>,
431    /// One writer at a time to `config_path` (`#399`). A setting is a read-edit-write over the
432    /// whole file, so two overlapping writes both read the old text and the later one silently
433    /// drops the earlier one — the value the user saw confirmed is simply gone. Held inside the
434    /// blocking closure, never across an await.
435    pub config_writes: Arc<std::sync::Mutex<()>>,
436    /// Last model-reachability probe, cached so /healthz is not a slow request every hit.
437    /// `(when, reachable)`; `None` when no probe has run yet.
438    pub model_probe: Arc<std::sync::Mutex<Option<(std::time::Instant, bool)>>>,
439    /// Sessions with a `/loop` tick in flight in this process (`#173`). The file says a loop is
440    /// due; this says one of this gateway's own ticks has already picked it up, so a second sweep
441    /// does not start the same turn twice.
442    ticking: Mutex<std::collections::HashSet<String>>,
443    /// Where the update badge is read from, when this process has an install to report on.
444    /// `None` in unit tests and in a checkout with no marker: the page then shows nothing rather
445    /// than inventing a version. A read, never a check — the gateway's schedule owns the network.
446    pub update: Option<eclipse_core::update::Watch>,
447    /// `#509`: the bots this config declared, each with the agent its conversation runs on. Empty
448    /// for every config without `[bots]`, which is what keeps the page identical for someone who
449    /// has none.
450    pub bots: crate::bots::Bots,
451}
452
453impl AppState {
454    pub fn new(
455        agent: Option<Arc<Agent>>,
456        store: eclipse_core::session::SessionStore,
457        model: String,
458        config_error: Option<String>,
459        auth_token: String,
460        login_ttl: Duration,
461    ) -> Self {
462        Self {
463            agent,
464            store,
465            model,
466            config_error,
467            chat_slots: Arc::new(Semaphore::new(MAX_CONCURRENT_CHATS)),
468            approvals: Approvals::default(),
469            cancels: Mutex::default(),
470            approval_timeout: APPROVAL_TIMEOUT,
471            // The dashboard decides its policy per call through `WebApprover`, so it starts at
472            // "ask": nothing in the config can have turned approvals off behind this switch.
473            yolo: eclipse_core::yolo::Yolo::new(false),
474            unasked: std::sync::atomic::AtomicUsize::new(0),
475            auth_token,
476            // Token mode unless the caller says otherwise, so an install with no password set
477            // behaves exactly as it did before there was a form with two fields.
478            auth: eclipse_core::auth::Credentials::Token,
479            login_ttl,
480            logins: Logins::new(login_ttl),
481            throttle: LoginThrottle::default(),
482            config_path: None,
483            profile: None,
484            config_explicit: false,
485            profiles_root: None,
486            cron_root: None,
487            config_writes: Arc::new(std::sync::Mutex::new(())),
488            model_probe: Arc::new(std::sync::Mutex::default()),
489            ticking: Mutex::default(),
490            update: None,
491            bots: crate::bots::Bots::empty(),
492        }
493    }
494
495    /// `#509`: the bots the config declared, with one agent each built from their declaration.
496    ///
497    /// A bot whose agent could not be built keeps the reason rather than failing startup: a broken
498    /// bot must not be able to lock the person out of their own dashboard.
499    pub fn with_bots(
500        mut self,
501        cfg: &eclipse_core::config::Config,
502        env: eclipse_core::config::EnvFn,
503    ) -> Self {
504        self.bots = crate::bots::Bots::build(cfg, env);
505        self
506    }
507
508    /// The agent a session's turn runs on (`#509`).
509    ///
510    /// A session whose `origin` is `bot:<name>` runs on that bot's own agent — its instructions,
511    /// its memory, its skills — and every other session runs on the dashboard's. This is the whole
512    /// of the send path: the row decides, so a transcript opened from the Bots tab is that bot's
513    /// conversation whether it was opened there or by id.
514    fn agent_for(&self, session: &str) -> std::result::Result<Option<Arc<Agent>>, String> {
515        let origin = self.store.origin(session).ok().flatten();
516        let Some(name) = origin.as_deref().and_then(|o| o.strip_prefix("bot:")) else {
517            return Ok(self.agent.clone());
518        };
519        match self.bots.agent(name) {
520            Some(Ok(agent)) => Ok(Some(Arc::clone(agent))),
521            Some(Err(why)) => Err(format!("bot `{name}` cannot run: {why}")),
522            None => Err(format!(
523                "this session belongs to bot `{name}`, which is no longer declared in `[bots]`"
524            )),
525        }
526    }
527
528    /// Claim a session's loop tick for this process. `false` when another sweep already has it.
529    pub fn claim_tick(&self, session: &str) -> bool {
530        self.ticking
531            .lock()
532            .unwrap_or_else(|e| e.into_inner())
533            .insert(session.to_string())
534    }
535
536    /// Release the claim. Called from the tick's own task, however it ended.
537    pub fn release_tick(&self, session: &str) {
538        self.ticking
539            .lock()
540            .unwrap_or_else(|e| e.into_inner())
541            .remove(session);
542    }
543
544    /// Take one of the [`MAX_CONCURRENT_CHATS`] slots, or `None` when the cap is reached. The
545    /// permit is held for the length of the run, so a caller takes it before starting the agent
546    /// and drops it when the response is done. Every route that can start a run goes through
547    /// here — the dashboard's own handler included — so the cap is one number and not one per
548    /// surface.
549    pub fn try_chat_slot(&self) -> Option<tokio::sync::OwnedSemaphorePermit> {
550        self.chat_slots.clone().try_acquire_owned().ok()
551    }
552
553    /// The shared credential the API checks as `Authorization: Bearer`. A getter rather than a
554    /// public field: the token is a credential, and the only readers should be auth checks.
555    pub fn token(&self) -> &str {
556        &self.auth_token
557    }
558
559    /// What a person signs in with. Set at startup from `.env`; `Token` until then.
560    pub fn with_credentials(mut self, auth: eclipse_core::auth::Credentials) -> Self {
561        self.auth = auth;
562        self
563    }
564
565    /// How the sign-in page should describe itself: `password` or `token`.
566    pub fn auth_mode(&self) -> &'static str {
567        self.auth.mode()
568    }
569
570    /// Where cron state lives, for the health check.
571    pub fn with_cron_root(mut self, root: std::path::PathBuf) -> Self {
572        self.cron_root = Some(root);
573        self
574    }
575
576    /// Where this process reads its config from, for the settings page.
577    pub fn with_config_path(
578        mut self,
579        path: Option<std::path::PathBuf>,
580        profile: Option<String>,
581    ) -> Self {
582        self.config_path = path;
583        self.profile = profile;
584        self
585    }
586
587    /// Whether that path was given with `--config`, and where `profiles/` lives. See
588    /// [`AppState::config_explicit`] and [`AppState::profiles_root`].
589    pub fn with_config_targets(
590        mut self,
591        explicit: bool,
592        profiles_root: Option<std::path::PathBuf>,
593    ) -> Self {
594        self.config_explicit = explicit;
595        self.profiles_root = profiles_root;
596        self
597    }
598
599    /// The file a write lands in: the served profile's own overlay, or the base file when there is
600    /// no profile — the same rule `config set` follows, from the same function (`#571`).
601    ///
602    /// It used to be `config_path` in both cases, so under `--profile` (or `[web] default_profile`)
603    /// every settings and MCP write edited the file every other profile reads, and a key the
604    /// overlay already pinned made the reload answer with the unchanged value.
605    pub(crate) fn write_path(&self) -> Option<std::path::PathBuf> {
606        let explicit = if self.config_explicit {
607            self.config_path.as_deref()
608        } else {
609            None
610        };
611        eclipse_core::config::write_target(
612            self.profiles_root.as_deref(),
613            explicit,
614            self.config_path.as_deref(),
615            self.profile.as_deref(),
616        )
617        .or_else(|| self.config_path.clone())
618    }
619
620    /// The config as the file says *now*.
621    pub(crate) fn reload_config(&self) -> Result<eclipse_core::config::Config, String> {
622        let path = self
623            .config_path
624            .as_ref()
625            .ok_or_else(|| "this dashboard was started without a config file".to_string())?;
626        eclipse_core::config::Config::load_with_profile(
627            Some(path),
628            self.profile.as_deref(),
629            &eclipse_core::config::process_env,
630        )
631        .map_err(|e| e.to_string())
632    }
633
634    /// What the next turn will be asked for. A model chosen in the picker wins over the one the
635    /// file names, so the header cannot keep claiming the old one after a switch.
636    ///
637    /// Public because the gateway's `/v1` door asks the same question — a reply that names a
638    /// different model than the one that answered is the one thing a client cannot check.
639    pub fn current_model(&self) -> Option<String> {
640        self.agent
641            .as_ref()
642            .and_then(|a| a.model())
643            .or_else(|| (!self.model.is_empty()).then(|| self.model.clone()))
644    }
645
646    /// The model the configuration names — the startup value, untouched by a runtime choice.
647    /// The page offers it as the way back only when it differs from the current one.
648    pub(crate) fn configured_model(&self) -> Option<String> {
649        (!self.model.is_empty()).then(|| self.model.clone())
650    }
651
652    /// Pre-authenticated browser session for tests.
653    #[cfg(test)]
654    fn with_login(self, id: &str) -> Self {
655        self.logins.lock().insert(
656            id.to_string(),
657            Session {
658                expires: Instant::now() + self.login_ttl,
659                csrf: TEST_CSRF.to_string(),
660            },
661        );
662        self
663    }
664
665    #[cfg(test)]
666    fn with_approval_timeout(mut self, timeout: Duration) -> Self {
667        self.approval_timeout = timeout;
668        self
669    }
670}
671
672pub type Shared = Arc<AppState>;
673
674/// The dashboard's routes, without the state applied: the gateway merges its own routes on
675/// before calling `.with_state`, so the origin guard is the only layer either side adds.
676pub fn routes(state: Shared) -> Router<Shared> {
677    Router::new()
678        .route("/", get(index))
679        .route("/login", get(login_page).post(login))
680        .route("/logout", post(logout))
681        .route("/healthz", get(health))
682        .route("/api/update", get(update_state))
683        .route("/api/sessions", get(list_sessions))
684        // `#509`: the Bots tab. Reading lists the declarations; the three writes act on a bot's
685        // live conversation, never on its identity — that is `[bots]` and belongs to the file.
686        .route("/api/bots", get(list_bots))
687        .route("/api/bots/:name/open", post(open_bot))
688        .route("/api/bots/:name/rename", post(rename_bot))
689        .route("/api/bots/:name/clear", post(clear_bot))
690        .route("/api/bots/:name/prompt", get(bot_prompt))
691        // `#171`: the Flares tab. Two reads over the run ledger (`flares list` and `flares show`
692        // answer from the same two store calls) and one write — "stop asking", the same flag
693        // `eclipse flares cancel` sets. Nothing here starts a run: a fan-out is the model calling
694        // the tool, and a page that could launch one would be a second scheduler.
695        .route("/api/flares", get(list_flares))
696        .route("/api/flares/:run", get(read_flare))
697        .route("/api/flares/:run/cancel", post(cancel_flare))
698        .route("/api/sessions/:id", get(get_session))
699        .route("/api/sessions/:id/rename", post(rename_session))
700        .route("/api/sessions/:id/pin", post(pin_session))
701        .route("/api/sessions/:id/archive", post(archive_session))
702        .route("/api/sessions/:id/delete", post(delete_session))
703        .route("/api/search", get(search_sessions))
704        .route("/api/settings", get(list_settings).post(write_setting))
705        // The three context files, resolved by the loader (`context_files::editable`) and written
706        // through the same lock and rename the `memory` tool uses. The request names one of three
707        // ids, never a path (#268).
708        .route("/api/context", get(list_context).post(write_context))
709        .route("/api/models", get(list_models))
710        .route("/api/commands", get(list_commands))
711        .route("/api/model", post(choose_model))
712        .route("/api/reasoning", get(read_reasoning).post(choose_reasoning))
713        .route("/api/chat", post(chat))
714        .route("/api/approvals/:id", post(decide_approval))
715        .route("/api/runs/:id/cancel", post(cancel_run))
716        // The mark and the tab's icon. No login: a favicon request carries no cookie the browser
717        // will use, and a sign-in page with a blank icon is exactly what #247 set out to fix.
718        .route("/logo.svg", get(logo))
719        .route("/favicon.ico", get(favicon))
720        // Cron: the same jobs `eclipse cron` reads and the timer runs. Every write goes through
721        // the store functions the CLI calls, and the layer's CSRF/origin guard covers these
722        // routes with no per-handler ceremony.
723        .route("/api/cron", get(list_cron).post(create_cron))
724        .route("/api/cron/:name", put(update_cron).delete(delete_cron))
725        .route("/api/cron/:name/enabled", post(set_cron_enabled))
726        .route("/api/cron/:name/run", post(run_cron_now))
727        .route("/api/cron/:name/logs", get(cron_logs))
728        // MCP: the same `[[mcp]]` entries `eclipse mcp list` prints, seen and edited from the
729        // page (#352). Every write goes through the `config::mcp_*` writers the CLI calls, under
730        // the same config write lock (`#399`), so the two surfaces cannot drift.
731        // `#505`: what the loaders complained about. Read-only and re-read on every call, so a
732        // fixed skill disappears without a restart — the same `Report` the CLI prints, one shape.
733        .route("/api/problems", get(list_problems))
734        .route("/api/mcp", get(list_mcp).post(add_mcp))
735        // `put` beside the `delete` (`#517`): the path is the one the pane already knows, and an
736        // edit is not a remove followed by an add — the writer keeps the entry's own lines.
737        .route("/api/mcp/:name", put(update_mcp).delete(remove_mcp))
738        .route("/api/mcp/:name/enabled", post(set_mcp_enabled))
739        .route("/api/mcp/:name/test", post(test_mcp))
740        // A message body is text a person pasted, not a file: the cap is generous enough for a long
741        // error log and small enough that one request cannot be a memory event. `refuse_oversized`
742        // runs first and answers over the declared length, so the refusal is a sentence rather than
743        // axum's bare 413; `DefaultBodyLimit` is the backstop for a body with no length declared.
744        .layer(middleware::from_fn(refuse_oversized))
745        .layer(DefaultBodyLimit::max(CHAT_BODY_LIMIT))
746        .layer(middleware::from_fn_with_state(state.clone(), require_login))
747        .layer(middleware::from_fn_with_state(
748            state.clone(),
749            guard_local_origin,
750        ))
751}
752
753/// A turn over [`CHAT_BODY_LIMIT`] is refused by name, before its body is read (#220).
754///
755/// axum's own limit fires inside the extractor and answers with a bare `413 Payload Too Large`
756/// and no body at all — nothing a person can act on. This runs earlier, on the length the request
757/// *declares*, so the ordinary case (a browser sending `Content-Length`) gets a sentence and a
758/// number. A chunked body with no declared length still meets axum's limit, which is the backstop;
759/// either way the body is never buffered past the cap.
760async fn refuse_oversized(req: Request, next: Next) -> Response {
761    if req.method() == Method::POST && req.uri().path() == "/api/chat" {
762        let declared = req
763            .headers()
764            .get(header::CONTENT_LENGTH)
765            .and_then(|v| v.to_str().ok())
766            .and_then(|v| v.parse::<usize>().ok());
767        if let Some(len) = declared {
768            if len > CHAT_BODY_LIMIT {
769                let mb = |n: usize| format!("{:.1} MB", n as f64 / (1024.0 * 1024.0));
770                let sentence = format!(
771                    "that message is {} ({} over the {} limit for one turn) — attach fewer or \
772                     smaller pictures, or write the text to a file and send its path",
773                    mb(len),
774                    mb(len - CHAT_BODY_LIMIT),
775                    mb(CHAT_BODY_LIMIT),
776                );
777                return error(StatusCode::PAYLOAD_TOO_LARGE, &sentence).into_response();
778            }
779        }
780    }
781    next.run(req).await
782}
783
784/// The dashboard on its own: every route above with its state.
785pub fn router(state: Shared) -> Router {
786    routes(state.clone()).with_state(state)
787}
788
789/// The one parser for a `Cookie:` header, over every `Cookie:` header the request sent.
790///
791/// There used to be a second, string-shaped copy that the origin guard used on the *first* header
792/// only. A request carrying two `Cookie:` headers was therefore logged in according to one parser
793/// and anonymous according to the other: fail-closed, so never a hole, but two readers of the same
794/// thing drift, and the next change to one does not reach the other.
795fn cookie_value<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
796    headers
797        .get_all(header::COOKIE)
798        .iter()
799        .filter_map(|v| v.to_str().ok())
800        .flat_map(|v| v.split(';'))
801        .find_map(|pair| {
802            let (k, v) = pair.trim().split_once('=')?;
803            (k == name).then_some(v)
804        })
805}
806
807fn is_logged_in(st: &AppState, headers: &HeaderMap) -> bool {
808    cookie_value(headers, SESSION_COOKIE).is_some_and(|id| st.logins.is_valid(id))
809}
810
811fn session_cookie(value: &str, max_age_secs: u64) -> HeaderValue {
812    // Loopback is plain HTTP, so no `Secure`; HttpOnly keeps it from scripts and
813    // SameSite=Strict keeps it off cross-site requests.
814    HeaderValue::from_str(&format!(
815        "{SESSION_COOKIE}={value}; HttpOnly; SameSite=Strict; Path=/; Max-Age={max_age_secs}"
816    ))
817    .expect("cookie is ascii")
818}
819
820/// The sign-in page. `hint` is empty unless the request itself says something worth knowing —
821/// that it arrived inside a frame, or without an origin — because those are the two situations
822/// where a correct token still leaves the person at this form.
823///
824/// The page is handed the same `palette_css()` the dashboard gets (#265). It used to carry a
825/// hand-typed `:root` with `--accent:#5aa2ff` — the blue the dashboard's own scan test bans, one
826/// character from the `#5aa9ff` it was meant to have replaced — so the first screen anyone saw was a
827/// different brand from the one behind it.
828fn login_html(mode: &str, error: &str, hint: &str) -> Html<String> {
829    // The page is one document in two shapes (`#266`): `password` asks for a user and a password,
830    // `token` asks for the one secret an install that predates them still has. Which shape it is
831    // comes from the server, not from the page — a page that guessed would be guessing about a
832    // credential.
833    let intro = match mode {
834        "password" => {
835            "Sign in with the user from <code>ECLIPSE_WEB_USER</code> in <code>.env</code>, and \
836             the password <code>eclipse web passwd</code> set for it."
837        }
838        _ => "Enter the dashboard token from <code>auth_token</code> in your config file.",
839    };
840    Html(
841        LOGIN_HTML
842            .replace("{{PALETTE}}", &palette_css())
843            .replace("{{VERSION}}", env!("CARGO_PKG_VERSION"))
844            .replace("{{AUTH_MODE}}", mode)
845            .replace("{{AUTH_INTRO}}", intro)
846            .replace("{{ERROR}}", &escape_html(error))
847            .replace("{{HINT}}", &escape_html(hint)),
848    )
849}
850
851/// Everything except `/healthz`, the login/logout routes and the two icons needs a valid login
852/// cookie. The icons are here because a browser asks for them *before* anyone signs in — a sign-in
853/// page with a blank tab icon is the thing #247 set out to fix — and because a mark is not a secret;
854/// the response carries no state and no config.
855/// Without one, `/` answers 401 with the login form and everything else 401 with JSON.
856async fn require_login(State(st): State<Shared>, req: Request, next: Next) -> Response {
857    let path = req.uri().path();
858    if matches!(
859        path,
860        "/healthz" | "/login" | "/logout" | "/logo.svg" | "/favicon.ico"
861    ) || is_logged_in(&st, req.headers())
862    {
863        return next.run(req).await;
864    }
865    if path == "/" {
866        return (StatusCode::UNAUTHORIZED, login_html(st.auth_mode(), "", "")).into_response();
867    }
868    error(StatusCode::UNAUTHORIZED, "login required").into_response()
869}
870
871async fn login_page(State(st): State<Shared>, headers: HeaderMap) -> Response {
872    if is_logged_in(&st, &headers) {
873        return redirect_home(None);
874    }
875    login_html(st.auth_mode(), "", frame_hint(&headers)).into_response()
876}
877
878/// Said on the sign-in page when the request arrives from inside a frame. A frame that cannot
879/// name its origin (the `Origin: null` a sandboxed iframe sends) also cannot keep a cookie, so a
880/// correct token would come back to this form — which is worth saying before it happens, not after.
881fn frame_hint(headers: &HeaderMap) -> &'static str {
882    let dest = headers
883        .get("sec-fetch-dest")
884        .and_then(|v| v.to_str().ok())
885        .unwrap_or("");
886    if dest == "iframe" || dest == "frame" || dest == "embed" || dest == "object" {
887        "This page is inside a frame. A frame that cannot name its origin cannot keep the session \
888         cookie either, so signing in will return you here — open the dashboard in its own browser \
889         tab instead."
890    } else {
891        ""
892    }
893}
894
895/// How long a wrong token buys the next attempt. Nothing on this path had a delay, a counter or a
896/// 429: guessing was free, and `MIN_TOKEN_LEN` allows a 32-character token, which is not a number an
897/// attacker cannot reach given unlimited attempts.
898///
899/// One bucket, not one per peer. The dashboard listens on loopback only, so the user's browser, a
900/// hostile local process and an SSRF pivot are all `127.0.0.1` — a peer key would put them in the
901/// same bucket anyway. In memory and per process: a restart forgets, and what this buys is that
902/// guessing costs time, not that it is impossible.
903pub struct LoginThrottle {
904    inner: Mutex<Attempts>,
905    /// Attempts before the first delay, and the delay that doubles from there.
906    free: u32,
907    base: Duration,
908    cap: Duration,
909}
910
911#[derive(Default)]
912struct Attempts {
913    wrong: u32,
914    /// `None` until the first attempt has to wait.
915    until: Option<Instant>,
916}
917
918impl Default for LoginThrottle {
919    fn default() -> Self {
920        Self::new(2, Duration::from_secs(1), Duration::from_secs(60))
921    }
922}
923
924impl LoginThrottle {
925    fn new(free: u32, base: Duration, cap: Duration) -> Self {
926        Self {
927            inner: Mutex::new(Attempts::default()),
928            free,
929            base,
930            cap,
931        }
932    }
933
934    /// How many seconds until another attempt is worth making, or `None` when it may be tried now.
935    /// Callers ask *before* comparing the token: a locked-out guess must cost nothing to refuse.
936    fn wait_for(&self) -> Option<u64> {
937        let g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
938        let until = g.until?;
939        let now = Instant::now();
940        if now >= until {
941            return None;
942        }
943        Some((until - now).as_secs().max(1))
944    }
945
946    /// A wrong token: count it, and once the free ones are gone make the next attempt wait —
947    /// doubling up to the cap, so a run of guesses slows to one a minute.
948    fn fail(&self) {
949        let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
950        g.wrong = g.wrong.saturating_add(1);
951        if g.wrong <= self.free {
952            return;
953        }
954        let step = g.wrong - self.free - 1;
955        let delay = self
956            .base
957            .saturating_mul(1u32.checked_shl(step.min(16)).unwrap_or(u32::MAX))
958            .min(self.cap);
959        g.until = Some(Instant::now() + delay);
960    }
961
962    /// A right token: whatever was counted is no longer this caller's problem.
963    fn reset(&self) {
964        let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
965        *g = Attempts::default();
966    }
967}
968
969fn redirect_home(cookie: Option<HeaderValue>) -> Response {
970    let mut resp = (StatusCode::SEE_OTHER, [(header::LOCATION, "/")]).into_response();
971    if let Some(c) = cookie {
972        resp.headers_mut().insert(header::SET_COOKIE, c);
973    }
974    resp
975}
976
977/// `POST /login`'s body, in either shape. The password form posts `username` + `password`; the
978/// token form (and anything scripted against the old route) posts `token`. All three are optional
979/// so a browser that submits an empty username field does not 400 into an empty page: the check is
980/// what refuses a bad sign-in, and it says so in words.
981#[derive(Deserialize)]
982struct LoginForm {
983    #[serde(default)]
984    username: String,
985    #[serde(default)]
986    password: String,
987    #[serde(default)]
988    token: String,
989}
990
991/// The find box's query string. Both fields are optional so `/api/search` alone answers an empty
992/// list rather than a 400 — the page calls it on the first keystroke and on clearing the box.
993#[derive(Deserialize)]
994struct Find {
995    q: Option<String>,
996    limit: Option<usize>,
997}
998
999/// `POST /login` (form field `token`): on success sets the session cookie and redirects
1000/// to `/`; otherwise 401 with the form again.
1001async fn login(
1002    State(st): State<Shared>,
1003    headers: HeaderMap,
1004    Form(form): Form<LoginForm>,
1005) -> Response {
1006    // Asked before the comparison, so a locked-out guess costs a comparison nothing.
1007    if let Some(secs) = st.throttle.wait_for() {
1008        let mut resp = (
1009            StatusCode::TOO_MANY_REQUESTS,
1010            login_html(
1011                st.auth_mode(),
1012                &format!("Too many wrong sign-ins. Try again in {secs} s."),
1013                "Each wrong sign-in makes the next attempt wait longer. Nothing is locked for good: \
1014                 wait it out, or restart the dashboard to clear the counter.",
1015            ),
1016        )
1017            .into_response();
1018        resp.headers_mut().insert(
1019            header::RETRY_AFTER,
1020            HeaderValue::from_str(&secs.to_string()).unwrap_or(HeaderValue::from_static("1")),
1021        );
1022        return resp;
1023    }
1024    // `#266`: both halves, in `eclipse_core::auth`. `secret` is the password in password mode and
1025    // the token in token mode, so one code path covers the migration case. The throttle above is
1026    // paid before this comparison either way, and `Credentials::check` computes the username and
1027    // the PBKDF2 derivation before looking at either — a stopwatch cannot tell an unknown user
1028    // from a wrong password.
1029    let secret = if form.password.is_empty() {
1030        form.token.as_str()
1031    } else {
1032        form.password.as_str()
1033    };
1034    // `#425`: the PBKDF2 derivation is the expensive part of signing in and it used to run on an
1035    // async worker. One attempt costs milliseconds of CPU; a burst of them occupies every worker
1036    // the server has, and the throttle that is meant to slow an attacker down is then waiting on a
1037    // thread that the attacker's own previous attempts are holding. Off the runtime, so a wrong
1038    // password is slow to answer and cheap to survive.
1039    let auth = st.auth.clone();
1040    let (user, token, secret) = (
1041        form.username.clone(),
1042        st.auth_token.clone(),
1043        secret.to_string(),
1044    );
1045    let passed = blocking(move || auth.check(&user, &secret, &token))
1046        .await
1047        .unwrap_or(false);
1048    if !passed {
1049        st.throttle.fail();
1050        // An opaque origin on the way in is the same story as an origin-less frame: the token may
1051        // well be right, and the cookie is what will not survive.
1052        let hint = match frame_hint(&headers) {
1053            "" if headers.contains_key(header::ORIGIN) => {
1054                "Your browser sent Origin: null, so it will not say which page submitted this \
1055                 form (a sandboxed frame, an embedded pane, a file:// page, or an extension that \
1056                 rewrites headers). If the credential is right and you land back here, open the \
1057                 dashboard in its own tab."
1058            }
1059            other => other,
1060        };
1061        let wrong = match st.auth_mode() {
1062            // One answer for a wrong user and a wrong password: telling them apart would turn the
1063            // form into a way to enumerate usernames.
1064            "password" => "Wrong user or password.",
1065            _ => "Wrong token.",
1066        };
1067        return (
1068            StatusCode::UNAUTHORIZED,
1069            login_html(st.auth_mode(), wrong, hint),
1070        )
1071            .into_response();
1072    }
1073    st.throttle.reset();
1074    match st.logins.create() {
1075        Some((id, _csrf)) => redirect_home(Some(session_cookie(&id, st.login_ttl.as_secs()))),
1076        None => error(StatusCode::INTERNAL_SERVER_ERROR, "cannot create a session").into_response(),
1077    }
1078}
1079
1080async fn logout(State(st): State<Shared>, headers: HeaderMap) -> Response {
1081    if let Some(id) = cookie_value(&headers, SESSION_COOKIE) {
1082        st.logins.remove(id);
1083    }
1084    let mut resp = (StatusCode::SEE_OTHER, [(header::LOCATION, "/")]).into_response();
1085    resp.headers_mut()
1086        .insert(header::SET_COOKIE, session_cookie("", 0));
1087    resp
1088}
1089
1090fn is_loopback_host(authority: &str) -> bool {
1091    let host = if let Some(rest) = authority.strip_prefix('[') {
1092        rest.split(']').next().unwrap_or("")
1093    } else {
1094        authority.split(':').next().unwrap_or("")
1095    };
1096    // `localhost.` is `localhost`: the trailing dot is the root label, not a different name, and a
1097    // browser that is handed one will send it back verbatim.
1098    let host = host.trim_end_matches('.');
1099    host == "127.0.0.1" || host == "::1" || host.eq_ignore_ascii_case("localhost")
1100}
1101
1102/// The header the page sends with every request that changes something.
1103const CSRF_HEADER: &str = "x-eclipse-csrf";
1104
1105/// The token `with_login` attaches to the session a test starts pre-authenticated.
1106#[cfg(test)]
1107const TEST_CSRF: &str = "test-csrf-token";
1108
1109/// A header value as text, copied out so nothing borrows the request across an await.
1110fn header_text(req: &Request, name: &str) -> Option<String> {
1111    req.headers()
1112        .get(name)
1113        .and_then(|v| v.to_str().ok())
1114        .map(str::to_string)
1115}
1116
1117/// The authority of an `Origin` value: `http://127.0.0.1:8787` → `127.0.0.1:8787`. `null` — the
1118/// opaque origin a browser reports for a sandboxed frame, an embedded pane or a `file://` page —
1119/// comes back as `null`, which never matches a host.
1120fn authority_of(origin: &str) -> &str {
1121    origin.split_once("://").map_or(origin, |(_, rest)| rest)
1122}
1123
1124/// Why this request is not from the dashboard, in the words the page will show. `None` means it
1125/// is allowed.
1126///
1127/// Three things can make a request legitimate, and being explicit about which one applied is what
1128/// keeps the guard honest:
1129///
1130/// 1. it changes nothing (a GET), or it came from this origin, which is the ordinary path;
1131/// 2. it is the login attempt, where the token in the body *is* the credential — a page on another
1132///    site gains nothing by submitting it that guessing the token would not give it;
1133/// 3. it carries this session's CSRF token, which only a page served from here could have read.
1134///
1135/// Rule 3 exists because rule 1 alone was too brittle: a browser that reports `Origin: null` is
1136/// not necessarily hostile, it may be telling the truth about an embedded pane or an extension
1137/// that rewrote the header, and refusing it with a sentence that accuses it of being cross-site
1138/// leaves the person with a dashboard that will not let them in and no idea why.
1139fn arrival_refusal(
1140    logins: &Logins,
1141    method: &Method,
1142    path: &str,
1143    host: Option<&str>,
1144    origin: Option<&str>,
1145    csrf: Option<&str>,
1146    session: Option<&str>,
1147) -> Option<String> {
1148    let Some(host) = host else {
1149        return Some("the request carried no Host header".to_string());
1150    };
1151    if !is_loopback_host(host) {
1152        return Some(format!(
1153            "Host {host:?} is not 127.0.0.1, ::1 or localhost. Open the dashboard on this \
1154             machine's own address, http://127.0.0.1:<port>; from another machine use an SSH \
1155             tunnel, which keeps the header local. A reverse proxy or a LAN name in front of the \
1156             dashboard is refused by design, because the token is the only thing guarding it"
1157        ));
1158    }
1159
1160    // Nothing that reads is what CSRF is about, and the session cookie is `SameSite=Strict`, so a
1161    // cross-site navigation does not even arrive holding one.
1162    if matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS) {
1163        return None;
1164    }
1165
1166    let stated = origin.map(authority_of);
1167    let same_origin = match stated {
1168        None => true, // no Origin at all: a form post from a page that declines to say, not a cross-site one
1169        Some(authority) => authority.eq_ignore_ascii_case(host),
1170    };
1171    if same_origin {
1172        return None;
1173    }
1174
1175    // Signing in: the credential is in the body, so an anonymous sender can do nothing a guesser
1176    // could not, and refusing here only locks out a browser whose pane reports no origin.
1177    let anonymous_but_harmless = path == "/login" && stated == Some("null");
1178    if anonymous_but_harmless {
1179        return None;
1180    }
1181
1182    // The origin was useless. Ask for the one thing a foreign page cannot produce.
1183    if let (Some(id), Some(presented)) = (session, csrf) {
1184        if logins.csrf_ok(id, presented) {
1185            return None;
1186        }
1187    }
1188
1189    let what = match stated {
1190        Some("null") => {
1191            "Origin \"null\" means the browser would not name the page that sent this request: a \
1192             sandboxed frame, an embedded preview pane, a file:// page, or an extension that \
1193             rewrites headers all look like this"
1194                .to_string()
1195        }
1196        Some(authority) => format!(
1197            "Origin {authority:?} is not this dashboard ({host:?}); that mismatch is what a \
1198             cross-site request looks like, or a proxy that rewrote the Host header"
1199        ),
1200        None => "the request says nothing about where it came from".to_string(),
1201    };
1202    Some(format!(
1203        "{what}. This request also carried no valid {CSRF_HEADER} token for its session, and a page \
1204         served from here always does. Open the dashboard in a normal browser tab at \
1205         http://127.0.0.1:<port>: a frame that cannot name its origin cannot keep the session \
1206         cookie either, so signing in from one would bounce straight back to the form"
1207    ))
1208}
1209
1210/// Defends the local dashboard against DNS-rebinding and cross-site requests: the `Host` header
1211/// must name a loopback host, and a request that changes something must either come from this
1212/// origin or carry the session's CSRF token (`arrival_refusal` explains the three ways through).
1213/// All responses also get headers that stop framing, sniffing and external loads.
1214pub async fn guard_local_origin(State(st): State<Shared>, req: Request, next: Next) -> Response {
1215    // Copied out before the request is handed on: the decision is made from these values and
1216    // nothing borrows `req` across the await.
1217    let method = req.method().clone();
1218    let path = req.uri().path().to_string();
1219    let host = header_text(&req, "host");
1220    let origin = header_text(&req, "origin");
1221    let csrf = header_text(&req, CSRF_HEADER);
1222    let session = cookie_value(req.headers(), SESSION_COOKIE).map(str::to_string);
1223    let refusal = arrival_refusal(
1224        &st.logins,
1225        &method,
1226        &path,
1227        host.as_deref(),
1228        origin.as_deref(),
1229        csrf.as_deref(),
1230        session.as_deref(),
1231    );
1232    let mut resp = match refusal {
1233        None => next.run(req).await,
1234        Some(why) => (StatusCode::FORBIDDEN, format!("forbidden: {why}")).into_response(),
1235    };
1236    let h = resp.headers_mut();
1237    h.insert(
1238        header::CONTENT_SECURITY_POLICY,
1239        HeaderValue::from_static(
1240            // `img-src 'self' data:` is the header's mark, the tab's icon, and the pictures a
1241            // message carries — those are `data:` URLs, because the page is the only thing that
1242            // read the bytes (`#365`: without `data:` here the browser refused every one of them
1243            // and a reopened session showed a broken-image box where its screenshot was). A `data:`
1244            // image cannot execute script, and `script-src` is untouched: still no remote host, so
1245            // a transcript that renders a URL cannot phone home.
1246            "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; \
1247             img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'self'; \
1248             frame-ancestors 'none'",
1249        ),
1250    );
1251    h.insert(
1252        header::X_CONTENT_TYPE_OPTIONS,
1253        HeaderValue::from_static("nosniff"),
1254    );
1255    h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
1256    h.insert(
1257        header::REFERRER_POLICY,
1258        HeaderValue::from_static("no-referrer"),
1259    );
1260    resp
1261}
1262
1263/// Run a blocking call somewhere that is not a tokio worker.
1264///
1265/// The session store is rusqlite behind a mutex, `/healthz` parses a JSON file, and the settings
1266/// write reads, rewrites and re-parses the config — all synchronous, all waiting on a disk. On a
1267/// worker they head-of-line-block every other request, including the unauthenticated `/healthz` a
1268/// supervisor polls, so they go to the blocking pool instead. A panicking closure comes back as
1269/// `None`: the answer to "the work did not finish" is a 500, not a dropped connection.
1270async fn blocking<T, F>(work: F) -> Option<T>
1271where
1272    F: FnOnce() -> T + Send + 'static,
1273    T: Send + 'static,
1274{
1275    tokio::task::spawn_blocking(work).await.ok()
1276}
1277
1278fn escape_html(s: &str) -> String {
1279    s.replace('&', "&amp;")
1280        .replace('<', "&lt;")
1281        .replace('>', "&gt;")
1282        .replace('"', "&quot;")
1283        .replace('\'', "&#39;")
1284}
1285
1286/// The page's palette, as custom properties, built from the one table in `eclipse_core::palette` —
1287/// the same triples the full-screen interface converts into terminal colours. A hex literal in the
1288/// page would be a second definition of the brand, and a second definition is how the terminal and
1289/// the dashboard ended up in two different colours.
1290fn palette_css() -> String {
1291    use eclipse_core::palette as p;
1292    let rgb = |c: (u8, u8, u8)| format!("rgb({}, {}, {})", c.0, c.1, c.2);
1293    format!(
1294        ":root {{ color-scheme: dark; \
1295         --bg:{}; --panel:{}; --line:{}; --hover:{}; \
1296         --fg:{}; --dim:{}; --faint:{}; --rule:{}; \
1297         --accent:{}; --user:{}; --ok:{}; --warn:{}; --bad:{}; --ink:{}; }}",
1298        rgb(p::BG),
1299        rgb(p::PANEL),
1300        rgb(p::LINE),
1301        rgb(p::HOVER),
1302        rgb(p::FG),
1303        rgb(p::MUTED),
1304        // `--faint` had been asked for four times by `index.html` and emitted never (#269). The
1305        // declaration it appeared in was invalid at computed-value time, so the property inherited
1306        // and every element meant to be recessive rendered at full strength.
1307        rgb(p::FAINT),
1308        rgb(p::RULE),
1309        rgb(p::ACCENT),
1310        rgb(p::USER),
1311        rgb(p::OK),
1312        rgb(p::WARN),
1313        rgb(p::BAD),
1314        rgb(p::INK),
1315    )
1316}
1317
1318async fn index(State(st): State<Shared>, headers: HeaderMap) -> Html<String> {
1319    // The page echoes this in `X-Eclipse-CSRF` on anything that changes something, so a request
1320    // that a browser will not attribute to this origin can still prove which page made it.
1321    let csrf = cookie_value(&headers, SESSION_COOKIE)
1322        .and_then(|id| st.logins.csrf_for(id))
1323        .unwrap_or_default();
1324    let store = st.store.clone();
1325    // `list()` on purpose: the page opens with the list a person reads, and the `show archived`
1326    // filter asks the server for the rest (`#240`).
1327    let sessions = blocking(move || store.list().unwrap_or_default())
1328        .await
1329        .unwrap_or_default()
1330        .into_iter()
1331        .map(|s| {
1332            // `data-updated` is what the page groups by: Today, Yesterday, and so on are the
1333            // reader's own midnight, so the bucket is decided there and the server only says when.
1334            //
1335            // `data-cost` is the last turn's numbers, escaped for an attribute: the first click
1336            // after a reload must paint the row before the list has been re-fetched (#344).
1337            let cost = s
1338                .cost
1339                .as_ref()
1340                .and_then(|c| serde_json::to_string(c).ok())
1341                .map(|json| escape_html(&json))
1342                .unwrap_or_default();
1343            format!(
1344                "<li class=\"session\" data-id=\"{}\" data-updated=\"{}\" data-pinned=\"{}\" data-archived=\"{}\" data-cost=\"{}\"><div class=\"name\">{}{}</div></li>",
1345                escape_html(&s.id),
1346                s.updated_ms,
1347                if s.pinned { "1" } else { "0" },
1348                if s.archived { "1" } else { "0" },
1349                cost,
1350                if s.pinned { "\u{2605} " } else { "" },
1351                escape_html(&s.tagged_label())
1352            )
1353        })
1354        .collect::<String>();
1355    let status = st.config_error.as_deref().unwrap_or("");
1356    // `#340`: read per page, not cached at startup — the word on the row must be the mode in
1357    // force now, and a config edit is exactly the kind of thing a reload is for.
1358    let judged = st
1359        .reload_config()
1360        .map(|c| c.cli.approval == eclipse_core::config::Approval::Smart)
1361        .unwrap_or(false);
1362    let model = st.current_model();
1363    let model = model.as_deref().unwrap_or("(not configured)");
1364    // The effort in force is a fact about the process rather than about a turn, so it is rendered
1365    // into the page and survives a reload (`#264`).
1366    //
1367    // The context row is the other way round (`#344`): a window is a fact about *a model*, and the
1368    // model at serve time need not be the one that ran or the one about to. It used to be baked in
1369    // here as `ctx --/328K ░░░░░░░░│░`, which is how the same session could show 262K while it ran
1370    // and 328K the moment you navigated. The row now arrives from the store (a session's recorded
1371    // turn) or from a live `stats` event, and shows `ctx --` when neither exists — because nothing
1372    // has been measured yet.
1373    let (effort, effort_detail, effort_session) = match st.agent.as_deref() {
1374        Some(agent) => {
1375            let report = agent.reasoning_report();
1376            let sentence = report.sentence();
1377            (report.label, sentence, report.session)
1378        }
1379        None => (
1380            eclipse_core::reasoning::NOT_SENT.to_string(),
1381            "no provider is configured: there is no effort to be in force".to_string(),
1382            false,
1383        ),
1384    };
1385    // `#171`: the Flares tab, kept out of the page the same way the Bots tab is — by the server,
1386    // not by a CSS rule someone has to remember. One row and `LIMIT 1`, because the page never
1387    // needs the count (the pane's own listing says it) and a dashboard with no flares must cost a
1388    // person nothing for the feature.
1389    let probe = st.store.clone();
1390    let has_flares = matches!(
1391        blocking(move || probe.flare_runs(1)).await,
1392        Some(Ok(runs)) if !runs.is_empty()
1393    );
1394    Html(
1395        INDEX_HTML
1396            .replace("{{PALETTE}}", &palette_css())
1397            .replace("{{CSRF}}", &escape_html(&csrf))
1398            .replace("{{MODEL}}", &escape_html(model))
1399            // `#344`: there is no `{{CTX}}` any more. The row is painted from a session's recorded
1400            // turn or from a live one, never from a window frozen into the HTML when the page was
1401            // served — that string was a fact about the model at serve time, printed as though it
1402            // were the one about to run.
1403            .replace("{{EFFORT}}", &escape_html(&effort))
1404            .replace("{{EFFORT_DETAIL}}", &escape_html(&effort_detail))
1405            .replace(
1406                "{{EFFORT_CLASS}}",
1407                if effort_session { "session" } else { "" },
1408            )
1409            // `#285`: the switch is the server's, so a reload shows the truth rather than
1410            // forgetting a mode that is still in force. `hidden` is the off state.
1411            .replace("{{YOLO_ATTR}}", if st.yolo.on() { "" } else { "hidden" })
1412            .replace(
1413                "{{YOLO_DETAIL}}",
1414                &escape_html(&eclipse_core::yolo::announce(st.yolo.on())),
1415            )
1416            // `#340`: `[cli] approval = "smart"` — a mode in which the aux route settles some
1417            // calls without a card. Same rule as `/yolo` (#285): a mode that decides without
1418            // asking is on the row, in the alert colour, before the first call it decides.
1419            .replace("{{JUDGE_ATTR}}", if judged { "" } else { "hidden" })
1420            .replace("{{VERSION}}", env!("CARGO_PKG_VERSION"))
1421            // The composer's "is this paste big" threshold is `eclipse_core::paste`'s, not a
1422            // number typed into the page: the terminal and the dashboard follow one rule (#220).
1423            .replace(
1424                "{{PASTE_LIMIT}}",
1425                &eclipse_core::paste::PASTE_INLINE_LIMIT.to_string(),
1426            )
1427            .replace("{{STATUS}}", &escape_html(status))
1428            .replace("{{SESSIONS}}", &sessions)
1429            // `#509`: empty for a config with no bots, which is the whole of "the Sessions tab is
1430            // unchanged for someone who has none". The count is the declaration's, not the store's:
1431            // a bot that has never spoken is still a bot the sidebar should offer.
1432            .replace(
1433                "{{BOTS_BUTTON}}",
1434                &if st.bots.is_empty() {
1435                    String::new()
1436                } else {
1437                    format!(
1438                        "  <button id=\"bots\" type=\"button\" aria-expanded=\"false\" \
1439title=\"the bots this config declared — open one and talk to it in its own conversation\">bots ({})</button>",
1440                        st.bots.declared().count()
1441                    )
1442                },
1443            )
1444            .replace(
1445                "{{BOTS_PANE}}",
1446                if st.bots.is_empty() { "" } else { BOTS_PANE },
1447            )
1448            // `#171`: the same rule, from the store rather than from the config — a run exists or
1449            // it does not, and a person who has never fanned one out gets no button and no pane.
1450            .replace(
1451                "{{FLARES_BUTTON}}",
1452                &if has_flares {
1453                    "  <button id=\"flares\" type=\"button\" aria-expanded=\"false\" \
1454title=\"the flare runs this install has started — one task split across N read-only agents\">flares</button>"
1455                        .to_string()
1456                } else {
1457                    String::new()
1458                },
1459            )
1460            .replace(
1461                "{{FLARES_PANE}}",
1462                if has_flares { FLARES_PANE } else { "" },
1463            ),
1464    )
1465}
1466
1467/// `GET /logo.svg` — the mark, in the palette's colours.
1468async fn logo() -> impl IntoResponse {
1469    (
1470        [
1471            ("content-type", "image/svg+xml; charset=utf-8"),
1472            ("cache-control", "public, max-age=3600"),
1473        ],
1474        mark_svg(),
1475    )
1476}
1477
1478/// `GET /favicon.ico` — the committed multi-size icon.
1479async fn favicon() -> impl IntoResponse {
1480    (
1481        [
1482            ("content-type", "image/x-icon"),
1483            ("cache-control", "public, max-age=3600"),
1484        ],
1485        FAVICON_ICO,
1486    )
1487}
1488
1489/// `GET /healthz` — up, or a full report to the person who is signed in.
1490///
1491/// The route is unauthenticated because a health probe has no cookie and a dead dashboard still has
1492/// to say it is dead. It used to answer the whole report to anyone: the version, whether a provider
1493/// is configured, when the model was last reachable, and the *names of failing cron jobs* — which
1494/// are a description of what the machine is doing and, for a job named after the thing it backs up,
1495/// of what it holds (`#425`). Now the public answer is the one word a probe needs, and the detail
1496/// is behind the cookie the dashboard already has.
1497async fn health(
1498    State(st): State<Shared>,
1499    headers: axum::http::HeaderMap,
1500) -> Json<serde_json::Value> {
1501    if !is_logged_in(&st, &headers) {
1502        return Json(json!({"status": "ok"}));
1503    }
1504    let model_probe = (*st.model_probe.lock().unwrap_or_else(|e| e.into_inner()))
1505        .map(|(when, ok)| json!({"reachable": ok, "at_secs_ago": when.elapsed().as_secs()}));
1506    let cron_root = st.cron_root.clone();
1507    let cron = match blocking(move || {
1508        cron_root.and_then(|root| eclipse_core::cron::load_state(&root).ok())
1509    })
1510    .await
1511    .flatten()
1512    {
1513        Some(state) => {
1514            let failed: Vec<&str> = state
1515                .jobs
1516                .iter()
1517                .filter(|(_, j)| j.last_outcome.as_deref() == Some("failed"))
1518                .map(|(name, _)| name.as_str())
1519                .collect();
1520            let last_tick = state.jobs.values().filter_map(|j| j.last_started_ms).max();
1521            Some(json!({
1522                "failed_jobs": failed,
1523                "last_tick_ms": last_tick,
1524            }))
1525        }
1526        None => None,
1527    };
1528    Json(json!({
1529        "status": "ok",
1530        "version": env!("CARGO_PKG_VERSION"),
1531        "configured": st.agent.is_some(),
1532        "model_reachable": model_probe,
1533        "cron": cron,
1534    }))
1535}
1536
1537/// `GET /api/update` — what the install has and what the newest answer is, compared on the same
1538/// rule the CLI uses. Read-only by design: a badge is not an upgrade button, and the network
1539/// check belongs to the gateway's schedule rather than to a page load (three open tabs would
1540/// otherwise ask GitHub three times).
1541async fn update_state(State(st): State<Shared>) -> Json<eclipse_core::update::Snapshot> {
1542    let Some(watch) = st.update.clone() else {
1543        return Json(eclipse_core::update::Snapshot::default());
1544    };
1545    let now = eclipse_core::session::now_ms() / 1000;
1546    match blocking(move || watch.snapshot(now)).await {
1547        Some(snapshot) => Json(snapshot),
1548        None => Json(eclipse_core::update::Snapshot::default()),
1549    }
1550}
1551
1552/// `GET /api/sessions` — the sidebar's list, and the same one `sessions list` prints.
1553///
1554/// `?archived=1` adds the filed-away rows, marked, which is the `--archived` flag on the command
1555/// line: one store call either way, so the page cannot order the rows differently (`#240`).
1556async fn list_sessions(State(st): State<Shared>, Query(list): Query<ListQuery>) -> Response {
1557    let store = st.store.clone();
1558    let all = list.archived.unwrap_or(0) != 0;
1559    let Some(listed) = blocking(move || {
1560        if all {
1561            store.list_with_archived()
1562        } else {
1563            store.list()
1564        }
1565    })
1566    .await
1567    else {
1568        return error(
1569            StatusCode::INTERNAL_SERVER_ERROR,
1570            "the store did not answer",
1571        )
1572        .into_response();
1573    };
1574    match listed {
1575        Ok(list) => Json(
1576            list.into_iter()
1577                .map(|s| {
1578                    json!({
1579                        "id": s.id, "messages": s.messages, "updated_ms": s.updated_ms,
1580                        "preview": s.preview, "title": s.title, "pinned": s.pinned,
1581                        "archived": s.archived,
1582                        // `#344`: what the last turn cost, so the row the reader clicks already
1583                        // knows it. Null for a session that has never finished a turn, which the
1584                        // page draws as `--` rather than as a zero.
1585                        "cost": s.cost,
1586                        "subagent": s.subagent().map(|o| json!({"parent": o.parent, "route": o.route})),
1587                    })
1588                })
1589                .collect::<Vec<_>>(),
1590        )
1591        .into_response(),
1592        Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
1593    }
1594}
1595
1596/// The sidebar's own query string: `archived=1` is the filter, absent is the list.
1597#[derive(Deserialize)]
1598struct ListQuery {
1599    archived: Option<u8>,
1600}
1601
1602/// `GET /api/bots` — the Bots tab (`#509`).
1603///
1604/// One row per declared identity: where it lives (its lane), when it last spoke, how much it says
1605/// it has said. The conversation data comes from the same listing the sidebar reads — `list_bots`
1606/// is a grouping over it, not a second query — so the two cannot disagree about which session is
1607/// the bot's newest or when it changed.
1608async fn list_bots(State(st): State<Shared>) -> Response {
1609    let store = st.store.clone();
1610    let conversations = match blocking(move || store.list_bots()).await {
1611        Some(Ok(list)) => list,
1612        Some(Err(e)) => {
1613            return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
1614        }
1615        None => {
1616            return error(
1617                StatusCode::INTERNAL_SERVER_ERROR,
1618                "the store did not answer",
1619            )
1620            .into_response()
1621        }
1622    };
1623    let rows: Vec<serde_json::Value> = st
1624        .bots
1625        .declared()
1626        .map(|(name, bot)| {
1627            let live = conversations.iter().find(|c| c.name == name);
1628            // A declared bot whose agent did not build is still a row: the declaration is real,
1629            // and the reason it cannot answer is the one thing the tab has to say. Silence here
1630            // would read as a bot that works and never speaks.
1631            let problem = match st.bots.agent(name) {
1632                Some(Err(why)) => serde_json::Value::String(why.clone()),
1633                _ => serde_json::Value::Null,
1634            };
1635            json!({
1636                "name": name,
1637                "lane": bot.adapter.clone().unwrap_or_else(|| "web".to_string()),
1638                "sessions": live.map(|c| c.sessions).unwrap_or(0),
1639                "messages": live.map(|c| c.messages).unwrap_or(0),
1640                "last_session": live.map(|c| c.last_session.clone()),
1641                "last_activity_ms": live.map(|c| c.last_activity_ms).unwrap_or(0),
1642                "archived": live.map(|c| c.archived).unwrap_or(false),
1643                "problem": problem,
1644            })
1645        })
1646        .collect();
1647    Json(rows).into_response()
1648}
1649
1650/// `POST /api/bots/<name>/open` — the bot's conversation, created on the first open (`#509`).
1651///
1652/// The id returned is the session the page then loads and sends into; the send path needs no
1653/// second field, because the row's own `origin` is what makes the turn run on that bot's agent.
1654async fn open_bot(State(st): State<Shared>, Path(name): Path<String>) -> Response {
1655    if !st.bots.declares(&name) {
1656        return error(
1657            StatusCode::NOT_FOUND,
1658            format!("no bot `{name}` is declared"),
1659        )
1660        .into_response();
1661    }
1662    if let Some(Err(why)) = st.bots.agent(&name) {
1663        return error(
1664            StatusCode::SERVICE_UNAVAILABLE,
1665            format!("bot `{name}` cannot run: {why}"),
1666        )
1667        .into_response();
1668    }
1669    let store = st.store.clone();
1670    let wanted = name.clone();
1671    let opened = blocking(move || store.bot_session(&wanted)).await;
1672    match opened {
1673        Some(Ok(session_id)) => {
1674            Json(json!({ "name": name, "session_id": session_id })).into_response()
1675        }
1676        Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
1677        None => error(
1678            StatusCode::INTERNAL_SERVER_ERROR,
1679            "the store did not answer",
1680        )
1681        .into_response(),
1682    }
1683}
1684
1685/// `POST /api/bots/<name>/rename` — name the bot's live conversation.
1686///
1687/// It is the session's own `rename`, with a `TitleSource::User` that no later naming call may take
1688/// back. The bot's *identity* is its key in `[bots]` and is not renamed from a page: a name the
1689/// config did not choose is a bot nothing addresses.
1690async fn rename_bot(
1691    State(st): State<Shared>,
1692    Path(name): Path<String>,
1693    Json(body): Json<RenameBody>,
1694) -> Response {
1695    if !st.bots.declares(&name) {
1696        return error(
1697            StatusCode::NOT_FOUND,
1698            format!("no bot `{name}` is declared"),
1699        )
1700        .into_response();
1701    }
1702    let title = body.title.trim().to_string();
1703    if title.is_empty() {
1704        return error(StatusCode::BAD_REQUEST, "title is empty").into_response();
1705    }
1706    let store = st.store.clone();
1707    let wanted = name.clone();
1708    let named = title.clone();
1709    let renamed = blocking(move || {
1710        let id = store.bot_session(&wanted)?;
1711        store.set_title(&id, &named, eclipse_core::session::TitleSource::User)
1712    })
1713    .await;
1714    match renamed {
1715        Some(Ok(_)) => Json(json!({ "name": name, "title": title })).into_response(),
1716        Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
1717        None => error(
1718            StatusCode::INTERNAL_SERVER_ERROR,
1719            "the store did not answer",
1720        )
1721        .into_response(),
1722    }
1723}
1724
1725/// `POST /api/bots/<name>/clear` — file the bot's conversation away and open a fresh one.
1726///
1727/// Archived rather than deleted, the same rule a session's own archive follows (`#240`): the
1728/// transcript stays in the archive and in a search that asks for bots, and the tab's count still
1729/// says how many conversations there have been. The bot keeps its identity — only the words go.
1730async fn clear_bot(State(st): State<Shared>, Path(name): Path<String>) -> Response {
1731    if !st.bots.declares(&name) {
1732        return error(
1733            StatusCode::NOT_FOUND,
1734            format!("no bot `{name}` is declared"),
1735        )
1736        .into_response();
1737    }
1738    let store = st.store.clone();
1739    let wanted = name.clone();
1740    let cleared = blocking(move || {
1741        let mut filed = 0usize;
1742        for id in store.bot_sessions(&wanted)? {
1743            store.set_archived(&id, true)?;
1744            filed += 1;
1745        }
1746        let fresh = store.bot_session(&wanted)?;
1747        Ok::<_, eclipse_core::Error>((filed, fresh))
1748    })
1749    .await;
1750    match cleared {
1751        Some(Ok((filed, session_id))) => {
1752            Json(json!({ "name": name, "archived": filed, "session_id": session_id }))
1753                .into_response()
1754        }
1755        Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
1756        None => error(
1757            StatusCode::INTERNAL_SERVER_ERROR,
1758            "the store did not answer",
1759        )
1760        .into_response(),
1761    }
1762}
1763
1764/// `GET /api/bots/<name>/prompt` — what makes this bot itself, as the file says it now (`#509`).
1765///
1766/// The instructions are re-read from disk rather than remembered from startup: a page that shows
1767/// the prompt the process was built with would be showing history the moment someone edits the
1768/// file, and this pane exists to answer "who is this bot" as it is.
1769async fn bot_prompt(State(st): State<Shared>, Path(name): Path<String>) -> Response {
1770    let Some((bot, ..)) = st
1771        .bots
1772        .declared()
1773        .find(|(declared, _)| *declared == name)
1774        .map(|(n, b)| (b.clone(), n))
1775    else {
1776        return error(
1777            StatusCode::NOT_FOUND,
1778            format!("no bot `{name}` is declared"),
1779        )
1780        .into_response();
1781    };
1782    let env: eclipse_core::config::EnvFn = &eclipse_core::config::process_env;
1783    let read = bot
1784        .instructions
1785        .as_deref()
1786        .filter(|p| !p.trim().is_empty())
1787        .map(|declared| {
1788            let Some(path) = st
1789                .reload_config()
1790                .ok()
1791                .and_then(|cfg| cfg.bot_file(env, declared))
1792            else {
1793                return (
1794                    None,
1795                    format!("cannot resolve `instructions = {declared:?}`"),
1796                );
1797            };
1798            match std::fs::read_to_string(&path) {
1799                Ok(text) => (Some((path, text)), String::new()),
1800                Err(e) => (None, format!("cannot read {}: {e}", path.display())),
1801            }
1802        });
1803    let (instructions, why) = match read {
1804        Some((Some((path, text)), _)) => (
1805            json!({ "path": path.display().to_string(), "body": text }),
1806            String::new(),
1807        ),
1808        Some((None, why)) => (serde_json::Value::Null, why),
1809        None => (serde_json::Value::Null, String::new()),
1810    };
1811    let memory = st
1812        .reload_config()
1813        .ok()
1814        .and_then(|cfg| cfg.bot_memory(env, &name, &bot))
1815        .map(|p| p.display().to_string());
1816    Json(json!({
1817        "name": name,
1818        "instructions": instructions,
1819        "skills": bot.skills,
1820        "memory": memory,
1821        "adapter": bot.adapter,
1822        "problem": match st.bots.agent(&name) { Some(Err(why)) => json!(why), _ => serde_json::Value::Null },
1823        "why": why,
1824    }))
1825    .into_response()
1826}
1827
1828// ---------------------------------------------------------------------------------------------
1829// Flares: the run ledger, read by the tab (`#171`)
1830// ---------------------------------------------------------------------------------------------
1831
1832/// One run, as `GET /api/flares` and `GET /api/flares/<run>` hand it over.
1833///
1834/// The keys carry the store's own names. Two are decided here and only here: `running` spells out
1835/// `!finished()`, so the page never has to derive a state word from a timestamp, and a token count
1836/// the run never reported stays `null` rather than becoming `0` — the page prints `?` for it, the
1837/// same thing `count_tokens` prints on the command line. A zero here would read as "it was free".
1838fn flare_json(run: &FlareRunRow) -> serde_json::Value {
1839    json!({
1840        "id": run.id,
1841        "task": run.task,
1842        "state": run.state,
1843        "routes": run.routes,
1844        "jobs": run.jobs,
1845        "parent": run.parent,
1846        "started_ms": run.started_ms,
1847        "finished_ms": run.finished_ms,
1848        "prompt_tokens": run.prompt_tokens,
1849        "completion_tokens": run.completion_tokens,
1850        "iterations": run.iterations,
1851        "running": !run.finished(),
1852    })
1853}
1854
1855/// One child of a run, as the pane's expansion draws it.
1856///
1857/// `session_id` is `null` for a **dropped** child: it never started, so it has no transcript to
1858/// open and no cost to show, and `why` is the line it ended with. The page prints that reason in
1859/// the row rather than leaving it blank — "never ran" and "ran for nothing" are different facts
1860/// and a blank says neither.
1861fn flare_job_json(job: &FlareJobRow) -> serde_json::Value {
1862    json!({
1863        "n": job.n,
1864        "route": job.route,
1865        "session_id": job.session_id,
1866        "state": job.state,
1867        "prompt_tokens": job.prompt_tokens,
1868        "completion_tokens": job.completion_tokens,
1869        "iterations": job.iterations,
1870        "why": job.why,
1871    })
1872}
1873
1874/// The list's own query string: how many runs back to go. The store clamps it to 1..=200, so a
1875/// wild number is a shorter list rather than an error.
1876#[derive(Deserialize)]
1877struct FlaresQuery {
1878    limit: Option<usize>,
1879}
1880
1881/// `GET /api/flares` — the Flares tab's listing (`#171`).
1882///
1883/// Newest first, from `flare_runs` — the same call `eclipse flares list` makes, so the pane and the
1884/// terminal cannot disagree about the order or about what a row says. A dashboard session that
1885/// started a run and a run started from a shell appear in the same list, because the ledger is the
1886/// store's and not the process's.
1887async fn list_flares(State(st): State<Shared>, Query(q): Query<FlaresQuery>) -> Response {
1888    let limit = q.limit.unwrap_or(50);
1889    let store = st.store.clone();
1890    match blocking(move || store.flare_runs(limit)).await {
1891        Some(Ok(runs)) => Json(
1892            runs.iter()
1893                .map(flare_json)
1894                .collect::<Vec<serde_json::Value>>(),
1895        )
1896        .into_response(),
1897        Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
1898        None => error(
1899            StatusCode::INTERNAL_SERVER_ERROR,
1900            "the store did not answer",
1901        )
1902        .into_response(),
1903    }
1904}
1905
1906/// `GET /api/flares/<run>` — one run and its children, in the order the lead asked for them.
1907///
1908/// The children come from `flare_run`, which reads `flare_jobs`: that is the ledger's own record of
1909/// how each child ended, so a run that was cancelled part-way lists fewer children than it planned
1910/// and says so with the ones it has. `flares_of` is deliberately not used here — it answers with
1911/// sessions, and a dropped child has none, which is exactly the row this pane must not lose.
1912async fn read_flare(State(st): State<Shared>, Path(run): Path<String>) -> Response {
1913    let store = st.store.clone();
1914    let wanted = run.clone();
1915    match blocking(move || store.flare_run(&wanted)).await {
1916        Some(Ok(Some((row, jobs)))) => {
1917            let jobs: Vec<serde_json::Value> = jobs.iter().map(flare_job_json).collect();
1918            Json(json!({ "run": flare_json(&row), "jobs": jobs })).into_response()
1919        }
1920        Some(Ok(None)) => {
1921            error(StatusCode::NOT_FOUND, format!("no flare run `{run}`")).into_response()
1922        }
1923        Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
1924        None => error(
1925            StatusCode::INTERNAL_SERVER_ERROR,
1926            "the store did not answer",
1927        )
1928        .into_response(),
1929    }
1930}
1931
1932/// `POST /api/flares/<run>/cancel` — the flag `eclipse flares cancel` sets (`#171`).
1933///
1934/// It asks rather than stops: the run checks between children, so a queued flare is dropped before
1935/// it starts and a running one ends at its next boundary. Saying that in the answer is the point —
1936/// a page that reported "cancelled" over a child that is still reading files would be lying about
1937/// what the flag does.
1938async fn cancel_flare(State(st): State<Shared>, Path(run): Path<String>) -> Response {
1939    let store = st.store.clone();
1940    let wanted = run.clone();
1941    match blocking(move || store.cancel_flare_run(&wanted)).await {
1942        Some(Ok(true)) => Json(json!({
1943            "run": run,
1944            "cancel_requested": true,
1945            "note": "cancel requested: queued flares are dropped, running ones stop at their next boundary",
1946        }))
1947        .into_response(),
1948        Some(Ok(false)) => {
1949            error(StatusCode::NOT_FOUND, format!("no flare run `{run}`")).into_response()
1950        }
1951        Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
1952        None => error(
1953            StatusCode::INTERNAL_SERVER_ERROR,
1954            "the store did not answer",
1955        )
1956        .into_response(),
1957    }
1958}
1959
1960/// `GET /api/search?q=term&limit=N` — the sidebar's find box.
1961///
1962/// [`eclipse_core::session::SessionStore::search`] answers per *message*, because that is what the
1963/// index holds; the sidebar wants the session's name next to each snippet, so the titles come from
1964/// one `list()` call and are joined here rather than by a query per hit. An empty query returns
1965/// nothing at all: a find box that answers "everything" on every keystroke is unusable.
1966async fn search_sessions(State(st): State<Shared>, Query(find): Query<Find>) -> Response {
1967    let term = find.q.unwrap_or_default();
1968    let term = term.trim();
1969    if term.is_empty() {
1970        return Json(Vec::<serde_json::Value>::new()).into_response();
1971    }
1972    let limit = find.limit.unwrap_or(20).clamp(1, 100);
1973    let store = st.store.clone();
1974    let term = term.to_string();
1975    let Some(found) = blocking(move || {
1976        let hits = store.search(&term, limit);
1977        // The titles come from one listing rather than a query per hit; inside the same closure,
1978        // so the two cannot straddle a write and disagree about which sessions exist.
1979        let named: HashMap<String, (Option<String>, u64)> = store
1980            .list()
1981            .map(|list| {
1982                list.into_iter()
1983                    .map(|s| (s.id, (s.title, s.updated_ms)))
1984                    .collect()
1985            })
1986            .unwrap_or_default();
1987        (hits, named)
1988    })
1989    .await
1990    else {
1991        return error(
1992            StatusCode::INTERNAL_SERVER_ERROR,
1993            "the store did not answer",
1994        )
1995        .into_response();
1996    };
1997    let (hits, named) = found;
1998    let hits = match hits {
1999        Ok(hits) => hits,
2000        Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2001    };
2002    Json(
2003        hits.into_iter()
2004            .map(|h| {
2005                let (title, updated_ms) = named.get(&h.session_id).cloned().unwrap_or((None, 0));
2006                json!({
2007                    "session_id": h.session_id,
2008                    "seq": h.seq,
2009                    "at_ms": h.at_ms,
2010                    "role": h.role,
2011                    "snippet": h.snippet,
2012                    "title": title,
2013                    "updated_ms": updated_ms,
2014                })
2015            })
2016            .collect::<Vec<_>>(),
2017    )
2018    .into_response()
2019}
2020
2021/// `GET /api/models` — what the endpoint says it serves, for the header's picker.
2022///
2023/// The list comes from the provider (`GET <base_url>/models`), not from a config file, because a
2024/// name the endpoint does not serve cannot be asked for. `model` is what the next turn would use
2025/// (a runtime choice included) and `configured` what the file names, so the page can offer "back
2026/// to the configured one" only when the two differ.
2027///
2028/// An endpoint that answers with nothing usable gives an empty list; one that cannot be reached
2029/// gives 502 with the reason, because "no models" and "wrong address" are different problems and
2030/// the picker has to say which happened.
2031/// `GET /api/commands` — the composer's `/` menu, as a render of the table (`#282`).
2032///
2033/// The page owns no names: this route and the server's parse read the same `COMMANDS`, so a row the
2034/// menu offers is a row `chat()` will run, and a verb this surface does not have cannot appear in
2035/// it. `label` is what the row shows (`/set <key> <value>` — the table's own spelling), `name` is
2036/// what completing it puts in the line.
2037async fn list_commands() -> Json<serde_json::Value> {
2038    use eclipse_core::commands::{Args, Command, Front, COMMANDS};
2039    let row = |c: &Command| {
2040        json!({
2041            "name": c.name,
2042            "aliases": c.aliases,
2043            "label": c.label(),
2044            "args": match c.args {
2045                Args::Shown(args) => json!(args),
2046                Args::None | Args::Unshown => serde_json::Value::Null,
2047            },
2048            "takes_arg": c.args.takes(),
2049            "help": c.help,
2050        })
2051    };
2052    Json(json!({
2053        "commands": COMMANDS
2054            .iter()
2055            .filter(|c| c.serves(Front::Web))
2056            .map(row)
2057            .collect::<Vec<_>>(),
2058    }))
2059}
2060
2061async fn list_models(State(st): State<Shared>) -> Response {
2062    let Some(agent) = st.agent.clone() else {
2063        return error(StatusCode::SERVICE_UNAVAILABLE, unconfigured(&st)).into_response();
2064    };
2065    match agent.list_models().await {
2066        Ok(models) => Json(json!({
2067            "model": st.current_model(),
2068            "configured": st.configured_model(),
2069            "models": models,
2070        }))
2071        .into_response(),
2072        Err(e) => error(StatusCode::BAD_GATEWAY, e.to_string()).into_response(),
2073    }
2074}
2075
2076#[derive(Deserialize)]
2077struct ModelChoice {
2078    /// The model the next turn should use. `null` goes back to the configured one; leaving the
2079    /// field out at all is a 400, so a malformed body cannot silently reset a choice.
2080    ///
2081    /// A plain `Option<String>` cannot tell those two apart — serde reads a null as "absent" —
2082    /// so the field is a double option and `some_option` keeps the null that arrived.
2083    #[serde(default, deserialize_with = "some_option")]
2084    model: Option<Option<String>>,
2085}
2086
2087/// `Option<String>` in, `Some(Option<String>)` out: a null that is present becomes `Some(None)`,
2088/// and the `default` above supplies the bare `None` for a field that never arrived.
2089fn some_option<'de, D>(d: D) -> Result<Option<Option<String>>, D::Error>
2090where
2091    D: serde::Deserializer<'de>,
2092{
2093    Option::<String>::deserialize(d).map(Some)
2094}
2095
2096/// `GET /api/settings` — every key this build reads, its value, and whether it is the default.
2097///
2098/// Read from the file on each request, not from a copy taken at startup: the point of the page is
2099/// to change the file, and a page that shows yesterday's answer to that is worse than none.
2100async fn list_settings(State(st): State<Shared>) -> Response {
2101    match st.reload_config() {
2102        Ok(cfg) => Json(json!({
2103            "profile": cfg.profile_name(),
2104            "settings": cfg.settings().iter().map(setting_json).collect::<Vec<_>>(),
2105        }))
2106        .into_response(),
2107        Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
2108    }
2109}
2110
2111/// A setting as the page may see it: a secret's value is never in the answer, only whether it is
2112/// set. Everything else is the TOML rendering a person would type.
2113/// One row of the settings window (`#267`): what the key is, what it holds, what it would fall back
2114/// to, and enough of its type for the page to draw the right control — from the catalogue, never
2115/// from a list written in the page.
2116fn setting_json(s: &eclipse_core::config::Setting) -> serde_json::Value {
2117    json!({
2118        "key": s.path(),
2119        "section": s.section,
2120        "value": if s.secret { serde_json::Value::Null } else { json!(s.rendered()) },
2121        "default": s.default.as_ref().map(std::string::ToString::to_string),
2122        "is_default": s.is_default(),
2123        "secret": s.secret,
2124        "set": s.value.is_some(),
2125        "applies": s.applies.as_str(),
2126        // The type, so a `Bool` is a toggle and an `Integer` is a number field rather than both
2127        // being a text box that happens to be right.
2128        "kind": s.kind.as_str(),
2129        // What it does, from `eclipse_core::config::about`.
2130        "about": s.about,
2131        // The values a closed set accepts; empty when the key takes what it takes.
2132        "choices": s.choices,
2133    })
2134}
2135
2136#[derive(Deserialize)]
2137struct SettingWrite {
2138    key: String,
2139    /// What the person typed, or `null` for "remove the key and let the default apply".
2140    ///
2141    /// A double option, for the reason `ModelChoice` is one: serde reads a null as "absent", so a
2142    /// plain `Option<String>` would quietly treat "reset this key" as "you forgot the value".
2143    /// Leaving the field out at all is a 400 — the same rule as `/api/model`.
2144    #[serde(default, deserialize_with = "some_option")]
2145    value: Option<Option<String>>,
2146}
2147
2148/// `POST /api/settings` `{"key": "provider.model", "value": "qwen"}` — one key, proved before it
2149/// is written, then read back from disk to answer with what the file now says.
2150async fn write_setting(State(st): State<Shared>, Json(body): Json<SettingWrite>) -> Response {
2151    let Some(value) = body.value else {
2152        return error(
2153            StatusCode::BAD_REQUEST,
2154            "name a value: {\"value\": \"text\"} to set it, or {\"value\": null} to go back to the \
2155             default",
2156        )
2157        .into_response();
2158    };
2159    match apply_setting(&st, &body.key, value.as_deref()).await {
2160        Ok(setting) => Json(setting).into_response(),
2161        Err((code, why)) => error(code, why).into_response(),
2162    }
2163}
2164
2165/// Write one key — the body of `POST /api/settings`, and what `/set <key> <value>` in the composer
2166/// runs (`#254`). Reads, rewrites and re-parses the file, so the answer is what the file now says
2167/// rather than what was asked for; the next run loads the file.
2168///
2169/// All four trips to disk are on the blocking pool, or every other request waits behind this one.
2170pub(crate) async fn apply_setting(
2171    st: &AppState,
2172    key: &str,
2173    value: Option<&str>,
2174) -> Result<serde_json::Value, (StatusCode, String)> {
2175    let Some(path) = st.write_path() else {
2176        return Err((
2177            StatusCode::SERVICE_UNAVAILABLE,
2178            "this dashboard was started without a config file".to_string(),
2179        ));
2180    };
2181    // The base file, for the read-back: the loader reads base + overlay, so handing it the overlay
2182    // would overlay the same file twice and answer with something no run would load.
2183    let base = st.config_path.clone();
2184    let (key, value) = (key.to_string(), value.map(str::to_string));
2185    let edited_key = key.clone();
2186    // A free function rather than a clone of the state: the closure only needs the two fields
2187    // `reload_config` reads, and `AppState` is not `Clone` (it holds locks and a semaphore).
2188    let profile = st.profile.clone();
2189    // `#399`: one writer at a time. The whole read-edit-write is a single transaction over the file
2190    // — two of them overlapping means the second rewrites text it read before the first landed, and
2191    // one of the two settings is gone with no error anywhere.
2192    let writes = st.config_writes.clone();
2193    // Read, rewrite, re-parse: four trips to the same file, and the last one builds a whole config.
2194    // All of it on the blocking pool, or every other request waits behind this one.
2195    let written = blocking(
2196        move || -> Result<eclipse_core::config::Config, (StatusCode, String)> {
2197            let _one_writer = writes
2198                .lock()
2199                .unwrap_or_else(|poisoned| poisoned.into_inner());
2200            // An overlay is written into existence by the first write that uses it, so a file that
2201            // is not there yet is empty text rather than an error (`config set` reads it the same
2202            // way).
2203            let text = match std::fs::read_to_string(&path) {
2204                Ok(text) => text,
2205                Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
2206                Err(e) => {
2207                    return Err((
2208                        StatusCode::INTERNAL_SERVER_ERROR,
2209                        format!("{}: {e}", path.display()),
2210                    ))
2211                }
2212            };
2213            // `None` is `{"value": null}`: comment the line out, so the file reads what a default
2214            // file reads. `Some` is a value, read as TOML when it parses and as a string when it
2215            // does not — the rule `config set` follows, so the two cannot disagree.
2216            let edited = match &value {
2217                Some(raw) => {
2218                    let typed = eclipse_core::config::parse_value(raw);
2219                    eclipse_core::config::set_in_text(&text, &edited_key, &typed)
2220                }
2221                None => eclipse_core::config::unset_in_text(&text, &edited_key),
2222            }
2223            .map_err(|why| (StatusCode::BAD_REQUEST, why))?;
2224            if let Some(dir) = path.parent() {
2225                std::fs::create_dir_all(dir).map_err(|e| {
2226                    (
2227                        StatusCode::INTERNAL_SERVER_ERROR,
2228                        format!("{}: {e}", dir.display()),
2229                    )
2230                })?;
2231            }
2232            eclipse_core::config::save_config_text(&path, &edited)
2233                .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
2234            eclipse_core::config::Config::load_with_profile(
2235                base.as_deref(),
2236                profile.as_deref(),
2237                &eclipse_core::config::process_env,
2238            )
2239            .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
2240        },
2241    )
2242    .await;
2243    let Some(written) = written else {
2244        return Err((
2245            StatusCode::INTERNAL_SERVER_ERROR,
2246            "the write did not finish".to_string(),
2247        ));
2248    };
2249    match written {
2250        Ok(cfg) => match cfg.setting(&key) {
2251            Some(setting) => Ok(setting_json(&setting)),
2252            None => Err((
2253                StatusCode::INTERNAL_SERVER_ERROR,
2254                format!("`{key}` is not in the file it was just written to"),
2255            )),
2256        },
2257        Err((code, why)) => Err((code, why)),
2258    }
2259}
2260
2261/// One context file as the editor needs it (#268): where it is, what is in it, and what the prompt
2262/// will do with it.
2263fn context_json(
2264    e: &eclipse_core::context_files::Editable,
2265    home: Option<&std::path::Path>,
2266) -> serde_json::Value {
2267    json!({
2268        "name": e.which.id(),
2269        "file": e.file,
2270        "path": short_path(&e.path, home),
2271        "exists": e.exists,
2272        "chars": e.chars,
2273        "kept": e.kept,
2274        "truncated": e.truncated(),
2275        "max_chars": e.max_chars,
2276        "own_budget": e.own_budget,
2277        "total": e.total,
2278        "total_budget": e.total_budget,
2279        "position": e.position,
2280        "others": e.others,
2281        "kind": match e.which {
2282            eclipse_core::context_files::Which::Memory => "memory",
2283            _ => "prose",
2284        },
2285        "text": e.text,
2286    })
2287}
2288
2289/// `~`-shortened, the way `Status::workspace_short` spells the workspace, so the path a person reads
2290/// on the page is the path they would type in a terminal.
2291fn short_path(path: &std::path::Path, home: Option<&std::path::Path>) -> String {
2292    let shown = path.to_string_lossy().into_owned();
2293    match home {
2294        Some(home) => {
2295            let home = home.to_string_lossy();
2296            match shown.strip_prefix(home.as_ref()) {
2297                Some(rest) => format!("~{rest}"),
2298                None => shown,
2299            }
2300        }
2301        None => shown,
2302    }
2303}
2304
2305/// `GET /api/context` — the three files, with their paths, their sizes and their budgets.
2306async fn list_context(State(st): State<Shared>) -> Response {
2307    let cfg = match st.reload_config() {
2308        Ok(cfg) => cfg,
2309        Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
2310    };
2311    let home = cfg.home(&eclipse_core::config::process_env);
2312    let files = blocking(move || {
2313        eclipse_core::context_files::editable(&cfg, &eclipse_core::config::process_env)
2314    })
2315    .await;
2316    match files {
2317        Some(files) => Json(json!({
2318            "profile": st.profile.clone(),
2319            "files": files.iter().map(|e| context_json(e, home.as_deref())).collect::<Vec<_>>(),
2320        }))
2321        .into_response(),
2322        None => error(
2323            StatusCode::INTERNAL_SERVER_ERROR,
2324            "the context files took too long to read",
2325        )
2326        .into_response(),
2327    }
2328}
2329
2330#[derive(Deserialize)]
2331struct ContextWrite {
2332    /// One of `agent`, `user`, `memory` — an id from a closed set, never a path.
2333    name: String,
2334    text: String,
2335}
2336
2337/// `POST /api/context` `{"name": "user", "text": "…"}` — write one file and answer with the row the
2338/// file now stands as.
2339///
2340/// The name is looked up in the loader's own list, so an unknown name, a path, or a traversing
2341/// string is a 400 before anything touches the disk. `MEMORY.md` goes through `Memory`, which takes
2342/// its lock and refuses a body past its budget rather than clipping it silently; the two prose files
2343/// are written temp-then-rename. Nothing here can name a file the prompt would not read.
2344async fn write_context(State(st): State<Shared>, Json(body): Json<ContextWrite>) -> Response {
2345    let Some(which) = eclipse_core::context_files::Which::from_id(&body.name) else {
2346        return error(
2347            StatusCode::BAD_REQUEST,
2348            format!(
2349                "name one of the three context files: \"agent\", \"user\" or \"memory\" — not {:?}",
2350                body.name
2351            ),
2352        )
2353        .into_response();
2354    };
2355    let cfg = match st.reload_config() {
2356        Ok(cfg) => cfg,
2357        Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
2358    };
2359    let home = cfg.home(&eclipse_core::config::process_env);
2360    let text = body.text;
2361    let written = blocking(move || {
2362        eclipse_core::context_files::write_file(
2363            &cfg,
2364            &eclipse_core::config::process_env,
2365            which,
2366            &text,
2367        )
2368    })
2369    .await;
2370    match written {
2371        Some(Ok(row)) => Json(json!({
2372            "file": context_json(&row, home.as_deref()),
2373            // Said once, in the wording the settings window uses: a turn in flight keeps the prompt
2374            // it was built with.
2375            "applies": "the next run uses it",
2376        }))
2377        .into_response(),
2378        Some(Err(e)) => error(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
2379        // A panic in the writer must not be reported as a success.
2380        None => error(
2381            StatusCode::INTERNAL_SERVER_ERROR,
2382            "the write did not finish",
2383        )
2384        .into_response(),
2385    }
2386}
2387
2388/// `POST /api/model` `{"model": "name"}` picks the model for the next turn, `{"model": null}`
2389/// goes back to the configured one. Nothing is written to the config file, and a run already in
2390/// flight keeps the provider it started with — the same rule `/model` follows in the terminal.
2391async fn choose_model(State(st): State<Shared>, Json(choice): Json<ModelChoice>) -> Response {
2392    let Some(choice) = choice.model else {
2393        return error(
2394            StatusCode::BAD_REQUEST,
2395            "name a model: {\"model\": \"name\"}, or {\"model\": null} to go back to the configured one",
2396        )
2397        .into_response();
2398    };
2399    match apply_model(&st, choice).await {
2400        Ok(answer) => Json(answer).into_response(),
2401        Err((code, why)) => error(code, why).into_response(),
2402    }
2403}
2404
2405/// Pick the model for the next turn — the body of `POST /api/model`, and what `/model <name>` in
2406/// the composer runs (`#254`). One function so a click and a line cannot disagree.
2407///
2408/// `None` goes back to the configured model. The window is re-probed in the background because it
2409/// belongs to the model rather than to the process; a slow endpoint costs the pick nothing.
2410pub(crate) async fn apply_model(
2411    st: &AppState,
2412    picked: Option<String>,
2413) -> Result<serde_json::Value, (StatusCode, String)> {
2414    let Some(agent) = st.agent.clone() else {
2415        return Err((StatusCode::SERVICE_UNAVAILABLE, unconfigured(st)));
2416    };
2417    let picked = match picked {
2418        Some(name) => {
2419            let name = name.trim().to_string();
2420            if name.is_empty() {
2421                return Err((StatusCode::BAD_REQUEST, "model is empty".to_string()));
2422            }
2423            Some(name)
2424        }
2425        None => None,
2426    };
2427    match agent.set_model(picked) {
2428        Ok(()) => {
2429            // The window belongs to the model, not to the process: ask the endpoint again, in the
2430            // background and bounded, so the read-out's `ctx …/…` and the compaction rail follow
2431            // the pick — the re-probe `/model` does in the interface. A slow or dead endpoint
2432            // costs this click nothing, and a window nobody states stays unknown.
2433            let probe = agent.clone();
2434            tokio::spawn(async move {
2435                if let Some(window) = probe
2436                    .advertised_context_window(Duration::from_secs(2))
2437                    .await
2438                {
2439                    probe.set_advertised_window(window);
2440                }
2441            });
2442            Ok(json!({
2443                "model": st.current_model(),
2444                "configured": st.configured_model(),
2445            }))
2446        }
2447        Err(e) => Err((StatusCode::BAD_REQUEST, e.to_string())),
2448    }
2449}
2450
2451/// Why there is no agent, in the words the startup error used.
2452pub(crate) fn unconfigured(st: &AppState) -> String {
2453    st.config_error
2454        .clone()
2455        .unwrap_or_else(|| "agent is not configured".into())
2456}
2457
2458/// The reasoning dial as data, for the submenu and the strip (`#275`).
2459///
2460/// One shape for `GET` and for the answer to `POST`, so the page renders from the reply to the
2461/// click rather than from a guess about what the click did. Every field the page needs is here:
2462/// the level in force, where it came from, the words this route actually takes, and the policy's
2463/// own sentence for each of them — a row that says `xhigh → sends high` is quoting the backend,
2464/// not repeating the request.
2465fn reasoning_json(agent: &Agent) -> serde_json::Value {
2466    use eclipse_core::provider::Reasoning;
2467    let report = agent.reasoning_report();
2468    let control = agent.reasoning_control();
2469    let (levels, described, note): (Vec<String>, serde_json::Value, String) = match &control {
2470        Some(Reasoning::Policy(policy)) => {
2471            let levels = policy.vocabulary();
2472            let said: serde_json::Map<String, serde_json::Value> = levels
2473                .iter()
2474                .map(|level| (level.clone(), json!(policy.describe(Some(level)))))
2475                .collect();
2476            (levels, serde_json::Value::Object(said), String::new())
2477        }
2478        // The three ways a route has nothing to pick. Said in words, so the menu shows the
2479        // sentence instead of a list of levels the backend would refuse.
2480        Some(Reasoning::Off) => (
2481            Vec::new(),
2482            json!({}),
2483            "no reasoning control on this model".to_string(),
2484        ),
2485        Some(Reasoning::Undeclared) => (
2486            Vec::new(),
2487            json!({}),
2488            "this backend declares no reasoning control, so a level goes out verbatim and only \
2489             `/reasoning` in the terminal can set one"
2490                .to_string(),
2491        ),
2492        None => (
2493            Vec::new(),
2494            json!({}),
2495            "this dashboard has no provider configuration to describe".to_string(),
2496        ),
2497    };
2498    // The off switch, as a switch needs it (`#293`): the word that asks for thinking to stop, or
2499    // `null` and the reason this route has none. The word is `none` whatever shape the switch takes
2500    // — a level, a bool, a body fragment — because that is what the dial's `asks_off` recognises;
2501    // what actually goes on the wire is the policy's business, and this endpoint never spells it.
2502    let (off_word, off_why) = match &control {
2503        Some(Reasoning::Policy(policy)) if policy.has_off() => (json!("none"), String::new()),
2504        Some(Reasoning::Policy(policy)) => (
2505            json!(null),
2506            format!(
2507                "this route has no off switch: nothing at {} turns thinking off on it",
2508                policy.field
2509            ),
2510        ),
2511        Some(Reasoning::Off) => (
2512            json!(null),
2513            "this model has no reasoning field, so there is nothing to switch off".to_string(),
2514        ),
2515        Some(Reasoning::Undeclared) => (
2516            json!(null),
2517            "this backend declares no reasoning control, so a level goes out verbatim: \
2518             `/reasoning none` in the terminal is the only off"
2519                .to_string(),
2520        ),
2521        None => (
2522            json!(null),
2523            "this dashboard has no provider configuration, so there is nothing to switch"
2524                .to_string(),
2525        ),
2526    };
2527    json!({
2528        "off_word": off_word,
2529        "off_why": off_why,
2530        "effort": report.label,
2531        "effort_detail": report.sentence(),
2532        "effort_session": report.session,
2533        "effort_default": report.by_default,
2534        "in_force": report.in_force,
2535        "resolved": report.resolved,
2536        // What the file names, so the submenu can offer "back to the file" with the level it
2537        // would go back to. `null` when the file sets nothing.
2538        "configured": agent.reasoning().configured(),
2539        "levels": levels,
2540        "described": described,
2541        "note": note,
2542    })
2543}
2544
2545/// `GET /api/reasoning` — the dial and this route's vocabulary, without changing anything.
2546async fn read_reasoning(State(st): State<Shared>) -> Response {
2547    let Some(agent) = st.agent.clone() else {
2548        return error(StatusCode::SERVICE_UNAVAILABLE, unconfigured(&st)).into_response();
2549    };
2550    Json(reasoning_json(&agent)).into_response()
2551}
2552
2553#[derive(Deserialize)]
2554struct ReasoningChoice {
2555    /// The level the next turn should ask for. `null` goes back to the file; leaving the field out
2556    /// at all is a 400, so a malformed body cannot silently reset the dial — the same shape
2557    /// [`ModelChoice`] uses, for the same reason.
2558    #[serde(default, deserialize_with = "some_option")]
2559    level: Option<Option<String>>,
2560}
2561
2562/// `POST /api/reasoning` `{"level": "high"}` sets the level for this dashboard run,
2563/// `{"level": null}` puts the file back in charge.
2564///
2565/// `agent.reasoning().set_session` is the same dial `/reasoning high` moves in the terminal, and
2566/// `choose_model` is the precedent: a live switch on the agent, nothing written to `config.toml`.
2567/// What makes this a fact about *this dashboard* rather than about one conversation is that the
2568/// dashboard owns one agent for the whole process (`AppState::agent`) — the reply says so in
2569/// words, and the durable write stays `/api/settings`.
2570async fn choose_reasoning(
2571    State(st): State<Shared>,
2572    Json(choice): Json<ReasoningChoice>,
2573) -> Response {
2574    let Some(level) = choice.level else {
2575        return error(
2576            StatusCode::BAD_REQUEST,
2577            "name a level: {\"level\": \"high\"}, or {\"level\": null} to go back to the file",
2578        )
2579        .into_response();
2580    };
2581    match apply_reasoning(&st, level).await {
2582        Ok(answer) => Json(answer).into_response(),
2583        Err((code, why)) => error(code, why).into_response(),
2584    }
2585}
2586
2587/// Turn the dial — the body of `POST /api/reasoning`, and what `/reasoning <level>` in the composer
2588/// runs (`#254`, `#275`). `None` is `clear_session`: "back to the file".
2589///
2590/// Refuses a level this route cannot take with the policy's own sentence, because a clamp reported
2591/// as a success is the failure mode the menu exists to prevent.
2592pub(crate) async fn apply_reasoning(
2593    st: &AppState,
2594    level: Option<String>,
2595) -> Result<serde_json::Value, (StatusCode, String)> {
2596    use eclipse_core::provider::Reasoning;
2597    use eclipse_core::reasoning::Wire;
2598    let Some(agent) = st.agent.clone() else {
2599        return Err((StatusCode::SERVICE_UNAVAILABLE, unconfigured(st)));
2600    };
2601    match level {
2602        Some(level) => {
2603            let level = level.trim().to_lowercase();
2604            if level.is_empty() {
2605                return Err((StatusCode::BAD_REQUEST, "level is empty".to_string()));
2606            }
2607            // Refused where the route cannot take it, with the policy's own sentence (`#275`): a
2608            // click that is clamped or dropped in silence is the thing the menu exists to stop.
2609            // `omit` is exempt: it is not a level the wire is asked to take, it is the absence of
2610            // the field, so every route can be told it and nothing can refuse it (`#278`).
2611            let omit = eclipse_core::reasoning::is_omit(&level);
2612            match agent.reasoning_control() {
2613                Some(Reasoning::Policy(policy)) => {
2614                    if !omit && matches!(policy.resolve(Some(&level)), Wire::Omit(_)) {
2615                        return Err((
2616                            StatusCode::BAD_REQUEST,
2617                            format!(
2618                                "{} — this route takes: {}",
2619                                policy.describe(Some(&level)),
2620                                policy.vocabulary().join(" · ")
2621                            ),
2622                        ));
2623                    }
2624                }
2625                Some(Reasoning::Off) => {
2626                    if !omit {
2627                        return Err((
2628                            StatusCode::BAD_REQUEST,
2629                            "no reasoning control on this model: it has no field to carry a level"
2630                                .to_string(),
2631                        ));
2632                    }
2633                }
2634                // An undeclared backend is sent a level verbatim, so the only thing to check is
2635                // that the word is one of ours — the ladder `/reasoning` accepts in the terminal.
2636                Some(Reasoning::Undeclared) => {
2637                    if !omit && !eclipse_core::reasoning::is_level(&level) {
2638                        return Err((
2639                            StatusCode::BAD_REQUEST,
2640                            format!(
2641                                "{level:?} is not a level; the ladder is {}",
2642                                eclipse_core::reasoning::LADDER.join(" · ")
2643                            ),
2644                        ));
2645                    }
2646                }
2647                None => {
2648                    return Err((
2649                        StatusCode::SERVICE_UNAVAILABLE,
2650                        "this dashboard has no provider configuration, so there is no dial to turn"
2651                            .to_string(),
2652                    ));
2653                }
2654            }
2655            agent.reasoning().set_session(Some(level));
2656        }
2657        None => agent.reasoning().clear_session(),
2658    }
2659    Ok(reasoning_json(&agent))
2660}
2661
2662async fn get_session(State(st): State<Shared>, Path(id): Path<String>) -> Response {
2663    if eclipse_core::session::validate_id(&id).is_err() {
2664        return error(StatusCode::BAD_REQUEST, "invalid session id").into_response();
2665    }
2666    let store = st.store.clone();
2667    let Some(loaded) = blocking(move || {
2668        if !store.exists(&id) {
2669            return Err(None::<eclipse_core::Error>);
2670        }
2671        let msgs = store.load(&id).map_err(Some)?;
2672        // `#447`: how each call ended, recorded beside the message when the result was appended.
2673        // A session written before that table existed answers with an empty map, which reads as
2674        // "no verdict on record" and falls back to the text.
2675        let marks = store.tool_outcomes(&id).map_err(Some)?;
2676        Ok((msgs, marks))
2677    })
2678    .await
2679    else {
2680        return error(
2681            StatusCode::INTERNAL_SERVER_ERROR,
2682            "the store did not answer",
2683        )
2684        .into_response();
2685    };
2686    match loaded {
2687        Ok((msgs, marks)) => {
2688            // The stored messages exactly as the provider would see them, plus `calls`: for each
2689            // tool call, by index, the one-line statement for its row and how the call ended.
2690            // Nothing is added inside the message itself — that shape belongs to the model, not to
2691            // the dashboard — and nothing here can reach a request.
2692            //
2693            // A stored result is a `tool` message of its own, carrying only its text and the id of
2694            // the call it answers; the verdict is read off that text (`calls::outcome`) because the
2695            // message has no `is_error` field and must not grow one. A call with no result yet is
2696            // still running, which is also what a session that died mid-call should say.
2697            let mut results: std::collections::HashMap<&str, (&str, Option<bool>)> =
2698                std::collections::HashMap::new();
2699            for m in &msgs {
2700                if let (Some(id), Some(text)) = (m.tool_call_id.as_deref(), m.content.as_deref()) {
2701                    // The recorded verdict when there is one; `None` on a session recorded before
2702                    // it was kept, which is what makes the text inference the fallback rather
2703                    // than the rule.
2704                    let mark = marks.get(id).copied();
2705                    results.entry(id).or_insert((text, mark));
2706                }
2707            }
2708            let shown: Vec<serde_json::Value> = msgs
2709                .iter()
2710                .filter_map(|m| {
2711                    let mut v = serde_json::to_value(m).ok()?;
2712                    let calls: Vec<serde_json::Value> = m
2713                        .tool_calls
2714                        .iter()
2715                        .map(|c| {
2716                            let state = results
2717                                .get(c.id.as_str())
2718                                .map(|(text, mark)| calls::outcome(text, *mark))
2719                                .unwrap_or(calls::Outcome::Running);
2720                            serde_json::json!({
2721                                "summary": calls::statement(&c.function.name, &c.function.arguments),
2722                                "state": state.as_str(),
2723                            })
2724                        })
2725                        .collect();
2726                    if !calls.is_empty() {
2727                        v["calls"] = serde_json::Value::Array(calls);
2728                    }
2729                    Some(v)
2730                })
2731                .collect();
2732            Json(shown).into_response()
2733        }
2734        Err(None) => error(StatusCode::NOT_FOUND, "no such session").into_response(),
2735        Err(Some(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2736    }
2737}
2738
2739type ApiError = (StatusCode, Json<serde_json::Value>);
2740
2741/// The four writes the dashboard makes on a session, all through the store method the CLI
2742/// calls: a rename here is the rename `eclipse sessions rename` performs, and there is no
2743/// second code path that could drift from it. A pinned one sorts first in every listing and no
2744/// prune deletes it; an archived one is out of the listing and still in the search (`#240`).
2745/// Nothing here touches the transcript except `delete`, which is the whole session —
2746/// transcript, title and memory — because a soft delete is a query that every later reader has
2747/// to remember to exclude.
2748fn session_id_ok(id: &str, st: &AppState) -> Option<ApiError> {
2749    if eclipse_core::session::validate_id(id).is_err() {
2750        return Some(error(StatusCode::BAD_REQUEST, "invalid session id"));
2751    }
2752    if !st.store.exists(id) {
2753        return Some(error(StatusCode::NOT_FOUND, "no such session"));
2754    }
2755    None
2756}
2757
2758#[derive(Deserialize)]
2759struct RenameBody {
2760    title: String,
2761}
2762
2763async fn rename_session(
2764    State(st): State<Shared>,
2765    Path(id): Path<String>,
2766    Json(body): Json<RenameBody>,
2767) -> Response {
2768    if let Some(refusal) = session_id_ok(&id, &st) {
2769        return refusal.into_response();
2770    }
2771    match st.store.rename(&id, &body.title) {
2772        Ok(()) => Json(json!({ "id": id, "title": body.title.trim() })).into_response(),
2773        // An empty title, one that is too long or one with control characters is the store's
2774        // rule, so it is reported in the store's words rather than restated here.
2775        Err(e) => error(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
2776    }
2777}
2778
2779#[derive(Deserialize)]
2780struct PinBody {
2781    pinned: bool,
2782}
2783
2784async fn pin_session(
2785    State(st): State<Shared>,
2786    Path(id): Path<String>,
2787    Json(body): Json<PinBody>,
2788) -> Response {
2789    if let Some(refusal) = session_id_ok(&id, &st) {
2790        return refusal.into_response();
2791    }
2792    match st.store.set_pinned(&id, body.pinned) {
2793        Ok(()) => Json(json!({ "id": id, "pinned": body.pinned })).into_response(),
2794        Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2795    }
2796}
2797
2798#[derive(Deserialize)]
2799struct ArchiveBody {
2800    archived: bool,
2801}
2802
2803async fn archive_session(
2804    State(st): State<Shared>,
2805    Path(id): Path<String>,
2806    Json(body): Json<ArchiveBody>,
2807) -> Response {
2808    if let Some(refusal) = session_id_ok(&id, &st) {
2809        return refusal.into_response();
2810    }
2811    match st.store.set_archived(&id, body.archived) {
2812        Ok(()) => Json(json!({ "id": id, "archived": body.archived })).into_response(),
2813        Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2814    }
2815}
2816
2817async fn delete_session(State(st): State<Shared>, Path(id): Path<String>) -> Response {
2818    if let Some(refusal) = session_id_ok(&id, &st) {
2819        return refusal.into_response();
2820    }
2821    match st.store.delete(&id) {
2822        Ok(()) => Json(json!({ "id": id, "deleted": true })).into_response(),
2823        Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2824    }
2825}
2826
2827/// The largest per-run iteration bound the dashboard route takes (`#425`). A conversation is
2828/// bounded by the agent's own budget (`[agent] max_iterations`, a dozen or so); this is the ceiling
2829/// for a client that wants more headroom, not a budget anyone should reach in a turn.
2830const MAX_ITERATIONS_BOUND: usize = 200;
2831
2832fn error(status: StatusCode, msg: impl Into<String>) -> ApiError {
2833    (status, Json(json!({"error": msg.into()})))
2834}
2835
2836// ---------------------------------------------------------------------------------------------
2837// Cron: the same jobs the timer runs, seen and edited from the dashboard
2838// ---------------------------------------------------------------------------------------------
2839
2840/// The install root the cron files live under, or the refusal that says this process has none.
2841///
2842/// Every handler below goes through here, so there is one answer to "which jobs does this page
2843/// mean" and it is the root `cron::load` is called with by the CLI. The error is the pair, not the
2844/// built response: a `Response` is a large value to carry in a `Result` (clippy's
2845/// `result_large_err`), and the handler turns it into one at the point it returns.
2846type Refusal = (StatusCode, String);
2847
2848fn cron_root(st: &AppState) -> Result<std::path::PathBuf, Refusal> {
2849    st.cron_root.clone().ok_or((
2850        StatusCode::SERVICE_UNAVAILABLE,
2851        "this dashboard was started without an install root, so it has no cron files to show"
2852            .to_string(),
2853    ))
2854}
2855
2856/// The job called `name`, or a 404 naming it.
2857fn cron_job(root: &std::path::Path, name: &str) -> Result<eclipse_core::cron::Job, Refusal> {
2858    let jobs = eclipse_core::cron::load(root)
2859        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
2860    jobs.into_iter().find(|j| j.name == name).ok_or((
2861        StatusCode::NOT_FOUND,
2862        format!("no job named `{name}`; the list shows the names"),
2863    ))
2864}
2865
2866/// `GET /api/cron` — every job with its next fire and what last ran, plus `now_ms` so the page can
2867/// say "in 8h 12m" without trusting the browser's clock.
2868async fn list_cron(State(st): State<Shared>) -> Response {
2869    let root = match cron_root(&st) {
2870        Ok(root) => root,
2871        Err((status, why)) => return error(status, why).into_response(),
2872    };
2873    let now = eclipse_core::session::now_ms() as i64;
2874    // `#425`: `views` reads the jobs file and every run log behind it — synchronous disk work that
2875    // used to happen on an async worker, so a slow disk held a request slot the whole server shares.
2876    let reader = {
2877        let root = root.clone();
2878        move || eclipse_core::cron::views(&root, now)
2879    };
2880    let Some(listing) = blocking(reader).await else {
2881        return error(
2882            StatusCode::SERVICE_UNAVAILABLE,
2883            "the blocking pool did not take the read; try again",
2884        )
2885        .into_response();
2886    };
2887    match listing {
2888        Ok(jobs) => Json(json!({
2889            "now_ms": now,
2890            "jobs_file": eclipse_core::cron::jobs_path(&root).display().to_string(),
2891            "runs_dir": eclipse_core::cron::runs_root(&root).display().to_string(),
2892            "jobs": jobs,
2893        }))
2894        .into_response(),
2895        // The file is the store's, and a file it cannot parse is the answer — not an empty list,
2896        // which would read as "nothing is scheduled" and invite a job that already exists.
2897        Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2898    }
2899}
2900
2901/// `POST /api/cron` — one new job, through the same `Draft` the CLI fills in.
2902async fn create_cron(
2903    State(st): State<Shared>,
2904    Json(draft): Json<eclipse_core::cron::Draft>,
2905) -> Response {
2906    let root = match cron_root(&st) {
2907        Ok(root) => root,
2908        Err((status, why)) => return error(status, why).into_response(),
2909    };
2910    let job = match draft.to_job() {
2911        Ok(job) => job,
2912        // The parser's own sentence, so the page and `cron add` refuse in the same words.
2913        Err(e) => return error(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
2914    };
2915    let existing = match eclipse_core::cron::load(&root) {
2916        Ok(jobs) => jobs,
2917        Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2918    };
2919    if existing.iter().any(|j| j.name == job.name) {
2920        return error(
2921            StatusCode::CONFLICT,
2922            format!("a job named `{}` already exists", job.name),
2923        )
2924        .into_response();
2925    }
2926    if let Err(e) = eclipse_core::cron::append_job(&root, &job) {
2927        return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
2928    }
2929    // Loading it back is the check that what was written is what this build reads.
2930    let now = eclipse_core::session::now_ms() as i64;
2931    match eclipse_core::cron::views(&root, now)
2932        .map(|all| all.into_iter().find(|v| v.name == job.name))
2933    {
2934        Ok(Some(view)) => (StatusCode::CREATED, Json(view)).into_response(),
2935        Ok(None) => error(
2936            StatusCode::INTERNAL_SERVER_ERROR,
2937            "the job was written but does not read back",
2938        )
2939        .into_response(),
2940        Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2941    }
2942}
2943
2944/// `PUT /api/cron/:name` — replace the editable fields of one job.
2945///
2946/// A name is the job's identity in the file the timer reads, so a rename here would be a delete and
2947/// an add wearing one request; the page keeps the field fixed while editing and this refuses a body
2948/// that disagrees rather than doing half of that.
2949async fn update_cron(
2950    State(st): State<Shared>,
2951    Path(name): Path<String>,
2952    Json(draft): Json<eclipse_core::cron::Draft>,
2953) -> Response {
2954    let root = match cron_root(&st) {
2955        Ok(root) => root,
2956        Err((status, why)) => return error(status, why).into_response(),
2957    };
2958    if draft.name != name {
2959        return error(
2960            StatusCode::BAD_REQUEST,
2961            "a job's name is its identity: remove this one and add the new name",
2962        )
2963        .into_response();
2964    }
2965    if let Err((status, why)) = cron_job(&root, &name) {
2966        return error(status, why).into_response();
2967    }
2968    let job = match draft.to_job() {
2969        Ok(job) => job,
2970        Err(e) => return error(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
2971    };
2972    if let Err(e) = eclipse_core::cron::replace_job(&root, &job) {
2973        return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
2974    }
2975    let now = eclipse_core::session::now_ms() as i64;
2976    match eclipse_core::cron::views(&root, now).map(|all| all.into_iter().find(|v| v.name == name))
2977    {
2978        Ok(Some(view)) => Json(view).into_response(),
2979        Ok(None) => error(
2980            StatusCode::INTERNAL_SERVER_ERROR,
2981            "the job was written but does not read back",
2982        )
2983        .into_response(),
2984        Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2985    }
2986}
2987
2988#[derive(Deserialize)]
2989struct EnabledBody {
2990    enabled: bool,
2991}
2992
2993/// `POST /api/cron/:name/enabled` — the row's switch, through `cron::set_enabled`.
2994///
2995/// Its own route rather than a field of `PUT`: a toggle is one bit, and sending the whole form back
2996/// to flip it would overwrite whatever was typed in another tab since.
2997async fn set_cron_enabled(
2998    State(st): State<Shared>,
2999    Path(name): Path<String>,
3000    Json(body): Json<EnabledBody>,
3001) -> Response {
3002    let root = match cron_root(&st) {
3003        Ok(root) => root,
3004        Err((status, why)) => return error(status, why).into_response(),
3005    };
3006    let job = match eclipse_core::cron::set_enabled(&root, &name, body.enabled) {
3007        Ok(Some(job)) => job,
3008        Ok(None) => {
3009            return error(StatusCode::NOT_FOUND, format!("no job named `{name}`")).into_response()
3010        }
3011        Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
3012    };
3013    let now = eclipse_core::session::now_ms() as i64;
3014    let state = eclipse_core::cron::load_state(&root).unwrap_or_default();
3015    Json(eclipse_core::cron::view(&job, &state, now)).into_response()
3016}
3017
3018/// `DELETE /api/cron/:name` — forget a job; its run logs stay on disk.
3019async fn delete_cron(State(st): State<Shared>, Path(name): Path<String>) -> Response {
3020    let root = match cron_root(&st) {
3021        Ok(root) => root,
3022        Err((status, why)) => return error(status, why).into_response(),
3023    };
3024    match eclipse_core::cron::remove_job(&root, &name) {
3025        Ok(true) => Json(json!({ "name": name, "removed": true })).into_response(),
3026        Ok(false) => error(StatusCode::NOT_FOUND, format!("no job named `{name}`")).into_response(),
3027        Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
3028    }
3029}
3030
3031/// Where the `eclipse` binary is, for the one thing this process cannot do in-process.
3032///
3033/// The tick lives in the CLI (`cron_cli::run` drives an agent, which is the CLI's job), and this
3034/// crate is the dashboard. `ECLIPSE_BIN` first so a test can point at a stand-in; then the sibling
3035/// of this executable, which is how `install.sh` lays the three binaries out; then `PATH`.
3036fn eclipse_bin() -> std::path::PathBuf {
3037    if let Some(path) = std::env::var_os("ECLIPSE_BIN") {
3038        return std::path::PathBuf::from(path);
3039    }
3040    if let Ok(exe) = std::env::current_exe() {
3041        if let Some(dir) = exe.parent() {
3042            let beside = dir.join("eclipse");
3043            if beside.is_file() {
3044                return beside;
3045            }
3046        }
3047    }
3048    std::path::PathBuf::from("eclipse")
3049}
3050
3051/// `POST /api/cron/:name/run` — start that job now and answer at once.
3052///
3053/// Not in the request thread: a job is a model turn, and the #112 defect is exactly a handler that
3054/// waits for one. The tick takes the cron lock itself, so a second click while it runs is a
3055/// sentence in the run log rather than a second run.
3056async fn run_cron_now(State(st): State<Shared>, Path(name): Path<String>) -> Response {
3057    let root = match cron_root(&st) {
3058        Ok(root) => root,
3059        Err((status, why)) => return error(status, why).into_response(),
3060    };
3061    let job = match cron_job(&root, &name) {
3062        Ok(job) => job,
3063        Err((status, why)) => return error(status, why).into_response(),
3064    };
3065    // `#398`: the child resolves its own cron root from `--profile`/`--config`, and a dashboard
3066    // started with either as a *flag* has it nowhere in the environment it hands down. Without
3067    // them the tick looks in the default profile for a job this handler just found in another
3068    // one — 202, a pid, and a run the page polls for that never comes. Both are global args on
3069    // `eclipse`, so they go before the subcommand.
3070    let mut command = std::process::Command::new(eclipse_bin());
3071    if let Some(profile) = st.profile.as_deref() {
3072        command.arg("--profile").arg(profile);
3073    }
3074    if let Some(config) = st.config_path.as_deref() {
3075        command.arg("--config").arg(config);
3076    }
3077    let spawned = command
3078        .arg("cron")
3079        .arg("run")
3080        .arg(&name)
3081        .stdin(std::process::Stdio::null())
3082        .stdout(std::process::Stdio::null())
3083        .stderr(std::process::Stdio::null())
3084        .spawn();
3085    match spawned {
3086        // 202: the work exists, its result does not. The page polls the job until
3087        // `last_started_ms` moves — the tick writes it before the model is asked anything.
3088        Ok(mut child) => {
3089            let pid = child.id();
3090            // `#397`: a `Child` is not reaped when it is dropped, so every click left a defunct
3091            // process in the dashboard's table for as long as the gateway ran — one per press.
3092            // Nothing here wants the outcome (the run file is the record), so the wait happens on
3093            // the blocking pool and its result is discarded.
3094            tokio::task::spawn_blocking(move || {
3095                let _ = child.wait();
3096            });
3097            (
3098                StatusCode::ACCEPTED,
3099                Json(json!({
3100                    "name": name,
3101                    "started": true,
3102                    "pid": pid,
3103                    "enabled": job.enabled,
3104                })),
3105            )
3106                .into_response()
3107        }
3108        Err(e) => error(
3109            StatusCode::INTERNAL_SERVER_ERROR,
3110            format!(
3111                "could not start `{} cron run {name}`: {e}",
3112                eclipse_bin().display()
3113            ),
3114        )
3115        .into_response(),
3116    }
3117}
3118
3119/// `GET /api/cron/:name/logs?limit=3` — what the last runs answered.
3120async fn cron_logs(
3121    State(st): State<Shared>,
3122    Path(name): Path<String>,
3123    Query(q): Query<LogsQuery>,
3124) -> Response {
3125    let root = match cron_root(&st) {
3126        Ok(root) => root,
3127        Err((status, why)) => return error(status, why).into_response(),
3128    };
3129    if let Err((status, why)) = cron_job(&root, &name) {
3130        return error(status, why).into_response();
3131    }
3132    // Bounded: a page that asks for a thousand runs gets six, and the CLI can still ask for more.
3133    let limit = q.limit.unwrap_or(3).clamp(1, 20);
3134    Json(json!({
3135        "job": name,
3136        "runs_dir": eclipse_core::cron::runs_dir(&root, &name).display().to_string(),
3137        "runs": eclipse_core::cron::runs(&root, &name, limit),
3138    }))
3139    .into_response()
3140}
3141
3142#[derive(Deserialize)]
3143struct LogsQuery {
3144    limit: Option<usize>,
3145}
3146
3147// ---------------------------------------------------------------------------------------------
3148// MCP: the servers config.toml and the plugins declare, seen and edited from the dashboard
3149// ---------------------------------------------------------------------------------------------
3150
3151/// Which `config.toml` the `[[mcp]]` entries live in, or the refusal that says this process has
3152/// none. The same shape as `cron_root`: one answer to "which file does this page mean".
3153fn mcp_config_path(st: &AppState) -> Result<std::path::PathBuf, Refusal> {
3154    // The file a write lands in — the served profile's overlay, or the base (`#571`). The listing
3155    // reports this one too, so `mcp add` in the page and `eclipse mcp add -p <profile>` put the
3156    // entry in the same place.
3157    st.write_path().ok_or((
3158        StatusCode::SERVICE_UNAVAILABLE,
3159        "this dashboard was started without a config file, so it has no `[[mcp]]` entries to \
3160         show or edit"
3161            .to_string(),
3162    ))
3163}
3164
3165/// One server as the page and `eclipse mcp list --json` print it. The fields are deliberately
3166/// the CLI's: one row read side by side on two surfaces must not be two shapes, and two shapes
3167/// is how drift starts (`#352`).
3168fn mcp_row(s: &eclipse_core::plugins::McpServerState) -> serde_json::Value {
3169    json!({
3170        "name": s.name,
3171        "source": s.source.label(),
3172        "owner": s.owner,
3173        "command": s.command,
3174        "policy": format!("{:?}", s.policy).to_lowercase(),
3175        "prefix": s.prefix,
3176        "timeout_secs": s.timeout_secs,
3177        "disabled": s.disabled,
3178        // `#517`: the entry as the file declares it, so the form can open with what is there,
3179        // and the word for whether its token resolves — never the value.
3180        "transport": s.transport.as_str(),
3181        "program": s.program,
3182        "args": s.args,
3183        "url": s.url,
3184        "token_env": s.token_env,
3185        "token": s.token.as_str(),
3186        "tools": s.tools,
3187        // A disabled entry is never started (`mcp_report` does not spawn it), so "no error" is
3188        // not the same thing as "it ran": the pane would show a green row for something it chose
3189        // not to try.
3190        "started": s.error.is_none() && !s.disabled,
3191        "error": s.error,
3192        "protocol": s.protocol,
3193        "server_name": s.server_name,
3194        "server_version": s.server_version,
3195    })
3196}
3197
3198/// The whole report, on the blocking pool: `mcp_report` starts every server that is not
3199/// disabled, which is process-spawning and pipe-writing work and must not sit on an async
3200/// worker — the same reasoning that put `cron::views` there.
3201fn mcp_listing(cfg: &eclipse_core::config::Config) -> (Vec<serde_json::Value>, Vec<String>) {
3202    let loaded = eclipse_core::plugins::load(
3203        &cfg.plugins_dirs(&eclipse_core::config::process_env),
3204        &cfg.plugins.enabled,
3205    )
3206    .with_mcp(eclipse_core::plugins::McpSettings::from_config(cfg))
3207    .with_config_mcp(cfg);
3208    let workspace = cfg.workspace_root(&eclipse_core::config::process_env);
3209    let (servers, problems) = loaded.mcp_report(&workspace);
3210    (servers.iter().map(mcp_row).collect(), problems)
3211}
3212
3213/// The status a `[[mcp]]` writer's sentence deserves, without re-saying it. The writers name
3214/// their own failures in fixed phrases (`config.rs` tests pin them): a missing entry always
3215/// opens with "no `[[mcp]]` entry", a duplicate always says where the earlier one is, and an
3216/// unusable entry always says it was not usable — so the pane can answer 404/409/400 with the
3217/// writer's own words rather than paraphrase it into something that drifts from `eclipse mcp`.
3218fn mcp_writer_error(why: String) -> (StatusCode, String) {
3219    let status = if why.starts_with("no `[[mcp]]` entry") {
3220        StatusCode::NOT_FOUND
3221    } else if why.contains("is already declared at line") {
3222        StatusCode::CONFLICT
3223    } else if why.starts_with("that entry is not usable") {
3224        StatusCode::BAD_REQUEST
3225    } else {
3226        StatusCode::INTERNAL_SERVER_ERROR
3227    };
3228    (status, why)
3229}
3230
3231/// Read `config.toml`, hand its text to one `config::mcp_*` writer, save, load back — all of it
3232/// inside the `#399` write lock and on the blocking pool, exactly as `apply_setting` does. The
3233/// re-read answers with what the file now says, not with what was asked for.
3234async fn mcp_edit(
3235    st: &AppState,
3236    edit: impl FnOnce(&str) -> Result<String, (StatusCode, String)> + Send + 'static,
3237) -> Result<eclipse_core::config::Config, (StatusCode, String)> {
3238    let path = mcp_config_path(st)?;
3239    let base = st.config_path.clone();
3240    let profile = st.profile.clone();
3241    let writes = st.config_writes.clone();
3242    let written = blocking(move || -> Result<_, (StatusCode, String)> {
3243        let _one_writer = writes
3244            .lock()
3245            .unwrap_or_else(|poisoned| poisoned.into_inner());
3246        // A profile's overlay is written into existence by the first write, so it reads as empty
3247        // text until then.
3248        let text = match std::fs::read_to_string(&path) {
3249            Ok(text) => text,
3250            Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
3251            Err(e) => {
3252                return Err((
3253                    StatusCode::INTERNAL_SERVER_ERROR,
3254                    format!("{}: {e}", path.display()),
3255                ))
3256            }
3257        };
3258        let edited = edit(&text)?;
3259        if let Some(dir) = path.parent() {
3260            std::fs::create_dir_all(dir).map_err(|e| {
3261                (
3262                    StatusCode::INTERNAL_SERVER_ERROR,
3263                    format!("{}: {e}", dir.display()),
3264                )
3265            })?;
3266        }
3267        eclipse_core::config::save_config_text(&path, &edited)
3268            .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
3269        // Read back through the loader, from the base file plus the served profile: handing it the
3270        // overlay would apply the same file twice.
3271        eclipse_core::config::Config::load_with_profile(
3272            base.as_deref(),
3273            profile.as_deref(),
3274            &eclipse_core::config::process_env,
3275        )
3276        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
3277    })
3278    .await;
3279    let Some(written) = written else {
3280        return Err((
3281            StatusCode::INTERNAL_SERVER_ERROR,
3282            "the write did not finish".to_string(),
3283        ));
3284    };
3285    written
3286}
3287
3288/// The listing after a write: the row called `name`, or the sentence that the file did not read
3289/// back — the same check `create_cron` makes on the jobs file.
3290async fn mcp_row_after(
3291    cfg: eclipse_core::config::Config,
3292    name: &str,
3293) -> Result<serde_json::Value, (StatusCode, String)> {
3294    let Some(rows) = blocking(move || mcp_listing(&cfg)).await else {
3295        return Err((
3296            StatusCode::SERVICE_UNAVAILABLE,
3297            "the blocking pool did not take the read; try again".to_string(),
3298        ));
3299    };
3300    rows.0
3301        .into_iter()
3302        .find(|r| r["name"] == name)
3303        .ok_or_else(|| {
3304            (
3305                StatusCode::INTERNAL_SERVER_ERROR,
3306                format!("the entry was written but `{name}` does not read back"),
3307            )
3308        })
3309}
3310
3311/// `GET /api/problems` — every manifest, skill and context warning the loaders produced.
3312///
3313/// The dashboard had no surface for these at all, so they existed only on the terminal of whoever
3314/// started the process (`#505`). This is the same `problems::collect` that a run's loaders perform,
3315/// re-read per call: nothing is cached, which is what makes a fix visible without a reload.
3316async fn list_problems(State(st): State<Shared>) -> Response {
3317    // A config this process cannot load is answered rather than refused, and it is the first thing
3318    // the answer says: the loaders below it did not really run, and a 500 with a bare sentence would
3319    // hide the one fact worth showing. The pane puts that line above the table for the same reason.
3320    let cfg = match st.reload_config() {
3321        Ok(cfg) => cfg,
3322        Err(e) => {
3323            return Json(json!({
3324                "summary": format!("the config could not be loaded: {e}"),
3325                "config_error": st.config_error.clone().unwrap_or_else(|| e.clone()),
3326                "problems": [],
3327                "checked": [],
3328            }))
3329            .into_response()
3330        }
3331    };
3332    let report =
3333        blocking(move || eclipse_core::problems::collect(&cfg, &eclipse_core::config::process_env))
3334            .await;
3335    let Some(report) = report else {
3336        return error(
3337            StatusCode::SERVICE_UNAVAILABLE,
3338            "the blocking pool did not take the read; try again",
3339        )
3340        .into_response();
3341    };
3342    let problems: Vec<serde_json::Value> = report
3343        .problems
3344        .iter()
3345        .map(|p| {
3346            json!({
3347                "kind": p.kind.as_str(),
3348                "text": p.text,
3349                "path": p.path.as_ref().map(|p| p.display().to_string()),
3350            })
3351        })
3352        .collect();
3353    Json(json!({
3354        "summary": report.summary(),
3355        // A config this process could not load at all is the loudest problem there is, and it is
3356        // not the loaders': it stopped them from running. Reported first, in its own field, so the
3357        // pane can put it at the top rather than in a list of lesser complaints.
3358        "config_error": st.config_error.clone(),
3359        "problems": problems,
3360        "checked": report.checked,
3361    }))
3362    .into_response()
3363}
3364
3365/// `GET /api/mcp` — every server the load would start, with where it is declared, what it
3366/// answered, and the problems (a shadowed manifest entry) that are not one server's row.
3367async fn list_mcp(State(st): State<Shared>) -> Response {
3368    let path = match mcp_config_path(&st) {
3369        Ok(path) => path,
3370        Err((status, why)) => return error(status, why).into_response(),
3371    };
3372    let cfg = match st.reload_config() {
3373        Ok(cfg) => cfg,
3374        Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
3375    };
3376    let Some(listing) = blocking(move || mcp_listing(&cfg)).await else {
3377        return error(
3378            StatusCode::SERVICE_UNAVAILABLE,
3379            "the blocking pool did not take the read; try again",
3380        )
3381        .into_response();
3382    };
3383    Json(json!({
3384        "config_path": path.display().to_string(),
3385        "servers": listing.0,
3386        "problems": listing.1,
3387    }))
3388    .into_response()
3389}
3390
3391/// The shape of `token_env`, under a name: the field carries a variable *name* (the rule
3392/// `Spec::token_env` states in core), and the alias keeps that visible where it is written.
3393type TokenEnv = Option<String>;
3394
3395/// What `POST /api/mcp` and `PUT /api/mcp/:name` accept: the two transports' fields as one shape,
3396/// because the entry decides which belong to it (`Spec::validate` is the judge, and its sentence is
3397/// the refusal). `name` is optional because a `PUT` takes it from the path (`#517`) and refuses a
3398/// body that disagrees, rather than silently renaming.
3399#[derive(Deserialize)]
3400struct McpEntry {
3401    #[serde(default)]
3402    name: Option<String>,
3403    /// `stdio` or `http`. Left out, the entry says which it is: a `url` and no `command` is an
3404    /// HTTP server — the same inference `eclipse mcp add` makes.
3405    #[serde(default)]
3406    transport: Option<String>,
3407    #[serde(default)]
3408    command: Option<String>,
3409    #[serde(default)]
3410    args: Option<Vec<String>>,
3411    #[serde(default)]
3412    url: Option<String>,
3413    #[serde(default)]
3414    prefix: Option<String>,
3415    #[serde(default)]
3416    policy: Option<String>,
3417    #[serde(default)]
3418    token_env: TokenEnv,
3419    #[serde(default)]
3420    timeout_secs: Option<u64>,
3421}
3422
3423fn filled(v: Option<&String>) -> bool {
3424    v.is_some_and(|s| !s.trim().is_empty())
3425}
3426
3427/// `POST /api/mcp` — one new `[[mcp]]` entry, through `config::mcp_add`. A duplicate name or a
3428/// nonsense entry comes back as the writer's own sentence, naming the line or the field, because
3429/// that is the sentence that says what to fix.
3430async fn add_mcp(State(st): State<Shared>, Json(body): Json<McpEntry>) -> Response {
3431    let name = body.name.clone().unwrap_or_default().trim().to_string();
3432    if name.is_empty() {
3433        return error(
3434            StatusCode::BAD_REQUEST,
3435            "a server needs a name — it is what `eclipse mcp test` and the tool names use",
3436        )
3437        .into_response();
3438    }
3439    let transport = match mcp_transport(&body) {
3440        Ok(transport) => transport,
3441        Err((status, why)) => return error(status, why).into_response(),
3442    };
3443    let policy = match mcp_policy(&body) {
3444        Ok(policy) => policy,
3445        Err((status, why)) => return error(status, why).into_response(),
3446    };
3447    let spec = eclipse_core::mcp::Spec {
3448        name: name.clone(),
3449        transport,
3450        command: body.command.unwrap_or_default(),
3451        args: body.args.unwrap_or_default(),
3452        env: Vec::new(),
3453        cwd: Default::default(),
3454        url: body.url.filter(|u| !u.trim().is_empty()),
3455        token_env: body.token_env.filter(|t| !t.trim().is_empty()),
3456        timeout_secs: body.timeout_secs,
3457        policy,
3458        policies: Default::default(),
3459        prefix: body.prefix.unwrap_or_default(),
3460        override_builtin: false,
3461        disabled: false,
3462    };
3463    let wrote = mcp_edit(&st, move |text| {
3464        eclipse_core::config::mcp_add(text, &spec).map_err(mcp_writer_error)
3465    })
3466    .await;
3467    let cfg = match wrote {
3468        Ok(cfg) => cfg,
3469        Err((status, why)) => return error(status, why).into_response(),
3470    };
3471    match mcp_row_after(cfg, &name).await {
3472        Ok(row) => (StatusCode::CREATED, Json(row)).into_response(),
3473        Err((status, why)) => error(status, why).into_response(),
3474    }
3475}
3476
3477/// The transport a body asks for. Left out, the entry says which it is: a `url` and no `command`
3478/// is an HTTP server — the same inference `eclipse mcp add` makes. One parser, because `POST` and
3479/// `PUT` must not disagree about what `transport = ""` means.
3480fn mcp_transport(body: &McpEntry) -> Result<eclipse_core::mcp::Transport, (StatusCode, String)> {
3481    match body.transport.as_deref() {
3482        None | Some("") => {
3483            if filled(body.url.as_ref()) && !filled(body.command.as_ref()) {
3484                Ok(eclipse_core::mcp::Transport::Http)
3485            } else {
3486                Ok(eclipse_core::mcp::Transport::Stdio)
3487            }
3488        }
3489        Some("stdio") => Ok(eclipse_core::mcp::Transport::Stdio),
3490        Some("http") => Ok(eclipse_core::mcp::Transport::Http),
3491        Some(other) => Err((
3492            StatusCode::BAD_REQUEST,
3493            format!("`{other}` is not a transport: this build speaks `stdio` and `http`"),
3494        )),
3495    }
3496}
3497
3498/// The policy a body asks for, parsed by serde so the words are the config's own (`ask`, `allow`,
3499/// `deny`) rather than a second list that can drift from the parser.
3500fn mcp_policy(body: &McpEntry) -> Result<eclipse_core::config::Policy, (StatusCode, String)> {
3501    match body.policy.as_deref() {
3502        None | Some("") => Ok(eclipse_core::config::Policy::Ask),
3503        Some(raw) => {
3504            serde_json::from_value::<eclipse_core::config::Policy>(json!(raw)).map_err(|_| {
3505                (
3506                    StatusCode::BAD_REQUEST,
3507                    format!("`{raw}` is not a policy: `ask`, `allow` or `deny`"),
3508                )
3509            })
3510        }
3511    }
3512}
3513
3514/// What a `PUT` writes: the fields the form shows, and nothing else. A key the form has no input
3515/// for is not a key the person cleared — `disabled`, `env`, `policies`, `override` and `cwd` stay
3516/// exactly as the file had them, because `mcp_update` starts from the entry the file declares.
3517struct McpFields {
3518    transport: eclipse_core::mcp::Transport,
3519    command: String,
3520    args: Vec<String>,
3521    url: Option<String>,
3522    prefix: String,
3523    policy: eclipse_core::config::Policy,
3524    token_env: Option<String>,
3525    /// `None` means "not sent", which means "leave it": the form has no field for it.
3526    timeout_secs: Option<u64>,
3527}
3528
3529/// `PUT /api/mcp/:name` — change one entry, through `config::mcp_update` (`#517`).
3530///
3531/// The path is the one the pane already knows, beside the `delete`. An unknown name is the
3532/// writer's own 404 sentence; a body that would produce an unusable entry is its 400, with the
3533/// field named; a malformed body never reaches the writer at all, so the file is untouched.
3534async fn update_mcp(
3535    State(st): State<Shared>,
3536    Path(name): Path<String>,
3537    Json(body): Json<McpEntry>,
3538) -> Response {
3539    if let Some(named) = body
3540        .name
3541        .as_deref()
3542        .map(str::trim)
3543        .filter(|n| !n.is_empty())
3544    {
3545        if named != name {
3546            return error(
3547                StatusCode::BAD_REQUEST,
3548                format!(
3549                    "this is the entry for `{name}`, and an edit does not rename it — remove it                      and add `{named}` instead"
3550                ),
3551            )
3552            .into_response();
3553        }
3554    }
3555    let transport = match mcp_transport(&body) {
3556        Ok(transport) => transport,
3557        Err((status, why)) => return error(status, why).into_response(),
3558    };
3559    let policy = match mcp_policy(&body) {
3560        Ok(policy) => policy,
3561        Err((status, why)) => return error(status, why).into_response(),
3562    };
3563    let edit = McpFields {
3564        transport,
3565        command: body.command.unwrap_or_default(),
3566        args: body.args.unwrap_or_default(),
3567        url: body.url.filter(|u| !u.trim().is_empty()),
3568        prefix: body.prefix.unwrap_or_default(),
3569        policy,
3570        token_env: body.token_env.filter(|t| !t.trim().is_empty()),
3571        timeout_secs: body.timeout_secs,
3572    };
3573    let for_writer = name.clone();
3574    let wrote = mcp_edit(&st, move |text| {
3575        eclipse_core::config::mcp_update(text, &for_writer, move |spec| {
3576            spec.transport = edit.transport;
3577            spec.command = edit.command;
3578            spec.args = edit.args;
3579            spec.url = edit.url;
3580            spec.prefix = edit.prefix;
3581            spec.policy = edit.policy;
3582            spec.token_env = edit.token_env;
3583            if edit.timeout_secs.is_some() {
3584                spec.timeout_secs = edit.timeout_secs;
3585            }
3586        })
3587        .map_err(mcp_writer_error)
3588    })
3589    .await;
3590    let cfg = match wrote {
3591        Ok(cfg) => cfg,
3592        Err((status, why)) => return error(status, why).into_response(),
3593    };
3594    match mcp_row_after(cfg, &name).await {
3595        Ok(row) => Json(row).into_response(),
3596        Err((status, why)) => error(status, why).into_response(),
3597    }
3598}
3599
3600/// `POST /api/mcp/:name/enabled` — the row's switch: `disabled = true` written into that entry,
3601/// the way `eclipse mcp disable` writes it. Its own route for the same reason cron's is: a
3602/// toggle is one bit, and resending a whole form would overwrite another tab's newer edit.
3603async fn set_mcp_enabled(
3604    State(st): State<Shared>,
3605    Path(name): Path<String>,
3606    Json(body): Json<EnabledBody>,
3607) -> Response {
3608    let for_writer = name.clone();
3609    let wrote = mcp_edit(&st, move |text| {
3610        eclipse_core::config::mcp_set_disabled(text, &for_writer, !body.enabled)
3611            .map_err(mcp_writer_error)
3612    })
3613    .await;
3614    let cfg = match wrote {
3615        Ok(cfg) => cfg,
3616        Err((status, why)) => return error(status, why).into_response(),
3617    };
3618    match mcp_row_after(cfg, &name).await {
3619        Ok(row) => Json(row).into_response(),
3620        Err((status, why)) => error(status, why).into_response(),
3621    }
3622}
3623
3624/// `POST /api/mcp/:name/test` — the same start-and-report the listing runs, for the one server,
3625/// answering with what it reported: the protocol it speaks, its own name and version, the tools
3626/// it listed, or the reason it did not. `mcp_report` is per-load and this builds a fresh one, so
3627/// the button re-runs the handshake rather than replaying a cache — which is the point of a
3628/// button whose whole job is turning "configured" into "works".
3629async fn test_mcp(State(st): State<Shared>, Path(name): Path<String>) -> Response {
3630    if let Err((status, why)) = mcp_config_path(&st) {
3631        return error(status, why).into_response();
3632    }
3633    let cfg = match st.reload_config() {
3634        Ok(cfg) => cfg,
3635        Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
3636    };
3637    let wanted = name.clone();
3638    let Some(rows) = blocking(move || mcp_listing(&cfg)).await else {
3639        return error(
3640            StatusCode::SERVICE_UNAVAILABLE,
3641            "the blocking pool did not take the run; try again",
3642        )
3643        .into_response();
3644    };
3645    match rows.0.into_iter().find(|r| r["name"] == wanted) {
3646        Some(row) => Json(row).into_response(),
3647        None => error(
3648            StatusCode::NOT_FOUND,
3649            format!("no MCP server is called `{name}` — the list shows the names this build sees"),
3650        )
3651        .into_response(),
3652    }
3653}
3654
3655/// `DELETE /api/mcp/:name` — the entry goes; a server a plugin declared is not this file's to
3656/// delete, and the writer's sentence says which entries the file does have.
3657async fn remove_mcp(State(st): State<Shared>, Path(name): Path<String>) -> Response {
3658    let for_writer = name.clone();
3659    let wrote = mcp_edit(&st, move |text| {
3660        eclipse_core::config::mcp_remove(text, &for_writer).map_err(mcp_writer_error)
3661    })
3662    .await;
3663    match wrote {
3664        Ok(_) => Json(json!({ "name": name, "removed": true })).into_response(),
3665        Err((status, why)) => error(status, why).into_response(),
3666    }
3667}
3668
3669#[derive(Deserialize)]
3670struct ChatRequest {
3671    #[serde(default)]
3672    message: String,
3673    session_id: Option<String>,
3674    /// Stop after this many model <-> tool round-trips. Unset means the agent's own budget
3675    /// (`[agent] max_iterations`); 0 is refused rather than silently read as 1.
3676    max_iterations: Option<usize>,
3677    /// What the `+` menu put in the composer (`#239`). Composed into the turn's text by
3678    /// [`compose_attachments`], so the request stays one JSON body and there is no second path
3679    /// that reads files behind the model's back.
3680    #[serde(default)]
3681    attachments: Vec<Attachment>,
3682}
3683
3684/// One thing the composer attached to a turn (`#239`).
3685///
3686/// Three kinds travel, and none of them makes this process read a file. `text` is a file the page
3687/// itself read — a file picker hands a page bytes and never a path, which is why the browser
3688/// cannot offer "attach a file by path". `path` is a reference spelled into the message, because
3689/// the model's own `read_file` is what confines a path to the workspace; `url` is a link, spelled
3690/// out the same way, because `fetch` is the tool that knows what to do with one.
3691///
3692/// `image` travels as the message's own part (`#346`); `audio` and anything else are refused rather
3693/// than accepted and quietly dropped, because the wire has no part for them yet (`docs/TODO.md`,
3694/// "the auxiliaries") — a sound file would arrive as a filename and the model would answer as if it
3695/// had heard something.
3696#[derive(Debug, Deserialize)]
3697struct Attachment {
3698    /// `text`, `path`, `url` or `image`. A row the page disables sends nothing, so a kind outside
3699    /// that list is a bug on the page's side and is refused by name.
3700    kind: String,
3701    /// What the chip is labelled with, and what the composed line quotes. Optional for `path` and
3702    /// `url`, where the value is its own name.
3703    #[serde(default)]
3704    name: String,
3705    #[serde(default)]
3706    value: String,
3707}
3708
3709/// How many things one turn may carry, and how big they may be. The per-item cap is the one a
3710/// paste already lives under (`PASTE_INLINE_LIMIT` is for the box); the total is what the composed
3711/// message may add, so a turn cannot quietly become a document.
3712const MAX_ATTACHMENTS: usize = 8;
3713const MAX_ATTACHMENT_CHARS: usize = 64 * 1024;
3714const MAX_ATTACHED_CHARS: usize = 192 * 1024;
3715
3716/// Fold what the composer attached into the turn's text (`#239`).
3717///
3718/// The shape is deliberately dull: one fenced-off block per item, in the order the chips were in,
3719/// each saying what it is and where it ends. A model reads that as data rather than as part of the
3720/// person's sentence, and a person reading the transcript later can see exactly what was sent.
3721///
3722/// `Err` is a sentence for the operator, not a 500: every refusal here is something the page could
3723/// have prevented, and the point of the sentence is that it says which item and why.
3724fn compose_attachments(
3725    message: &str,
3726    items: &[Attachment],
3727) -> Result<(String, Vec<eclipse_core::message::ImagePart>), String> {
3728    if items.is_empty() {
3729        return Ok((message.to_string(), Vec::new()));
3730    }
3731    if items.len() > MAX_ATTACHMENTS {
3732        return Err(format!(
3733            "at most {MAX_ATTACHMENTS} attachments per turn; this one has {}",
3734            items.len()
3735        ));
3736    }
3737    let mut blocks: Vec<String> = Vec::new();
3738    let mut pictures: Vec<eclipse_core::message::ImagePart> = Vec::new();
3739    let mut added = 0usize;
3740    for item in items {
3741        let name = if item.name.trim().is_empty() {
3742            item.value.trim().to_string()
3743        } else {
3744            item.name.trim().to_string()
3745        };
3746        let block = match item.kind.as_str() {
3747            "text" => {
3748                // One trailing newline is the file's, not a second blank line inside the block.
3749                let body = item.value.trim_end_matches('\n');
3750                let chars = body.chars().count();
3751                if chars > MAX_ATTACHMENT_CHARS {
3752                    return Err(format!(
3753                        "{name} is {chars} characters and the limit is {MAX_ATTACHMENT_CHARS}: \
3754                         attach it as a path and let the agent read the part it needs"
3755                    ));
3756                }
3757                added = added.saturating_add(chars);
3758                format!("--- attached file: {name} ({chars} chars) ---\n{body}\n--- end of {name} ---")
3759            }
3760            "path" => {
3761                let path = item.value.trim();
3762                if path.is_empty() || path.chars().count() > 512 || path.chars().any(char::is_control) {
3763                    return Err(format!(
3764                        "cannot attach {path:?} as a path: a path is one line, at most 512 characters"
3765                    ));
3766                }
3767                format!(
3768                    "--- attached path: {path} (not inlined; read it with read_file if you need it) ---"
3769                )
3770            }
3771            "url" => {
3772                let url = item.value.trim();
3773                let ok = (url.starts_with("http://") || url.starts_with("https://"))
3774                    && url.chars().count() <= 2048
3775                    && !url.chars().any(|c| c.is_whitespace() || c.is_control());
3776                if !ok {
3777                    return Err(format!(
3778                        "cannot attach {url:?} as a link: it has to start with http:// or https:// and hold no spaces"
3779                    ));
3780                }
3781                format!("--- attached link: {url} (fetch it if you need it) ---")
3782            }
3783            // `#346`: a picture is the one kind that is neither a reference nor text, so it
3784            // travels as the message's own part and never as a line in the composed body. Its
3785            // block is a line saying so — the words still have to read sensibly if a model is
3786            // being sent a description instead.
3787            "image" => {
3788                let parts = image_parts(std::slice::from_ref(item))?;
3789                let part = parts.into_iter().next().expect("one item, one part");
3790                // The part's own name, not `name`: that fell back to `item.value` for an unnamed
3791                // item, which for a picture is the entire data URL — so a 2 MB screenshot landed in
3792                // the message text, the store, the preview and the naming call (`#379`).
3793                let label = part.name.clone();
3794                pictures.push(part.clone());
3795                format!("--- attached picture: {label} ({}) ---", part.mime)
3796            }
3797            other => {
3798                return Err(format!(
3799                    "this page cannot attach {other} yet: the request has no part for one, so it would \
3800                     be dropped rather than read. Attach a file, a picture, a path or a link."
3801                ))
3802            }
3803        };
3804        blocks.push(block);
3805    }
3806    if added > MAX_ATTACHED_CHARS {
3807        return Err(format!(
3808            "the attachments add {added} characters and the limit is {MAX_ATTACHED_CHARS}: \
3809             send fewer, or attach the paths instead"
3810        ));
3811    }
3812    // A turn may be attachments alone ("this is the file"), and then there is no sentence to
3813    // separate them from.
3814    let blocks = blocks.join("\n\n");
3815    let head = message.trim_end();
3816    let text = if head.is_empty() {
3817        blocks
3818    } else {
3819        format!("{head}\n\n{blocks}")
3820    };
3821    Ok((text, pictures))
3822}
3823
3824/// The picture types a page may attach, and how big one may carry (`#346`).
3825///
3826/// Turn the composer's `image` rows into parts the message can carry.
3827///
3828/// The rule itself lives in the core (`ImagePart::from_data_url`) and is the same one the gateway
3829/// applies to a caller's `image_url` part (`#364`): the page is the only thing that has read these
3830/// bytes, so they arrive as a `data:` URL or they are not a picture.
3831fn image_parts(items: &[Attachment]) -> Result<Vec<eclipse_core::message::ImagePart>, String> {
3832    items
3833        .iter()
3834        .map(|item| {
3835            eclipse_core::message::ImagePart::from_data_url(item.name.trim(), item.value.trim())
3836        })
3837        .collect()
3838}
3839
3840enum Out {
3841    Event(AgentEvent),
3842    ApprovalRequest {
3843        id: String,
3844        tool: String,
3845        summary: String,
3846        timeout_secs: u64,
3847    },
3848    ApprovalResolved {
3849        id: String,
3850        verdict: Verdict,
3851    },
3852    /// The run stopped because it was cancelled (the browser's Stop button, or the
3853    /// connection closing).
3854    Cancelled,
3855    Failed(String),
3856    Done,
3857}
3858
3859#[derive(Deserialize)]
3860struct Decision {
3861    approved: bool,
3862}
3863
3864/// `POST /api/runs/:id/cancel` stops a chat run. The id is the `run_id` from the `session`
3865/// SSE event. Answers `{"cancelled": true}`; an unknown or already-finished run is 404.
3866async fn cancel_run(State(st): State<Shared>, Path(id): Path<String>) -> Response {
3867    if id.is_empty() || id.len() > 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
3868        return error(StatusCode::BAD_REQUEST, "invalid run id").into_response();
3869    }
3870    let cancel = st
3871        .cancels
3872        .lock()
3873        .unwrap_or_else(|e| e.into_inner())
3874        .get(&id)
3875        .cloned();
3876    match cancel {
3877        Some(cancel) => {
3878            cancel.cancel();
3879            Json(json!({"cancelled": true})).into_response()
3880        }
3881        None => error(StatusCode::NOT_FOUND, "no such run").into_response(),
3882    }
3883}
3884
3885/// `POST /api/approvals/:id` `{"approved": bool}` answers a pending `approval_request`.
3886async fn decide_approval(
3887    State(st): State<Shared>,
3888    Path(id): Path<String>,
3889    Json(decision): Json<Decision>,
3890) -> Response {
3891    if id.is_empty() || id.len() > 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
3892        return error(StatusCode::BAD_REQUEST, "invalid approval id").into_response();
3893    }
3894    if st.approvals.resolve(&id, decision.approved) {
3895        Json(json!({"ok": true})).into_response()
3896    } else {
3897        error(
3898            StatusCode::NOT_FOUND,
3899            "no such pending approval (already answered or expired)",
3900        )
3901        .into_response()
3902    }
3903}
3904
3905fn sse(name: &str, data: serde_json::Value) -> Event {
3906    Event::default().event(name).data(data.to_string())
3907}
3908
3909/// The response body every `POST /api/chat` answer is: one SSE stream, whichever kind of answer it
3910/// is. Boxed because a command's answer and a run are two different streams in one handler — and
3911/// an unboxed `impl Stream` cannot be one of two types.
3912type EventStream = Sse<std::pin::Pin<Box<dyn Stream<Item = Result<Event, Infallible>> + Send>>>;
3913
3914/// A command's whole answer, as the same kind of stream a run uses: one `notice`, then `done`.
3915///
3916/// The page already reads one transport, so a command needs no second one — and a stream that ends
3917/// with `done` returns the composer to idle by the path it already has.
3918fn notice_stream(answer: Answer) -> EventStream {
3919    let events = vec![
3920        Ok(sse(
3921            "notice",
3922            json!({
3923                "text": answer.text,
3924                "kind": if answer.refused { "refusal" } else { "command" },
3925                "clear_session": answer.clear_session,
3926                // `#285`: the page paints the switch from the server's state, never from what was
3927                // typed — a tab that echoed the word it sent would show "on" after a refusal.
3928                "yolo": answer.yolo,
3929            }),
3930        )),
3931        Ok(sse("done", json!({}))),
3932    ];
3933    Sse::new(stream::iter(events).boxed())
3934}
3935
3936/// Streams agent progress as server-sent events: `session`, then `delta` (assistant text
3937/// as it is generated, when the provider streams), `tool_call` / `tool_result` as they
3938/// happen, then `message` (the complete text, always sent) or `error`, then `done`.
3939/// A tool whose policy is "ask" first sends `approval_request` `{id, tool, summary,
3940/// timeout_secs}`; the UI answers via `POST /api/approvals/:id`, and `approval_resolved`
3941/// `{id, outcome}` follows (`approved`, `denied`, `timeout` or `cancelled`).
3942async fn chat(
3943    State(st): State<Shared>,
3944    Json(req): Json<ChatRequest>,
3945) -> Result<EventStream, ApiError> {
3946    // A turn needs words or something attached: a file with no sentence beside it is a real turn
3947    // ("this is the file"), and refusing it would make the `+` menu a decoration (#239).
3948    if req.message.trim().is_empty() && req.attachments.is_empty() {
3949        return Err(error(StatusCode::BAD_REQUEST, "message is empty"));
3950    }
3951    // The commands come first, before the agent is looked for: a verb needs no model. `/help`,
3952    // `/settings` and `/set` are worth having in a dashboard started without a provider — that is
3953    // exactly when a person wants to read the keys back — and each verb that *does* need one says
3954    // so itself, in `verb::serve`'s words rather than this function's 503.
3955    //
3956    // The composer speaks the terminal's commands (`#254`), parsed here so a verb cannot mean one
3957    // thing in the browser and another in a terminal. Three outcomes, and each is the table's:
3958    //
3959    //   * `Run` — execute it and answer with one `notice`. No run, so no session lock, no chat
3960    //     slot and no tokens.
3961    //   * `Elsewhere` — a real command this surface does not have, refused in the table's own
3962    //     words. `/bg` is here now; the dashboard used to special-case it in this function.
3963    //   * `Unknown` — prose, and it reaches the model exactly as before. A line that starts with
3964    //     `/` is not prose, though: the terminal answers `/nope` with "unknown command; try
3965    //     /help" rather than asking the model about it, and this surface did the opposite.
3966    // A `!` line is neither a verb nor prose (`#283`): the dashboard has no bang, and forwarding the
3967    // line would turn "run this" into "ask the model about this" — see `verb::bang_refusal`.
3968    if let Some(answer) = verb::bang_refusal(&req.message) {
3969        return Ok(notice_stream(answer));
3970    }
3971    let parsed = eclipse_core::commands::parse(&req.message, Front::Web);
3972    // A verb runs on its own. An attachment arriving on a command line would be dropped without a
3973    // word — the command answers and the chip is gone — and a chip that disappears is worse than
3974    // one that is refused (#239).
3975    let command_line = matches!(parsed, Parsed::Run(..) | Parsed::Elsewhere(..))
3976        || matches!(&parsed, Parsed::Unknown(line) if line.starts_with('/'));
3977    if command_line && !req.attachments.is_empty() {
3978        return Ok(notice_stream(Answer::refused(
3979            "a command runs on its own: remove the attachment, or send it with a message",
3980        )));
3981    }
3982    match parsed {
3983        Parsed::Run(command, arg) => {
3984            let answer = verb::serve(&st, command, arg, req.session_id.as_deref()).await;
3985            return Ok(notice_stream(answer));
3986        }
3987        Parsed::Elsewhere(command) => {
3988            return Ok(notice_stream(Answer::refused(
3989                command.unavailable_in(Front::Web),
3990            )))
3991        }
3992        Parsed::Unknown(line) if line.starts_with('/') => {
3993            return Ok(notice_stream(Answer::refused("unknown command; try /help")))
3994        }
3995        Parsed::Unknown(_) => {}
3996    }
3997    // What the model is given: the person's words, then one block per attachment, in the order
3998    // the chips were in (#239). A refusal here is a sentence — a path that is not one, a file over
3999    // the cap, a kind the wire has no part for — because every one of them is something the page
4000    // could have caught and the person should be told about rather than see a 500.
4001    let (message, pictures) = compose_attachments(&req.message, &req.attachments)
4002        .map_err(|e| error(StatusCode::BAD_REQUEST, e))?;
4003    let Some(_) = st.agent.clone() else {
4004        return Err(error(StatusCode::SERVICE_UNAVAILABLE, unconfigured(&st)));
4005    };
4006    if req.max_iterations == Some(0) {
4007        return Err(error(
4008            StatusCode::BAD_REQUEST,
4009            "max_iterations must be at least 1: a run allowed no request is not a run",
4010        ));
4011    }
4012    // `#425`: the browser chose the loop bound and only 0 was refused, so a page — or anything
4013    // driving the same route — could ask for ten thousand round-trips and hold the model for as
4014    // long as it liked. Refused rather than clamped: a client that asked for 5000 and silently got
4015    // 200 is being lied to, and the number it is told back is the one that runs.
4016    if let Some(n) = req.max_iterations.filter(|n| *n > MAX_ITERATIONS_BOUND) {
4017        return Err(error(
4018            StatusCode::BAD_REQUEST,
4019            format!(
4020                "max_iterations is at most {MAX_ITERATIONS_BOUND} (asked for {n}): a bound that \
4021                 large is a request for the model, not a turn"
4022            ),
4023        ));
4024    }
4025    let session_id = match req.session_id.filter(|s| !s.is_empty()) {
4026        Some(id) => {
4027            eclipse_core::session::validate_id(&id)
4028                .map_err(|e| error(StatusCode::BAD_REQUEST, e.to_string()))?;
4029            id
4030        }
4031        None => st.store.new_id(),
4032    };
4033    // `#509`: the row decides which agent answers. A session whose `origin` is `bot:<name>` runs
4034    // on that bot's agent — its instructions, its own memory file, the skills it declared — and
4035    // every other session runs on the dashboard's own. The page sends no second field: the
4036    // transcript opened from the Bots tab is the same transcript opened by id.
4037    let agent = match st.agent_for(&session_id) {
4038        Ok(Some(agent)) => agent,
4039        Ok(None) => return Err(error(StatusCode::SERVICE_UNAVAILABLE, unconfigured(&st))),
4040        Err(why) => return Err(error(StatusCode::SERVICE_UNAVAILABLE, why)),
4041    };
4042
4043    let Some(permit) = st.try_chat_slot() else {
4044        return Err(error(
4045            StatusCode::TOO_MANY_REQUESTS,
4046            "too many chats in progress; try again shortly",
4047        ));
4048    };
4049
4050    let (tx, rx) = mpsc::unbounded_channel::<Out>();
4051    let sid = session_id.clone();
4052    let run = st.approvals.next_run.fetch_add(1, Ordering::Relaxed);
4053    // The browser gets this id in the first SSE event and stops the run with
4054    // `POST /api/runs/<run_id>/cancel`.
4055    let run_id = eclipse_core::token::random_hex(16)
4056        .map_err(|e| error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
4057    let cancel = Cancel::new();
4058    st.cancels
4059        .lock()
4060        .unwrap_or_else(|e| e.into_inner())
4061        .insert(run_id.clone(), cancel.clone());
4062    let run_token = run_id.clone();
4063    let guard_cancel = cancel.clone();
4064    // The budget this run gets, decided once: the body's override, else the agent's own.
4065    // It is reported in the `session` event so the dashboard never has to guess.
4066    let budget = req.max_iterations.unwrap_or_else(|| agent.max_iterations());
4067    let opts = RunOptions {
4068        max_iterations: req.max_iterations,
4069        // A dashboard turn always carries a prompt: continuing a paused transcript is what
4070        // `eclipse approve` does, and it is not this path.
4071        resume: false,
4072        // No schema: a chat pane has no type to parse into, so asking for a shape here would be a
4073        // promise nobody checks. `[agent] output_schema` and `run --schema` are the typed door,
4074        // and both judge what they ask for.
4075        output_schema: None,
4076        // The dashboard process outlives the turn, and the name it writes shows up in the sidebar
4077        // a few seconds later: this is exactly the surface the naming call is for.
4078        title: true,
4079        // `#346`: the pictures ride on the user message the run stores, so the transcript still
4080        // shows them and `[vision]` decides what the model is sent.
4081        images: pictures,
4082    };
4083    // `#264`: the denominator and the tripwire are facts about the run, not about a turn, so they
4084    // are read once, here — before the agent is moved into the task. Each `stats` event then hands
4085    // the page `Reading`'s own string, the same call the terminal makes, instead of a second
4086    // percentage computed in JavaScript from whatever number the event happened to carry.
4087    let rail = agent.context_reading(None);
4088    let report = agent.reasoning_report();
4089    tokio::spawn(async move {
4090        let _permit = permit;
4091        let _scope = RunScope {
4092            state: st.clone(),
4093            run,
4094            token: run_token,
4095        };
4096        let events = tx.clone();
4097        let sink = move |e: AgentEvent| {
4098            let _ = events.send(Out::Event(e));
4099        };
4100        let approver = WebApprover {
4101            state: st.clone(),
4102            run,
4103            events: tx.clone(),
4104        };
4105        match agent
4106            .run_cancellable_with(Some(&sid), &message, &approver, &sink, &cancel, &opts)
4107            .await
4108        {
4109            Ok(_) => {}
4110            Err(eclipse_core::Error::Cancelled) => {
4111                let _ = tx.send(Out::Cancelled);
4112            }
4113            Err(e) => {
4114                let _ = tx.send(Out::Failed(e.to_string()));
4115            }
4116        }
4117        let _ = tx.send(Out::Done);
4118    });
4119
4120    let first = stream::once(async move {
4121        Ok::<_, Infallible>(sse(
4122            "session",
4123            json!({"session_id": session_id, "run_id": run_id, "max_iterations": budget}),
4124        ))
4125    });
4126    // Dropping the response (the browser closed the tab, reloaded or navigated away) drops
4127    // this stream and with it the guard, which cancels the run instead of leaving it to
4128    // finish in the background.
4129    let guard = DisconnectGuard {
4130        cancel: guard_cancel,
4131    };
4132    // Both ride in the stream's own state rather than in the closure's captures: `unfold` hands its
4133    // state back to itself, so the reading costs no clone per event and the body below keeps the
4134    // indentation it had.
4135    let state = (rx, guard, rail, report);
4136    let rest = stream::unfold(state, |(mut rx, guard, rail, report)| async move {
4137        let item = rx.recv().await?;
4138        let ev = match item {
4139            Out::Event(AgentEvent::ToolCall {
4140                call_id,
4141                name,
4142                arguments,
4143            }) => {
4144                // The row the page draws is one line, and the line is decided here so it can be
4145                // tested; `arguments` still travels whole for the toggle.
4146                let summary = calls::statement(&name, &arguments);
4147                sse(
4148                    "tool_call",
4149                    json!({
4150                        "call_id": call_id,
4151                        "name": name,
4152                        "arguments": arguments,
4153                        "summary": summary,
4154                    }),
4155                )
4156            }
4157            Out::Event(AgentEvent::ToolResult {
4158                call_id,
4159                name,
4160                output,
4161                is_error,
4162            }) => sse(
4163                "tool_result",
4164                json!({
4165                    "call_id": call_id,
4166                    "name": name,
4167                    // The verdict is the server's, so a live row and the same row replayed from
4168                    // the store carry the same mark: `⊘` for a refusal, `✗` for a break, `✓` for a
4169                    // call that worked. The output travels for the row's toggle, not for the page.
4170                    "state": calls::outcome(&output, Some(is_error)).as_str(),
4171                    "output": output,
4172                    "is_error": is_error,
4173                }),
4174            ),
4175            Out::Event(AgentEvent::Delta(text)) => sse("delta", json!({"text": text})),
4176            Out::Event(AgentEvent::ReasoningDelta(text)) => sse("reasoning", json!({"text": text})),
4177            Out::Event(AgentEvent::ToolCallDelta { index, json }) => {
4178                sse("tool_call_delta", json!({"index": index, "json": json}))
4179            }
4180            Out::Event(AgentEvent::Message(text)) => sse("message", json!({"text": text})),
4181            Out::Event(AgentEvent::TurnStats {
4182                usage,
4183                context_tokens,
4184                budget_tokens,
4185            }) => sse(
4186                "stats",
4187                json!({
4188                    "prompt_tokens": usage.prompt_tokens,
4189                    "completion_tokens": usage.completion_tokens,
4190                    "total_tokens": usage.total_tokens,
4191                    "cached_tokens": usage.cached_tokens,
4192                    "prompt_ms": usage.prompt_ms,
4193                    "completion_ms": usage.completion_ms,
4194                    "latency_ms": usage.latency_ms,
4195                    "ttft_ms": usage.ttft_ms,
4196                    "tokens_per_sec": usage.tokens_per_sec(),
4197                    "context_tokens": context_tokens,
4198                    "budget_tokens": budget_tokens,
4199                    "window_tokens": rail.denominator,
4200                    // The prompt the server counted, else the runtime's estimate — the CLI's
4201                    // preference, in the CLI's own function.
4202                    "ctx": Reading::new(
4203                        usage
4204                            .prompt_tokens
4205                            .or((context_tokens > 0).then_some(context_tokens as u64)),
4206                        rail.denominator,
4207                        rail.marker,
4208                        )
4209                        .text(12),
4210                        "effort": report.label.clone(),
4211                        "effort_detail": report.sentence(),
4212                        "effort_session": report.session,
4213                }),
4214            ),
4215            // The dashboard reports the refusal so a run that took two turns says why it did.
4216            // There is no schema input here yet, so this can only arrive from a config default.
4217            Out::Event(AgentEvent::SchemaRejected { error, retrying }) => sse(
4218                "schema_rejected",
4219                json!({ "error": error, "retrying": retrying }),
4220            ),
4221            Out::Event(AgentEvent::ContextTrimmed {
4222                turns,
4223                messages,
4224                memory,
4225                judgement,
4226            }) => {
4227                let (memory, memory_error) = match memory {
4228                    eclipse_core::MemoryStatus::NotUsed => ("not_used", None),
4229                    eclipse_core::MemoryStatus::Reused => ("reused", None),
4230                    eclipse_core::MemoryStatus::Saved => ("saved", None),
4231                    eclipse_core::MemoryStatus::SaveFailed(e) => ("save_failed", Some(e)),
4232                };
4233                // The judgement pass is the one part of a trim that a model wrote, so the
4234                // dashboard says whether it ran, how much of it survived, and why not.
4235                let (judgement, judgement_bullets, judgement_error) = match judgement {
4236                    eclipse_core::JudgementStatus::Off => ("off", 0, None),
4237                    eclipse_core::JudgementStatus::Used { bullets } => ("used", bullets, None),
4238                    eclipse_core::JudgementStatus::Rejected(e) => ("rejected", 0, Some(e)),
4239                    eclipse_core::JudgementStatus::Failed(e) => ("failed", 0, Some(e)),
4240                };
4241                sse(
4242                    "context_trimmed",
4243                    json!({
4244                        "turns": turns,
4245                        "messages": messages,
4246                        "memory": memory,
4247                        "memory_error": memory_error,
4248                        "judgement": judgement,
4249                        "judgement_bullets": judgement_bullets,
4250                        "judgement_error": judgement_error,
4251                    }),
4252                )
4253            }
4254            Out::ApprovalRequest {
4255                id,
4256                tool,
4257                summary,
4258                timeout_secs,
4259            } => sse(
4260                "approval_request",
4261                json!({"id": id, "tool": tool, "summary": summary, "timeout_secs": timeout_secs}),
4262            ),
4263            Out::ApprovalResolved { id, verdict } => sse(
4264                "approval_resolved",
4265                json!({"id": id, "outcome": verdict.as_str()}),
4266            ),
4267            Out::Cancelled => sse("cancelled", json!({})),
4268            Out::Failed(message) => sse("error", json!({"message": message})),
4269            Out::Done => sse("done", json!({})),
4270        };
4271        Some((Ok::<_, Infallible>(ev), (rx, guard, rail, report)))
4272    });
4273    Ok(Sse::new(first.chain(rest).boxed()).keep_alive(KeepAlive::default()))
4274}
4275
4276#[cfg(test)]
4277mod tests {
4278    use super::*;
4279    use async_trait::async_trait;
4280    use axum::body::Body;
4281    use axum::http::Request as HttpRequest;
4282    use eclipse_core::error::Result as CoreResult;
4283    use eclipse_core::message::Message;
4284    use eclipse_core::provider::ChatProvider;
4285    use eclipse_core::session::SessionStore;
4286    use eclipse_core::tools::{ToolRegistry, ToolSpec};
4287    use eclipse_core::usage::TurnUsage;
4288    use tower::ServiceExt;
4289
4290    struct Canned;
4291
4292    #[async_trait]
4293    impl ChatProvider for Canned {
4294        async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
4295            Ok(Message::assistant("canned reply"))
4296        }
4297    }
4298
4299    /// Says what a warm llama.cpp server says: a prompt with a cached prefix, decode timings,
4300    /// and a measured wall time. Nothing is estimated here — these are the numbers the footer
4301    /// has to print, and the ones a browser run is checked against by eye.
4302    struct Measured;
4303
4304    #[async_trait]
4305    impl ChatProvider for Measured {
4306        async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
4307            unreachable!()
4308        }
4309        async fn chat_stream(
4310            &self,
4311            _: &[Message],
4312            _: &[ToolSpec],
4313            on_delta: eclipse_core::stream::DeltaFn<'_>,
4314        ) -> CoreResult<Message> {
4315            // A real pause, so the client's own time-to-first-token is a number rather than 0:
4316            // the runtime measures `ttft_ms` itself and ignores whatever a provider claims.
4317            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
4318            on_delta(eclipse_core::stream::Delta::Text("measured ".into()));
4319            on_delta(eclipse_core::stream::Delta::Text("reply".into()));
4320            Ok(Message::assistant("measured reply"))
4321        }
4322
4323        fn take_usage(&self) -> Option<TurnUsage> {
4324            // Named so the numbers are not bare literals after a `*_tokens` key: a file write
4325            // that puts `tokens: 30000` on a line reads like a secret assignment to the
4326            // redactor on the way in.
4327            let prompt = 30_000_u64;
4328            let total = 30_120_u64;
4329            let cached = 19_000_u64;
4330            Some(TurnUsage {
4331                prompt_tokens: Some(prompt),
4332                completion_tokens: Some(120),
4333                total_tokens: Some(total),
4334                cached_tokens: Some(cached),
4335                prompt_ms: Some(300),
4336                completion_ms: Some(2_500),
4337                latency_ms: 2_900,
4338                ttft_ms: Some(1_500),
4339            })
4340        }
4341    }
4342
4343    /// Replays scripted replies, one per model call.
4344    struct Scripted(Mutex<Vec<Message>>);
4345
4346    impl Scripted {
4347        fn new(mut replies: Vec<Message>) -> Arc<Self> {
4348            replies.reverse();
4349            Arc::new(Self(Mutex::new(replies)))
4350        }
4351    }
4352
4353    #[async_trait]
4354    impl ChatProvider for Scripted {
4355        async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
4356            Ok(self.0.lock().unwrap().pop().expect("script exhausted"))
4357        }
4358    }
4359
4360    struct Streaming;
4361
4362    #[async_trait]
4363    impl ChatProvider for Streaming {
4364        async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
4365            unreachable!()
4366        }
4367        async fn chat_stream(
4368            &self,
4369            _: &[Message],
4370            _: &[ToolSpec],
4371            on_delta: eclipse_core::stream::DeltaFn<'_>,
4372        ) -> CoreResult<Message> {
4373            on_delta(eclipse_core::stream::Delta::Text("tok".into()));
4374            on_delta(eclipse_core::stream::Delta::Text("ens".into()));
4375            Ok(Message::assistant("tokens"))
4376        }
4377    }
4378
4379    /// Never answers: a run against it stays in flight until something cancels it.
4380    /// `entered` is set when the model call starts, `dropped` when that call's future is
4381    /// dropped — which is exactly what cancellation does to it.
4382    struct Hangs {
4383        entered: Arc<std::sync::atomic::AtomicBool>,
4384        dropped: Arc<std::sync::atomic::AtomicBool>,
4385    }
4386
4387    struct MarkDropped(Arc<std::sync::atomic::AtomicBool>);
4388
4389    impl Drop for MarkDropped {
4390        fn drop(&mut self) {
4391            self.0.store(true, Ordering::SeqCst);
4392        }
4393    }
4394
4395    #[async_trait]
4396    impl ChatProvider for Hangs {
4397        async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
4398            unreachable!()
4399        }
4400        async fn chat_stream(
4401            &self,
4402            _: &[Message],
4403            _: &[ToolSpec],
4404            _: eclipse_core::stream::DeltaFn<'_>,
4405        ) -> CoreResult<Message> {
4406            self.entered.store(true, Ordering::SeqCst);
4407            let _dropped = MarkDropped(self.dropped.clone());
4408            tokio::time::sleep(Duration::from_secs(600)).await;
4409            Ok(Message::assistant("too late"))
4410        }
4411    }
4412
4413    /// A dashboard whose provider never answers, plus the two flags to watch it with.
4414    fn hanging_state(
4415        dir: &std::path::Path,
4416    ) -> (
4417        Shared,
4418        Arc<std::sync::atomic::AtomicBool>,
4419        Arc<std::sync::atomic::AtomicBool>,
4420    ) {
4421        let store = SessionStore::new(dir.join("sessions"));
4422        let entered = Arc::new(std::sync::atomic::AtomicBool::new(false));
4423        let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false));
4424        let agent = Agent::new(
4425            Arc::new(Hangs {
4426                entered: entered.clone(),
4427                dropped: dropped.clone(),
4428            }),
4429            Arc::new(ToolRegistry::default()),
4430            store.clone(),
4431            "sys".into(),
4432            3,
4433        );
4434        let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
4435        (st, entered, dropped)
4436    }
4437
4438    /// Poll a flag for up to `ms`, so a test never depends on a fixed sleep being enough.
4439    async fn wait_for(flag: &Arc<std::sync::atomic::AtomicBool>, ms: u64) -> bool {
4440        for _ in 0..(ms / 20) {
4441            if flag.load(Ordering::SeqCst) {
4442                return true;
4443            }
4444            tokio::time::sleep(Duration::from_millis(20)).await;
4445        }
4446        flag.load(Ordering::SeqCst)
4447    }
4448
4449    fn cancel_req(run_id: &str) -> HttpRequest<Body> {
4450        HttpRequest::post(format!("/api/runs/{run_id}/cancel"))
4451            .header("host", "127.0.0.1:8787")
4452            .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
4453            .body(Body::empty())
4454            .unwrap()
4455    }
4456
4457    const TOKEN: &str = "0123456789abcdef0123456789abcdef";
4458    const LOGIN_ID: &str = "test-login-id";
4459
4460    fn authed(
4461        agent: Option<Arc<Agent>>,
4462        store: SessionStore,
4463        model: &str,
4464        config_error: Option<String>,
4465    ) -> AppState {
4466        AppState::new(
4467            agent,
4468            store,
4469            model.into(),
4470            config_error,
4471            TOKEN.into(),
4472            std::time::Duration::from_secs(
4473                eclipse_core::config::DEFAULT_SESSION_TTL_HOURS * 60 * 60,
4474            ),
4475        )
4476        .with_login(LOGIN_ID)
4477    }
4478
4479    fn state(dir: &std::path::Path, configured: bool) -> Shared {
4480        state_with(dir, configured, None)
4481    }
4482
4483    /// State whose login throttle waits on test-sized delays instead of seconds.
4484    fn state_throttled(dir: &std::path::Path, throttle: LoginThrottle) -> Shared {
4485        match Arc::try_unwrap(state(dir, true)) {
4486            Ok(mut st) => {
4487                st.throttle = throttle;
4488                Arc::new(st)
4489            }
4490            Err(_) => panic!("a state built here is not shared yet"),
4491        }
4492    }
4493
4494    /// The same router state, with a config file the settings endpoints can read and write.
4495    fn state_with(
4496        dir: &std::path::Path,
4497        configured: bool,
4498        config: Option<std::path::PathBuf>,
4499    ) -> Shared {
4500        let store = SessionStore::new(dir.join("sessions"));
4501        let agent = configured.then(|| {
4502            Arc::new(Agent::new(
4503                Arc::new(Canned),
4504                Arc::new(ToolRegistry::default()),
4505                store.clone(),
4506                "sys".into(),
4507                3,
4508            ))
4509        });
4510        Arc::new(
4511            authed(
4512                agent,
4513                store,
4514                "test-<model>",
4515                (!configured).then(|| "provider.base_url is not set".into()),
4516            )
4517            .with_config_path(config, None),
4518        )
4519    }
4520
4521    /// The response body as text: the refusals are read by a person, so what they say is tested.
4522    ///
4523    /// The cap is generous because the page itself is one: it carries the CSS, the palette and the
4524    /// script, so it grew past 64 KB when the cron pane moved in — and a body over the limit is
4525    /// silently empty here, which reads as "the server said nothing" rather than "the test was
4526    /// too small".
4527    async fn body_text(r: Response) -> String {
4528        let bytes = axum::body::to_bytes(r.into_body(), 512 * 1024)
4529            .await
4530            .unwrap_or_default();
4531        String::from_utf8_lossy(&bytes).into_owned()
4532    }
4533
4534    /// The same state, with an update watch over a state directory the test can fill.
4535    fn state_watching(dir: &std::path::Path, check: eclipse_core::config::UpdateCheck) -> Shared {
4536        let store = SessionStore::new(dir.join("sessions"));
4537        let mut st = authed(None, store, "test-<model>", None);
4538        st.update = Some(eclipse_core::update::Watch::at(
4539            dir.join("state"),
4540            &eclipse_core::config::UpdateConfig {
4541                check,
4542                track: eclipse_core::config::Track::Release,
4543                remote: None,
4544                releases: Some("http://127.0.0.1:1/latest".into()),
4545            },
4546        ));
4547        Arc::new(st)
4548    }
4549
4550    /// `GET /api/update` is a read of the two files the CLI reads, and it says the same thing
4551    /// they say: same numbers, same comparison, no request of its own.
4552    #[tokio::test]
4553    async fn api_update_reports_the_cache_the_cli_would_show() {
4554        let dir = tempfile::tempdir().unwrap();
4555        let state = dir.path().join("state");
4556        std::fs::create_dir_all(&state).unwrap();
4557        std::fs::write(
4558            state.join("install.json"),
4559            r#"{"channel":"release","prefix":"/x","installed_at":"t","version":"0.2.0"}"#,
4560        )
4561        .unwrap();
4562        let now = eclipse_core::session::now_ms() / 1000;
4563        std::fs::write(
4564            state.join("update.json"),
4565            format!(r#"{{"checked_at":{now},"latest":"v0.3.0"}}"#),
4566        )
4567        .unwrap();
4568
4569        let app = router(state_watching(
4570            dir.path(),
4571            eclipse_core::config::UpdateCheck::Daily,
4572        ));
4573        let resp = app
4574            .clone()
4575            .oneshot(get_req("/api/update", "127.0.0.1:8787"))
4576            .await
4577            .unwrap();
4578        assert_eq!(resp.status(), StatusCode::OK);
4579        let body: serde_json::Value = serde_json::from_str(&text(resp).await).unwrap();
4580        assert_eq!(body["installed"], "0.2.0");
4581        assert_eq!(body["latest"], "v0.3.0");
4582        assert_eq!(body["behind"], true, "the same answer the CLI badges");
4583        assert_eq!(body["channel"], "release");
4584        assert_eq!(body["checked_at"], now);
4585
4586        // Read-only: the path answers GET and nothing else, so a badge cannot be a button.
4587        let post = HttpRequest::post("/api/update")
4588            .header("host", "127.0.0.1:8787")
4589            .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
4590            .header("origin", "http://127.0.0.1:8787")
4591            .body(Body::empty())
4592            .unwrap();
4593        let resp = app.oneshot(post).await.unwrap();
4594        assert_eq!(
4595            resp.status(),
4596            StatusCode::METHOD_NOT_ALLOWED,
4597            "nothing writes this endpoint"
4598        );
4599    }
4600
4601    /// The switch the user asked for: `[update] check = "off"` means no badge, even though the
4602    /// cache still holds an answer that would otherwise be one.
4603    #[tokio::test]
4604    async fn api_update_shows_nothing_when_the_check_is_off() {
4605        let dir = tempfile::tempdir().unwrap();
4606        let state = dir.path().join("state");
4607        std::fs::create_dir_all(&state).unwrap();
4608        std::fs::write(
4609            state.join("install.json"),
4610            r#"{"channel":"release","prefix":"/x","installed_at":"t","version":"0.2.0"}"#,
4611        )
4612        .unwrap();
4613        let now = eclipse_core::session::now_ms() / 1000;
4614        std::fs::write(
4615            state.join("update.json"),
4616            format!(r#"{{"checked_at":{now},"latest":"v0.3.0"}}"#),
4617        )
4618        .unwrap();
4619
4620        let app = router(state_watching(
4621            dir.path(),
4622            eclipse_core::config::UpdateCheck::Off,
4623        ));
4624        let resp = app
4625            .oneshot(get_req("/api/update", "127.0.0.1:8787"))
4626            .await
4627            .unwrap();
4628        assert_eq!(resp.status(), StatusCode::OK);
4629        let body: serde_json::Value = serde_json::from_str(&text(resp).await).unwrap();
4630        assert_eq!(body["behind"], false, "the user said not to be told");
4631        assert_eq!(body["latest"], serde_json::Value::Null);
4632    }
4633
4634    /// `GET /api/sessions/:id` is what the page replays a session from. It carries the stored
4635    /// messages exactly as the provider would see them, with one statement per tool call in a
4636    /// `calls` array beside them — so the row on screen is the server's rule, and the arguments
4637    /// inside the message stay byte-identical to what was stored and what a request would send.
4638    #[tokio::test]
4639    async fn a_stored_session_carries_a_statement_beside_each_call() {
4640        let dir = tempfile::tempdir().unwrap();
4641        let st = state(dir.path(), true);
4642        let store = st.agent.as_ref().unwrap().store().clone();
4643        let id = store.new_id();
4644        let arguments = r#"{"path":"crates/x/src/session.rs","content":"abc"}"#;
4645        store.append(&id, &Message::user("write it")).unwrap();
4646        store
4647            .append(
4648                &id,
4649                &Message::assistant_tool_calls(
4650                    None,
4651                    vec![eclipse_core::message::ToolCall {
4652                        id: "c1".into(),
4653                        kind: "function".into(),
4654                        function: eclipse_core::message::FunctionCall {
4655                            name: "write_file".into(),
4656                            arguments: arguments.into(),
4657                        },
4658                    }],
4659                ),
4660            )
4661            .unwrap();
4662        store
4663            .append(&id, &Message::tool_result("c1", "wrote it"))
4664            .unwrap();
4665        let app = router(st);
4666
4667        let r = app
4668            .clone()
4669            .oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
4670            .await
4671            .unwrap();
4672        assert_eq!(r.status(), StatusCode::OK);
4673        let body: Vec<serde_json::Value> = serde_json::from_str(&text(r).await).unwrap();
4674        assert_eq!(body.len(), 3, "the whole transcript, oldest first");
4675        assert!(
4676            body[0].get("calls").is_none(),
4677            "a message with no calls grows no array"
4678        );
4679        assert_eq!(
4680            body[1]["calls"][0]["summary"], "write_file crates/x/src/session.rs · 3 B",
4681            "the statement the page puts on the row"
4682        );
4683        assert_eq!(
4684            body[1]["calls"][0]["state"], "ok",
4685            "and the verdict, so the row's mark is right on replay and not only live"
4686        );
4687        assert_eq!(
4688            body[1]["tool_calls"][0]["function"]["arguments"], arguments,
4689            "and the arguments are exactly what the store holds, for the toggle"
4690        );
4691        assert_eq!(body[2]["content"], "wrote it", "a result is unaffected");
4692    }
4693
4694    /// The verdict is read off a stored result because the message carries no `is_error`: a shell
4695    /// call opens with its exit code and a refusal says the user declined. A call with no result
4696    /// yet is still running — the state a session that died mid-call should show.
4697    #[tokio::test]
4698    async fn a_replayed_session_marks_each_call_the_way_it_ended() {
4699        let dir = tempfile::tempdir().unwrap();
4700        let st = state(dir.path(), true);
4701        let store = st.agent.as_ref().unwrap().store().clone();
4702        let id = store.new_id();
4703        let call = |id: &str| eclipse_core::message::ToolCall {
4704            id: id.into(),
4705            kind: "function".into(),
4706            function: eclipse_core::message::FunctionCall {
4707                name: "shell".into(),
4708                arguments: r#"{"command":"date"}"#.into(),
4709            },
4710        };
4711        store.append(&id, &Message::user("three of them")).unwrap();
4712        store
4713            .append(
4714                &id,
4715                &Message::assistant_tool_calls(None, vec![call("a"), call("b"), call("c")]),
4716            )
4717            .unwrap();
4718        store
4719            .append(
4720                &id,
4721                &Message::tool_result("a", "exit code: 0\nstdout:\nMon Nov 30\n"),
4722            )
4723            .unwrap();
4724        store
4725            .append(
4726                &id,
4727                &Message::tool_result("b", "exit code: 2\nstdout:\n\nstderr:\nno\n"),
4728            )
4729            .unwrap();
4730        store
4731            .append(
4732                &id,
4733                &Message::tool_result("c", "the user declined to run `shell`: that is a delete"),
4734            )
4735            .unwrap();
4736        let app = router(st);
4737
4738        let r = app
4739            .clone()
4740            .oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
4741            .await
4742            .unwrap();
4743        let body: Vec<serde_json::Value> = serde_json::from_str(&text(r).await).unwrap();
4744        let states: Vec<&str> = body[1]["calls"]
4745            .as_array()
4746            .unwrap()
4747            .iter()
4748            .map(|c| c["state"].as_str().unwrap())
4749            .collect();
4750        assert_eq!(
4751            states,
4752            ["ok", "failed", "refused"],
4753            "the exit code and the refusal are read off the text, one mark each"
4754        );
4755        assert_eq!(
4756            body[1]["calls"][2]["summary"], "shell date",
4757            "and every row still has its statement"
4758        );
4759    }
4760
4761    /// `#447`: a `read_file` that failed stores a bare sentence — no exit code, no denial — so the
4762    /// text says nothing about whether it worked, and the replayed row drew ✓ over a call that
4763    /// broke. The verdict is recorded beside the message now, and the text stays the fallback for
4764    /// sessions written before that was kept.
4765    #[tokio::test]
4766    async fn a_replayed_failure_with_no_exit_code_is_marked_failed() {
4767        let dir = tempfile::tempdir().unwrap();
4768        let st = state(dir.path(), true);
4769        let store = st.agent.as_ref().unwrap().store().clone();
4770        let id = store.new_id();
4771        let call = |call_id: &str| eclipse_core::message::ToolCall {
4772            id: call_id.into(),
4773            kind: "function".into(),
4774            function: eclipse_core::message::FunctionCall {
4775                name: "read_file".into(),
4776                arguments: r#"{"path":"gone.txt"}"#.into(),
4777            },
4778        };
4779        store.append(&id, &Message::user("read two files")).unwrap();
4780        store
4781            .append(
4782                &id,
4783                &Message::assistant_tool_calls(None, vec![call("a"), call("b")]),
4784            )
4785            .unwrap();
4786        // `a`: the record says it broke. `b`: nothing on record, which is the old shape.
4787        store
4788            .append(&id, &Message::tool_result("a", "no such file: gone.txt"))
4789            .unwrap();
4790        store.set_tool_outcome(&id, "a", true).unwrap();
4791        store
4792            .append(&id, &Message::tool_result("b", "no such file: gone.txt"))
4793            .unwrap();
4794        let app = router(st);
4795
4796        let r = app
4797            .oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
4798            .await
4799            .unwrap();
4800        let body: Vec<serde_json::Value> = serde_json::from_str(&text(r).await).unwrap();
4801        let states: Vec<&str> = body[1]["calls"]
4802            .as_array()
4803            .unwrap()
4804            .iter()
4805            .map(|c| c["state"].as_str().unwrap())
4806            .collect();
4807        assert_eq!(
4808            states,
4809            ["failed", "ok"],
4810            "the record decides when there is one; without it the text still guesses"
4811        );
4812    }
4813
4814    /// A call whose result never landed is running, not ok: a session that ended mid-call must not
4815    /// claim the call worked.
4816    #[tokio::test]
4817    async fn a_call_with_no_result_is_still_running() {
4818        let dir = tempfile::tempdir().unwrap();
4819        let st = state(dir.path(), true);
4820        let store = st.agent.as_ref().unwrap().store().clone();
4821        let id = store.new_id();
4822        store
4823            .append(
4824                &id,
4825                &Message::assistant_tool_calls(
4826                    None,
4827                    vec![eclipse_core::message::ToolCall {
4828                        id: "c1".into(),
4829                        kind: "function".into(),
4830                        function: eclipse_core::message::FunctionCall {
4831                            name: "shell".into(),
4832                            arguments: r#"{"command":"sleep 900"}"#.into(),
4833                        },
4834                    }],
4835                ),
4836            )
4837            .unwrap();
4838        let app = router(st);
4839
4840        let r = app
4841            .clone()
4842            .oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
4843            .await
4844            .unwrap();
4845        let body: Vec<serde_json::Value> = serde_json::from_str(&text(r).await).unwrap();
4846        assert_eq!(body[0]["calls"][0]["state"], "running");
4847    }
4848
4849    #[test]
4850    fn the_refusal_names_which_check_failed_and_what_arrived() {
4851        let logins = Logins::new(Duration::from_secs(60));
4852        let post = Method::POST;
4853        let at = |h: Option<&str>, o: Option<&str>| {
4854            arrival_refusal(&logins, &post, "/api/chat", h, o, None, None)
4855        };
4856
4857        let no_host = at(None, None).expect("refused");
4858        assert!(no_host.contains("no Host header"), "{no_host}");
4859        let foreign = at(Some("dash.example.com"), None).expect("refused");
4860        assert!(foreign.contains("dash.example.com"), "{foreign}");
4861        let cross_site =
4862            at(Some("127.0.0.1:8787"), Some("http://127.0.0.1:9999")).expect("refused");
4863        assert!(
4864            cross_site.contains("Origin") && cross_site.contains("9999"),
4865            "{cross_site}"
4866        );
4867
4868        // `null` is its own case and says what it means, because a person reading it has to decide
4869        // whether they are in an embedded pane or under attack.
4870        let anonymous = at(Some("127.0.0.1:8787"), Some("null")).expect("refused");
4871        assert!(anonymous.contains("Origin \"null\""), "{anonymous}");
4872        assert!(
4873            anonymous.contains(CSRF_HEADER),
4874            "and names the token that would have let it through: {anonymous}"
4875        );
4876
4877        // A plain navigation sends no Origin; the same authority under either scheme is this
4878        // dashboard; a trailing dot is the same name.
4879        assert!(at(Some("localhost:8787"), None).is_none());
4880        assert!(at(Some("127.0.0.1:8787"), Some("http://127.0.0.1:8787")).is_none());
4881        assert!(at(Some("127.0.0.1:8787"), Some("https://127.0.0.1:8787")).is_none());
4882        assert!(at(Some("localhost.:8787"), Some("http://localhost.:8787")).is_none());
4883    }
4884
4885    #[test]
4886    fn reading_is_never_refused_and_signing_in_survives_a_null_origin() {
4887        let logins = Logins::new(Duration::from_secs(60));
4888        let at = |m: Method, path: &str, o: Option<&str>| {
4889            arrival_refusal(&logins, &m, path, Some("127.0.0.1:8787"), o, None, None)
4890        };
4891        // A cross-site GET changes nothing, and `SameSite=Strict` means it does not even carry the
4892        // cookie; refusing it would only break the page that a browser renders inside a frame.
4893        assert!(at(Method::GET, "/api/sessions", Some("https://evil.example")).is_none());
4894        // Signing in: the token in the body is the credential, so a sender with no origin gains
4895        // nothing a guesser could not, and refusing it locks out an embedded pane for no reason.
4896        assert!(at(Method::POST, "/login", Some("null")).is_none());
4897        // A named foreign origin on the login route is still refused: nothing legitimate does that.
4898        assert!(at(Method::POST, "/login", Some("https://evil.example")).is_some());
4899    }
4900
4901    #[test]
4902    fn the_csrf_token_is_what_lets_an_anonymous_origin_change_something() {
4903        let logins = Logins::new(Duration::from_secs(60));
4904        let (id, csrf) = logins.create().expect("session");
4905        let at = |o: &str, presented: Option<&str>, session: &str| {
4906            arrival_refusal(
4907                &logins,
4908                &Method::POST,
4909                "/api/chat",
4910                Some("127.0.0.1:8787"),
4911                Some(o),
4912                presented,
4913                Some(session),
4914            )
4915        };
4916        assert!(
4917            at("null", Some(&csrf), &id).is_none(),
4918            "the session token is the second lock"
4919        );
4920        assert!(at("https://evil.example", Some(&csrf), &id).is_none());
4921        assert!(at("null", None, &id).is_some(), "no token, no entry");
4922        assert!(at("null", Some("not-the-token"), &id).is_some());
4923        assert!(at("null", Some(&csrf), "some-other-session").is_some());
4924
4925        // Another session's token is not this session's token.
4926        let (other, other_csrf) = logins.create().expect("session");
4927        assert_ne!(other, id);
4928        assert!(at("null", Some(&other_csrf), &id).is_some());
4929    }
4930
4931    /// A signed-in cookie jar and the page's CSRF token, for a router built on `dir`.
4932    async fn sign_in(app: &axum::Router) -> (String, String) {
4933        let r = app
4934            .clone()
4935            .oneshot(
4936                HttpRequest::post("/login")
4937                    .header("host", "127.0.0.1:8787")
4938                    .header("content-type", "application/x-www-form-urlencoded")
4939                    .body(Body::from(format!("token={TOKEN}")))
4940                    .unwrap(),
4941            )
4942            .await
4943            .unwrap();
4944        assert_eq!(r.status(), StatusCode::SEE_OTHER, "signed in");
4945        let cookie = r
4946            .headers()
4947            .get(header::SET_COOKIE)
4948            .and_then(|v| v.to_str().ok())
4949            .expect("a session cookie")
4950            .to_string();
4951        let jar = cookie.split(';').next().unwrap().to_string();
4952        let page = body_text(
4953            app.clone()
4954                .oneshot(
4955                    HttpRequest::get("/")
4956                        .header("host", "127.0.0.1:8787")
4957                        .header("cookie", &jar)
4958                        .body(Body::empty())
4959                        .unwrap(),
4960                )
4961                .await
4962                .unwrap(),
4963        )
4964        .await;
4965        let csrf = csrf_of(&page);
4966        (jar, csrf)
4967    }
4968
4969    #[tokio::test]
4970    async fn the_settings_endpoints_read_the_file_write_it_and_never_show_a_secret() {
4971        let dir = tempfile::tempdir().unwrap();
4972        let config_path = dir.path().join("config.toml");
4973        std::fs::write(
4974            &config_path,
4975            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"seed\"\n",
4976        )
4977        .unwrap();
4978        let app = router(state_with(dir.path(), true, Some(config_path.clone())));
4979        let (jar, csrf) = sign_in(&app).await;
4980
4981        // GET: the catalogue `/settings` prints and `config keys` lists.
4982        let body = body_text(
4983            app.clone()
4984                .oneshot(
4985                    HttpRequest::get("/api/settings")
4986                        .header("host", "127.0.0.1:8787")
4987                        .header("cookie", &jar)
4988                        .body(Body::empty())
4989                        .unwrap(),
4990                )
4991                .await
4992                .unwrap(),
4993        )
4994        .await;
4995        let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
4996        let keys: Vec<&str> = parsed["settings"]
4997            .as_array()
4998            .expect("a settings array")
4999            .iter()
5000            .filter_map(|s| s["key"].as_str())
5001            .collect();
5002        assert!(keys.contains(&"provider.model"), "{keys:?}");
5003
5004        // POST: one key, typed the way a person types it — the same parse `config set` uses.
5005        let written = body_text(
5006            app.clone()
5007                .oneshot(
5008                    HttpRequest::post("/api/settings")
5009                        .header("host", "127.0.0.1:8787")
5010                        .header("cookie", &jar)
5011                        .header("x-eclipse-csrf", &csrf)
5012                        .header("content-type", "application/json")
5013                        .body(Body::from(
5014                            r#"{"key":"provider.model","value":"qwen3-coder"}"#,
5015                        ))
5016                        .unwrap(),
5017                )
5018                .await
5019                .unwrap(),
5020        )
5021        .await;
5022        let parsed: serde_json::Value = serde_json::from_str(&written).expect("json");
5023        assert_eq!(parsed["key"], "provider.model");
5024        assert_eq!(parsed["value"], "\"qwen3-coder\"");
5025        assert_eq!(parsed["is_default"], false);
5026        // The file, not a copy in memory: this is what the next run loads.
5027        let on_disk = std::fs::read_to_string(&config_path).unwrap();
5028        assert!(on_disk.contains("qwen3-coder"), "{on_disk}");
5029    }
5030
5031    /// `#571`: under a profile, every dashboard config write landed in the shared base
5032    /// `config.toml`. `apply_setting` and `mcp_edit` read and saved `config_path` directly, and
5033    /// `config_path` is the base the process was started with — so a key the profile's overlay
5034    /// pinned made the reload answer with the *unchanged* value while every other profile's file
5035    /// was being edited. `config set` under the same profile writes the overlay; the page now asks
5036    /// the same function.
5037    #[tokio::test]
5038    async fn a_settings_write_under_a_profile_lands_in_that_profiles_overlay() {
5039        let dir = tempfile::tempdir().unwrap();
5040        let root = dir.path().join("home/.eclipse");
5041        std::fs::create_dir_all(&root).unwrap();
5042        let base = root.join("config.toml");
5043        let before = "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"seed\"\n";
5044        std::fs::write(&base, before).unwrap();
5045        let overlay = root.join("profiles/work/config.toml");
5046
5047        let st = match Arc::try_unwrap(state(dir.path(), true)) {
5048            Ok(st) => st,
5049            Err(_) => panic!("a state built here is not shared yet"),
5050        }
5051        .with_config_path(Some(base.clone()), Some("work".into()))
5052        .with_config_targets(false, Some(root.clone()));
5053        let app = router(Arc::new(st));
5054        let (jar, csrf) = sign_in(&app).await;
5055
5056        let written = body_text(
5057            app.clone()
5058                .oneshot(
5059                    HttpRequest::post("/api/settings")
5060                        .header("host", "127.0.0.1:8787")
5061                        .header("cookie", &jar)
5062                        .header("x-eclipse-csrf", &csrf)
5063                        .header("content-type", "application/json")
5064                        .body(Body::from(
5065                            r#"{"key":"provider.model","value":"work-model"}"#,
5066                        ))
5067                        .unwrap(),
5068                )
5069                .await
5070                .unwrap(),
5071        )
5072        .await;
5073        assert_eq!(
5074            serde_json::from_str::<serde_json::Value>(&written).expect("json")["key"],
5075            "provider.model",
5076            "the write answered for the key it was given: {written}"
5077        );
5078
5079        // The overlay holds it, and the base file is byte-identical: no other profile moved.
5080        let overlay_text = std::fs::read_to_string(&overlay).expect("the overlay was written");
5081        assert!(overlay_text.contains("work-model"), "{overlay_text}");
5082        assert_eq!(
5083            std::fs::read_to_string(&base).unwrap(),
5084            before,
5085            "the shared base file was not touched"
5086        );
5087        // ...and the profile reads it: base + overlay is where this value now comes from. The
5088        // loader is handed the same root the dashboard was, so this is the answer the page's own
5089        // read-back gives on a machine where the process env is the one that built the state.
5090        let home = root.parent().unwrap().display().to_string();
5091        let env = |key: &str| match key {
5092            "HOME" => Some(home.clone()),
5093            _ => None,
5094        };
5095        let loaded =
5096            eclipse_core::config::Config::load_with_profile(Some(&base), Some("work"), &env)
5097                .expect("the profile loads");
5098        assert_eq!(loaded.provider.model, "work-model");
5099
5100        // The MCP pane names the same file, because that is where the entry it writes would go.
5101        let listing = body_text(
5102            app.clone()
5103                .oneshot(
5104                    HttpRequest::get("/api/mcp")
5105                        .header("host", "127.0.0.1:8787")
5106                        .header("cookie", &jar)
5107                        .body(Body::empty())
5108                        .unwrap(),
5109                )
5110                .await
5111                .unwrap(),
5112        )
5113        .await;
5114        let parsed: serde_json::Value = serde_json::from_str(&listing).expect("json");
5115        assert_eq!(parsed["config_path"], overlay.display().to_string());
5116    }
5117
5118    /// The other half, so "writes go to the overlay" does not become "writes never go to the base":
5119    /// with no profile served, the same write lands in the file the process was started with.
5120    #[tokio::test]
5121    async fn a_settings_write_with_no_profile_still_lands_in_the_file_it_was_started_with() {
5122        let dir = tempfile::tempdir().unwrap();
5123        let root = dir.path().join("home/.eclipse");
5124        std::fs::create_dir_all(&root).unwrap();
5125        let base = root.join("config.toml");
5126        std::fs::write(
5127            &base,
5128            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"seed\"\n",
5129        )
5130        .unwrap();
5131
5132        let st = match Arc::try_unwrap(state(dir.path(), true)) {
5133            Ok(st) => st,
5134            Err(_) => panic!("a state built here is not shared yet"),
5135        }
5136        .with_config_path(Some(base.clone()), None)
5137        .with_config_targets(false, Some(root.clone()));
5138        let st = Arc::new(st);
5139        let _app = router(st.clone());
5140
5141        let written = apply_setting(&st, "provider.model", Some("base-model")).await;
5142        assert!(written.is_ok(), "{written:?}");
5143        let on_disk = std::fs::read_to_string(&base).unwrap();
5144        assert!(on_disk.contains("base-model"), "{on_disk}");
5145        assert!(
5146            !root.join("profiles").exists(),
5147            "nothing was created for a profile nobody serves"
5148        );
5149    }
5150
5151    /// `#399`: a setting is a read-edit-write over the whole file, so two of them at once both read
5152    /// the old text and the later write drops the earlier one — a setting the user saw confirmed,
5153    /// gone, with no error anywhere. The lock is what serialises them; this holds it and watches the
5154    /// write wait, which is deterministic where racing two real writes would not be.
5155    #[tokio::test]
5156    async fn a_settings_write_waits_for_the_one_already_in_flight() {
5157        let dir = tempfile::tempdir().unwrap();
5158        let config_path = dir.path().join("config.toml");
5159        std::fs::write(
5160            &config_path,
5161            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"seed\"\n",
5162        )
5163        .unwrap();
5164        let st = state_with(dir.path(), true, Some(config_path.clone()));
5165
5166        let writes = st.config_writes.clone();
5167        let holder = tokio::task::spawn_blocking(move || {
5168            let guard = writes
5169                .lock()
5170                .unwrap_or_else(|poisoned| poisoned.into_inner());
5171            std::thread::sleep(std::time::Duration::from_millis(1000));
5172            drop(guard);
5173        });
5174        // Give the holder the lock before the write asks for it.
5175        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
5176
5177        let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
5178        let finished = done.clone();
5179        let writer = tokio::spawn(async move {
5180            let written = apply_setting(&st, "provider.model", Some("waited")).await;
5181            finished.store(true, std::sync::atomic::Ordering::SeqCst);
5182            written
5183        });
5184        // Uncontended, the whole read-edit-write takes ~75 ms here even cold; 300 ms into a write
5185        // whose file another writer is holding means the lock was never consulted.
5186        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
5187        assert!(
5188            !done.load(std::sync::atomic::Ordering::SeqCst),
5189            "the second write finished while the first one held the file"
5190        );
5191        holder.await.unwrap();
5192        let written = writer.await.unwrap();
5193        assert!(written.is_ok(), "the write failed: {written:?}");
5194        let on_disk = std::fs::read_to_string(&config_path).unwrap();
5195        assert!(on_disk.contains("waited"), "{on_disk}");
5196    }
5197
5198    #[tokio::test]
5199    async fn a_key_nothing_reads_is_refused_rather_than_written() {
5200        let dir = tempfile::tempdir().unwrap();
5201        let path = dir.path().join("config.toml");
5202        std::fs::write(&path, "[provider]\nmodel = \"seed\"\n").unwrap();
5203        let app = router(state_with(dir.path(), true, Some(path.clone())));
5204        let (jar, csrf) = sign_in(&app).await;
5205        let r = app
5206            .clone()
5207            .oneshot(
5208                HttpRequest::post("/api/settings")
5209                    .header("host", "127.0.0.1:8787")
5210                    .header("cookie", &jar)
5211                    .header("x-eclipse-csrf", &csrf)
5212                    .header("content-type", "application/json")
5213                    .body(Body::from(r#"{"key":"nope.nope","value":"1"}"#))
5214                    .unwrap(),
5215            )
5216            .await
5217            .unwrap();
5218        assert_eq!(r.status(), StatusCode::BAD_REQUEST);
5219        let on_disk = std::fs::read_to_string(&path).unwrap();
5220        assert!(!on_disk.contains("nope"), "{on_disk}");
5221    }
5222
5223    #[tokio::test]
5224    async fn a_secret_setting_is_listed_without_its_value() {
5225        let dir = tempfile::tempdir().unwrap();
5226        let path = dir.path().join("config.toml");
5227        std::fs::write(
5228            &path,
5229            "[provider]\napi_key = \"sk-live-0123456789abcdef\"\n",
5230        )
5231        .unwrap();
5232        let app = router(state_with(dir.path(), true, Some(path)));
5233        let (jar, _csrf) = sign_in(&app).await;
5234        let page = body_text(
5235            app.clone()
5236                .oneshot(
5237                    HttpRequest::get("/api/settings")
5238                        .header("host", "127.0.0.1:8787")
5239                        .header("cookie", &jar)
5240                        .body(Body::empty())
5241                        .unwrap(),
5242                )
5243                .await
5244                .unwrap(),
5245        )
5246        .await;
5247        assert!(!page.contains("sk-live"), "the key leaked: {page}");
5248        assert!(page.contains("\"secret\":true"), "{page}");
5249        assert!(page.contains("\"set\":true"), "{page}");
5250    }
5251    /// `#267`: a row carries enough for a control — the type, one line of explanation, and the
5252    /// values a closed set accepts. All three come from the catalogue, so the page can be a view of
5253    /// it rather than a second table that has to be kept in step.
5254    #[tokio::test]
5255    async fn a_setting_row_carries_its_type_its_words_and_its_choices() {
5256        let dir = tempfile::tempdir().unwrap();
5257        let path = dir.path().join("config.toml");
5258        std::fs::write(&path, "[provider]\nmodel = \"seed\"\n").unwrap();
5259        let app = router(state_with(dir.path(), true, Some(path)));
5260        let (jar, _csrf) = sign_in(&app).await;
5261        let body = body_text(
5262            app.oneshot(
5263                HttpRequest::get("/api/settings")
5264                    .header("host", "127.0.0.1:8787")
5265                    .header("cookie", &jar)
5266                    .body(Body::empty())
5267                    .unwrap(),
5268            )
5269            .await
5270            .unwrap(),
5271        )
5272        .await;
5273        let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
5274        let rows = parsed["settings"].as_array().expect("an array");
5275        let row = |key: &str| {
5276            rows.iter()
5277                .find(|r| r["key"] == json!(key))
5278                .unwrap_or_else(|| panic!("{key} is in the catalogue"))
5279        };
5280
5281        // A type the page can switch on, and a sentence it can print.
5282        assert_eq!(row("agent.trace_content")["kind"], json!("bool"));
5283        assert_eq!(row("provider.temperature")["kind"], json!("float"));
5284        assert_eq!(row("provider.model")["kind"], json!("str"));
5285        assert_eq!(row("tools.deferred")["kind"], json!("list"));
5286
5287        // The closed sets are the enums' own words, and an open key offers none.
5288        assert_eq!(row("cli.approval")["choices"], json!(["ask", "auto"]));
5289        assert_eq!(
5290            row("tools.shell")["choices"],
5291            json!(["deny", "ask", "allow"])
5292        );
5293        assert_eq!(
5294            row("update.check")["choices"],
5295            json!(["daily", "weekly", "off"])
5296        );
5297        assert_eq!(row("provider.model")["choices"], json!([]));
5298
5299        // Every key says what it does — the invariant a new key has to keep.
5300        for r in rows {
5301            let about = r["about"].as_str().unwrap_or("");
5302            assert!(
5303                !about.trim().is_empty(),
5304                "{} has no description: {}",
5305                r["key"],
5306                r
5307            );
5308        }
5309    }
5310
5311    /// `#267`: `{"value": null}` is "back to the default", which the page needs as a button and the
5312    /// CLI has as `config unset`. Leaving `value` out is a different thing and is refused, because
5313    /// a reset must never be the thing that happens when a field was forgotten.
5314    #[tokio::test]
5315    async fn a_null_value_puts_a_key_back_to_its_default_and_a_missing_one_is_refused() {
5316        let dir = tempfile::tempdir().unwrap();
5317        let path = dir.path().join("config.toml");
5318        std::fs::write(&path, "[agent]\nmax_iterations = 3\n").unwrap();
5319        let app = router(state_with(dir.path(), true, Some(path.clone())));
5320        let (jar, csrf) = sign_in(&app).await;
5321
5322        let write = |body: &'static str| {
5323            let app = app.clone();
5324            let jar = jar.clone();
5325            let csrf = csrf.clone();
5326            async move {
5327                app.oneshot(
5328                    HttpRequest::post("/api/settings")
5329                        .header("host", "127.0.0.1:8787")
5330                        .header("cookie", &jar)
5331                        .header("x-eclipse-csrf", &csrf)
5332                        .header("content-type", "application/json")
5333                        .body(Body::from(body))
5334                        .unwrap(),
5335                )
5336                .await
5337                .unwrap()
5338            }
5339        };
5340
5341        // Set it to something that is not the default, so the reset has something to do.
5342        let r = write(r#"{"key":"agent.max_iterations","value":"42"}"#).await;
5343        assert_eq!(r.status(), StatusCode::OK);
5344        assert!(std::fs::read_to_string(&path).unwrap().contains("42"));
5345
5346        // Now unset it: the line is commented out, so the file reads what a default file reads.
5347        let r = write(r#"{"key":"agent.max_iterations","value":null}"#).await;
5348        assert_eq!(r.status(), StatusCode::OK);
5349        let said = body_text(r).await;
5350        let row: serde_json::Value = serde_json::from_str(&said).expect("json");
5351        // The catalogue reports the *effective* value, so a key the file no longer sets reads what
5352        // the resolver fills in — for a turn budget, the word `unlimited`. `is_default` is the
5353        // button's own claim: this key is back where it started.
5354        assert_eq!(row["is_default"], json!(true), "{row}");
5355        assert_eq!(row["value"], json!("\"unlimited\""), "{row}");
5356        let on_disk = std::fs::read_to_string(&path).unwrap();
5357        assert!(
5358            !on_disk
5359                .lines()
5360                .any(|l| l.trim_start().starts_with("max_iterations")),
5361            "the line is gone or commented: {on_disk}"
5362        );
5363
5364        // A body with no `value` at all is not a reset.
5365        let r = write(r#"{"key":"agent.max_iterations"}"#).await;
5366        assert_eq!(r.status(), StatusCode::BAD_REQUEST);
5367    }
5368
5369    /// `#267`: a `Bool` is written as a TOML boolean. A page that sends `"true"` would pass the
5370    /// string through and be refused by `set_in_text` for being the wrong type — so the toggle has
5371    /// to send a value the parser reads as `true`, and this checks the file, not the answer.
5372    #[tokio::test]
5373    async fn a_boolean_is_written_as_a_boolean() {
5374        let dir = tempfile::tempdir().unwrap();
5375        let path = dir.path().join("config.toml");
5376        std::fs::write(&path, "[agent]\nmax_iterations = 3\n").unwrap();
5377        let app = router(state_with(dir.path(), true, Some(path.clone())));
5378        let (jar, csrf) = sign_in(&app).await;
5379        let r = app
5380            .clone()
5381            .oneshot(
5382                HttpRequest::post("/api/settings")
5383                    .header("host", "127.0.0.1:8787")
5384                    .header("cookie", &jar)
5385                    .header("x-eclipse-csrf", &csrf)
5386                    .header("content-type", "application/json")
5387                    .body(Body::from(
5388                        r#"{"key":"agent.trace_content","value":"true"}"#,
5389                    ))
5390                    .unwrap(),
5391            )
5392            .await
5393            .unwrap();
5394        assert_eq!(r.status(), StatusCode::OK);
5395        let on_disk = std::fs::read_to_string(&path).unwrap();
5396        assert!(
5397            on_disk.contains("trace_content = true"),
5398            "a boolean, not a string: {on_disk}"
5399        );
5400    }
5401
5402    /// `#268`: the editor's list, resolved by the loader. The paths come from the config and the
5403    /// discovery walk, so a request never names one — and a file that does not exist yet is
5404    /// reported with where it would be created rather than being invented.
5405    /// A dashboard whose three context files are all inside `dir`.
5406    ///
5407    /// The paths are absolute in `[user]`, on purpose: the dashboard reads `HOME` from the process,
5408    /// and a test cannot set that for everyone else in the binary. An absolute path wins over the
5409    /// memory directory (the documented rule), so these tests cannot reach a real `~/.eclipse` —
5410    /// which they did once, harmlessly, because what they found there was the starter file.
5411    fn context_fixture(dir: &std::path::Path) -> std::path::PathBuf {
5412        let workspace = dir.join("work");
5413        std::fs::create_dir_all(&workspace).unwrap();
5414        std::fs::write(workspace.join("AGENT.md"), "RULE: in the tree\n").unwrap();
5415        let memory = dir.join("memory");
5416        std::fs::create_dir_all(&memory).unwrap();
5417        std::fs::write(memory.join("USER.md"), "USER FACT: one line").unwrap();
5418        let path = dir.join(".eclipse/config.toml");
5419        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
5420        std::fs::write(
5421            &path,
5422            format!(
5423                "[provider]\nmodel = \"m\"\n[tools]\nworkspace_root = \"{ws}\"\n\
5424                 [user]\nfile = \"{user}\"\nmemory_file = \"{mem}\"\n",
5425                ws = workspace.display(),
5426                user = memory.join("USER.md").display(),
5427                mem = memory.join("MEMORY.md").display(),
5428            ),
5429        )
5430        .unwrap();
5431        path
5432    }
5433
5434    #[tokio::test]
5435    async fn the_context_list_resolves_three_files_from_the_config_not_the_request() {
5436        let dir = tempfile::tempdir().unwrap();
5437        let workspace = dir.path().join("work");
5438        let memory = dir.path().join("memory");
5439        let path = context_fixture(dir.path());
5440
5441        let app = router(state_with(dir.path(), true, Some(path)));
5442        let (jar, _csrf) = sign_in(&app).await;
5443        let body = body_text(
5444            app.oneshot(
5445                HttpRequest::get("/api/context")
5446                    .header("host", "127.0.0.1:8787")
5447                    .header("cookie", &jar)
5448                    .body(Body::empty())
5449                    .unwrap(),
5450            )
5451            .await
5452            .unwrap(),
5453        )
5454        .await;
5455        let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
5456        let files = parsed["files"].as_array().expect("an array");
5457        assert_eq!(
5458            files
5459                .iter()
5460                .map(|f| f["name"].as_str().unwrap())
5461                .collect::<Vec<_>>(),
5462            vec!["agent", "user", "memory"]
5463        );
5464        let user = &files[1];
5465        assert_eq!(user["file"], json!("USER.md"));
5466        assert_eq!(user["exists"], json!(true));
5467        assert_eq!(user["chars"], json!(19));
5468        assert_eq!(user["text"], json!("USER FACT: one line"));
5469        assert_eq!(user["kind"], json!("prose"));
5470        assert!(
5471            user["path"].as_str().unwrap().ends_with("memory/USER.md"),
5472            "{user}"
5473        );
5474        // The nearest `AGENT.md` is the one in the workspace, and it exists.
5475        assert_eq!(files[0]["exists"], json!(true));
5476        assert!(
5477            files[0]["path"]
5478                .as_str()
5479                .unwrap()
5480                .ends_with("work/AGENT.md"),
5481            "{}",
5482            files[0]["path"]
5483        );
5484        // How many wider `AGENT.md` layers are also injected — a number, not a promise: the real
5485        // `$HOME` always contributes the global one. The counting itself is a core test.
5486        assert!(files[0]["others"].as_u64().is_some(), "{}", files[0]);
5487        // The memory file's own budget travels with it; the prose files have none.
5488        assert_eq!(files[2]["own_budget"], json!(3000));
5489        assert_eq!(user["own_budget"], serde_json::Value::Null);
5490        // A file that does not exist yet is still a row that says so, with where it would go.
5491        assert_eq!(files[2]["exists"], json!(false));
5492        assert!(
5493            files[2]["path"]
5494                .as_str()
5495                .unwrap()
5496                .ends_with("memory/MEMORY.md"),
5497            "{}",
5498            files[2]["path"]
5499        );
5500        // Nothing here is outside the fixture.
5501        for f in files {
5502            let shown = f["path"].as_str().unwrap();
5503            assert!(!shown.contains("/home/mmhorda/.eclipse"), "{shown}");
5504        }
5505        let _ = (&workspace, &memory);
5506    }
5507
5508    /// `#268`: a name that is not one of the three — a path, a traversal, a typo — is a 400 before
5509    /// anything touches the disk. This is the whole reason the body carries an id and not a path.
5510    #[tokio::test]
5511    async fn a_context_write_may_not_name_a_path_and_lands_where_the_file_belongs() {
5512        let dir = tempfile::tempdir().unwrap();
5513        let memory = dir.path().join("memory");
5514        let path = context_fixture(dir.path());
5515
5516        let app = router(state_with(dir.path(), true, Some(path)));
5517        let (jar, csrf) = sign_in(&app).await;
5518        let write = |body: &'static str| {
5519            let app = app.clone();
5520            let jar = jar.clone();
5521            let csrf = csrf.clone();
5522            async move {
5523                app.oneshot(
5524                    HttpRequest::post("/api/context")
5525                        .header("host", "127.0.0.1:8787")
5526                        .header("cookie", &jar)
5527                        .header("x-eclipse-csrf", &csrf)
5528                        .header("content-type", "application/json")
5529                        .body(Body::from(body))
5530                        .unwrap(),
5531                )
5532                .await
5533                .unwrap()
5534            }
5535        };
5536
5537        for bad in [
5538            r#"{"name":"../../../etc/passwd","text":"x"}"#,
5539            r#"{"name":"/etc/passwd","text":"x"}"#,
5540            r#"{"name":"AGENT.md","text":"x"}"#,
5541            r#"{"name":"skill","text":"x"}"#,
5542        ] {
5543            let r = write(Box::leak(bad.to_string().into_boxed_str())).await;
5544            assert_eq!(r.status(), StatusCode::BAD_REQUEST, "{bad}");
5545            let said = body_text(r).await;
5546            assert!(
5547                said.contains("agent"),
5548                "the refusal names the legal ones: {said}"
5549            );
5550        }
5551        assert!(!dir.path().join("etc/passwd").exists());
5552
5553        // A legal name writes, and the answer is the file as it now stands.
5554        let r = write(r#"{"name":"user","text":"USER FACT: written from the page"}"#).await;
5555        assert_eq!(r.status(), StatusCode::OK);
5556        let said: serde_json::Value = serde_json::from_str(&body_text(r).await).expect("json");
5557        assert_eq!(said["file"]["name"], json!("user"));
5558        assert_eq!(
5559            said["file"]["text"],
5560            json!("USER FACT: written from the page")
5561        );
5562        assert_eq!(said["applies"], json!("the next run uses it"));
5563        assert_eq!(
5564            std::fs::read_to_string(memory.join("USER.md")).unwrap(),
5565            "USER FACT: written from the page"
5566        );
5567
5568        // A memory save keeps the `§` layout the writer owns, and is visible to the memory type.
5569        let r = write(r#"{"name":"memory","text":"one\n§\ntwo"}"#).await;
5570        assert_eq!(r.status(), StatusCode::OK);
5571        let mem = eclipse_core::memory::Memory::new(memory.join("MEMORY.md"), 3000);
5572        assert_eq!(mem.read().unwrap(), vec!["one", "two"]);
5573    }
5574
5575    /// A request may carry more than one `Cookie:` header. Both readers of it — `is_logged_in`
5576    /// (every header) and the origin guard (the first header only, before this) — have to agree
5577    /// about who is asking, or a signed-in browser is refused with a sentence about CSRF.
5578    #[tokio::test]
5579    async fn two_cookie_headers_are_read_the_same_way_by_the_guard_and_the_login_check() {
5580        let dir = tempfile::tempdir().unwrap();
5581        let app = router(state(dir.path(), true));
5582
5583        let r = app.clone().oneshot(login_req(TOKEN)).await.unwrap();
5584        assert_eq!(r.status(), StatusCode::SEE_OTHER);
5585        let jar = r
5586            .headers()
5587            .get(header::SET_COOKIE)
5588            .and_then(|v| v.to_str().ok())
5589            .expect("a session cookie")
5590            .split(';')
5591            .next()
5592            .unwrap()
5593            .to_string();
5594        let page = body_text(
5595            app.clone()
5596                .oneshot(
5597                    HttpRequest::get("/")
5598                        .header("host", "127.0.0.1:8787")
5599                        .header("cookie", &jar)
5600                        .body(Body::empty())
5601                        .unwrap(),
5602                )
5603                .await
5604                .unwrap(),
5605        )
5606        .await;
5607        let csrf = csrf_of(&page);
5608
5609        // Two headers: a harmless one first, this session's second. Origin null, so the guard has
5610        // to fall back on the CSRF token — which it can only check if it found the session.
5611        let r = app
5612            .clone()
5613            .oneshot(
5614                HttpRequest::post("/api/chat")
5615                    .header("host", "127.0.0.1:8787")
5616                    .header("origin", "null")
5617                    .header("cookie", "theme=dark")
5618                    .header("cookie", &jar)
5619                    .header(CSRF_HEADER, &csrf)
5620                    .header("content-type", "application/json")
5621                    .body(Body::from(json!({ "message": "hi" }).to_string()))
5622                    .unwrap(),
5623            )
5624            .await
5625            .unwrap();
5626        assert_ne!(
5627            r.status(),
5628            StatusCode::FORBIDDEN,
5629            "the second Cookie header carries the session; the guard must see it"
5630        );
5631    }
5632
5633    #[tokio::test]
5634    async fn a_browser_that_reports_no_origin_can_sign_in_and_then_act() {
5635        let dir = tempfile::tempdir().unwrap();
5636        let app = router(state(dir.path(), true));
5637
5638        // The sign-in form post from a pane that reports `Origin: null`: the token decides.
5639        let r = app
5640            .clone()
5641            .oneshot(
5642                HttpRequest::post("/login")
5643                    .header("host", "127.0.0.1:8787")
5644                    .header("origin", "null")
5645                    .header("content-type", "application/x-www-form-urlencoded")
5646                    .body(Body::from(format!("token={TOKEN}")))
5647                    .unwrap(),
5648            )
5649            .await
5650            .unwrap();
5651        assert_eq!(
5652            r.status(),
5653            StatusCode::SEE_OTHER,
5654            "not refused at the guard"
5655        );
5656        let cookie = r
5657            .headers()
5658            .get(header::SET_COOKIE)
5659            .and_then(|v| v.to_str().ok())
5660            .expect("a session cookie")
5661            .to_string();
5662
5663        // The page the browser lands on hands out this session's token; that token, not an Origin
5664        // header, is what carries every later request from a pane that reports `null`.
5665        let jar = cookie.split(';').next().unwrap().to_string();
5666        let page = body_text(
5667            app.clone()
5668                .oneshot(
5669                    HttpRequest::get("/")
5670                        .header("host", "127.0.0.1:8787")
5671                        .header("cookie", &jar)
5672                        .body(Body::empty())
5673                        .unwrap(),
5674                )
5675                .await
5676                .unwrap(),
5677        )
5678        .await;
5679        let csrf = csrf_of(&page);
5680        assert_eq!(csrf.len(), 64, "a real token, not an empty meta tag");
5681
5682        let r = app
5683            .clone()
5684            .oneshot(
5685                HttpRequest::post("/api/chat")
5686                    .header("host", "127.0.0.1:8787")
5687                    .header("origin", "null")
5688                    .header("cookie", &jar)
5689                    .header(CSRF_HEADER, &csrf)
5690                    .header("content-type", "application/json")
5691                    .body(Body::from(json!({ "message": "hi" }).to_string()))
5692                    .unwrap(),
5693            )
5694            .await
5695            .unwrap();
5696        assert_ne!(r.status(), StatusCode::FORBIDDEN, "the token opened it");
5697
5698        // The same request with another session's token is refused, so the token is bound to the
5699        // cookie rather than being a shared secret handed to any page that asks.
5700        let r = app
5701            .clone()
5702            .oneshot(
5703                HttpRequest::post("/api/chat")
5704                    .header("host", "127.0.0.1:8787")
5705                    .header("origin", "null")
5706                    .header("cookie", &jar)
5707                    .header(CSRF_HEADER, TEST_CSRF)
5708                    .header("content-type", "application/json")
5709                    .body(Body::from(json!({ "message": "hi" }).to_string()))
5710                    .unwrap(),
5711            )
5712            .await
5713            .unwrap();
5714        assert_eq!(
5715            r.status(),
5716            StatusCode::FORBIDDEN,
5717            "a foreign token is no token"
5718        );
5719
5720        // And without the token it is refused, with the reason on the screen.
5721        let r = app
5722            .clone()
5723            .oneshot(
5724                HttpRequest::post("/api/model")
5725                    .header("host", "127.0.0.1:8787")
5726                    .header("origin", "null")
5727                    .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
5728                    .header("content-type", "application/json")
5729                    .body(Body::from(json!({ "model": "picked" }).to_string()))
5730                    .unwrap(),
5731            )
5732            .await
5733            .unwrap();
5734        assert_eq!(r.status(), StatusCode::FORBIDDEN);
5735        let said = body_text(r).await;
5736        assert!(said.contains(CSRF_HEADER), "{said}");
5737    }
5738
5739    #[tokio::test]
5740    async fn the_page_hands_the_token_to_every_request_it_makes() {
5741        let dir = tempfile::tempdir().unwrap();
5742        let app = router(state(dir.path(), true));
5743        let page = body_text(
5744            app.clone()
5745                .oneshot(get_req("/", "127.0.0.1:8787"))
5746                .await
5747                .unwrap(),
5748        )
5749        .await;
5750        assert!(
5751            page.contains(&format!("<meta name=\"csrf\" content=\"{TEST_CSRF}\">")),
5752            "the meta tag the script reads"
5753        );
5754        // Every POST in the page goes through the helper that adds the header: model, reasoning,
5755        // settings, the context files, approval, chat, cancel, sign-out, the session writes
5756        // (rename, pin, delete), the bot writes (`#509`) and the flare cancel (`#171`) — one
5757        // helper, so another verb cannot be the one request that forgot the token. The flare
5758        // *reads* are `fetch` and do not count: a GET that changes nothing needs no proof, and
5759        // the count is of writes for exactly that reason.
5760        assert_eq!(
5761            page.matches("await post(").count(),
5762            11,
5763            "model, reasoning, settings, context, approval, chat, cancel, logout, the session \
5764             writes, the bot writes and the flare cancel"
5765        );
5766        assert!(page.contains("'X-Eclipse-CSRF': CSRF"), "{page:.0}");
5767        assert!(page.contains("id=\"logout\""), "sign-out is a fetch too");
5768    }
5769
5770    /// `#268`: the window's second pane is the three context files — a textarea over the file, a
5771    /// meter against the budget it is judged by, and a save that names the file by id rather than by
5772    /// path. The names and the paths come from `GET /api/context`; the page spells none of them.
5773    #[test]
5774    fn the_context_pane_edits_the_files_by_id_and_shows_their_budget() {
5775        assert!(
5776            INDEX_HTML.contains("area.id = 'filetext'")
5777                && INDEX_HTML.contains("const area = document.createElement('textarea')"),
5778            "a textarea, because these are prose"
5779        );
5780        assert!(
5781            INDEX_HTML.contains("fetch('/api/context')"),
5782            "the list is the server's, not the page's"
5783        );
5784        assert!(
5785            INDEX_HTML.contains("post('/api/context', { name: row.name, text: area.value })"),
5786            "a save names an id and the text"
5787        );
5788        assert!(
5789            INDEX_HTML.contains("row.own_budget === null"),
5790            "MEMORY.md is measured against its own budget, not the per-file ceiling"
5791        );
5792        assert!(
5793            INDEX_HTML.contains("a save applies to the next run"),
5794            "what a save applies to is said once, in the same words the settings rows use"
5795        );
5796        assert!(
5797            INDEX_HTML.contains("entries are separated by a line holding"),
5798            "the `§` storage format is explained where it is edited"
5799        );
5800        // A file name may appear in a comment — the pane has to be explained somewhere — but never
5801        // as a value the page could send or show on its own, and never as a path.
5802        for literal in [
5803            "'USER.md'",
5804            "'MEMORY.md'",
5805            "\"USER.md\"",
5806            ".eclipse/memory",
5807            "\"agent\"",
5808            "\"memory\"",
5809        ] {
5810            assert!(
5811                !INDEX_HTML.contains(literal),
5812                "the page spells {literal}: the names come from `GET /api/context`"
5813            );
5814        }
5815        assert!(
5816            INDEX_HTML.contains("for (const f of ctxFiles)"),
5817            "the rail's file entries are built from the server's list"
5818        );
5819    }
5820
5821    #[tokio::test]
5822    async fn the_sign_in_page_says_when_it_is_inside_a_frame() {
5823        let dir = tempfile::tempdir().unwrap();
5824        let app = router(state(dir.path(), false));
5825        let framed = body_text(
5826            app.clone()
5827                .oneshot(
5828                    HttpRequest::get("/login")
5829                        .header("host", "127.0.0.1:8787")
5830                        .header("sec-fetch-dest", "iframe")
5831                        .body(Body::empty())
5832                        .unwrap(),
5833                )
5834                .await
5835                .unwrap(),
5836        )
5837        .await;
5838        assert!(framed.contains("inside a frame"), "{framed}");
5839        let plain = body_text(
5840            app.oneshot(
5841                HttpRequest::get("/login")
5842                    .header("host", "127.0.0.1:8787")
5843                    .body(Body::empty())
5844                    .unwrap(),
5845            )
5846            .await
5847            .unwrap(),
5848        )
5849        .await;
5850        assert!(!plain.contains("inside a frame"), "{plain}");
5851    }
5852
5853    /// The token the served page carries in its `<meta name="csrf">`.
5854    fn csrf_of(page: &str) -> String {
5855        const AT: &str = "name=\"csrf\" content=\"";
5856        let start = page.find(AT).expect("the page carries a csrf token") + AT.len();
5857        page[start..].split('"').next().unwrap_or("").to_string()
5858    }
5859
5860    fn get_req(uri: &str, host: &str) -> HttpRequest<Body> {
5861        HttpRequest::get(uri)
5862            .header("host", host)
5863            .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
5864            .body(Body::empty())
5865            .unwrap()
5866    }
5867
5868    fn model_req(body: serde_json::Value) -> HttpRequest<Body> {
5869        HttpRequest::post("/api/model")
5870            .header("host", "127.0.0.1:8787")
5871            .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
5872            .header("content-type", "application/json")
5873            .body(Body::from(body.to_string()))
5874            .unwrap()
5875    }
5876
5877    /// A provider endpoint on a real socket, answering `GET /models` with these names and, when
5878    /// a window is given, the `context_length` each one advertises. The picker is then tested
5879    /// against an HTTP reply rather than a canned list, which is the only way to see that the
5880    /// list really comes from the endpoint.
5881    async fn serve_models(names: &[(&str, Option<u64>)]) -> String {
5882        let rows: Vec<serde_json::Value> = names
5883            .iter()
5884            .map(|(n, window)| match window {
5885                Some(w) => json!({ "id": n, "context_length": w }),
5886                None => json!({ "id": n }),
5887            })
5888            .collect();
5889        let app = Router::new().route(
5890            "/v1/models",
5891            get(move || {
5892                let body = json!({ "data": rows });
5893                async move { Json(body) }
5894            }),
5895        );
5896        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
5897        let addr = listener.local_addr().unwrap();
5898        tokio::spawn(async move {
5899            let _ = axum::serve(listener, app).await;
5900        });
5901        format!("http://{addr}/v1")
5902    }
5903
5904    /// A dashboard whose agent has a provider configuration, so `set_model` has something to
5905    /// check a name against. The store still lives in the temp dir; the endpoint is whatever
5906    /// `base_url` names and is never contacted by a switch.
5907    fn provider_state(dir: &std::path::Path, base_url: &str, model: &str) -> (Shared, Arc<Agent>) {
5908        let store = SessionStore::new(dir.join("sessions"));
5909        let cfg = eclipse_core::config::ProviderConfig {
5910            base_url: base_url.into(),
5911            model: model.into(),
5912            ..Default::default()
5913        };
5914        let agent = Arc::new(
5915            Agent::new(
5916                Arc::new(Canned),
5917                Arc::new(ToolRegistry::default()),
5918                store.clone(),
5919                "sys".into(),
5920                3,
5921            )
5922            .with_provider_config(cfg),
5923        );
5924        (
5925            Arc::new(authed(Some(agent.clone()), store, model, None)),
5926            agent,
5927        )
5928    }
5929
5930    fn chat_req(body: serde_json::Value) -> HttpRequest<Body> {
5931        HttpRequest::post("/api/chat")
5932            .header("host", "127.0.0.1:8787")
5933            .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
5934            .header("content-type", "application/json")
5935            .body(Body::from(body.to_string()))
5936            .unwrap()
5937    }
5938
5939    async fn text(resp: Response) -> String {
5940        let bytes = axum::body::to_bytes(resp.into_body(), 1 << 20)
5941            .await
5942            .unwrap();
5943        String::from_utf8(bytes.to_vec()).unwrap()
5944    }
5945
5946    fn anon(method: &str, uri: &str) -> axum::http::request::Builder {
5947        HttpRequest::builder()
5948            .method(method)
5949            .uri(uri)
5950            .header("host", "127.0.0.1:8787")
5951    }
5952
5953    fn login_req(token: &str) -> HttpRequest<Body> {
5954        anon("POST", "/login")
5955            .header("content-type", "application/x-www-form-urlencoded")
5956            .header("origin", "http://127.0.0.1:8787")
5957            .body(Body::from(format!("token={token}")))
5958            .unwrap()
5959    }
5960
5961    /// The password form's POST (`#266`).
5962    fn pair_req(user: &str, password: &str) -> HttpRequest<Body> {
5963        anon("POST", "/login")
5964            .header("content-type", "application/x-www-form-urlencoded")
5965            .header("origin", "http://127.0.0.1:8787")
5966            .body(Body::from(format!("username={user}&password={password}")))
5967            .unwrap()
5968    }
5969
5970    /// A dashboard whose human door is a username and a password.
5971    /// A dashboard whose human door is a username and a password. The throttle is wide open so a
5972    /// test about *which* answers are refused is not measuring the throttle instead.
5973    fn state_with_password(dir: &std::path::Path, user: &str, password: &str) -> Arc<AppState> {
5974        state_with_password_throttled(
5975            dir,
5976            user,
5977            password,
5978            LoginThrottle::new(100, Duration::from_millis(1), Duration::from_millis(1)),
5979        )
5980    }
5981
5982    fn state_with_password_throttled(
5983        dir: &std::path::Path,
5984        user: &str,
5985        password: &str,
5986        throttle: LoginThrottle,
5987    ) -> Arc<AppState> {
5988        let mut st = match Arc::try_unwrap(state_with_password_inner(dir, user, password)) {
5989            Ok(st) => st,
5990            Err(_) => panic!("a state built here is not shared yet"),
5991        };
5992        st.throttle = throttle;
5993        Arc::new(st)
5994    }
5995
5996    fn state_with_password_inner(
5997        dir: &std::path::Path,
5998        user: &str,
5999        password: &str,
6000    ) -> Arc<AppState> {
6001        let hash = eclipse_core::auth::hash_password(password).unwrap();
6002        Arc::new(
6003            authed(None, SessionStore::new(dir.join("sessions")), "m", None).with_credentials(
6004                eclipse_core::auth::Credentials::Password {
6005                    user: user.into(),
6006                    hash: eclipse_core::auth::Stored::parse(&hash).unwrap(),
6007                },
6008            ),
6009        )
6010    }
6011
6012    /// `#266`: the door a person actually walks through. A right pair signs in, and three kinds of
6013    /// wrong answer all get the same one — telling a wrong user from a wrong password apart would
6014    /// turn the form into a way to enumerate usernames.
6015    #[tokio::test]
6016    async fn a_username_and_password_sign_in_and_every_wrong_answer_is_the_same() {
6017        let dir = tempfile::tempdir().unwrap();
6018        let app = router(state_with_password(dir.path(), "max", "open sesame"));
6019
6020        let r = app
6021            .clone()
6022            .oneshot(pair_req("max", "open sesame"))
6023            .await
6024            .unwrap();
6025        assert_eq!(r.status(), StatusCode::SEE_OTHER, "the right pair");
6026        assert!(
6027            r.headers().get("set-cookie").is_some(),
6028            "and it hands out the session cookie"
6029        );
6030
6031        for (user, password) in [
6032            ("max", "open sesam"),
6033            ("mor", "open sesame"),
6034            ("", "open sesame"),
6035            ("max", ""),
6036        ] {
6037            let r = app.clone().oneshot(pair_req(user, password)).await.unwrap();
6038            assert_eq!(r.status(), StatusCode::UNAUTHORIZED, "{user}/{password}");
6039            let body = text(r).await;
6040            assert!(body.contains("Wrong user or password."), "{body}");
6041            assert!(
6042                !body.contains("Wrong token."),
6043                "the page does not offer the old wording in this mode: {body}"
6044            );
6045        }
6046    }
6047
6048    /// `#266`'s last case: the wait is a delay, not a lockout. A wrong pair starts the clock, the
6049    /// next attempt is refused with the seconds remaining, and once those pass the right pair gets
6050    /// in — which is also what says the password comparison did not eat the session it had just
6051    /// created.
6052    #[tokio::test]
6053    async fn the_right_pair_gets_in_after_the_failed_attempt_wait() {
6054        let dir = tempfile::tempdir().unwrap();
6055        let app = router(state_with_password_throttled(
6056            dir.path(),
6057            "max",
6058            "open sesame",
6059            // Zero free attempts, so the first wrong pair starts the wait; two seconds, not
6060            // milliseconds, because a PBKDF2 comparison in a debug build is slow enough to outrun
6061            // a short one — a test that race would be flaky in the way it is meant to disprove.
6062            LoginThrottle::new(0, Duration::from_secs(2), Duration::from_secs(2)),
6063        ));
6064
6065        let wrong = app.clone().oneshot(pair_req("max", "nope")).await.unwrap();
6066        assert_eq!(wrong.status(), StatusCode::UNAUTHORIZED);
6067
6068        // The attempt clock is running: the next one is refused before any comparison happens.
6069        let held = app
6070            .clone()
6071            .oneshot(pair_req("max", "open sesame"))
6072            .await
6073            .unwrap();
6074        assert_eq!(held.status(), StatusCode::TOO_MANY_REQUESTS);
6075        let wait: u64 = held
6076            .headers()
6077            .get("retry-after")
6078            .expect("the wait says how long")
6079            .to_str()
6080            .unwrap()
6081            .parse()
6082            .unwrap();
6083        assert!(wait >= 1, "at least a second: {wait}");
6084
6085        // Past the wait, the right pair signs in: the delay is a delay, not a lockout.
6086        tokio::time::sleep(Duration::from_millis(2_100)).await;
6087        let r = app.oneshot(pair_req("max", "open sesame")).await.unwrap();
6088        assert_eq!(r.status(), StatusCode::SEE_OTHER);
6089    }
6090
6091    /// The migration case: an install whose `.env` has only `ECLIPSE_WEB_AUTH_TOKEN` keeps signing
6092    /// in with it, through the same form, until somebody runs `eclipse web passwd`.
6093    #[tokio::test]
6094    async fn a_token_only_install_still_signs_in_through_the_new_form() {
6095        let dir = tempfile::tempdir().unwrap();
6096        let app = router(state(dir.path(), true));
6097        let r = app.clone().oneshot(pair_req("", TOKEN)).await.unwrap();
6098        assert_eq!(r.status(), StatusCode::SEE_OTHER, "the token still works");
6099        // And the page says which shape it is, so the username box is not on screen.
6100        let r = router(state(dir.path(), true))
6101            .oneshot(anon("GET", "/login").body(Body::empty()).unwrap())
6102            .await
6103            .unwrap();
6104        let html = text(r).await;
6105        assert!(html.contains("class=\"token\""), "token mode: {html:.0}");
6106        assert!(html.contains("Enter the dashboard token from"), "{html:.0}");
6107        assert!(!html.contains("ECLIPSE_WEB_USER"), "no password advice yet");
6108    }
6109
6110    /// The password mode's page: two fields a password manager can fill, and no hint of the token.
6111    #[tokio::test]
6112    async fn the_password_page_asks_for_a_user_and_a_password() {
6113        let dir = tempfile::tempdir().unwrap();
6114        let r = router(state_with_password(dir.path(), "max", "open sesame"))
6115            .oneshot(anon("GET", "/login").body(Body::empty()).unwrap())
6116            .await
6117            .unwrap();
6118        let html = text(r).await;
6119        assert!(
6120            html.contains("class=\"password\""),
6121            "password mode: {html:.0}"
6122        );
6123        assert!(html.contains("autocomplete=\"username\""), "{html:.0}");
6124        assert!(
6125            html.contains("autocomplete=\"current-password\""),
6126            "{html:.0}"
6127        );
6128        assert!(
6129            html.contains("ECLIPSE_WEB_USER"),
6130            "it names where the user comes from"
6131        );
6132        assert!(
6133            !html.contains("auth_token"),
6134            "the token is the machine credential; the page does not offer it as a human one"
6135        );
6136    }
6137
6138    /// The point of `blocking` is *where* the work runs: on a worker it stalls every other request
6139    /// for as long as the disk takes, including the `/healthz` a supervisor polls.
6140    #[tokio::test]
6141    async fn blocking_runs_the_work_off_the_async_worker() {
6142        let here = std::thread::current().id();
6143        let there = blocking(move || std::thread::current().id()).await;
6144        assert!(there.is_some(), "the work finished");
6145        assert_ne!(
6146            there.unwrap(),
6147            here,
6148            "a blocking call must not run on the async worker"
6149        );
6150    }
6151
6152    /// A panicking closure must not take the connection down with it: the endpoint answers 500.
6153    #[tokio::test]
6154    async fn blocking_turns_a_panic_into_nothing() {
6155        let died = blocking(|| -> usize { panic!("the disk went away") }).await;
6156        assert!(
6157            died.is_none(),
6158            "a panic comes back as None, not a dropped request"
6159        );
6160    }
6161
6162    /// Two wrong tokens are a typo and a retry: they stay plain 401s.
6163    #[tokio::test]
6164    async fn a_couple_of_wrong_tokens_is_not_an_attack() {
6165        let dir = tempfile::tempdir().unwrap();
6166        let app = router(state(dir.path(), true));
6167        for attempt in 1..=2 {
6168            let r = app
6169                .clone()
6170                .oneshot(login_req("not-the-token"))
6171                .await
6172                .unwrap();
6173            assert_eq!(r.status(), StatusCode::UNAUTHORIZED, "attempt {attempt}");
6174        }
6175    }
6176
6177    /// The third one waits — and the wait is checked *before* the token is compared, so the right
6178    /// token during the lockout is refused too. That is the whole point: guessing stops being free.
6179    #[tokio::test]
6180    async fn a_run_of_wrong_tokens_is_answered_429_and_even_the_right_one_waits() {
6181        let dir = tempfile::tempdir().unwrap();
6182        let app = router(state_throttled(
6183            dir.path(),
6184            LoginThrottle::new(2, Duration::from_secs(1), Duration::from_secs(30)),
6185        ));
6186        for _ in 1..=2 {
6187            let r = app
6188                .clone()
6189                .oneshot(login_req("not-the-token"))
6190                .await
6191                .unwrap();
6192            assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
6193        }
6194        let r = app
6195            .clone()
6196            .oneshot(login_req("not-the-token"))
6197            .await
6198            .unwrap();
6199        assert_eq!(
6200            r.status(),
6201            StatusCode::UNAUTHORIZED,
6202            "the 2 free ones, then the wait"
6203        );
6204
6205        let r = app.clone().oneshot(login_req(TOKEN)).await.unwrap();
6206        assert_eq!(r.status(), StatusCode::TOO_MANY_REQUESTS);
6207        assert!(
6208            r.headers().contains_key("retry-after"),
6209            "a 429 without Retry-After is a riddle"
6210        );
6211    }
6212
6213    /// And it is a delay, not a lock: once it has passed, the right token signs in and clears it.
6214    #[tokio::test]
6215    async fn the_wait_ends_and_a_right_token_clears_it() {
6216        let dir = tempfile::tempdir().unwrap();
6217        let app = router(state_throttled(
6218            dir.path(),
6219            LoginThrottle::new(1, Duration::from_millis(30), Duration::from_millis(60)),
6220        ));
6221        for _ in 1..=2 {
6222            let _ = app
6223                .clone()
6224                .oneshot(login_req("not-the-token"))
6225                .await
6226                .unwrap();
6227        }
6228        let r = app.clone().oneshot(login_req(TOKEN)).await.unwrap();
6229        assert_eq!(r.status(), StatusCode::TOO_MANY_REQUESTS, "still waiting");
6230
6231        tokio::time::sleep(Duration::from_millis(70)).await;
6232        let r = app.clone().oneshot(login_req(TOKEN)).await.unwrap();
6233        assert_eq!(r.status(), StatusCode::SEE_OTHER, "the wait is over");
6234        // Cleared: the counter does not creep back up after a good login.
6235        let r = app
6236            .clone()
6237            .oneshot(login_req("not-the-token"))
6238            .await
6239            .unwrap();
6240        assert_eq!(r.status(), StatusCode::UNAUTHORIZED, "free attempts again");
6241    }
6242
6243    #[tokio::test]
6244    async fn everything_but_healthz_and_login_needs_the_cookie() {
6245        let dir = tempfile::tempdir().unwrap();
6246        let app = router(state(dir.path(), true));
6247        for (method, uri) in [
6248            ("GET", "/"),
6249            ("GET", "/api/sessions"),
6250            ("GET", "/api/sessions/s1"),
6251            ("GET", "/api/models"),
6252            ("GET", "/api/update"),
6253            ("POST", "/api/model"),
6254            ("POST", "/api/chat"),
6255            ("POST", "/api/approvals/deadbeef"),
6256            ("POST", "/api/runs/deadbeef/cancel"),
6257            ("GET", "/nonexistent"),
6258        ] {
6259            let r = app
6260                .clone()
6261                .oneshot(anon(method, uri).body(Body::empty()).unwrap())
6262                .await
6263                .unwrap();
6264            assert_eq!(r.status(), StatusCode::UNAUTHORIZED, "{method} {uri}");
6265        }
6266        // A cookie value that was never issued is no better than none.
6267        let r = app
6268            .clone()
6269            .oneshot(
6270                anon("GET", "/api/sessions")
6271                    .header("cookie", format!("{SESSION_COOKIE}=forged"))
6272                    .body(Body::empty())
6273                    .unwrap(),
6274            )
6275            .await
6276            .unwrap();
6277        assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
6278        // The token itself is not a valid cookie value either.
6279        let r = app
6280            .clone()
6281            .oneshot(
6282                anon("GET", "/api/sessions")
6283                    .header("cookie", format!("{SESSION_COOKIE}={TOKEN}"))
6284                    .body(Body::empty())
6285                    .unwrap(),
6286            )
6287            .await
6288            .unwrap();
6289        assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
6290
6291        for uri in ["/", "/api/sessions"] {
6292            let r = app
6293                .clone()
6294                .oneshot(get_req(uri, "127.0.0.1:8787"))
6295                .await
6296                .unwrap();
6297            assert_eq!(r.status(), StatusCode::OK, "{uri} with cookie");
6298        }
6299        let r = app
6300            .clone()
6301            .oneshot(anon("GET", "/healthz").body(Body::empty()).unwrap())
6302            .await
6303            .unwrap();
6304        assert_eq!(r.status(), StatusCode::OK);
6305    }
6306
6307    /// `#425`: `/healthz` is unauthenticated, and it used to answer the version, whether a provider
6308    /// is configured, when the model was last reachable and the names of failing cron jobs to
6309    /// anyone who could reach the port. A probe needs one word; the report is for the signed-in
6310    /// person who can already see the dashboard.
6311    #[tokio::test]
6312    async fn healthz_tells_an_anonymous_caller_only_that_it_is_up() {
6313        let dir = tempfile::tempdir().unwrap();
6314        let root = dir.path().join("state");
6315        std::fs::create_dir_all(&root).unwrap();
6316        std::fs::write(
6317            root.join("cron.json"),
6318            r#"{"jobs": {"backup-everything": {"runs": 1, "last_outcome": "failed"}}}"#,
6319        )
6320        .unwrap();
6321        let store = SessionStore::new(dir.path().join("sessions"));
6322        let agent = Some(Arc::new(Agent::new(
6323            Arc::new(Canned),
6324            Arc::new(ToolRegistry::default()),
6325            store.clone(),
6326            "sys".into(),
6327            3,
6328        )));
6329        let st = Arc::new(
6330            authed(agent, store, "test-<model>", None).with_cron_root(dir.path().to_path_buf()),
6331        );
6332        let app = router(st);
6333
6334        let public: serde_json::Value = serde_json::from_str(
6335            &text(
6336                app.clone()
6337                    .oneshot(anon("GET", "/healthz").body(Body::empty()).unwrap())
6338                    .await
6339                    .unwrap(),
6340            )
6341            .await,
6342        )
6343        .unwrap();
6344        assert_eq!(public, json!({"status": "ok"}), "one word and nothing else");
6345
6346        let signed_in: serde_json::Value = serde_json::from_str(
6347            &text(
6348                app.oneshot(get_req("/healthz", "127.0.0.1:8787"))
6349                    .await
6350                    .unwrap(),
6351            )
6352            .await,
6353        )
6354        .unwrap();
6355        assert_eq!(signed_in["status"], "ok");
6356        assert!(signed_in.get("version").is_some(), "{signed_in}");
6357        assert_eq!(
6358            signed_in["cron"]["failed_jobs"][0], "backup-everything",
6359            "the detail is still there for the person who is signed in"
6360        );
6361    }
6362
6363    #[tokio::test]
6364    async fn unauthenticated_index_is_the_login_form_without_the_app() {
6365        let dir = tempfile::tempdir().unwrap();
6366        let st = state(dir.path(), true);
6367        st.store
6368            .append("s1", &Message::user("secret preview"))
6369            .unwrap();
6370        let r = router(st)
6371            .oneshot(anon("GET", "/").body(Body::empty()).unwrap())
6372            .await
6373            .unwrap();
6374        assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
6375        let html = text(r).await;
6376        // `#266`: the form is a username and a password now. This state has no password hash, so
6377        // it is still the token door — but the field is named for what a person is typing, and the
6378        // page says which of the two shapes it is.
6379        assert!(html.contains("name=\"username\"") && html.contains("name=\"password\""));
6380        assert!(html.contains("method=\"post\"") && html.contains("class=\"token\""));
6381        assert!(!html.contains("secret preview") && !html.contains("test-&lt;model"));
6382        let r = router(state(dir.path(), true))
6383            .oneshot(anon("GET", "/login").body(Body::empty()).unwrap())
6384            .await
6385            .unwrap();
6386        assert_eq!(r.status(), StatusCode::OK);
6387        assert!(text(r).await.contains("name=\"password\""));
6388    }
6389
6390    #[tokio::test]
6391    async fn login_with_the_token_sets_a_strict_httponly_cookie_that_works() {
6392        let dir = tempfile::tempdir().unwrap();
6393        let app = router(state(dir.path(), true));
6394        let r = app.clone().oneshot(login_req(TOKEN)).await.unwrap();
6395        assert_eq!(r.status(), StatusCode::SEE_OTHER);
6396        assert_eq!(r.headers()[header::LOCATION], "/");
6397        let set = r.headers()[header::SET_COOKIE]
6398            .to_str()
6399            .unwrap()
6400            .to_string();
6401        assert!(set.starts_with(&format!("{SESSION_COOKIE}=")));
6402        assert!(set.contains("HttpOnly") && set.contains("SameSite=Strict"));
6403        assert!(set.contains("Path=/") && set.contains("Max-Age="));
6404        assert!(!set.contains(TOKEN), "the cookie must not carry the token");
6405
6406        let cookie = set.split(';').next().unwrap();
6407        let r = app
6408            .clone()
6409            .oneshot(
6410                anon("GET", "/api/sessions")
6411                    .header("cookie", cookie)
6412                    .body(Body::empty())
6413                    .unwrap(),
6414            )
6415            .await
6416            .unwrap();
6417        assert_eq!(r.status(), StatusCode::OK);
6418
6419        // Logging out invalidates the id on the server, not just in the browser.
6420        let r = app
6421            .clone()
6422            .oneshot(
6423                anon("POST", "/logout")
6424                    .header("cookie", cookie)
6425                    .body(Body::empty())
6426                    .unwrap(),
6427            )
6428            .await
6429            .unwrap();
6430        assert!(r.headers()[header::SET_COOKIE]
6431            .to_str()
6432            .unwrap()
6433            .contains("Max-Age=0"));
6434        let r = app
6435            .clone()
6436            .oneshot(
6437                anon("GET", "/api/sessions")
6438                    .header("cookie", cookie)
6439                    .body(Body::empty())
6440                    .unwrap(),
6441            )
6442            .await
6443            .unwrap();
6444        assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
6445    }
6446
6447    #[tokio::test]
6448    async fn wrong_or_empty_token_is_rejected_without_a_cookie() {
6449        let dir = tempfile::tempdir().unwrap();
6450        // Every variant here has to reach the comparison, so this test's throttle does not get in
6451        // the way: it is about the four shapes of a wrong token, not about the delay between them.
6452        let app = router(state_throttled(
6453            dir.path(),
6454            LoginThrottle::new(8, Duration::from_secs(1), Duration::from_secs(1)),
6455        ));
6456        for req in [
6457            login_req("nope"),
6458            login_req(""),
6459            login_req(&TOKEN[..TOKEN.len() - 1]),
6460            login_req(&format!("{TOKEN}x")),
6461        ] {
6462            let r = app.clone().oneshot(req).await.unwrap();
6463            assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
6464            assert!(r.headers().get(header::SET_COOKIE).is_none());
6465        }
6466        let malformed = anon("POST", "/login")
6467            .header("content-type", "application/x-www-form-urlencoded")
6468            .body(Body::from("other=1"))
6469            .unwrap();
6470        let r = app.oneshot(malformed).await.unwrap();
6471        assert!(r.status().is_client_error());
6472        assert!(r.headers().get(header::SET_COOKIE).is_none());
6473    }
6474
6475    #[tokio::test]
6476    async fn login_from_a_foreign_origin_is_forbidden() {
6477        let dir = tempfile::tempdir().unwrap();
6478        let req = anon("POST", "/login")
6479            .header("content-type", "application/x-www-form-urlencoded")
6480            .header("origin", "https://evil.example.com")
6481            .body(Body::from(format!("token={TOKEN}")))
6482            .unwrap();
6483        let r = router(state(dir.path(), true)).oneshot(req).await.unwrap();
6484        assert_eq!(r.status(), StatusCode::FORBIDDEN);
6485        assert!(r.headers().get(header::SET_COOKIE).is_none());
6486    }
6487
6488    /// The cookie's lifetime and the server's expiry are one number: if the cookie outlives
6489    /// the login, the browser keeps handing over a session the server has forgotten.
6490    #[tokio::test]
6491    async fn the_login_cookie_lives_as_long_as_the_configured_ttl() {
6492        let dir = tempfile::tempdir().unwrap();
6493        let store = SessionStore::new(dir.path().join("sessions"));
6494        let st = AppState::new(
6495            None,
6496            store,
6497            "m".into(),
6498            None,
6499            TOKEN.into(),
6500            Duration::from_secs(3600),
6501        );
6502        let req = login_req(TOKEN);
6503        let r = router(Arc::new(st)).oneshot(req).await.unwrap();
6504        assert_eq!(r.status(), StatusCode::SEE_OTHER);
6505        let cookie = r
6506            .headers()
6507            .get(header::SET_COOKIE)
6508            .expect("a login sets a cookie")
6509            .to_str()
6510            .unwrap()
6511            .to_string();
6512        assert!(cookie.contains("Max-Age=3600"), "{cookie}");
6513        assert!(cookie.contains("HttpOnly"), "{cookie}");
6514    }
6515
6516    #[test]
6517    fn login_ids_expire_and_are_capped() {
6518        let logins = Logins::new(Duration::from_secs(
6519            eclipse_core::config::DEFAULT_SESSION_TTL_HOURS * 60 * 60,
6520        ));
6521        let first = logins.create().unwrap().0;
6522        assert!(logins.is_valid(&first));
6523        for _ in 0..MAX_LOGINS + 5 {
6524            logins.create().unwrap();
6525        }
6526        assert!(logins.lock().len() <= MAX_LOGINS);
6527        logins.lock().insert(
6528            "old".into(),
6529            Session {
6530                expires: Instant::now() - Duration::from_secs(1),
6531                csrf: String::new(),
6532            },
6533        );
6534        assert!(!logins.is_valid("old"));
6535        assert!(!logins.is_valid(""));
6536    }
6537
6538    #[tokio::test]
6539    async fn health_reports_configuration() {
6540        let dir = tempfile::tempdir().unwrap();
6541        let resp = router(state(dir.path(), true))
6542            .oneshot(get_req("/healthz", "127.0.0.1:8787"))
6543            .await
6544            .unwrap();
6545        assert_eq!(resp.status(), StatusCode::OK);
6546        let v: serde_json::Value = serde_json::from_str(&text(resp).await).unwrap();
6547        assert_eq!(v["status"], "ok");
6548        assert_eq!(v["configured"], true);
6549    }
6550
6551    #[tokio::test]
6552    async fn health_reports_the_cron_state_when_a_root_is_set() {
6553        let dir = tempfile::tempdir().unwrap();
6554        let root = dir.path().join("state");
6555        std::fs::create_dir_all(&root).unwrap();
6556        let jobs = root.join("cron.json");
6557        std::fs::write(
6558            &jobs,
6559            r#"{"jobs": {"brief": {"runs": 1, "last_started_ms": 1000, "last_finished_ms": 1100, "last_outcome": "failed"}}}"#,
6560        ).unwrap();
6561        let store = SessionStore::new(dir.path().join("sessions"));
6562        let agent = Some(Arc::new(Agent::new(
6563            Arc::new(Canned),
6564            Arc::new(ToolRegistry::default()),
6565            store.clone(),
6566            "sys".into(),
6567            3,
6568        )));
6569        let st = Arc::new(
6570            authed(agent, store, "test-<model>", None).with_cron_root(dir.path().to_path_buf()),
6571        );
6572        let resp = router(st)
6573            .oneshot(get_req("/healthz", "127.0.0.1:8787"))
6574            .await
6575            .unwrap();
6576        let v: serde_json::Value = serde_json::from_str(&text(resp).await).unwrap();
6577        assert_eq!(v["cron"]["failed_jobs"][0], "brief");
6578        assert_eq!(v["cron"]["last_tick_ms"], 1000);
6579    }
6580
6581    #[tokio::test]
6582    async fn index_is_server_rendered_and_escaped() {
6583        let dir = tempfile::tempdir().unwrap();
6584        let st = state(dir.path(), true);
6585        st.store.append("s1", &Message::user("<b>hi</b>")).unwrap();
6586        let html = text(
6587            router(st)
6588                .oneshot(get_req("/", "localhost:8787"))
6589                .await
6590                .unwrap(),
6591        )
6592        .await;
6593        assert!(html.contains("test-&lt;model&gt;"));
6594        assert!(html.contains("data-id=\"s1\""));
6595        assert!(
6596            html.contains("class=\"name\">&lt;b&gt;hi&lt;/b&gt;"),
6597            "the label is escaped text, not markup"
6598        );
6599        assert!(
6600            html.contains("data-updated=") && html.contains("class=\"session\""),
6601            "a row says when it last moved, which is what the page sections by"
6602        );
6603        assert!(!html.contains("{{"));
6604    }
6605
6606    /// The palette is the table's, not the page's. `:root` is generated from `eclipse_core::palette`
6607    /// at render time, so a hex literal in `index.html` would be a second definition of the brand —
6608    /// which is exactly how the terminal and the dashboard ended up in two colours.
6609    #[tokio::test]
6610    async fn the_page_cannot_spell_a_colour_of_its_own() {
6611        let dir = tempfile::tempdir().unwrap();
6612        let html = text(
6613            router(state(dir.path(), true))
6614                .oneshot(get_req("/", "localhost:8787"))
6615                .await
6616                .unwrap(),
6617        )
6618        .await;
6619        let accent = eclipse_core::palette::ACCENT;
6620        assert!(
6621            html.contains(&format!(
6622                "--accent:rgb({}, {}, {})",
6623                accent.0, accent.1, accent.2
6624            )),
6625            "the accent arrives as a custom property from the table"
6626        );
6627        assert!(
6628            !html.to_lowercase().contains("#5aa9ff"),
6629            "the blue the dashboard used to be is gone, not merely overridden"
6630        );
6631        let styles = html.split("</style>").next().unwrap_or_default();
6632        assert!(
6633            !styles.contains(":#") && !styles.contains(": #"),
6634            "no colour literal in the stylesheet: {:?}",
6635            styles
6636                .match_indices(":#")
6637                .map(|(i, _)| &styles[i..(i + 8).min(styles.len())])
6638                .collect::<Vec<_>>()
6639        );
6640    }
6641
6642    /// `#339`: the transcript pane decides where the pane is, in one place.
6643    ///
6644    /// The bug was nine call sites each ending in the same scroll to the bottom, so every streamed
6645    /// token dragged the reader back — reading anything older than the newest word was impossible.
6646    /// One rule now, and this is what keeps it one: a tenth site would pass every behavioural test
6647    /// (they all go through `follow`) while quietly restoring the drag for its own event.
6648    #[test]
6649    fn only_the_pane_decides_where_the_pane_is() {
6650        let assignments: Vec<&str> = INDEX_HTML
6651            .lines()
6652            .filter(|l| !l.trim_start().starts_with("//"))
6653            .filter(|l| l.contains("log.scrollTop ="))
6654            .collect();
6655        assert_eq!(
6656            assignments.len(),
6657            1,
6658            "the pane is scrolled from `pin()` and nowhere else, found: {assignments:?}"
6659        );
6660        // …and `pin()` is the one that holds it.
6661        let pin = INDEX_HTML
6662            .split("function pin()")
6663            .nth(1)
6664            .expect("the page has a `pin()`");
6665        let body = pin.split("\n  }").next().unwrap_or_default();
6666        assert!(
6667            body.contains("log.scrollTop = log.scrollHeight"),
6668            "the single assignment lives in `pin()`: {body:?}"
6669        );
6670        // The reader's own intent is read from the pane, not inferred.
6671        assert!(
6672            INDEX_HTML.contains("log.addEventListener('scroll'"),
6673            "the page learns where the reader is by listening to the pane"
6674        );
6675    }
6676
6677    /// `#339`: the button that gets a reader back down exists, starts hidden, and is not a tenth
6678    /// place that scrolls.
6679    #[test]
6680    fn the_way_back_down_is_a_button_on_the_stats_row() {
6681        assert!(
6682            INDEX_HTML.contains(r#"<button id="jump" type="button" hidden"#),
6683            "the control starts hidden and says what it is"
6684        );
6685        let css = INDEX_HTML
6686            .split("#statsrow #yolo[hidden] { display:none; }")
6687            .nth(1)
6688            .expect("the stats row's rules come before the button's");
6689        assert!(
6690            css.contains("#jump { position:absolute") && css.contains("bottom:calc(100% + 8px)"),
6691            "it floats over the transcript's corner, the way the model menu does"
6692        );
6693        assert!(
6694            INDEX_HTML.contains("jump.addEventListener('click'"),
6695            "and clicking it is wired"
6696        );
6697    }
6698
6699    /// `#269` / `#265`: every `var(--x)` either page asks for is a `--x` the generated `:root`
6700    /// emits.
6701    ///
6702    /// A property that nobody emitted is not a visible error. The declaration is invalid at
6703    /// computed-value time, so the property **inherits** — the version label renders at the
6704    /// accent's full strength and a disabled row looks enabled. `--faint` was asked for four times
6705    /// in `index.html` and emitted zero times for exactly that reason, and a test that only checks
6706    /// "the accent arrived" cannot see it. Both pages are scanned: the page nobody reads is the one
6707    /// that drifts, and it did.
6708    #[test]
6709    fn every_token_a_page_asks_for_is_one_the_palette_emits() {
6710        let css = palette_css();
6711        // What the block actually declares: `--name:` pairs, read back out of the CSS it emitted
6712        // rather than out of the table, so a formatter mistake in `palette_css` is caught too.
6713        let emitted: Vec<&str> = css
6714            .match_indices("--")
6715            .filter_map(|(i, _)| {
6716                let rest = &css[i + 2..];
6717                let end = rest.find(':')?;
6718                let name = &rest[..end];
6719                if name.chars().next()?.is_ascii_alphanumeric() {
6720                    Some(name)
6721                } else {
6722                    None
6723                }
6724            })
6725            .collect();
6726        assert!(
6727            emitted.len() >= 14,
6728            "the palette block reads back as {emitted:?}"
6729        );
6730
6731        for (name, page) in [("index.html", INDEX_HTML), ("login.html", LOGIN_HTML)] {
6732            let mut asked = std::collections::BTreeSet::new();
6733            for (i, _) in page.match_indices("var(--") {
6734                // `var(--fg)`, `var(--fg, red)` and `var(--fg,var(--bg))` all ask for `--fg`: stop
6735                // at the first character a custom-property name cannot contain.
6736                let rest = &page[i + "var(--".len()..];
6737                let end = rest
6738                    .find(|c: char| !(c.is_ascii_alphanumeric() || c == '-'))
6739                    .unwrap_or(rest.len());
6740                asked.insert(&rest[..end]);
6741            }
6742            assert!(
6743                asked.len() >= 6,
6744                "{name} asks for {asked:?} — the scan found almost nothing to check"
6745            );
6746            for token in asked {
6747                assert!(
6748                    emitted.contains(&token),
6749                    "{name} uses var(--{token}) and the palette emits no --{token}: \
6750                     the declaration would be dropped and the property would inherit"
6751                );
6752            }
6753        }
6754    }
6755
6756    /// `#265`: the sign-in page is this brand, not a second one.
6757    ///
6758    /// It carried a hand-copied `:root` — `--accent:#5aa2ff`, the old blue, one character from the
6759    /// `#5aa9ff` the dashboard's own scan test bans — so the only screen a person sees *before*
6760    /// they trust the dashboard was drawn in another product's colours.
6761    #[test]
6762    fn the_sign_in_page_is_the_same_brand() {
6763        use eclipse_core::palette as p;
6764        let page = login_html("token", "", "").0;
6765
6766        assert!(
6767            page.contains(&format!(
6768                "--accent:rgb({}, {}, {})",
6769                p::ACCENT.0,
6770                p::ACCENT.1,
6771                p::ACCENT.2
6772            )),
6773            "the accent arrives from the table, on this page too"
6774        );
6775        // The two colours this page is allowed to add to the block: the error and the ink on the
6776        // button's accent fill. Both are the table's.
6777        assert!(page.contains(&format!(
6778            "--bad:rgb({}, {}, {})",
6779            p::BAD.0,
6780            p::BAD.1,
6781            p::BAD.2
6782        )));
6783        assert!(page.contains(&format!(
6784            "--ink:rgb({}, {}, {})",
6785            p::INK.0,
6786            p::INK.1,
6787            p::INK.2
6788        )));
6789
6790        // The header the dashboard draws: the served mark, the word, the version.
6791        assert!(page.contains("src=\"/logo.svg\""), "the mark is on it");
6792        assert!(page.contains("class=\"version\""), "and the version");
6793        assert!(
6794            page.contains(&format!("v{}", env!("CARGO_PKG_VERSION"))),
6795            "the version is this build's"
6796        );
6797
6798        // Nothing it spells itself. The colours are the block above it or they are nothing.
6799        let styles = page.split("</style>").next().unwrap_or_default();
6800        assert!(
6801            !styles.contains(":#") && !styles.contains(": #"),
6802            "no colour literal in the sign-in sheet: {:?}",
6803            styles
6804                .match_indices(":#")
6805                .map(|(i, _)| &styles[i..(i + 8).min(styles.len())])
6806                .collect::<Vec<_>>()
6807        );
6808        for gone in ["#5aa2ff", "#5aa9ff"] {
6809            assert!(
6810                !page.to_lowercase().contains(gone),
6811                "{gone} is the blue this page used to be, and is not this brand"
6812            );
6813        }
6814        assert!(
6815            !page.contains("{{"),
6816            "a placeholder was left unfilled, and would render literally"
6817        );
6818    }
6819
6820    /// `#247`: the mark is served, its colours are the palette's, and the tab has an icon.
6821    ///
6822    /// The file on disk names four colours of its own. Serving it verbatim would make the dashboard
6823    /// a second definition of the brand, which is exactly the drift the palette exists to stop — so
6824    /// the test reads the served bytes, not the committed file.
6825    #[tokio::test]
6826    async fn the_mark_is_served_in_the_palettes_colours() {
6827        use eclipse_core::palette as p;
6828        let dir = tempfile::tempdir().unwrap();
6829        let app = router(state(dir.path(), true));
6830
6831        let r = app
6832            .clone()
6833            .oneshot(get_req("/logo.svg", "localhost:8787"))
6834            .await
6835            .unwrap();
6836        // No login: a browser asks for this before anyone has signed in, and a mark is not a secret.
6837        assert_eq!(r.status(), StatusCode::OK);
6838        assert!(
6839            r.headers()["content-type"]
6840                .to_str()
6841                .unwrap_or_default()
6842                .starts_with("image/svg+xml"),
6843            "{:?}",
6844            r.headers()["content-type"]
6845        );
6846        let svg = text(r).await;
6847        let hex = |c: (u8, u8, u8)| format!("#{:02X}{:02X}{:02X}", c.0, c.1, c.2);
6848        for (label, colour) in [
6849            ("the accent", p::ACCENT),
6850            ("the wordmark's hot end", p::WORDMARK_TOP),
6851            ("the page background", p::BG),
6852        ] {
6853            assert!(
6854                svg.contains(&hex(colour)),
6855                "{label} is {} in the served mark",
6856                hex(colour)
6857            );
6858        }
6859        // None of the file's own four survive: the geometry is the file's, the colour is the table's.
6860        for literal in ["#FF8A2B", "#FFB45E", "#FFF7E8", "#05060D"] {
6861            assert!(
6862                !svg.contains(literal),
6863                "{literal} is the file's, not the brand's"
6864            );
6865        }
6866        // And the geometry did survive — it is an eclipse, not a substitute circle.
6867        assert!(
6868            svg.contains("feGaussianBlur"),
6869            "the corona's blur is the file's"
6870        );
6871
6872        let ico = app
6873            .clone()
6874            .oneshot(get_req("/favicon.ico", "localhost:8787"))
6875            .await
6876            .unwrap();
6877        assert_eq!(ico.status(), StatusCode::OK);
6878        assert_eq!(ico.headers()["content-type"], "image/x-icon");
6879        let bytes = axum::body::to_bytes(ico.into_body(), 1 << 20)
6880            .await
6881            .unwrap();
6882        assert_eq!(
6883            bytes.len(),
6884            FAVICON_ICO.len(),
6885            "the committed icon, byte for byte"
6886        );
6887        assert!(bytes.starts_with(&[0, 0, 1, 0]), "an ICO header");
6888
6889        // Both pages name it, so neither tab is a blank page.
6890        let page = text(
6891            app.clone()
6892                .oneshot(get_req("/", "localhost:8787"))
6893                .await
6894                .unwrap(),
6895        )
6896        .await;
6897        assert_eq!(page.matches("rel=\"icon\"").count(), 1, "one icon link");
6898        assert!(page.contains("href=\"/favicon.ico\""), "{page:.0}");
6899        // `get_req` carries the login cookie, and a signed-in request to `/login` is a redirect —
6900        // the page in question is the one an *anonymous* browser gets.
6901        let login = text(
6902            app.oneshot(anon("GET", "/login").body(Body::empty()).unwrap())
6903                .await
6904                .unwrap(),
6905        )
6906        .await;
6907        assert!(
6908            login.contains("rel=\"icon\""),
6909            "the sign-in page too: {:?}",
6910            &login[..login.len().min(400)]
6911        );
6912    }
6913
6914    /// `#247`: the header says the same three things the terminal's header line does, and the mark is
6915    /// decorative — the accessible name is the word, not a picture.
6916    #[tokio::test]
6917    async fn the_header_carries_the_mark_and_a_readable_name() {
6918        let dir = tempfile::tempdir().unwrap();
6919        let html = text(
6920            router(state(dir.path(), true))
6921                .oneshot(get_req("/", "localhost:8787"))
6922                .await
6923                .unwrap(),
6924        )
6925        .await;
6926        let h1 = html
6927            .split("<h1>")
6928            .nth(1)
6929            .and_then(|rest| rest.split("</h1>").next())
6930            .expect("the header");
6931        assert!(h1.contains("id=\"mark\""), "{h1}");
6932        assert!(h1.contains("src=\"/logo.svg\""), "{h1}");
6933        assert!(
6934            h1.contains("aria-hidden=\"true\""),
6935            "the picture is not the name: {h1}"
6936        );
6937        assert!(h1.contains("alt=\"\""), "{h1}");
6938        assert!(h1.contains(">eclipse"), "the word is still there: {h1}");
6939        assert!(
6940            h1.contains(env!("CARGO_PKG_VERSION")),
6941            "the version is the binary's: {h1}"
6942        );
6943    }
6944
6945    /// `#389`, `#390`, `#391`: the composer's failure paths. There is no JavaScript runtime here, so
6946    /// these are assertions about the served page, over the region between two markers. Each one
6947    /// fails if the guard it names is removed; each guard was removed once to prove that.
6948    #[tokio::test]
6949    async fn a_turn_that_never_started_gives_the_composer_back() {
6950        let dir = tempfile::tempdir().unwrap();
6951        let html = text(
6952            router(state(dir.path(), true))
6953                .oneshot(get_req("/", "localhost:8787"))
6954                .await
6955                .unwrap(),
6956        )
6957        .await;
6958
6959        // `#389`: the composer is emptied before the POST, so the refusal branch has to give back
6960        // the words, the pastes and the attachments — and take away the bubble it drew, which no
6961        // store has.
6962        let refused = html
6963            .split("if (!resp.ok) {")
6964            .nth(1)
6965            .and_then(|rest| rest.split("let finished = false;").next())
6966            .expect("the refusal branch");
6967        assert!(
6968            refused.contains("restoreComposer();"),
6969            "what the press took goes back: {refused}"
6970        );
6971        assert!(
6972            refused.contains("if (echo) echo.remove();"),
6973            "and the bubble the press drew goes with it"
6974        );
6975        assert!(
6976            html.contains("const restoreComposer = () => {"),
6977            "the snapshot is taken before anything is cleared"
6978        );
6979
6980        // `#390`: a `/command` line belongs to the run that carried it. Every event that could use
6981        // it has been handled by the time `finally` runs, so it is cleared there whatever happened.
6982        let end = html
6983            .split("} finally {")
6984            .nth(1)
6985            .and_then(|rest| rest.split("busy = false;").next())
6986            .expect("the finally block");
6987        assert!(
6988            end.contains("deferredLine = null;"),
6989            "an unlanded command line is not echoed into the next turn: {end}"
6990        );
6991
6992        // `#391`: a malformed event is a row, not the end of the run, and the stream is closed on
6993        // every way out so the server's disconnect guard cancels what the page can no longer show.
6994        assert!(
6995            html.contains("try { handle(event, JSON.parse(data)); }"),
6996            "one bad event is contained where it happens"
6997        );
6998        assert!(
6999            html.contains("await reader.cancel()"),
7000            "the connection is closed on the way out"
7001        );
7002        assert!(
7003            html.contains("let reader = null;"),
7004            "and `finally` can reach the reader to do it"
7005        );
7006    }
7007
7008    /// `#238`: the model is a control in the stats row, not a footnote under the wordmark.
7009    #[tokio::test]
7010    async fn the_model_picker_lives_in_the_stats_row() {
7011        let dir = tempfile::tempdir().unwrap();
7012        let html = text(
7013            router(state(dir.path(), true))
7014                .oneshot(get_req("/", "localhost:8787"))
7015                .await
7016                .unwrap(),
7017        )
7018        .await;
7019        let aside = html
7020            .split("<aside>")
7021            .nth(1)
7022            .and_then(|rest| rest.split("</aside>").next())
7023            .expect("the sidebar");
7024        assert!(
7025            !aside.contains("id=\"model\""),
7026            "the sidebar no longer carries a model control: {aside:.0}"
7027        );
7028        let row = html
7029            .split("id=\"statsrow\"")
7030            .nth(1)
7031            .and_then(|rest| rest.split("<form id=\"form\"").next())
7032            .expect("the stats row");
7033        assert!(
7034            row.contains("id=\"model\""),
7035            "the button is in the row: {row}"
7036        );
7037        assert!(
7038            row.contains("id=\"models\""),
7039            "and its panel is anchored to it"
7040        );
7041        assert!(row.contains("role=\"menu\""), "a menu, not a panel");
7042
7043        // The submenu exists and its rows are live: the level list comes from the route's policy
7044        // (`GET /api/reasoning`), a pick posts to `/api/reasoning`, and the note says what a pick
7045        // lasts for (`#275`) — no hardcoded union of levels anywhere in the page.
7046        assert!(html.contains("showReasoning"), "the reasoning submenu");
7047        assert!(
7048            html.contains("fetch('/api/reasoning')"),
7049            "the words on offer are served, not spelled here"
7050        );
7051        assert!(
7052            !html.contains("const EFFORTS"),
7053            "the page owns no level list of its own"
7054        );
7055        assert!(
7056            !html.contains("the effort is fixed when eclipse-web starts"),
7057            "the page is no longer ignorant of the level"
7058        );
7059        assert!(
7060            html.contains("eclipse-web restarts. config.toml is not touched"),
7061            "the note says what a pick lasts for and what it does not write"
7062        );
7063        assert!(
7064            html.contains("modelRow('effort · '"),
7065            "a head row that names the level and cannot be picked"
7066        );
7067        // The level is in the page before the first turn, from the agent — `not sent` when the
7068        // configured route cannot take a level, which is a fact about the backend and not an
7069        // absence (`#276`: an unset file on a route that declares a default says that level).
7070        assert!(
7071            html.contains("id=\"effort\""),
7072            "the row carries the effort the next turn will ask for"
7073        );
7074        assert!(html.contains(">effort not sent</span>"), "{html:.0}");
7075        assert!(
7076            !html.contains("{{EFFORT}}"),
7077            "every placeholder is filled on the way out"
7078        );
7079        // `#401`: the value is HTML-escaped on the way out, which is right in an attribute and wrong
7080        // inside a JS string literal — the fallback tooltip read `&#39;`, and a value ending in a
7081        // backslash made the string unterminated and the whole script dead. The script reads the
7082        // element that already shows them instead.
7083        assert!(
7084            html.contains("const EFFORT0 = effortEl.dataset.label;")
7085                && html.contains("const EFFORT_DETAIL0 = effortEl.title;"),
7086            "the level and its sentence are read from the element, not written into the script"
7087        );
7088        assert!(
7089            !html.contains("const EFFORT0 = \""),
7090            "an interpolated literal is escaped for HTML and then parsed as JavaScript"
7091        );
7092        assert!(
7093            html.contains("data-label=\"not sent\""),
7094            "the label the script reads rides on the element"
7095        );
7096        // `#344`: the context row is not a fact about the page, it is a fact about a turn. The
7097        // window that used to be rendered here belonged to whichever model was configured when the
7098        // request came in, which is how one session could show 262K while running and 328K the
7099        // moment the reader navigated.
7100        assert!(
7101            !html.contains("{{CTX}}") && !html.contains("CTX0"),
7102            "the page-load window is gone, not merely unfilled"
7103        );
7104        assert!(
7105            html.contains("ctx -- · first --"),
7106            "an unmeasured row states no denominator"
7107        );
7108        assert!(
7109            html.contains("li.dataset.cost = s.cost"),
7110            "the sidebar's rows carry what the session last cost, so a click needs no request"
7111        );
7112        // Keyboard: one level at a time, and focus goes back where it came from.
7113        assert!(html.contains("focusRow"), "arrows walk the rows");
7114        assert!(
7115            html.contains("if (!modelSub.hidden) showModelList();"),
7116            "esc is one level"
7117        );
7118        assert!(html.contains("modelLabel.focus()"), "and focus returns");
7119
7120        // The page cannot know the level the process loaded, so it must not mark one.
7121        assert!(
7122            !html.contains("· current' : level"),
7123            "no guessed current effort"
7124        );
7125    }
7126
7127    /// `#237`: the transcript and the composer are the pane, and only the person's turn is a block.
7128    ///
7129    /// The cap was the bug — `max-width:800px; margin:0 auto` on `.msg` and `840px` on `#form` made
7130    /// the conversation a ribbon between two gutters while the sidebar ran to its own edge. A test
7131    /// that asserts the *absence* is the only kind that stops it coming back, because re-adding a
7132    /// cap looks like a tidy-up.
7133    #[tokio::test]
7134    async fn the_transcript_column_is_the_pane() {
7135        let dir = tempfile::tempdir().unwrap();
7136        let html = text(
7137            router(state(dir.path(), true))
7138                .oneshot(get_req("/", "localhost:8787"))
7139                .await
7140                .unwrap(),
7141        )
7142        .await;
7143        let styles = html.split("</style>").next().unwrap_or_default();
7144
7145        let rule = |selector: &str| -> String {
7146            styles
7147                .split(selector)
7148                .nth(1)
7149                .and_then(|rest| rest.split('}').next())
7150                .map(|body| body.to_string())
7151                .unwrap_or_default()
7152        };
7153
7154        for (selector, what) in [(".msg {", "the transcript"), ("#form {", "the composer")] {
7155            let body = rule(selector);
7156            assert!(!body.is_empty(), "{selector} is styled");
7157            assert!(
7158                !body.contains("max-width"),
7159                "{what} reaches the pane's edges: {selector} {body}"
7160            );
7161            assert!(
7162                !body.contains("margin:0 auto"),
7163                "{what} is not centred in a wider row: {selector} {body}"
7164            );
7165        }
7166        // The gutter is the padding on the scroll box, once.
7167        assert!(
7168            rule("#log {").contains("padding:20px"),
7169            "one gutter, on the box that scrolls"
7170        );
7171
7172        // The model's answer, the reasoning and tool rows carry no frame; the user's turn does.
7173        let assistant = rule(".msg.assistant {");
7174        assert!(!assistant.contains("background"), "{assistant}");
7175        assert!(!assistant.contains("border"), "{assistant}");
7176        let user = rule(".msg.user {");
7177        assert!(user.contains("background:var(--panel)"), "{user}");
7178        assert!(user.contains("border-left:3px solid var(--user)"), "{user}");
7179        // A framing turn still gets its padding back, now that `.msg` carries none.
7180        assert!(user.contains("padding"), "{user}");
7181        assert!(
7182            rule(".msg.approval {").contains("padding"),
7183            "the approval card"
7184        );
7185        assert!(
7186            rule(".msg.error {").contains("padding"),
7187            "the error verdict"
7188        );
7189    }
7190
7191    /// `#236`: one control for one job — Send while idle, Stop while a turn runs, small.
7192    #[tokio::test]
7193    async fn the_composer_has_one_control_with_two_states() {
7194        let dir = tempfile::tempdir().unwrap();
7195        let html = text(
7196            router(state(dir.path(), true))
7197                .oneshot(get_req("/", "localhost:8787"))
7198                .await
7199                .unwrap(),
7200        )
7201        .await;
7202        let form = html
7203            .split("<form id=\"form\"")
7204            .nth(1)
7205            .and_then(|rest| rest.split("</form>").next())
7206            .expect("the composer form");
7207
7208        // One *send* control with two states (#262) — not one button in the form: `#239` put the
7209        // `+` menu in there, and its rows are buttons too. What this test is for is that sending
7210        // and stopping are the same element, and that is `class="go"`.
7211        assert_eq!(form.matches("class=\"go\"").count(), 1, "{form}");
7212        assert!(form.contains("id=\"go\""), "{form}");
7213        assert!(!html.contains("id=\"send\""), "the second button is gone");
7214        assert!(!html.contains("id=\"stop\""), "not hidden, removed");
7215
7216        // It is a button, not an edge of the textarea.
7217        let styles = html.split("</style>").next().unwrap_or_default();
7218        let go = styles
7219            .split("button.go {")
7220            .nth(1)
7221            .and_then(|rest| rest.split('}').next())
7222            .unwrap_or_default();
7223        assert!(go.contains("align-self:center"), "{go}");
7224        assert!(go.contains("height:34px"), "{go}");
7225
7226        // Both states say what they are, and the stop state reaches the cancel route.
7227        assert!(
7228            html.contains("setGo('starting')"),
7229            "the press is acknowledged"
7230        );
7231        assert!(
7232            html.contains("setGo('stop')"),
7233            "a run with an id can be stopped"
7234        );
7235        assert!(html.contains("setGo('idle')"), "and the control comes back");
7236        assert!(
7237            html.contains("'Stop the run in flight'"),
7238            "the accessible name changes with the state"
7239        );
7240        assert!(
7241            html.contains("/cancel"),
7242            "the Stop state posts the route the server has"
7243        );
7244        assert!(
7245            html.contains("nothing to cancel yet"),
7246            "a press in the gap says so instead of doing nothing"
7247        );
7248    }
7249
7250    /// `#235`: the cron pane is one view of the main column, and every path that changes that view
7251    /// closes it. The failure was structural — `main.cron` was a class only the cron button ever
7252    /// cleared — so the test is structural too: each function that switches the column must route
7253    /// through `setView`, which sets the class, the button and `aria-expanded` together.
7254    ///
7255    /// It cannot see a *new* function forgetting the call; what it can see is the three switches
7256    /// that exist, and the shape of the helper they must use. The browser sequence is covered in
7257    /// `TECHNICAL.md`'s dashboard notes and was driven for real when this landed.
7258    #[tokio::test]
7259    async fn every_view_switch_closes_the_cron_pane() {
7260        let dir = tempfile::tempdir().unwrap();
7261        let html = text(
7262            router(state(dir.path(), true))
7263                .oneshot(get_req("/", "localhost:8787"))
7264                .await
7265                .unwrap(),
7266        )
7267        .await;
7268
7269        // The helper owns every dependent bit, so no caller can set one without the others.
7270        let helper = function_body(&html, "setView").expect("setView is the one switch");
7271        for bit in [
7272            "main').classList.toggle('cron'",
7273            "cronBtn.classList.toggle('on'",
7274            "aria-expanded",
7275            "cronPane.hidden",
7276        ] {
7277            assert!(helper.contains(bit), "`setView` sets {bit}: {helper}");
7278        }
7279        // And nothing else may write that class.
7280        let writers = html.matches("classList.toggle('cron'").count();
7281        assert_eq!(writers, 1, "the class is written in one place, not two");
7282
7283        // `showCron` is a thin rename, so the button and the interval cannot bypass the helper.
7284        let wrapper = function_body(&html, "showCron").expect("showCron still exists");
7285        assert!(
7286            wrapper.contains("setView(open ? 'cron' : 'session')"),
7287            "{wrapper}"
7288        );
7289
7290        // The three paths that replace the column: a stored session, a new one, a run's first turn.
7291        let loads = function_body(&html, "loadSession").expect("loadSession");
7292        assert!(
7293            loads.contains("setView('session')"),
7294            "opening a session closes the pane: {loads}"
7295        );
7296        let new_session = html
7297            .split("getElementById('new').addEventListener")
7298            .nth(1)
7299            .and_then(|rest| rest.split("\n  });").next())
7300            .expect("the + New session handler");
7301        assert!(new_session.contains("setView('session')"), "{new_session}");
7302        let stream = html
7303            .split("case 'session':")
7304            .nth(1)
7305            .and_then(|rest| rest.split("break;").next())
7306            .expect("the SSE session case");
7307        assert!(
7308            stream.contains("setView('session')"),
7309            "a run that starts a session takes the column: {stream}"
7310        );
7311    }
7312
7313    /// '#'345: a closed section must stay closed across the rebuild that follows every refresh, and
7314    /// the rows it holds must still be findable by the three readers that ask "where am I".
7315    #[tokio::test]
7316    async fn a_closed_section_reads_its_state_from_outside_the_rebuild() {
7317        let dir = tempfile::tempdir().unwrap();
7318        let html = text(
7319            router(state(dir.path(), true))
7320                .oneshot(get_req("/", "localhost:8787"))
7321                .await
7322                .unwrap(),
7323        )
7324        .await;
7325
7326        // The set of closed sections is module state, not the DOM. `groupList` re-runs after every
7327        // refresh, so a section that read its own state off the rows it had just rebuilt would
7328        // reopen itself the moment anything was renamed, pinned or written.
7329        let groups = function_body(&html, "groupList").expect("groupList is the one partition");
7330        assert!(
7331            groups.contains("collapsed.has"),
7332            "the rebuild consults the closed set: {groups}"
7333        );
7334        assert!(
7335            !groups.contains("saveCollapsed"),
7336            "the rebuild never writes the set back: {groups}"
7337        );
7338        assert!(
7339            !groups.contains("list.children"),
7340            "rows come from `master`, not from what is currently on screen: {groups}"
7341        );
7342        // One listener for every heading, present and future, because the headings are rebuilt.
7343        assert!(
7344            html.contains("closest('.grouptoggle')"),
7345            "one delegated listener toggles any heading"
7346        );
7347
7348        // A heading is a control now, so it is a button carrying `aria-expanded`, and the count is
7349        // built from the same partition that builds the rows.
7350        let head = function_body(&html, "header").expect("header builds every heading");
7351        for bit in [
7352            "createElement('button')",
7353            "aria-expanded",
7354            "grouptoggle",
7355            "\\u00b7",
7356        ] {
7357            assert!(head.contains(bit), "a heading carries {bit}: {head}");
7358        }
7359
7360        // Remembered per browser, because a collapse that forgets is the same annoyance as a stats
7361        // row that forgets.
7362        assert!(
7363            html.contains("localStorage.setItem(COLLAPSED_KEY"),
7364            "the set persists"
7365        );
7366        assert!(
7367            html.contains("localStorage.getItem(COLLAPSED_KEY"),
7368            "and is read back"
7369        );
7370
7371        // The row being read can be off screen, so the mark has two homes.
7372        let mark = function_body(&html, "markActive").expect("markActive");
7373        assert!(
7374            mark.contains("isConnected"),
7375            "a row that is not in the DOM marks its heading instead: {mark}"
7376        );
7377    }
7378
7379    /// The body of `function <name>(`: a one-liner closes on its own line, a block at its indent.
7380    fn function_body<'a>(html: &'a str, name: &str) -> Option<&'a str> {
7381        let start = html.find(&format!("function {name}("))?;
7382        let rest = &html[start..];
7383        if let Some(line) = rest.split('\n').next() {
7384            if line.contains('}') {
7385                return Some(line);
7386            }
7387        }
7388        let end = rest.find("\n  }")? + 3;
7389        Some(&rest[..end])
7390    }
7391
7392    #[tokio::test]
7393    async fn rejects_foreign_host_and_origin() {
7394        let dir = tempfile::tempdir().unwrap();
7395        let app = router(state(dir.path(), true));
7396        let r = app
7397            .clone()
7398            .oneshot(get_req("/healthz", "evil.example.com"))
7399            .await
7400            .unwrap();
7401        assert_eq!(r.status(), StatusCode::FORBIDDEN);
7402        // The refusal names the header it did not like. A person who typed a LAN name or clicked
7403        // a proxied link reads why, instead of suspecting their token.
7404        let said = body_text(r).await;
7405        assert!(
7406            said.contains("evil.example.com") && said.contains("127.0.0.1"),
7407            "{said}"
7408        );
7409        assert!(said.contains("SSH tunnel"), "{said}");
7410        // A read is never refused for its Origin: it changes nothing, and `SameSite=Strict` means a
7411        // cross-site navigation does not even carry the cookie. Refusing it only broke pages that
7412        // render inside a frame.
7413        let req = HttpRequest::get("/healthz")
7414            .header("host", "127.0.0.1:8787")
7415            .header("origin", "https://evil.example.com")
7416            .body(Body::empty())
7417            .unwrap();
7418        assert_eq!(
7419            app.clone().oneshot(req).await.unwrap().status(),
7420            StatusCode::OK
7421        );
7422
7423        // A write from a named foreign origin is refused, and the refusal has to be
7424        // distinguishable from the Host one: same port-less name, different port.
7425        let req = HttpRequest::post("/api/model")
7426            .header("host", "127.0.0.1:8787")
7427            .header("origin", "http://127.0.0.1:9999")
7428            .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
7429            .header("content-type", "application/json")
7430            .body(Body::from(json!({ "model": "picked" }).to_string()))
7431            .unwrap();
7432        let r = app.clone().oneshot(req).await.unwrap();
7433        assert_eq!(r.status(), StatusCode::FORBIDDEN);
7434        let said = body_text(r).await;
7435        assert!(
7436            said.contains("Origin") && said.contains("9999") && said.contains("8787"),
7437            "the message names both sides: {said}"
7438        );
7439        assert!(
7440            !said.contains("is not 127.0.0.1"),
7441            "not the Host refusal: {said}"
7442        );
7443        let req = HttpRequest::get("/healthz")
7444            .header("host", "localhost:8787")
7445            .header("origin", "http://localhost:8787")
7446            .body(Body::empty())
7447            .unwrap();
7448        assert_eq!(app.oneshot(req).await.unwrap().status(), StatusCode::OK);
7449    }
7450
7451    #[tokio::test]
7452    async fn responses_carry_hardening_headers() {
7453        let dir = tempfile::tempdir().unwrap();
7454        let r = router(state(dir.path(), true))
7455            .oneshot(get_req("/", "127.0.0.1:8787"))
7456            .await
7457            .unwrap();
7458        let csp = r.headers()[header::CONTENT_SECURITY_POLICY]
7459            .to_str()
7460            .unwrap();
7461        assert!(csp.contains("frame-ancestors 'none'") && csp.contains("default-src 'none'"));
7462        // The mark and the tab's icon arrive from this origin; a message's picture arrives as a
7463        // `data:` URL, and `data:` is the half that was missing — every replayed screenshot was a
7464        // broken-image box (`#365`). `script-src` is what keeps this from being a hole, so the
7465        // assertion names it too: an `img-src` that grew a remote host would be a different bug.
7466        assert!(
7467            csp.contains("img-src 'self' data:;"),
7468            "the mark, the icon and a message's picture are loadable: {csp}"
7469        );
7470        assert!(!csp.contains("img-src 'self' https:"), "{csp}");
7471        assert!(csp.contains("script-src 'unsafe-inline';"), "{csp}");
7472        assert_eq!(r.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
7473    }
7474
7475    #[tokio::test]
7476    async fn chat_is_rejected_when_all_slots_are_busy() {
7477        let dir = tempfile::tempdir().unwrap();
7478        let st = state(dir.path(), true);
7479        let _held = st
7480            .chat_slots
7481            .clone()
7482            .acquire_many_owned(MAX_CONCURRENT_CHATS as u32)
7483            .await
7484            .unwrap();
7485        let r = router(st)
7486            .oneshot(chat_req(json!({"message": "x"})))
7487            .await
7488            .unwrap();
7489        assert_eq!(r.status(), StatusCode::TOO_MANY_REQUESTS);
7490    }
7491
7492    #[tokio::test]
7493    async fn chat_streams_events_and_persists_session() {
7494        let dir = tempfile::tempdir().unwrap();
7495        let st = state(dir.path(), true);
7496        let resp = router(st.clone())
7497            .oneshot(chat_req(json!({"message": "hello"})))
7498            .await
7499            .unwrap();
7500        assert_eq!(resp.status(), StatusCode::OK);
7501        let body = text(resp).await;
7502        let order: Vec<_> = ["event: session", "event: message", "event: done"]
7503            .iter()
7504            .map(|m| {
7505                body.find(m)
7506                    .unwrap_or_else(|| panic!("missing {m} in {body}"))
7507            })
7508            .collect();
7509        assert!(order.windows(2).all(|w| w[0] < w[1]));
7510        assert!(body.contains("canned reply"));
7511
7512        let list = st.store.list().unwrap();
7513        assert_eq!(list.len(), 1);
7514        assert_eq!(list[0].messages, 2);
7515    }
7516
7517    /// `#220`: a big paste is one chip in the composer and one fold in the transcript, the threshold
7518    /// is the terminal's (`eclipse_core::paste`), and every character of the text still reaches the
7519    /// model — the chips are a display, and forgetting to expand them sends a placeholder.
7520    #[tokio::test]
7521    async fn a_large_paste_is_one_chip_and_the_model_still_gets_the_text() {
7522        use eclipse_core::paste::{chip_for, expand, fits_inline, Paste, PASTE_INLINE_LIMIT};
7523
7524        let dir = tempfile::tempdir().unwrap();
7525        let st = state(dir.path(), true);
7526        let page = text(
7527            router(st.clone())
7528                .oneshot(get_req("/", "localhost:8787"))
7529                .await
7530                .unwrap(),
7531        )
7532        .await;
7533
7534        // The threshold on the page is the binary's constant, rendered, not a number typed in HTML.
7535        assert!(
7536            page.contains(&format!("data-paste-limit=\"{PASTE_INLINE_LIMIT}\"")),
7537            "the composer reads its limit from `eclipse_core::paste`"
7538        );
7539        assert!(
7540            !page.contains("{{PASTE_LIMIT}}"),
7541            "the placeholder was filled"
7542        );
7543        // The machinery: a paste that does not fit becomes a chip, chips expand on submit, and a
7544        // folded user turn says how big it is.
7545        for needle in [
7546            "function fitsInline",
7547            "function chipFor",
7548            "function expandPastes",
7549            "addEventListener('paste'",
7550            "function userMessage",
7551            "PASTE_FOLD_LINES",
7552        ] {
7553            assert!(page.contains(needle), "the composer's paste rule: {needle}");
7554        }
7555
7556        // The rule itself, on the same text the page would see: 200 lines of a log is not inline,
7557        // and the chip it becomes names what it stands for.
7558        let log: String = (1..=200).map(|i| format!("line {i}\n")).collect();
7559        assert!(!fits_inline(&log));
7560        let chip = chip_for(&log, 1);
7561        // The counts are the text's own, not a number written into the test.
7562        assert_eq!(
7563            chip,
7564            format!("[Pasted #1: 200 line(s), {} chars]", log.chars().count())
7565        );
7566        assert_eq!(
7567            expand(
7568                &format!("why is this failing? {chip}"),
7569                &[Paste {
7570                    chip: chip.clone(),
7571                    text: log.clone(),
7572                }]
7573            ),
7574            format!("why is this failing? {log}")
7575        );
7576
7577        // And the wire: a message this size is a normal turn, not a 413, and what the store holds is
7578        // the text — no chip, nothing truncated.
7579        let message = format!("here is the log:\n{log}");
7580        let resp = router(st.clone())
7581            .oneshot(chat_req(json!({ "message": message })))
7582            .await
7583            .unwrap();
7584        assert_eq!(resp.status(), StatusCode::OK);
7585        assert!(text(resp).await.contains("event: done"));
7586
7587        let list = st.store.list().unwrap();
7588        assert_eq!(list.len(), 1);
7589        let stored = st.store.load(&list[0].id).unwrap();
7590        let first = &stored[0];
7591        assert_eq!(first.role, eclipse_core::message::Role::User);
7592        let content = first.content.as_deref().unwrap_or_default();
7593        assert_eq!(content, message, "every character, and no chip");
7594        assert!(
7595            !content.contains("[Pasted"),
7596            "a chip is a display, not a message"
7597        );
7598    }
7599
7600    /// `#220`: a turn over the cap is refused by name, before its body is read. The request below
7601    /// declares five megabytes and carries none — if the refusal came from axum's extractor instead
7602    /// of from `refuse_oversized`, the sentence would be missing and this would be a bare 413.
7603    #[tokio::test]
7604    async fn a_body_over_the_limit_is_refused_by_name() {
7605        let dir = tempfile::tempdir().unwrap();
7606        let st = state(dir.path(), true);
7607        let too_big = CHAT_BODY_LIMIT * 2;
7608        let r = router(st)
7609            .oneshot(
7610                HttpRequest::post("/api/chat")
7611                    .header("host", "127.0.0.1:8787")
7612                    .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
7613                    .header("content-type", "application/json")
7614                    .header("content-length", too_big.to_string())
7615                    .body(Body::empty())
7616                    .unwrap(),
7617            )
7618            .await
7619            .unwrap();
7620        assert_eq!(r.status(), StatusCode::PAYLOAD_TOO_LARGE);
7621        let body = text(r).await;
7622        assert!(body.contains("that message is"), "{body}");
7623        // The limit is quoted from the constant, not typed: it is derived from the picture rules
7624        // and moved once already (`#382`).
7625        let named = format!("{:.1} MB limit", CHAT_BODY_LIMIT as f64 / (1024.0 * 1024.0));
7626        assert!(
7627            body.contains(&named),
7628            "the limit is named in the sentence: {body}"
7629        );
7630        assert!(
7631            body.contains("smaller pictures") && body.contains("send its path"),
7632            "and so is what to do instead: {body}"
7633        );
7634
7635        // A turn under the cap is not touched by the guard.
7636        let r = router(state(dir.path(), true))
7637            .oneshot(chat_req(json!({ "message": "small" })))
7638            .await
7639            .unwrap();
7640        assert_eq!(r.status(), StatusCode::OK);
7641    }
7642
7643    #[tokio::test]
7644    async fn chat_emits_a_delta_event_per_chunk_before_the_final_message() {
7645        let dir = tempfile::tempdir().unwrap();
7646        let store = SessionStore::new(dir.path().join("sessions"));
7647        let agent = Agent::new(
7648            Arc::new(Streaming),
7649            Arc::new(ToolRegistry::default()),
7650            store.clone(),
7651            "sys".into(),
7652            3,
7653        );
7654        let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
7655        let body = text(
7656            router(st)
7657                .oneshot(chat_req(json!({"message": "hi"})))
7658                .await
7659                .unwrap(),
7660        )
7661        .await;
7662        let at = |needle: &str| {
7663            body.find(needle)
7664                .unwrap_or_else(|| panic!("missing {needle} in {body}"))
7665        };
7666        assert_eq!(body.matches("event: delta").count(), 2);
7667        assert!(at("data: {\"text\":\"tok\"}") < at("data: {\"text\":\"ens\"}"));
7668        assert!(at("event: delta") < at("event: message"));
7669        assert!(body.contains("data: {\"text\":\"tokens\"}"));
7670    }
7671
7672    /// The footer bar reads exactly one event. It has to carry the numbers the terminal line
7673    /// prints — context fill against the budget, the cache share, first token, wall time, t/s —
7674    /// so a browser run and a CLI run of the same turn can be compared by eye.
7675    #[tokio::test]
7676    async fn the_stats_event_carries_the_numbers_the_footer_prints() {
7677        let dir = tempfile::tempdir().unwrap();
7678        let store = SessionStore::new(dir.path().join("sessions"));
7679        let agent = Agent::new(
7680            Arc::new(Measured),
7681            Arc::new(ToolRegistry::default()),
7682            store.clone(),
7683            "sys".into(),
7684            3,
7685        );
7686        let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
7687        let body = text(
7688            router(st)
7689                .oneshot(chat_req(json!({"message": "hi"})))
7690                .await
7691                .unwrap(),
7692        )
7693        .await;
7694        assert!(body.contains("event: stats"), "{body}");
7695        let stats = stats_payload(&body);
7696        assert_eq!(stats["prompt_tokens"], json!(30000));
7697        assert_eq!(stats["completion_tokens"], json!(120));
7698        assert_eq!(stats["cached_tokens"], json!(19000));
7699        assert_eq!(stats["latency_ms"], json!(2900));
7700        assert_eq!(
7701            stats["tokens_per_sec"],
7702            json!(48.0),
7703            "120 tokens over the 2.5 s the server timed"
7704        );
7705        assert!(
7706            stats["ttft_ms"].as_u64().unwrap_or(0) >= 20,
7707            "the client's own first-token time: {}",
7708            stats["ttft_ms"]
7709        );
7710        assert!(
7711            stats["context_tokens"].as_u64().unwrap() > 0,
7712            "the assembled prompt is a size, not a placeholder"
7713        );
7714        assert_eq!(
7715            stats["budget_tokens"],
7716            json!(0),
7717            "no budget set is 0, and the footer draws that as `ctx <used>` with no denominator"
7718        );
7719        // `#264`: what the page prints is `eclipse_core::contextbar`'s answer, not arithmetic done
7720        // again in JavaScript. With no window stated, the window is not invented — the reading says
7721        // so in words, exactly as the terminal says it.
7722        assert_eq!(
7723            stats["ctx"],
7724            json!("ctx 30.0K tokens · no budget"),
7725            "the page's context field is the shared reading: {}",
7726            stats["ctx"]
7727        );
7728        assert_eq!(stats["window_tokens"], json!(0), "nobody stated a window");
7729        assert_eq!(
7730            stats["effort"],
7731            json!("not sent"),
7732            "this agent has no provider configuration, so nothing is sent — and the label says \
7733             that rather than naming a level"
7734        );
7735        assert_eq!(stats["effort_session"], json!(false), "nothing overrode it");
7736        assert!(
7737            !stats["effort_detail"].as_str().unwrap_or("").is_empty(),
7738            "the long sentence travels for the row's title: {}",
7739            stats["effort_detail"]
7740        );
7741        assert!(
7742            INDEX_HTML.contains(
7743                "case 'stats':\n        // A turn in flight is the one row that is current"
7744            ) && INDEX_HTML.contains("paintLive(data);")
7745                && INDEX_HTML.contains("if (data.effort) setEffort("),
7746            "the page has to put the event in the bar, or the numbers go nowhere"
7747        );
7748    }
7749
7750    /// `#264`, the half that was wrong on the dashboard: the bar's end is the model's **window**,
7751    /// and the compaction threshold is a mark inside it. The old footer divided by the rail — the
7752    /// only number the event carried — so `ctx 12.3K/279K` claimed a percentage of a number the
7753    /// model had never been told, and the rail's own share of the window was drawn nowhere.
7754    #[tokio::test]
7755    async fn the_context_bar_ends_at_the_window_and_marks_the_threshold_inside_it() {
7756        let dir = tempfile::tempdir().unwrap();
7757        let store = SessionStore::new(dir.path().join("sessions"));
7758        let agent = Agent::new(
7759            Arc::new(Measured),
7760            Arc::new(ToolRegistry::default()),
7761            store.clone(),
7762            "sys".into(),
7763            3,
7764        )
7765        // 328K window, compaction at 85% of it.
7766        .with_context_policy(0.85, 20, 328_000, 120_000);
7767        let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
7768        let body = text(
7769            router(st)
7770                .oneshot(chat_req(json!({"message": "hi"})))
7771                .await
7772                .unwrap(),
7773        )
7774        .await;
7775        let stats = stats_payload(&body);
7776        assert_eq!(
7777            stats["window_tokens"],
7778            json!(328_000),
7779            "the window is the end"
7780        );
7781        let ctx = stats["ctx"].as_str().unwrap_or_default();
7782        assert!(
7783            ctx.starts_with("ctx 30.0K/328K "),
7784            "the prompt out of the window, not out of the rail: {ctx}"
7785        );
7786        assert!(
7787            ctx.contains('│'),
7788            "the compaction threshold is a mark inside the bar, not its end: {ctx}"
7789        );
7790        assert!(
7791            ctx.ends_with(" 9%"),
7792            "the same percentage the CLI prints: {ctx}"
7793        );
7794        // The bar's own share of the window is the reading's, so a rail above the window cannot
7795        // produce a marker: 85% of the *rail* is not a place in the window.
7796        assert!(!ctx.contains("compacts at"));
7797    }
7798
7799    /// The one `stats` event in a chat stream, parsed.
7800    fn stats_payload(body: &str) -> serde_json::Value {
7801        let data = body
7802            .lines()
7803            .skip_while(|l| *l != "event: stats")
7804            .nth(1)
7805            .and_then(|l| l.strip_prefix("data: "))
7806            .unwrap_or_else(|| panic!("no stats event in {body}"));
7807        serde_json::from_str(data).unwrap()
7808    }
7809
7810    /// A server that reports nothing sends `null`, never `0`: the page draws `--` for a field
7811    /// that did not arrive, and it cannot tell "nothing" from "zero" if the server invents one.
7812    #[tokio::test]
7813    async fn a_silent_server_sends_nulls_and_the_footer_draws_dashes_for_them() {
7814        let dir = tempfile::tempdir().unwrap();
7815        let st = state(dir.path(), true);
7816        let body = text(
7817            router(st)
7818                .oneshot(chat_req(json!({"message": "hi"})))
7819                .await
7820                .unwrap(),
7821        )
7822        .await;
7823        for needle in [
7824            "\"cached_tokens\":null",
7825            "\"ttft_ms\":null",
7826            "\"tokens_per_sec\":null",
7827            "\"prompt_tokens\":null",
7828        ] {
7829            assert!(
7830                body.contains(needle),
7831                "an unreported field is null, never a made-up number: {needle} in {body}"
7832            );
7833        }
7834        for needle in [
7835            "id=\"stats\"",
7836            "const UNKNOWN = '--'",
7837            // `#264` and `#344`: the context field is the server's own string, and with nothing
7838            // measured there is no window to fall back to — the page-load one is gone.
7839            "const ctx = d.ctx || 'ctx --';",
7840            "'first ' + duration(d.ttft_ms)",
7841        ] {
7842            assert!(INDEX_HTML.contains(needle), "the page draws {needle}");
7843        }
7844    }
7845
7846    /// Reasoning and tool-argument fragments are their own events, in the order the turn
7847    /// produced them: what the model thought, then what it was composing, then its reply.
7848    /// The dashboard renders them as separate blocks, so the events have to arrive separate.
7849    #[tokio::test]
7850    async fn reasoning_and_argument_fragments_are_their_own_events_before_the_reply() {
7851        let dir = tempfile::tempdir().unwrap();
7852        let store = SessionStore::new(dir.path().join("sessions"));
7853        let agent = Agent::new(
7854            Arc::new(ThinksAloud),
7855            Arc::new(ToolRegistry::default()),
7856            store.clone(),
7857            "sys".into(),
7858            3,
7859        );
7860        let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
7861        let body = text(
7862            router(st)
7863                .oneshot(chat_req(json!({"message": "hi"})))
7864                .await
7865                .unwrap(),
7866        )
7867        .await;
7868        let at = |needle: &str| {
7869            body.find(needle)
7870                .unwrap_or_else(|| panic!("missing {needle} in {body}"))
7871        };
7872        assert!(body.contains("event: reasoning"), "{body}");
7873        assert!(
7874            body.contains("data: {\"text\":\"weighing \"}")
7875                && body.contains("data: {\"text\":\"it\"}"),
7876            "each reasoning fragment is its own event: {body}"
7877        );
7878        assert!(
7879            body.contains("event: tool_call_delta")
7880                && body.contains("data: {\"index\":0,\"json\":\"{\\\"path\\\"\"}"),
7881            "the argument fragment keeps its call index: {body}"
7882        );
7883        assert!(
7884            at("event: reasoning") < at("event: tool_call_delta"),
7885            "reasoning comes before the call it explains"
7886        );
7887        assert!(at("event: tool_call_delta") < at("event: message"));
7888        // The dashboard has no reasoning panel that could invent one: the page has to handle
7889        // both events, or the stream is emitted into nothing.
7890        for handler in [
7891            "case 'reasoning'",
7892            "case 'tool_call_delta'",
7893            "addThinking(",
7894            "addCall(",
7895        ] {
7896            assert!(INDEX_HTML.contains(handler), "the page handles {handler}");
7897        }
7898        // Both arrive folded, and a fold that is not a <details> is a fold with no keyboard.
7899        for rule in ["details.reasoning", "details.tool", "#thinkall"] {
7900            assert!(INDEX_HTML.contains(rule), "the page styles {rule}");
7901        }
7902        assert!(
7903            INDEX_HTML.contains("function addThinking") && INDEX_HTML.contains("function addCall"),
7904            "a reload rebuilds the same folds the stream built"
7905        );
7906        assert!(
7907            INDEX_HTML.contains("m.reasoning_content"),
7908            "a reloaded session shows the reasoning it stored"
7909        );
7910    }
7911
7912    /// Emits a reasoning fragment, then a tool-argument fragment, then a plain reply. No
7913    /// tool call completes, so the run ends with `stop`.
7914    struct ThinksAloud;
7915
7916    #[async_trait]
7917    impl ChatProvider for ThinksAloud {
7918        async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
7919            unreachable!()
7920        }
7921        async fn chat_stream(
7922            &self,
7923            _: &[Message],
7924            _: &[ToolSpec],
7925            on_delta: eclipse_core::stream::DeltaFn<'_>,
7926        ) -> CoreResult<Message> {
7927            on_delta(eclipse_core::stream::Delta::Reasoning("weighing ".into()));
7928            on_delta(eclipse_core::stream::Delta::Reasoning("it".into()));
7929            on_delta(eclipse_core::stream::Delta::ToolCallArgs {
7930                index: 0,
7931                json: "{\"path\"".into(),
7932            });
7933            on_delta(eclipse_core::stream::Delta::Text("done".into()));
7934            Ok(Message::assistant("done"))
7935        }
7936    }
7937
7938    #[tokio::test]
7939    async fn context_trimmed_event_reports_the_judgement_pass_and_the_handoff() {
7940        let dir = tempfile::tempdir().unwrap();
7941        let store = SessionStore::new(dir.path().join("sessions"));
7942        for i in 0..3 {
7943            store
7944                .append("s", &Message::user(format!("old{i} {}", "y".repeat(400))))
7945                .unwrap();
7946            store.append("s", &Message::assistant("ok")).unwrap();
7947        }
7948        let agent = Agent::new(
7949            Arc::new(Canned),
7950            Arc::new(ToolRegistry::default()),
7951            store.clone(),
7952            "sys".into(),
7953            3,
7954        )
7955        .with_context_budget(150)
7956        .with_judgement(false, std::time::Duration::from_secs(1));
7957        let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
7958        let body = text(
7959            router(st)
7960                .oneshot(chat_req(json!({"message": "hi", "session_id": "s"})))
7961                .await
7962                .unwrap(),
7963        )
7964        .await;
7965        assert!(body.contains("event: context_trimmed"), "{body}");
7966        // The judgement pass is off in this app, and the dashboard says exactly that rather than
7967        // implying a model wrote something.
7968        assert!(
7969            body.contains("\"judgement\":\"off\"")
7970                && body.contains("\"judgement_bullets\":0")
7971                && body.contains("\"judgement_error\":null"),
7972            "{body}"
7973        );
7974        assert!(
7975            body.contains("\"memory\":\"saved\"") && body.contains("\"memory_error\":null"),
7976            "{body}"
7977        );
7978        assert!(
7979            !body.contains("summarized") && !body.contains("summary_error"),
7980            "the summary path is gone from the wire too: {body}"
7981        );
7982        assert!(body.contains("event: message"));
7983    }
7984
7985    /// App whose model asks to write `ws/o.txt` (policy "ask") and then finishes.
7986    fn approval_app(dir: &std::path::Path, timeout: Duration) -> (Router, Shared) {
7987        use eclipse_core::config::ToolsConfig;
7988        std::fs::create_dir_all(dir.join("ws")).unwrap();
7989        let store = SessionStore::new(dir.join("sessions"));
7990        let call = Message::assistant_tool_calls(
7991            None,
7992            vec![eclipse_core::message::ToolCall {
7993                id: "c1".into(),
7994                kind: "function".into(),
7995                function: eclipse_core::message::FunctionCall {
7996                    name: "write_file".into(),
7997                    arguments: r#"{"path":"o.txt","content":"x"}"#.into(),
7998                },
7999            }],
8000        );
8001        // These tests are about the approval plumbing, not about which calls are worth asking
8002        // about, so they set a policy that asks rather than relying on the shell's risk list.
8003        let cfg = ToolsConfig {
8004            write_file: eclipse_core::config::Policy::Ask,
8005            ..ToolsConfig::default()
8006        };
8007        let agent = Agent::new(
8008            Scripted::new(vec![call, Message::assistant("finished")]),
8009            Arc::new(ToolRegistry::from_config(&cfg, dir.join("ws"))),
8010            store.clone(),
8011            "sys".into(),
8012            4,
8013        );
8014        let st = Arc::new(
8015            authed(Some(Arc::new(agent)), store, "m", None).with_approval_timeout(timeout),
8016        );
8017        (router(st.clone()), st)
8018    }
8019
8020    async fn read_until(
8021        body: &mut (impl Stream<Item = Result<axum::body::Bytes, axum::Error>> + Unpin),
8022        seen: &mut String,
8023        needle: &str,
8024    ) {
8025        while !seen.contains(needle) {
8026            let chunk = tokio::time::timeout(Duration::from_secs(5), body.next())
8027                .await
8028                .unwrap_or_else(|_| panic!("timed out waiting for {needle} in {seen}"))
8029                .unwrap_or_else(|| panic!("stream ended before {needle}: {seen}"))
8030                .unwrap();
8031            seen.push_str(&String::from_utf8_lossy(&chunk));
8032        }
8033    }
8034
8035    /// Value of the first `"id":"…"` after `event: approval_request`.
8036    fn request_id(seen: &str) -> String {
8037        let at = seen.find("event: approval_request").unwrap();
8038        let data = seen[at..]
8039            .lines()
8040            .nth(1)
8041            .unwrap()
8042            .trim_start_matches("data: ");
8043        serde_json::from_str::<serde_json::Value>(data).unwrap()["id"]
8044            .as_str()
8045            .unwrap()
8046            .to_string()
8047    }
8048
8049    fn decision_req(id: &str, body: serde_json::Value) -> HttpRequest<Body> {
8050        HttpRequest::post(format!("/api/approvals/{id}"))
8051            .header("host", "127.0.0.1:8787")
8052            .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
8053            .header("content-type", "application/json")
8054            .body(Body::from(body.to_string()))
8055            .unwrap()
8056    }
8057
8058    async fn run_with_decision(approved: bool) -> (String, bool, usize) {
8059        let dir = tempfile::tempdir().unwrap();
8060        let (app, st) = approval_app(dir.path(), Duration::from_secs(30));
8061        let resp = app
8062            .clone()
8063            .oneshot(chat_req(json!({"message": "write it"})))
8064            .await
8065            .unwrap();
8066        let mut body = resp.into_body().into_data_stream();
8067        let mut seen = String::new();
8068        read_until(&mut body, &mut seen, "event: approval_request").await;
8069        read_until(&mut body, &mut seen, "\"tool\":\"write_file\"}").await;
8070        let id = request_id(&seen);
8071        // Nothing may have run before the decision.
8072        assert!(!dir.path().join("ws/o.txt").exists());
8073        let r = app
8074            .clone()
8075            .oneshot(decision_req(&id, json!({"approved": approved})))
8076            .await
8077            .unwrap();
8078        assert_eq!(r.status(), StatusCode::OK);
8079        while let Some(chunk) = body.next().await {
8080            seen.push_str(&String::from_utf8_lossy(&chunk.unwrap()));
8081        }
8082        // A second answer for the same request is refused.
8083        let again = app
8084            .oneshot(decision_req(&id, json!({"approved": true})))
8085            .await
8086            .unwrap();
8087        assert_eq!(again.status(), StatusCode::NOT_FOUND);
8088        let written = dir.path().join("ws/o.txt").exists();
8089        (seen, written, st.approvals.len())
8090    }
8091
8092    #[tokio::test]
8093    async fn approving_an_ask_tool_in_the_ui_runs_it() {
8094        let (events, written, pending) = run_with_decision(true).await;
8095        assert!(written, "{events}");
8096        assert!(events.contains(r#""outcome":"approved""#), "{events}");
8097        assert!(events.contains("event: done") && events.contains("finished"));
8098        assert_eq!(pending, 0);
8099        // The row the page draws is one line, and the line is the server's: if this stops
8100        // travelling, the page falls back to printing the arguments and the fold is pointless.
8101        assert!(
8102            events.contains(r#""summary":"write_file o.txt · 1 B""#),
8103            "the call's statement travels with it: {events}"
8104        );
8105    }
8106
8107    #[tokio::test]
8108    async fn denying_an_ask_tool_in_the_ui_declines_it_and_the_run_continues() {
8109        let (events, written, pending) = run_with_decision(false).await;
8110        assert!(!written, "{events}");
8111        assert!(events.contains(r#""outcome":"denied""#), "{events}");
8112        assert!(events.contains("declined"), "{events}");
8113        assert!(events.contains("finished"));
8114        assert_eq!(pending, 0);
8115    }
8116
8117    #[tokio::test]
8118    async fn unanswered_approval_times_out_declined_and_is_cleaned_up() {
8119        let dir = tempfile::tempdir().unwrap();
8120        let (app, st) = approval_app(dir.path(), Duration::from_millis(100));
8121        let resp = app
8122            .clone()
8123            .oneshot(chat_req(json!({"message": "write it"})))
8124            .await
8125            .unwrap();
8126        let events = text(resp).await;
8127        assert!(events.contains(r#""outcome":"timeout""#), "{events}");
8128        assert!(events.contains("declined") && events.contains("event: done"));
8129        assert!(!dir.path().join("ws/o.txt").exists());
8130        assert_eq!(st.approvals.len(), 0);
8131        let id = request_id(&events);
8132        let late = app
8133            .oneshot(decision_req(&id, json!({"approved": true})))
8134            .await
8135            .unwrap();
8136        assert_eq!(late.status(), StatusCode::NOT_FOUND);
8137        assert!(!dir.path().join("ws/o.txt").exists());
8138    }
8139
8140    #[tokio::test]
8141    async fn disconnecting_while_an_approval_is_pending_frees_the_run() {
8142        let dir = tempfile::tempdir().unwrap();
8143        let (app, st) = approval_app(dir.path(), Duration::from_secs(60));
8144        let resp = app
8145            .oneshot(chat_req(json!({"message": "write it"})))
8146            .await
8147            .unwrap();
8148        let mut body = resp.into_body().into_data_stream();
8149        let mut seen = String::new();
8150        read_until(&mut body, &mut seen, "event: approval_request").await;
8151        assert_eq!(st.approvals.len(), 1);
8152        drop(body);
8153        for _ in 0..100 {
8154            if st.approvals.len() == 0 && st.chat_slots.available_permits() == MAX_CONCURRENT_CHATS
8155            {
8156                break;
8157            }
8158            tokio::time::sleep(Duration::from_millis(20)).await;
8159        }
8160        assert_eq!(st.approvals.len(), 0);
8161        assert_eq!(st.chat_slots.available_permits(), MAX_CONCURRENT_CHATS);
8162        assert!(!dir.path().join("ws/o.txt").exists());
8163    }
8164
8165    #[tokio::test]
8166    async fn approval_endpoint_rejects_bad_ids_and_bodies() {
8167        let dir = tempfile::tempdir().unwrap();
8168        let (app, _) = approval_app(dir.path(), Duration::from_secs(1));
8169        let r = app
8170            .clone()
8171            .oneshot(decision_req("deadbeef", json!({"approved": true})))
8172            .await
8173            .unwrap();
8174        assert_eq!(r.status(), StatusCode::NOT_FOUND);
8175        let r = app
8176            .clone()
8177            .oneshot(decision_req("not-hex!", json!({"approved": true})))
8178            .await
8179            .unwrap();
8180        assert_eq!(r.status(), StatusCode::BAD_REQUEST);
8181        let r = app
8182            .clone()
8183            .oneshot(decision_req("deadbeef", json!({"approve": true})))
8184            .await
8185            .unwrap();
8186        assert!(r.status().is_client_error());
8187    }
8188
8189    #[tokio::test]
8190    async fn chat_validates_input_and_configuration() {
8191        let dir = tempfile::tempdir().unwrap();
8192        let app = router(state(dir.path(), true));
8193        let r = app
8194            .clone()
8195            .oneshot(chat_req(json!({"message": "  "})))
8196            .await
8197            .unwrap();
8198        assert_eq!(r.status(), StatusCode::BAD_REQUEST);
8199        let r = app
8200            .clone()
8201            .oneshot(chat_req(json!({"message": "x", "session_id": "../x"})))
8202            .await
8203            .unwrap();
8204        assert_eq!(r.status(), StatusCode::BAD_REQUEST);
8205        // `#254`: `/bg` is the table's refusal now, not a special case in this handler — a 200
8206        // with a `notice` whose text says where the verb lives, because a refused command is an
8207        // answer in the transcript rather than an HTTP error the page has to translate.
8208        let r = app
8209            .clone()
8210            .oneshot(chat_req(json!({"message": "/bg count the files"})))
8211            .await
8212            .unwrap();
8213        assert_eq!(r.status(), StatusCode::OK);
8214        let said = text(r).await;
8215        assert!(
8216            said.contains("only in the full-screen interface and the plain REPL"),
8217            "{said}"
8218        );
8219
8220        let r = router(state(dir.path(), false))
8221            .oneshot(chat_req(json!({"message": "x"})))
8222            .await
8223            .unwrap();
8224        assert_eq!(r.status(), StatusCode::SERVICE_UNAVAILABLE);
8225        assert!(text(r).await.contains("base_url"));
8226    }
8227
8228    #[tokio::test]
8229    async fn renamed_sessions_show_their_title() {
8230        let dir = tempfile::tempdir().unwrap();
8231        let st = state(dir.path(), true);
8232        st.store
8233            .append("s1", &Message::user("first words"))
8234            .unwrap();
8235        st.store.rename("s1", "Trip <plan>").unwrap();
8236        let app = router(st);
8237        let html = text(
8238            app.clone()
8239                .oneshot(get_req("/", "127.0.0.1:1"))
8240                .await
8241                .unwrap(),
8242        )
8243        .await;
8244        assert!(
8245            html.contains("data-id=\"s1\"") && html.contains("class=\"name\">Trip &lt;plan&gt;"),
8246            "{html}"
8247        );
8248        let r = app
8249            .clone()
8250            .oneshot(get_req("/api/sessions", "127.0.0.1:1"))
8251            .await
8252            .unwrap();
8253        let v: serde_json::Value = serde_json::from_str(&text(r).await).unwrap();
8254        assert_eq!(v[0]["title"], "Trip <plan>");
8255        assert_eq!(v[0]["preview"], "first words");
8256    }
8257
8258    #[tokio::test]
8259    async fn search_finds_the_message_and_names_its_session() {
8260        let dir = tempfile::tempdir().unwrap();
8261        let st = state(dir.path(), true);
8262        st.store
8263            .append("s1", &Message::user("the quick brown fox"))
8264            .unwrap();
8265        st.store
8266            .append("s2", &Message::user("nothing here"))
8267            .unwrap();
8268        let app = router(st);
8269
8270        // No query, and a blank one, are both "nothing to look for" — not "everything".
8271        for path in ["/api/search", "/api/search?q=", "/api/search?q=%20%20"] {
8272            let r = app
8273                .clone()
8274                .oneshot(get_req(path, "127.0.0.1:1"))
8275                .await
8276                .unwrap();
8277            assert_eq!(r.status(), StatusCode::OK, "{path}");
8278            assert_eq!(text(r).await.trim(), "[]", "{path}");
8279        }
8280
8281        let r = app
8282            .clone()
8283            .oneshot(get_req("/api/search?q=brown", "127.0.0.1:1"))
8284            .await
8285            .unwrap();
8286        assert_eq!(r.status(), StatusCode::OK);
8287        let body = text(r).await;
8288        assert!(body.contains("\"s1\""), "{body}");
8289        assert!(
8290            !body.contains("\"s2\""),
8291            "only the matching session: {body}"
8292        );
8293        assert!(
8294            body.contains("brown"),
8295            "the snippet carries the match: {body}"
8296        );
8297        assert!(
8298            body.contains("\"seq\":0"),
8299            "the hit says where it is: {body}"
8300        );
8301
8302        // A word nobody said finds nothing rather than falling over.
8303        let r = app
8304            .clone()
8305            .oneshot(get_req("/api/search?q=zebra", "127.0.0.1:1"))
8306            .await
8307            .unwrap();
8308        assert_eq!(text(r).await.trim(), "[]");
8309    }
8310
8311    #[tokio::test]
8312    async fn search_demands_a_login_like_everything_else() {
8313        let dir = tempfile::tempdir().unwrap();
8314        let st = state(dir.path(), false);
8315        let app = router(st);
8316        // No cookie at all: `get_req` would carry a valid one.
8317        let req = HttpRequest::get("/api/search?q=anything")
8318            .header("host", "127.0.0.1:1")
8319            .body(Body::empty())
8320            .unwrap();
8321        let r = app.oneshot(req).await.unwrap();
8322        assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
8323    }
8324
8325    #[test]
8326    fn the_page_has_a_cron_pane_that_talks_to_the_cron_routes() {
8327        for needle in [
8328            "id=\"cron\"",
8329            "id=\"cronpane\"",
8330            "id=\"cronrows\"",
8331            "id=\"cronform\"",
8332            "id=\"cr-schedule\"",
8333        ] {
8334            assert!(INDEX_HTML.contains(needle), "the pane has {needle}");
8335        }
8336        // Every button has a route, and the write carries the token like the rest of the page.
8337        for route in [
8338            "'/api/cron'",
8339            "'/api/cron/' + encodeURIComponent(name) + '/run'",
8340            "'/api/cron/' + encodeURIComponent(name) + '/enabled'",
8341            "'/api/cron/' + encodeURIComponent(name) + '/logs?limit=3'",
8342        ] {
8343            assert!(INDEX_HTML.contains(route), "the pane calls {route}");
8344        }
8345        // A job's own text — its name, its answer, its run body — is written as text, never as
8346        // markup: `cronrows` and the log body are model- and person-written.
8347        assert!(!INDEX_HTML.contains("cronRows.innerHTML"));
8348        assert!(INDEX_HTML.contains("pre.textContent = body.trim()"));
8349    }
8350
8351    #[test]
8352    fn the_page_has_a_find_box_that_draws_hits_as_text() {
8353        assert!(INDEX_HTML.contains("id=\"find\""), "a box to type in");
8354        assert!(INDEX_HTML.contains("/api/search?q="), "wired to the route");
8355        // A snippet is model- and user-written text: it goes in as text, never as markup.
8356        assert!(INDEX_HTML.contains("snip.textContent ="));
8357        assert!(
8358            !INDEX_HTML.contains("list.innerHTML"),
8359            "no markup is rebuilt from data"
8360        );
8361    }
8362
8363    #[tokio::test]
8364    async fn search_is_bounded_and_says_so() {
8365        let dir = tempfile::tempdir().unwrap();
8366        let st = state(dir.path(), true);
8367        for i in 0..5 {
8368            st.store
8369                .append(&format!("s{i}"), &Message::user("repeated needle"))
8370                .unwrap();
8371        }
8372        let app = router(st);
8373        let r = app
8374            .clone()
8375            .oneshot(get_req("/api/search?q=needle&limit=2", "127.0.0.1:1"))
8376            .await
8377            .unwrap();
8378        let body = text(r).await;
8379        let hits: serde_json::Value = serde_json::from_str(&body).unwrap();
8380        assert_eq!(hits.as_array().unwrap().len(), 2, "{body}");
8381
8382        // A silly limit is clamped rather than trusted.
8383        let r = app
8384            .clone()
8385            .oneshot(get_req("/api/search?q=needle&limit=99999", "127.0.0.1:1"))
8386            .await
8387            .unwrap();
8388        let body = text(r).await;
8389        let hits: serde_json::Value = serde_json::from_str(&body).unwrap();
8390        assert!(hits.as_array().unwrap().len() <= 100, "{body}");
8391    }
8392
8393    #[tokio::test]
8394    async fn the_picker_lists_what_the_endpoint_serves_and_names_the_one_in_use() {
8395        let dir = tempfile::tempdir().unwrap();
8396        let base = serve_models(&[("small", None), ("big", None)]).await;
8397        let (st, _agent) = provider_state(dir.path(), &base, "small");
8398        let app = router(st);
8399        let r = app
8400            .clone()
8401            .oneshot(get_req("/api/models", "127.0.0.1:8787"))
8402            .await
8403            .unwrap();
8404        assert_eq!(r.status(), StatusCode::OK);
8405        let body = text(r).await;
8406        let v: serde_json::Value = serde_json::from_str(&body).unwrap();
8407        assert_eq!(v["models"], json!(["small", "big"]), "{body}");
8408        assert_eq!(v["model"], "small", "the one the next turn uses: {body}");
8409        assert_eq!(v["configured"], "small", "{body}");
8410    }
8411
8412    #[tokio::test]
8413    async fn choosing_a_model_changes_the_next_turn_and_leaves_the_file_alone() {
8414        let dir = tempfile::tempdir().unwrap();
8415        // A port nothing listens on: a switch must not need the endpoint to answer, because the
8416        // name is checked against the configuration, not against the network.
8417        let (st, agent) = provider_state(dir.path(), "http://127.0.0.1:9/v1", "configured");
8418        let app = router(st);
8419        let r = app
8420            .clone()
8421            .oneshot(model_req(json!({ "model": "picked" })))
8422            .await
8423            .unwrap();
8424        assert_eq!(r.status(), StatusCode::OK);
8425        let body = text(r).await;
8426        assert!(body.contains("\"model\":\"picked\""), "{body}");
8427        assert_eq!(agent.model().as_deref(), Some("picked"));
8428
8429        // The header is re-rendered from the agent, not from the startup string.
8430        let page = text(
8431            app.clone()
8432                .oneshot(get_req("/", "127.0.0.1:8787"))
8433                .await
8434                .unwrap(),
8435        )
8436        .await;
8437        // `#238`: the choice is on the stats row's button now, as the bare name.
8438        assert!(
8439            page.contains(">picked</button>") || page.contains(">picked\n"),
8440            "the model button follows the choice: {page:.0}"
8441        );
8442
8443        // Going back is a null, and the runtime choice is gone rather than replaced by a copy of
8444        // the configured name.
8445        let r = app
8446            .clone()
8447            .oneshot(model_req(json!({ "model": null })))
8448            .await
8449            .unwrap();
8450        assert_eq!(r.status(), StatusCode::OK);
8451        assert_eq!(agent.model().as_deref(), Some("configured"));
8452        assert!(dir.path().join("sessions").exists(), "state untouched");
8453
8454        // Nothing was written to a config file: this is a runtime choice only.
8455        assert!(!dir.path().join("config.toml").exists());
8456    }
8457
8458    #[tokio::test]
8459    async fn a_body_that_names_no_model_is_refused_rather_than_read_as_a_reset() {
8460        let dir = tempfile::tempdir().unwrap();
8461        let (st, agent) = provider_state(dir.path(), "http://127.0.0.1:9/v1", "configured");
8462        let app = router(st);
8463        for body in [json!({}), json!({ "model": "   " }), json!({ "model": "" })] {
8464            let r = app.clone().oneshot(model_req(body.clone())).await.unwrap();
8465            assert_eq!(r.status(), StatusCode::BAD_REQUEST, "{body}");
8466        }
8467        assert_eq!(agent.model().as_deref(), Some("configured"));
8468    }
8469
8470    #[tokio::test]
8471    async fn a_model_cannot_be_picked_on_an_agent_with_no_provider_configuration() {
8472        let dir = tempfile::tempdir().unwrap();
8473        // `state()` builds the agent with a canned provider and no `ProviderConfig`, which is
8474        // what tests use for the rest of the page; switching has nothing to check a name against.
8475        let app = router(state(dir.path(), true));
8476        let r = app
8477            .clone()
8478            .oneshot(model_req(json!({ "model": "picked" })))
8479            .await
8480            .unwrap();
8481        assert_eq!(r.status(), StatusCode::BAD_REQUEST);
8482        assert!(
8483            text(r)
8484                .await
8485                .contains("not built from a provider configuration"),
8486            "the reason says what is missing"
8487        );
8488    }
8489
8490    #[tokio::test]
8491    async fn an_endpoint_that_cannot_be_reached_says_so_instead_of_listing_nothing() {
8492        let dir = tempfile::tempdir().unwrap();
8493        let (st, _agent) = provider_state(dir.path(), "http://127.0.0.1:9/v1", "m");
8494        let app = router(st);
8495        let r = app
8496            .clone()
8497            .oneshot(get_req("/api/models", "127.0.0.1:8787"))
8498            .await
8499            .unwrap();
8500        assert_eq!(r.status(), StatusCode::BAD_GATEWAY);
8501        let body = text(r).await;
8502        assert!(body.contains("\"error\""), "{body}");
8503    }
8504
8505    /// A verb needs no model: a dashboard started without a provider still answers `/help`, and
8506    /// `/model` says the dashboard has no provider rather than the handler refusing the request
8507    /// with a 503 before the line is even parsed. Found by running the real binary against a config
8508    /// with no `provider.base_url`, which is a state `config init` leaves behind.
8509    #[tokio::test]
8510    async fn a_command_needs_no_provider() {
8511        let dir = tempfile::tempdir().unwrap();
8512        // `false`: the state this helper builds has no agent at all.
8513        let app = router(state(dir.path(), false));
8514
8515        let events = notices(
8516            app.clone()
8517                .oneshot(chat_req(json!({"message": "/help"})))
8518                .await
8519                .unwrap(),
8520        )
8521        .await;
8522        assert_eq!(events[0].1["kind"], json!("command"), "{events:?}");
8523        assert!(events[0].1["text"].as_str().unwrap().contains("/settings"));
8524
8525        // A verb that does need one refuses in its own words, with the reason in it.
8526        let events = notices(
8527            app.clone()
8528                .oneshot(chat_req(json!({"message": "/model"})))
8529                .await
8530                .unwrap(),
8531        )
8532        .await;
8533        assert_eq!(events[0].1["kind"], json!("refusal"));
8534        assert!(events[0].1["text"]
8535            .as_str()
8536            .unwrap()
8537            .contains("provider.base_url"));
8538
8539        // A prompt still cannot run: prose is the agent's, and there is no agent.
8540        let r = app
8541            .clone()
8542            .oneshot(chat_req(json!({"message": "hello"})))
8543            .await
8544            .unwrap();
8545        assert_eq!(r.status(), StatusCode::SERVICE_UNAVAILABLE);
8546    }
8547
8548    /// The SSE body of a command's answer, as `(event, json)` pairs.
8549    async fn notices(resp: Response) -> Vec<(String, serde_json::Value)> {
8550        let body = text(resp).await;
8551        let mut out = Vec::new();
8552        for block in body.split("\n\n") {
8553            let mut event = "message".to_string();
8554            let mut data = String::new();
8555            for line in block.split('\n') {
8556                if let Some(rest) = line.strip_prefix("event:") {
8557                    event = rest.trim().to_string();
8558                } else if let Some(rest) = line.strip_prefix("data:") {
8559                    data.push_str(rest.trim());
8560                }
8561            }
8562            if !data.is_empty() {
8563                out.push((event, serde_json::from_str(&data).unwrap_or_default()));
8564            }
8565        }
8566        out
8567    }
8568
8569    /// `#283`: there is no `!command` in the browser, and the composer says so rather than passing
8570    /// the line on. A forwarded `!ls` would be a prompt the model could answer by calling `shell` —
8571    /// the person would then approve a command they believed they had already typed.
8572    #[tokio::test]
8573    async fn a_bang_line_is_refused_and_nothing_runs() {
8574        let dir = tempfile::tempdir().unwrap();
8575        let cfg = eclipse_core::config::ProviderConfig {
8576            base_url: "http://127.0.0.1:9/v1".into(),
8577            model: "m".into(),
8578            ..Default::default()
8579        };
8580        let (st, _agent) = agent_state(dir.path(), cfg, Default::default());
8581        let app = router(st);
8582
8583        for line in ["!ls", "  !rm -rf /", "!!echo hi"] {
8584            let events = notices(
8585                app.clone()
8586                    .oneshot(chat_req(json!({ "message": line })))
8587                    .await
8588                    .unwrap(),
8589            )
8590            .await;
8591            assert_eq!(events.len(), 2, "{line}: {events:?}");
8592            assert_eq!(events[0].0, "notice", "{line}");
8593            assert_eq!(events[0].1["kind"], json!("refusal"), "{line}: {events:?}");
8594            let said = events[0].1["text"].as_str().unwrap();
8595            assert!(said.contains("terminal and nowhere else"), "{line}: {said}");
8596            // No run, no session, no provider: the stream is the refusal and the return to idle.
8597            assert_eq!(events[1].0, "done", "{line}: the composer returns to idle");
8598            assert!(
8599                !events
8600                    .iter()
8601                    .any(|(kind, _)| kind == "session" || kind == "error"),
8602                "{line}: nothing was started"
8603            );
8604        }
8605
8606        // The rule is the terminal's: only a leading bang. A trailing one is prose, and prose still
8607        // reaches the model — which, against this fixture's dead provider, is a run that fails
8608        // inside the stream rather than a refusal from the composer.
8609        let r = app
8610            .clone()
8611            .oneshot(chat_req(json!({ "message": "fix the bug!" })))
8612            .await
8613            .unwrap();
8614        assert_eq!(r.status(), StatusCode::OK, "a message is a message");
8615        let events = notices(r).await;
8616        assert!(
8617            !events
8618                .iter()
8619                .any(|(_, data)| data["kind"] == json!("refusal")),
8620            "prose is not refused by the bang rule: {events:?}"
8621        );
8622    }
8623
8624    /// `#254`: a line the table serves for the dashboard is executed by the server, and its result
8625    /// is a row — not a turn. `Unknown` prose still reaches the model; a `/` word that is not a
8626    /// command is refused, exactly as the terminal refuses it.
8627    #[tokio::test]
8628    async fn the_composer_speaks_the_table_and_a_command_is_a_row() {
8629        let dir = tempfile::tempdir().unwrap();
8630        let cfg = eclipse_core::config::ProviderConfig {
8631            base_url: "http://127.0.0.1:9/v1".into(),
8632            model: "m".into(),
8633            ..Default::default()
8634        };
8635        let (st, agent) = agent_state(dir.path(), cfg, Default::default());
8636        let app = router(st);
8637
8638        // `/help` prints the table for this front: the verbs, and no `!command` line, because the
8639        // dashboard has no bang.
8640        let events = notices(
8641            app.clone()
8642                .oneshot(chat_req(json!({"message": "/help"})))
8643                .await
8644                .unwrap(),
8645        )
8646        .await;
8647        assert_eq!(events.len(), 2, "{events:?}");
8648        assert_eq!(events[0].0, "notice");
8649        assert_eq!(events[1].0, "done", "the composer returns to idle");
8650        let help = events[0].1["text"].as_str().unwrap();
8651        assert_eq!(events[0].1["kind"], json!("command"));
8652        assert!(help.contains("/reasoning"), "{help}");
8653        assert!(!help.contains("!command"), "no bang in a browser: {help}");
8654        assert!(
8655            !help.contains("/resume"),
8656            "a terminal-only verb is not in this list: {help}"
8657        );
8658
8659        // `/reasoning` reads the dial; `/reasoning high` turns it, and the dial is the one the
8660        // strip and the submenu read.
8661        let events = notices(
8662            app.clone()
8663                .oneshot(chat_req(json!({"message": "/reasoning"})))
8664                .await
8665                .unwrap(),
8666        )
8667        .await;
8668        assert!(events[0].1["text"]
8669            .as_str()
8670            .unwrap()
8671            .contains("effort: medium"));
8672        let events = notices(
8673            app.clone()
8674                .oneshot(chat_req(json!({"message": "/reasoning high"})))
8675                .await
8676                .unwrap(),
8677        )
8678        .await;
8679        assert!(events[0].1["text"]
8680            .as_str()
8681            .unwrap()
8682            .contains("effort: high"));
8683        assert_eq!(agent.reasoning().effort(), Some("high".to_string()));
8684
8685        // A level this route cannot take is refused in the policy's words, in the transcript.
8686        let events = notices(
8687            app.clone()
8688                .oneshot(chat_req(json!({"message": "/reasoning none"})))
8689                .await
8690                .unwrap(),
8691        )
8692        .await;
8693        assert_eq!(events[0].1["kind"], json!("refusal"));
8694        assert!(events[0].1["text"]
8695            .as_str()
8696            .unwrap()
8697            .contains("this route takes"));
8698
8699        // A terminal-only verb says where it lives instead of becoming a question for the model.
8700        let events = notices(
8701            app.clone()
8702                .oneshot(chat_req(json!({"message": "/resume"})))
8703                .await
8704                .unwrap(),
8705        )
8706        .await;
8707        assert_eq!(events[0].1["kind"], json!("refusal"));
8708        assert!(events[0].1["text"]
8709            .as_str()
8710            .unwrap()
8711            .contains("only in the full-screen interface"));
8712
8713        // `/bg` used to be a hardcoded refusal in this handler; it is the table's refusal now.
8714        let events = notices(
8715            app.clone()
8716                .oneshot(chat_req(json!({"message": "/bg write me a poem"})))
8717                .await
8718                .unwrap(),
8719        )
8720        .await;
8721        assert!(events[0].1["text"]
8722            .as_str()
8723            .unwrap()
8724            .contains("only in the full-screen interface and the plain REPL"));
8725
8726        // A word the table does not know is a refusal, not prose — the terminal's own sentence.
8727        let events = notices(
8728            app.clone()
8729                .oneshot(chat_req(json!({"message": "/nope"})))
8730                .await
8731                .unwrap(),
8732        )
8733        .await;
8734        assert_eq!(events[0].1["kind"], json!("refusal"));
8735        assert_eq!(events[0].1["text"], json!("unknown command; try /help"));
8736
8737        // `/new` is a promise plus a flag the page acts on.
8738        let events = notices(
8739            app.clone()
8740                .oneshot(chat_req(json!({"message": "/new"})))
8741                .await
8742                .unwrap(),
8743        )
8744        .await;
8745        assert_eq!(events[0].1["clear_session"], json!(true));
8746    }
8747
8748    /// `#285`: the dashboard owns `/yolo` now, and it earns it by being visible — the answer names
8749    /// the state, the page paints it from the server's flag, and with it on a tool call runs with no
8750    /// card at all. What must not happen is the old thing: cards off with nothing on screen saying so.
8751    #[tokio::test]
8752    async fn yolo_in_the_dashboard_is_a_switch_the_page_can_show() {
8753        use eclipse_core::approvals::{Decision, Pending};
8754        use eclipse_core::tools::Approver;
8755
8756        let dir = tempfile::tempdir().unwrap();
8757        std::fs::write(
8758            dir.path().join("config.toml"),
8759            "[provider]\nbase_url = \"http://h:1/v1\"\nmodel = \"m\"\n",
8760        )
8761        .unwrap();
8762        let cfg = eclipse_core::config::ProviderConfig {
8763            base_url: "http://h:1/v1".into(),
8764            model: "m".into(),
8765            ..Default::default()
8766        };
8767        let (st, _agent) = agent_state(dir.path(), cfg, Default::default());
8768        let st = match Arc::try_unwrap(st) {
8769            Ok(st) => Arc::new(st.with_config_path(Some(dir.path().join("config.toml")), None)),
8770            Err(_) => panic!("a state built here is not shared yet"),
8771        };
8772        let app = router(st.clone());
8773
8774        // Off to begin with, and the page says nothing: the chip is in the markup, hidden.
8775        assert!(!st.yolo.on());
8776        // Rendered through the same handler the route uses, without the host/auth plumbing the
8777        // router needs: what is under test is the markup the server paints, not the door.
8778        let Html(html) = index(State(st.clone()), HeaderMap::new()).await;
8779        assert!(
8780            html.contains("id=\"yolo\""),
8781            "the chip exists: {html:.4000}"
8782        );
8783        assert!(
8784            html.contains("id=\"yolo\" hidden"),
8785            "and it is hidden while approvals are on: {html:.4000}"
8786        );
8787
8788        // `/yolo` turns it on, in `Yolo::apply`'s words, and the answer carries the new state.
8789        let events = notices(
8790            app.clone()
8791                .oneshot(chat_req(json!({"message": "/yolo"})))
8792                .await
8793                .unwrap(),
8794        )
8795        .await;
8796        assert_eq!(events[0].1["kind"], json!("command"));
8797        let said = events[0].1["text"].as_str().unwrap();
8798        assert!(said.contains("approvals: auto"), "{said}");
8799        assert!(
8800            said.contains("config.toml"),
8801            "the promise is still there: {said}"
8802        );
8803        assert_eq!(
8804            events[0].1["yolo"],
8805            json!(true),
8806            "the page learns the state"
8807        );
8808
8809        // The page now renders it visible, because the server is what it asks.
8810        let Html(html) = index(State(st.clone()), HeaderMap::new()).await;
8811        assert!(
8812            !html.contains("id=\"yolo\" hidden"),
8813            "a reload shows a mode that is still in force: {html:.4000}"
8814        );
8815
8816        // And a call that would have parked runs instead: no card, no event, counted.
8817        let (tx, mut rx) = mpsc::unbounded_channel();
8818        let approver = WebApprover {
8819            state: st.clone(),
8820            run: 1,
8821            events: tx,
8822        };
8823        let call = Pending {
8824            call_id: "c1".into(),
8825            tool: "shell".into(),
8826            summary: "echo hi".into(),
8827            args: "{}".into(),
8828        };
8829        let decision = approver.decide(&call).await;
8830        assert!(
8831            matches!(decision, Decision::Allow),
8832            "with yolo on the call runs: {decision:?}"
8833        );
8834        assert!(
8835            rx.try_recv().is_err(),
8836            "and nothing was sent to the browser to click"
8837        );
8838        assert_eq!(
8839            st.unasked.load(std::sync::atomic::Ordering::Relaxed),
8840            1,
8841            "the count is the honest part"
8842        );
8843        assert!(st.approvals.lock().is_empty(), "nothing left waiting");
8844
8845        // `/yolo off` puts the cards back and the chip away, and the count is reported.
8846        let events = notices(
8847            app.clone()
8848                .oneshot(chat_req(json!({"message": "/yolo off"})))
8849                .await
8850                .unwrap(),
8851        )
8852        .await;
8853        let said = events[0].1["text"].as_str().unwrap();
8854        assert!(said.contains("approvals: ask"), "{said}");
8855        assert!(
8856            said.contains("1 tool call"),
8857            "the count rides along: {said}"
8858        );
8859        assert_eq!(events[0].1["yolo"], json!(false));
8860
8861        // Off means the card comes back: the approver parks and sends the request.
8862        let (tx, mut rx) = mpsc::unbounded_channel();
8863        let approver = WebApprover {
8864            state: st.clone(),
8865            run: 2,
8866            events: tx,
8867        };
8868        let call = Pending {
8869            call_id: "c2".into(),
8870            tool: "shell".into(),
8871            summary: "echo hi".into(),
8872            args: "{}".into(),
8873        };
8874        let asked = tokio::spawn(async move { approver.decide(&call).await });
8875        // It emits the request and waits; answer it the way the page does.
8876        let id = match rx.recv().await.expect("an approval request") {
8877            Out::ApprovalRequest { id, .. } => id,
8878            // Everything else means the approver did not park the call, which is the failure.
8879            Out::Event(_) | Out::Done | Out::Cancelled | Out::Failed(_) => {
8880                panic!("the approver did not ask before running the call")
8881            }
8882            Out::ApprovalResolved { .. } => {
8883                panic!("the approval resolved before it was sent")
8884            }
8885        };
8886        assert_eq!(
8887            st.unasked.load(std::sync::atomic::Ordering::Relaxed),
8888            1,
8889            "a parked call is not an unasked one"
8890        );
8891        // The page's own door: POST /api/approvals/:id lands in this same map.
8892        let sender = st
8893            .approvals
8894            .lock()
8895            .remove(&id)
8896            .expect("the pending call")
8897            .decide;
8898        let _ = sender.send(true);
8899        assert!(
8900            matches!(asked.await.unwrap(), Decision::Allow),
8901            "an explicit yes is still an allow"
8902        );
8903    }
8904
8905    /// The verbs that change something go through the same function their route does — one
8906    /// implementation, so a line in the composer and a click in a panel cannot disagree.
8907    #[tokio::test]
8908    async fn a_verb_and_its_route_are_one_implementation() {
8909        use eclipse_core::config::ProviderConfig;
8910
8911        let dir = tempfile::tempdir().unwrap();
8912        let path = dir.path().join("config.toml");
8913        std::fs::write(
8914            &path,
8915            "[provider]\nbase_url = \"http://h:1/v1\"\nmodel = \"m\"\n",
8916        )
8917        .unwrap();
8918        let cfg = ProviderConfig {
8919            base_url: "http://h:1/v1".into(),
8920            model: "m".into(),
8921            ..Default::default()
8922        };
8923        let (st, agent) = agent_state(dir.path(), cfg, Default::default());
8924        let st = match Arc::try_unwrap(st) {
8925            Ok(st) => Arc::new(st.with_config_path(Some(path.clone()), None)),
8926            Err(_) => panic!("a state built here is not shared yet"),
8927        };
8928        let app = router(st);
8929
8930        // `/reasoning low` in the composer, then the picker's own `GET /api/reasoning`.
8931        let _ = notices(
8932            app.clone()
8933                .oneshot(chat_req(json!({"message": "/reasoning low"})))
8934                .await
8935                .unwrap(),
8936        )
8937        .await;
8938        let body = json_body(
8939            app.clone()
8940                .oneshot(get_req("/api/reasoning", "127.0.0.1:8787"))
8941                .await
8942                .unwrap(),
8943        )
8944        .await;
8945        assert_eq!(
8946            body["effort"],
8947            json!("low"),
8948            "the route sees the command's pick"
8949        );
8950
8951        // `/set` writes the file through `apply_setting`, and `GET /api/settings` reads it back.
8952        let _ = notices(
8953            app.clone()
8954                .oneshot(chat_req(json!({"message": "/set provider.model other"})))
8955                .await
8956                .unwrap(),
8957        )
8958        .await;
8959        let text = std::fs::read_to_string(&path).unwrap();
8960        assert!(
8961            text.contains("model = \"other\""),
8962            "the file is the store: {text}"
8963        );
8964        let body = json_body(
8965            app.clone()
8966                .oneshot(get_req("/api/settings", "127.0.0.1:8787"))
8967                .await
8968                .unwrap(),
8969        )
8970        .await;
8971        let row = body["settings"]
8972            .as_array()
8973            .unwrap()
8974            .iter()
8975            .find(|r| r["key"] == json!("provider.model"))
8976            .expect("the key");
8977        assert_eq!(row["value"], json!("\"other\""));
8978
8979        // `/model` with no argument is a read-out of what is in force, not a switch.
8980        let events = notices(
8981            app.clone()
8982                .oneshot(chat_req(json!({"message": "/model"})))
8983                .await
8984                .unwrap(),
8985        )
8986        .await;
8987        assert!(events[0].1["text"]
8988            .as_str()
8989            .unwrap()
8990            .contains("configured:"));
8991        let _ = agent;
8992    }
8993
8994    /// A dashboard whose agent has this provider configuration, and — when given — these plugins,
8995    /// so a route can be a manifest rather than a built-in.
8996    fn agent_state(
8997        dir: &std::path::Path,
8998        cfg: eclipse_core::config::ProviderConfig,
8999        plugins: eclipse_core::plugins::Plugins,
9000    ) -> (Shared, Arc<Agent>) {
9001        let store = SessionStore::new(dir.join("sessions"));
9002        let agent = Arc::new(
9003            Agent::new(
9004                Arc::new(Canned),
9005                Arc::new(ToolRegistry::default()),
9006                store.clone(),
9007                "sys".into(),
9008                3,
9009            )
9010            .with_provider_config(cfg)
9011            .with_plugins(plugins),
9012        );
9013        (
9014            Arc::new(authed(Some(agent.clone()), store, "m", None)),
9015            agent,
9016        )
9017    }
9018
9019    fn reasoning_req(body: serde_json::Value) -> HttpRequest<Body> {
9020        HttpRequest::post("/api/reasoning")
9021            .header("host", "127.0.0.1:8787")
9022            .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
9023            .header("content-type", "application/json")
9024            .body(Body::from(body.to_string()))
9025            .unwrap()
9026    }
9027
9028    /// The reply as JSON: these routes answer with the state a page renders, so a test reads the
9029    /// fields rather than substrings of a body.
9030    async fn json_body(resp: Response) -> serde_json::Value {
9031        serde_json::from_str(&text(resp).await).expect("a JSON reply")
9032    }
9033
9034    /// `#275`: the words a person is offered are the route's own, not a union of every level this
9035    /// build knows. `openai` has four rungs and no off switch — `reasoning_effort: "none"` is a
9036    /// 400 there — `llamacpp` has three and `none`, a manifest that declares nothing offers
9037    /// nothing but says so, and the level in force is the shipped default from `#276`.
9038    #[tokio::test]
9039    async fn the_submenu_is_served_the_levels_this_route_takes() {
9040        use eclipse_core::config::ProviderConfig;
9041
9042        let dir = tempfile::tempdir().unwrap();
9043        let openai = ProviderConfig {
9044            base_url: "http://h:1/v1".into(),
9045            model: "m".into(),
9046            ..Default::default()
9047        };
9048        let (st, _agent) = agent_state(dir.path(), openai, Default::default());
9049        let body = json_body(
9050            router(st)
9051                .oneshot(get_req("/api/reasoning", "127.0.0.1:8787"))
9052                .await
9053                .unwrap(),
9054        )
9055        .await;
9056        assert_eq!(
9057            body["levels"],
9058            json!(["minimal", "low", "medium", "high"]),
9059            "four rungs, and no off switch to offer"
9060        );
9061        assert_eq!(
9062            body["effort"],
9063            json!("medium"),
9064            "the shipped default is what an unconfigured install reasons at"
9065        );
9066        assert_eq!(body["effort_default"], json!(true));
9067        assert_eq!(body["effort_session"], json!(false));
9068        assert!(
9069            body["configured"].is_null(),
9070            "the file sets nothing: {}",
9071            body["configured"]
9072        );
9073        assert_eq!(
9074            body["described"]["high"],
9075            json!("sends high"),
9076            "each row quotes the policy, so a clamp is visible before the click"
9077        );
9078        // `openai` has no off switch, and says so rather than letting a switch press into a 400.
9079        assert_eq!(body["off_word"], json!(null), "no off to offer");
9080        assert!(
9081            body["off_why"]
9082                .as_str()
9083                .unwrap_or_default()
9084                .contains("no off switch"),
9085            "and the switch's title carries the reason: {}",
9086            body["off_why"]
9087        );
9088
9089        // llamacpp: `minimal` is mapped, not a rung, so it is not offered; `none` is its off
9090        // switch, so it is.
9091        let dir = tempfile::tempdir().unwrap();
9092        let llama = ProviderConfig {
9093            base_url: "http://h:1/v1".into(),
9094            model: "mmnuc/inkling-2-mini".into(),
9095            profile: Some("llamacpp".into()),
9096            ..Default::default()
9097        };
9098        let (st, _agent) = agent_state(dir.path(), llama, Default::default());
9099        let body = json_body(
9100            router(st)
9101                .oneshot(get_req("/api/reasoning", "127.0.0.1:8787"))
9102                .await
9103                .unwrap(),
9104        )
9105        .await;
9106        assert_eq!(body["levels"], json!(["low", "medium", "high", "none"]));
9107        assert_eq!(
9108            body["described"]["none"],
9109            json!("sends none"),
9110            "the off switch is named as the wire takes it"
9111        );
9112        // `#293`: the switch asks for `none` and the policy turns that into whatever this route
9113        // actually takes — the page never spells the wire shape.
9114        assert_eq!(
9115            body["off_word"],
9116            json!("none"),
9117            "this route declares an off, so the switch is live"
9118        );
9119        assert_eq!(body["off_why"], json!(""));
9120
9121        // A profile that declares no reasoning at all: no rows, and the note carries the reason
9122        // instead of six dead words.
9123        let dir = tempfile::tempdir().unwrap();
9124        let plugins_dir = dir.path().join("plugins").join("provider-profile-bare");
9125        std::fs::create_dir_all(&plugins_dir).unwrap();
9126        std::fs::write(
9127            plugins_dir.join("plugin.toml"),
9128            "name = \"provider-profile-bare\"\nversion = \"0.1.0\"\napi = 1\n\
9129             description = \"a profile that declares no reasoning control\"\n\n\
9130             [[provider_profile]]\nname = \"bare\"\n",
9131        )
9132        .unwrap();
9133        let loaded = eclipse_core::plugins::load(&[dir.path().join("plugins")], &[]);
9134        let bare = ProviderConfig {
9135            base_url: "http://h:1/v1".into(),
9136            model: "m".into(),
9137            profile: Some("bare".into()),
9138            ..Default::default()
9139        };
9140        let (st, _agent) = agent_state(dir.path(), bare, loaded);
9141        let body = json_body(
9142            router(st)
9143                .oneshot(get_req("/api/reasoning", "127.0.0.1:8787"))
9144                .await
9145                .unwrap(),
9146        )
9147        .await;
9148        assert_eq!(
9149            body["levels"],
9150            json!([]),
9151            "nothing to offer is the honest list for this backend"
9152        );
9153        assert!(
9154            body["note"]
9155                .as_str()
9156                .unwrap_or_default()
9157                .contains("declares no reasoning control"),
9158            "and the menu says why: {}",
9159            body["note"]
9160        );
9161    }
9162
9163    /// `#275`: a click changes the level the *next request body* carries, and nothing else about
9164    /// the request. Two identical prompts against a stub endpoint, one at `low` and one at `high`,
9165    /// the way `provider.rs`'s dial tests do it — this is the end-to-end version of that.
9166    #[tokio::test]
9167    async fn a_pick_changes_the_next_request_body_and_nothing_else() {
9168        use eclipse_core::config::ProviderConfig;
9169
9170        let seen: Arc<Mutex<Vec<serde_json::Value>>> = Arc::new(Mutex::new(Vec::new()));
9171        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
9172        let addr = listener.local_addr().unwrap();
9173        let recorder = {
9174            let seen = Arc::clone(&seen);
9175            Router::new().route(
9176                "/v1/chat/completions",
9177                post(move |Json(body): Json<serde_json::Value>| {
9178                    let seen = Arc::clone(&seen);
9179                    async move {
9180                        seen.lock().unwrap().push(body);
9181                        Json(json!({
9182                            "choices": [{"message": {"role": "assistant", "content": "ok"}}]
9183                        }))
9184                    }
9185                }),
9186            )
9187        };
9188        tokio::spawn(async move {
9189            let _ = axum::serve(listener, recorder).await;
9190        });
9191
9192        let dir = tempfile::tempdir().unwrap();
9193        let cfg = ProviderConfig {
9194            base_url: format!("http://{addr}/v1"),
9195            model: "m".into(),
9196            stream: false,
9197            retry_base_delay_ms: 20,
9198            ..Default::default()
9199        };
9200        let (st, agent) = agent_state(dir.path(), cfg, Default::default());
9201        let app = router(st);
9202        // A runtime model choice is the path that rebuilds a provider from the configuration —
9203        // the one a run uses — so the two turns below really go over the socket.
9204        let r = app
9205            .clone()
9206            .oneshot(model_req(json!({ "model": "m" })))
9207            .await
9208            .unwrap();
9209        assert_eq!(r.status(), StatusCode::OK);
9210
9211        for level in ["low", "high"] {
9212            let r = app
9213                .clone()
9214                .oneshot(reasoning_req(json!({ "level": level })))
9215                .await
9216                .unwrap();
9217            assert_eq!(r.status(), StatusCode::OK, "{level}");
9218            let body = json_body(r).await;
9219            assert_eq!(body["effort"], json!(level));
9220            assert_eq!(body["effort_session"], json!(true), "and it says why");
9221
9222            let r = app
9223                .clone()
9224                .oneshot(chat_req(json!({ "message": "same prompt" })))
9225                .await
9226                .unwrap();
9227            assert_eq!(r.status(), StatusCode::OK);
9228            let _ = text(r).await; // drain the turn, so the request has certainly been made
9229        }
9230
9231        let seen = seen.lock().unwrap().clone();
9232        assert_eq!(seen.len(), 2, "one request per turn: {seen:?}");
9233        assert_eq!(seen[0]["reasoning_effort"], json!("low"), "{:?}", seen[0]);
9234        assert_eq!(seen[1]["reasoning_effort"], json!("high"), "{:?}", seen[1]);
9235        // The rest of the two bodies is identical: a pick moves one field, not the request.
9236        let strip = |mut body: serde_json::Value| {
9237            body.as_object_mut().unwrap().remove("reasoning_effort");
9238            body
9239        };
9240        assert_eq!(
9241            strip(seen[0].clone()),
9242            strip(seen[1].clone()),
9243            "two identical prompts, and only the level differs"
9244        );
9245        assert!(agent.reasoning().overridden(), "a session dial, not a file");
9246    }
9247
9248    /// `#293`: the off switch reaches the wire as *this route* spells it. Picking the off word is
9249    /// what the switch does, and the request body afterwards carries what the policy resolved it
9250    /// to — `reasoning_effort: "none"` on llamacpp — not a sentinel the page made up.
9251    #[tokio::test]
9252    async fn the_off_switch_reaches_the_wire_as_this_route_spells_it() {
9253        use eclipse_core::config::ProviderConfig;
9254
9255        let seen: Arc<Mutex<Vec<serde_json::Value>>> = Arc::new(Mutex::new(Vec::new()));
9256        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
9257        let addr = listener.local_addr().unwrap();
9258        let recorder = {
9259            let seen = Arc::clone(&seen);
9260            Router::new().route(
9261                "/v1/chat/completions",
9262                post(move |Json(body): Json<serde_json::Value>| {
9263                    let seen = Arc::clone(&seen);
9264                    async move {
9265                        seen.lock().unwrap().push(body);
9266                        Json(json!({
9267                            "choices": [{"message": {"role": "assistant", "content": "ok"}}]
9268                        }))
9269                    }
9270                }),
9271            )
9272        };
9273        tokio::spawn(async move {
9274            let _ = axum::serve(listener, recorder).await;
9275        });
9276
9277        let dir = tempfile::tempdir().unwrap();
9278        let cfg = ProviderConfig {
9279            base_url: format!("http://{addr}/v1"),
9280            model: "mmnuc/inkling-2-mini".into(),
9281            profile: Some("llamacpp".into()),
9282            stream: false,
9283            retry_base_delay_ms: 20,
9284            ..Default::default()
9285        };
9286        let (st, agent) = agent_state(dir.path(), cfg, Default::default());
9287        let app = router(st);
9288        let r = app
9289            .clone()
9290            .oneshot(model_req(json!({ "model": "mmnuc/inkling-2-mini" })))
9291            .await
9292            .unwrap();
9293        assert_eq!(r.status(), StatusCode::OK);
9294
9295        // On, then the switch's off.
9296        for level in ["high", "none"] {
9297            let r = app
9298                .clone()
9299                .oneshot(reasoning_req(json!({ "level": level })))
9300                .await
9301                .unwrap();
9302            assert_eq!(r.status(), StatusCode::OK, "{level}");
9303        }
9304        let r = app
9305            .clone()
9306            .oneshot(chat_req(json!({ "message": "same prompt" })))
9307            .await
9308            .unwrap();
9309        assert_eq!(r.status(), StatusCode::OK);
9310        let _ = text(r).await;
9311
9312        let first = seen.lock().unwrap().clone();
9313        assert_eq!(first.len(), 1, "one request for the turn: {first:?}");
9314        assert_eq!(
9315            first[0]["reasoning_effort"],
9316            json!("none"),
9317            "the off is the policy's own word on this wire: {:?}",
9318            first[0]
9319        );
9320        assert!(agent.reasoning().overridden(), "still a session dial");
9321
9322        // `#278`: `omit` is not a level, it is the absence of the field — accepted on every route,
9323        // including the ones that would refuse `none`, and the body afterwards has no key at all.
9324        let r = app
9325            .clone()
9326            .oneshot(reasoning_req(json!({ "level": "omit" })))
9327            .await
9328            .unwrap();
9329        assert_eq!(r.status(), StatusCode::OK, "omit on the route with a dial");
9330        let r = app
9331            .clone()
9332            .oneshot(chat_req(json!({ "message": "now quiet" })))
9333            .await
9334            .unwrap();
9335        assert_eq!(r.status(), StatusCode::OK);
9336        let _ = text(r).await;
9337        let bodies = seen.lock().unwrap().clone();
9338        assert_eq!(bodies.len(), 2, "one request per turn: {bodies:?}");
9339        assert!(
9340            bodies[1].get("reasoning_effort").is_none(),
9341            "asked for no field, and none is sent: {:?}",
9342            bodies[1]
9343        );
9344
9345        // A route with no off switch refuses the flip instead of sending a level it would 400 on,
9346        // and the body afterwards is the one the file named.
9347        let dir = tempfile::tempdir().unwrap();
9348        let openai = ProviderConfig {
9349            base_url: format!("http://{addr}/v1"),
9350            model: "m".into(),
9351            stream: false,
9352            retry_base_delay_ms: 20,
9353            ..Default::default()
9354        };
9355        let (st, _agent) = agent_state(dir.path(), openai, Default::default());
9356        let app = router(st);
9357        let r = app
9358            .clone()
9359            .oneshot(reasoning_req(json!({ "level": "none" })))
9360            .await
9361            .unwrap();
9362        assert_eq!(
9363            r.status(),
9364            StatusCode::BAD_REQUEST,
9365            "there is no off to ask for on this route"
9366        );
9367        let why = text(r).await;
9368        assert!(why.contains("not a level this backend takes"), "{why}");
9369
9370        // ...but `omit` is not that flip: nothing is sent, so there is nothing to refuse.
9371        let r = app
9372            .clone()
9373            .oneshot(reasoning_req(json!({ "level": "omit" })))
9374            .await
9375            .unwrap();
9376        assert_eq!(
9377            r.status(),
9378            StatusCode::OK,
9379            "a route with no off switch can still be told to send nothing"
9380        );
9381    }
9382
9383    /// `#293`, the page's half. The row is a switch in every state, the levels are drawn from the
9384    /// route's vocabulary with the off word removed (it is the switch now), and the row no longer
9385    /// folds anything — `#thinkall` keeps that job.
9386    #[test]
9387    fn the_reasoning_row_is_a_switch_and_never_a_renamed_verb() {
9388        for verb in ["show reasoning", "hide reasoning"] {
9389            assert!(
9390                !INDEX_HTML.contains(verb),
9391                "the row is not a phrase that changes {verb:?}"
9392            );
9393        }
9394        assert!(
9395            INDEX_HTML.contains("switchRow('Reasoning'"),
9396            "one row, labelled with the setting"
9397        );
9398        assert!(
9399            INDEX_HTML.contains("b.setAttribute('role', 'switch')")
9400                && INDEX_HTML.contains("b.setAttribute('aria-checked'"),
9401            "a switch with a state on the control, so Up/Down still reaches it"
9402        );
9403        // Off asks the route for its own off word; on asks for a level the route is offering.
9404        assert!(
9405            INDEX_HTML.contains("pickEffort(isOff ? restore : offWord)"),
9406            "the flip posts the route's off word, never a sentinel"
9407        );
9408        assert!(
9409            INDEX_HTML.contains("onClick: offWord ?"),
9410            "a route with no off gets a switch with no handler"
9411        );
9412        assert!(
9413            INDEX_HTML.contains("if (word === offWord) continue;"),
9414            "the off word is not also a level row: one dial, one control"
9415        );
9416        // The switch is not the transcript's fold control.
9417        let submenu = INDEX_HTML
9418            .split("function renderReasoning(")
9419            .nth(1)
9420            .and_then(|rest| rest.split("async function showReasoning(").next())
9421            .expect("the submenu's renderer");
9422        assert!(
9423            !submenu.contains("setThinking"),
9424            "the menu row must not fold a single block: {submenu:.0}"
9425        );
9426        assert!(
9427            INDEX_HTML.contains("id=\"thinkall\""),
9428            "the fold control is where it was"
9429        );
9430    }
9431
9432    /// `#275`: a pick is a fact about this dashboard run. The file is byte-identical afterwards
9433    /// and the settings page still reports what the file says — the durable path is that page,
9434    /// and it takes effect on the next start.
9435    #[tokio::test]
9436    async fn a_pick_never_writes_the_config_file() {
9437        use eclipse_core::config::ProviderConfig;
9438
9439        let dir = tempfile::tempdir().unwrap();
9440        let path = dir.path().join("config.toml");
9441        std::fs::write(
9442            &path,
9443            "[provider]\nbase_url = \"http://h:1/v1\"\nmodel = \"m\"\nreasoning_effort = \"low\"\n",
9444        )
9445        .unwrap();
9446        let before = std::fs::read(&path).unwrap();
9447        let cfg = ProviderConfig {
9448            base_url: "http://h:1/v1".into(),
9449            model: "m".into(),
9450            reasoning_effort: Some("low".into()),
9451            ..Default::default()
9452        };
9453        let (st, agent) = agent_state(dir.path(), cfg, Default::default());
9454        let st = match Arc::try_unwrap(st) {
9455            Ok(st) => Arc::new(st.with_config_path(Some(path.clone()), None)),
9456            Err(_) => panic!("a state built here is not shared yet"),
9457        };
9458        let app = router(st);
9459
9460        let body = json_body(
9461            app.clone()
9462                .oneshot(reasoning_req(json!({ "level": "high" })))
9463                .await
9464                .unwrap(),
9465        )
9466        .await;
9467        assert_eq!(body["effort"], json!("high"));
9468        assert_eq!(
9469            body["configured"],
9470            json!("low"),
9471            "the row that goes back to the file says what it would go back to"
9472        );
9473        assert_eq!(
9474            std::fs::read(&path).unwrap(),
9475            before,
9476            "a click is not a `config set`"
9477        );
9478        assert_eq!(
9479            agent.reasoning().configured(),
9480            Some("low"),
9481            "the agent still holds the file's level underneath"
9482        );
9483
9484        // And the settings page still reports the file, unchanged.
9485        let body = json_body(
9486            app.clone()
9487                .oneshot(get_req("/api/settings", "127.0.0.1:8787"))
9488                .await
9489                .unwrap(),
9490        )
9491        .await;
9492        let rows = body["settings"]
9493            .as_array()
9494            .unwrap_or_else(|| panic!("the settings page answers rows: {body}"));
9495        let row = rows
9496            .iter()
9497            .find(|r| r["key"] == json!("provider.reasoning_effort"))
9498            .expect("the key is on the settings page");
9499        assert_eq!(
9500            row["value"],
9501            json!("\"low\""),
9502            "the page reports the file, not the dashboard's dial"
9503        );
9504    }
9505
9506    /// `#275` done-when: `null` is "back to the file", and a level this route cannot take is
9507    /// refused with the sentence the policy already writes — not accepted and quietly dropped.
9508    #[tokio::test]
9509    async fn default_goes_back_to_the_file_and_a_level_the_route_lacks_is_refused() {
9510        use eclipse_core::config::ProviderConfig;
9511
9512        let dir = tempfile::tempdir().unwrap();
9513        let cfg = ProviderConfig {
9514            base_url: "http://h:1/v1".into(),
9515            model: "m".into(),
9516            reasoning_effort: Some("low".into()),
9517            ..Default::default()
9518        };
9519        let (st, agent) = agent_state(dir.path(), cfg, Default::default());
9520        let app = router(st);
9521
9522        let body = json_body(
9523            app.clone()
9524                .oneshot(reasoning_req(json!({ "level": "high" })))
9525                .await
9526                .unwrap(),
9527        )
9528        .await;
9529        assert_eq!(body["effort_session"], json!(true));
9530
9531        // `null` clears the override: the file is in charge again.
9532        let body = json_body(
9533            app.clone()
9534                .oneshot(reasoning_req(json!({ "level": null })))
9535                .await
9536                .unwrap(),
9537        )
9538        .await;
9539        assert_eq!(body["effort"], json!("low"));
9540        assert_eq!(body["effort_session"], json!(false));
9541        assert!(!agent.reasoning().overridden());
9542
9543        // `none` is not a level this endpoint takes: `openai` has no off switch, and inventing
9544        // one is the 400 the policy exists to prevent.
9545        let r = app
9546            .clone()
9547            .oneshot(reasoning_req(json!({ "level": "none" })))
9548            .await
9549            .unwrap();
9550        assert_eq!(r.status(), StatusCode::BAD_REQUEST);
9551        let said = text(r).await;
9552        assert!(
9553            said.contains("not sent") && said.contains("this route takes"),
9554            "the refusal is the policy's sentence plus the vocabulary: {said}"
9555        );
9556        assert!(!agent.reasoning().overridden(), "a refusal changes nothing");
9557
9558        // A body with no `level` at all is a mistake, not a reset.
9559        let r = app.clone().oneshot(reasoning_req(json!({}))).await.unwrap();
9560        assert_eq!(r.status(), StatusCode::BAD_REQUEST);
9561    }
9562
9563    #[tokio::test]
9564    async fn a_pick_moves_the_context_window_to_the_new_model() {
9565        let dir = tempfile::tempdir().unwrap();
9566        let base = serve_models(&[("small", Some(4_096)), ("big", Some(131_072))]).await;
9567        let (st, agent) = provider_state(dir.path(), &base, "small");
9568        assert_eq!(agent.context_window(), 0, "nothing probed yet");
9569        let app = router(st);
9570        let r = app
9571            .clone()
9572            .oneshot(model_req(json!({ "model": "big" })))
9573            .await
9574            .unwrap();
9575        assert_eq!(r.status(), StatusCode::OK);
9576        // The re-probe runs in the background so a slow endpoint cannot hold the click; give it a
9577        // moment and then read the rail it decided.
9578        for _ in 0..100 {
9579            if agent.context_window() == 131_072 {
9580                return;
9581            }
9582            tokio::time::sleep(Duration::from_millis(20)).await;
9583        }
9584        panic!(
9585            "the window still reads {} after a pick",
9586            agent.context_window()
9587        );
9588    }
9589
9590    /// The pane says which session is being read. The sidebar scrolls away from the row that was
9591    /// clicked, so "which session am I in" cannot be answered by looking at the list — and the name
9592    /// there is the same `title` the store keeps, so a rename or a name that lands after the first
9593    /// turn shows up without another route.
9594    #[test]
9595    fn the_pane_names_the_session_that_is_open() {
9596        assert!(
9597            INDEX_HTML.contains("id=\"openname\"") && INDEX_HTML.contains("id=\"openid\""),
9598            "a name and its id, above the transcript"
9599        );
9600        let script = INDEX_HTML.split("<script>").nth(1).unwrap_or_default();
9601        assert!(
9602            script.contains("row.querySelector('.name')"),
9603            "the name is read off the row the list already drew, not fetched again"
9604        );
9605        assert!(
9606            script.contains("showOpen(parked)"),
9607            "and it follows every rebuild of the list, naming the row the list may not be showing \
9608             (#345: the section holding the open session can be closed)"
9609        );
9610        assert!(
9611            INDEX_HTML.contains("#open[hidden] { display:none; }"),
9612            "an empty bar takes no height"
9613        );
9614    }
9615
9616    /// `#240`: the sidebar's half of the flag. The filter is a checkbox that re-asks the server,
9617    /// the row menu carries the two words, and an archived row is marked and not the danger one.
9618    #[test]
9619    fn the_page_has_the_archive_filter_and_the_row_menu_word() {
9620        assert!(
9621            INDEX_HTML.contains("id=\"showarchived\""),
9622            "the filter exists"
9623        );
9624        assert!(
9625            INDEX_HTML.contains("?archived=1"),
9626            "and it is the server's list with the filed rows back in it"
9627        );
9628        assert!(
9629            INDEX_HTML.contains("li.dataset.archived"),
9630            "a row says whether it is filed away"
9631        );
9632        assert!(
9633            INDEX_HTML.contains("data-archived=\""),
9634            "and the first paint says so too"
9635        );
9636        assert!(
9637            INDEX_HTML.contains("'archive'") && INDEX_HTML.contains("'unarchive'"),
9638            "the menu offers the write and its undo"
9639        );
9640        assert!(
9641            INDEX_HTML.contains("add('Archived', archived)"),
9642            "filed rows get their own heading, not a date bucket"
9643        );
9644        // The menu row is not the `.danger` one: delete still is, and archive says what it keeps.
9645        assert!(INDEX_HTML.contains("out of the list, still in the find box"));
9646        assert!(
9647            INDEX_HTML.contains("'delete the transcript, its title and its memory', 'danger'"),
9648            "delete is still the only irreversible row"
9649        );
9650    }
9651
9652    #[test]
9653    fn the_page_has_a_model_picker_wired_to_its_routes() {
9654        assert!(INDEX_HTML.contains("id=\"model\""), "the label is a button");
9655        assert!(INDEX_HTML.contains("/api/models"), "asked for the list");
9656        assert!(
9657            INDEX_HTML.contains("'/api/model'"),
9658            "and tells the server a choice"
9659        );
9660        // A model name is endpoint- and config-written text; rows are built as text, never markup.
9661        assert!(INDEX_HTML.contains("b.textContent = text"));
9662        assert!(!INDEX_HTML.contains("innerHTML"));
9663        // The settings window goes through the same rules: `/api/settings` both ways, rows as text.
9664        assert!(
9665            INDEX_HTML.contains("/api/settings"),
9666            "the catalogue is asked for"
9667        );
9668        assert!(
9669            INDEX_HTML.contains("name.textContent = row.key"),
9670            "a key is text, not markup"
9671        );
9672        assert!(
9673            INDEX_HTML.contains("about.textContent = row.about"),
9674            "a description is text too — it comes from the catalogue"
9675        );
9676    }
9677
9678    /// `#282`: the menu is the table, served. The reply is `COMMANDS` filtered to `Front::Web`,
9679    /// compared against the table rather than against a list written here — a second list is the
9680    /// drift this route exists to prevent.
9681    #[tokio::test]
9682    async fn the_commands_route_is_the_table() {
9683        use eclipse_core::commands::{Args, Front, COMMANDS};
9684
9685        let dir = tempfile::tempdir().unwrap();
9686        let app = router(state(dir.path(), true));
9687        let body = json_body(
9688            app.oneshot(get_req("/api/commands", "127.0.0.1:1"))
9689                .await
9690                .unwrap(),
9691        )
9692        .await;
9693        let served: Vec<&str> = body["commands"]
9694            .as_array()
9695            .expect("a list")
9696            .iter()
9697            .map(|r| r["name"].as_str().expect("a name"))
9698            .collect();
9699        let expected: Vec<&str> = COMMANDS
9700            .iter()
9701            .filter(|c| c.serves(Front::Web))
9702            .map(|c| c.name)
9703            .collect();
9704        assert_eq!(served, expected, "the route is the table, in table order");
9705        assert!(
9706            !served.contains(&"/resume"),
9707            "a terminal-only verb is not offered: {served:?}"
9708        );
9709
9710        // Every field the menu draws comes from the table, including the spelling of an argument.
9711        for row in body["commands"].as_array().unwrap() {
9712            let name = row["name"].as_str().unwrap();
9713            let command = COMMANDS.iter().find(|c| c.name == name).unwrap();
9714            assert_eq!(row["label"], json!(command.label()));
9715            assert_eq!(row["help"], json!(command.help));
9716            assert_eq!(row["aliases"], json!(command.aliases));
9717            assert_eq!(row["takes_arg"], json!(command.args.takes()));
9718            match command.args {
9719                Args::Shown(args) => assert_eq!(row["args"], json!(args)),
9720                Args::None | Args::Unshown => assert_eq!(row["args"], serde_json::Value::Null),
9721            }
9722        }
9723        // `/set` is the one row that shows its shape, so the menu can teach the syntax it needs.
9724        let set = body["commands"]
9725            .as_array()
9726            .unwrap()
9727            .iter()
9728            .find(|r| r["name"] == json!("/set"))
9729            .expect("/set");
9730        assert_eq!(set["label"], json!("/set <key> <value>"));
9731    }
9732
9733    /// `#282`: the page fetches the menu and owns no command names of its own — the `const EFFORTS`
9734    /// lesson from `#275`, applied to a list that is longer and easier to copy.
9735    #[test]
9736    fn the_command_menu_is_the_servers_list_not_the_pages() {
9737        use eclipse_core::commands::{Front, COMMANDS};
9738
9739        assert!(
9740            INDEX_HTML.contains("fetch('/api/commands')"),
9741            "the menu asks the server"
9742        );
9743        for c in COMMANDS.iter().filter(|c| c.serves(Front::Web)) {
9744            for quoted in [format!("'{}'", c.name), format!("\"{}\"", c.name)] {
9745                assert!(
9746                    !INDEX_HTML.contains(&quoted),
9747                    "the page spells {} — the menu must come from the table",
9748                    c.name
9749                );
9750            }
9751        }
9752        // The keys the issue names, and Escape leaving the line alone.
9753        for key in ["ArrowDown", "ArrowUp", "'Tab'", "'Escape'"] {
9754            assert!(
9755                INDEX_HTML.contains(key),
9756                "{key} is handled: the menu owns {key}"
9757            );
9758        }
9759        assert!(INDEX_HTML.contains("role=\"listbox\""));
9760        assert!(INDEX_HTML.contains("aria-activedescendant"));
9761    }
9762
9763    /// `#267`: the settings button opens a dialog, and every row it draws is built from the reply —
9764    /// the control from `kind`, a select's options from `choices`, the sentence from `about`, the
9765    /// "reset" button from `is_default`. No key is named in this file, so the window cannot drift
9766    /// from the catalogue the way the old `prompt` did.
9767    #[test]
9768    fn the_settings_window_draws_its_rows_from_the_catalogue() {
9769        use eclipse_core::commands::COMMANDS;
9770
9771        assert!(
9772            INDEX_HTML.contains("<dialog id=\"settingswindow\""),
9773            "a dialog, not a box in the sidebar"
9774        );
9775        assert!(INDEX_HTML.contains("setWin.showModal()"));
9776        assert!(
9777            INDEX_HTML.contains("for (const choice of row.choices)"),
9778            "a select's options are the server's words"
9779        );
9780        assert!(
9781            INDEX_HTML.contains("row.kind === 'bool'"),
9782            "a boolean is a toggle, chosen by kind"
9783        );
9784        assert!(
9785            INDEX_HTML.contains("send(null)"),
9786            "reset is a null, which the route reads as \"comment the line out\""
9787        );
9788        for key in [
9789            "provider.model",
9790            "agent.max_iterations",
9791            "tools.shell",
9792            "web.port",
9793            "cli.approval",
9794        ] {
9795            assert!(
9796                !INDEX_HTML.contains(key),
9797                "the page spells {key} — the rows must come from the catalogue"
9798            );
9799        }
9800        // Nothing here is a config key by accident, and the command table is unrelated but nearby:
9801        // this catches a stray copy-paste that would otherwise pass the loop above.
9802        assert!(COMMANDS.iter().any(|c| c.name == "/settings"));
9803    }
9804
9805    /// `#297`: the window's frame is a size, not a maximum. A dialog that grows for `all` and
9806    /// shrinks for a section with six rows reads as a page reload every time a section is picked,
9807    /// and the fix is two properties the page cannot drift out of without this test saying so.
9808    #[test]
9809    fn the_settings_window_keeps_its_frame_whatever_section_is_picked() {
9810        assert!(
9811            INDEX_HTML.contains("height:min(760px, 84vh)"),
9812            "the dialog states a height rather than a maximum, so it cannot be as small as its rows"
9813        );
9814        assert!(
9815            INDEX_HTML.contains("#settingswindow[open] { display:flex; flex-direction:column; }"),
9816            "and the body is a column that fills it — `[open]`, or the dialog would draw closed"
9817        );
9818        assert!(
9819            INDEX_HTML.contains("scrollbar-gutter:stable"),
9820            "the rows pane reserves its scrollbar, so picking a long section does not shift the text"
9821        );
9822        assert!(
9823            !INDEX_HTML.contains("max-height:62vh"),
9824            "the old cap is what let the window collapse: the rows pane scrolls instead"
9825        );
9826        // The four things a row says, on two lines rather than four: the provenance rides the
9827        // control's line, pushed right.
9828        assert!(
9829            INDEX_HTML.contains("ctl.appendChild(where)"),
9830            "`now: …` is on the control's line, not a fourth line under it"
9831        );
9832        // A boolean reads as a state without reading the key: a track with a knob, and the state
9833        // word beside it.
9834        assert!(
9835            INDEX_HTML.contains("setAttribute('role', 'switch')"),
9836            "a boolean is a switch, not a button shaped like `set`"
9837        );
9838        assert!(
9839            INDEX_HTML.contains(".srow .switch[aria-checked=\"true\"] .track"),
9840            "and the switch has a drawn on-state"
9841        );
9842        // Sections say what they are for. The map is the page's own words about its own layout, so
9843        // a section the catalogue adds later simply gets none — it is not a key, and the loop above
9844        // still forbids those.
9845        assert!(INDEX_HTML.contains("SET_SECTION_ABOUT"));
9846        for section in ["agent", "provider", "web", "tools"] {
9847            assert!(
9848                INDEX_HTML.contains(&format!("    {section}: '")),
9849                "the {section} section has a sentence"
9850            );
9851        }
9852    }
9853
9854    /// `#239`: what the `+` menu attaches is folded into the turn's text, and the block says what
9855    /// it is and where it ends. The four cases that matter: an inlined file, a reference (a path,
9856    /// a link), a size that is refused with a sentence, and the two kinds the wire cannot carry.
9857    #[test]
9858    fn an_attachment_becomes_a_block_the_model_can_tell_from_the_sentence() {
9859        let said = compose_attachments(
9860            "here is the trace",
9861            &[Attachment {
9862                kind: "text".into(),
9863                name: "trace.txt".into(),
9864                value: "ERROR: the pool was rebuilt\n".into(),
9865            }],
9866        )
9867        .unwrap()
9868        .0;
9869        assert!(said.starts_with("here is the trace"), "{said}");
9870        assert!(
9871            said.contains("--- attached file: trace.txt (27 chars) ---"),
9872            "the block names the file and its size: {said}"
9873        );
9874        assert!(said.contains("ERROR: the pool was rebuilt"), "{said}");
9875        assert!(
9876            said.contains("--- end of trace.txt ---"),
9877            "and says where the file stopped, so the model does not read on: {said}"
9878        );
9879
9880        // A path and a link are references, not contents: the tools that own those rules are
9881        // `read_file` and `fetch`, and neither is replaced here.
9882        let said = compose_attachments(
9883            "",
9884            &[
9885                Attachment {
9886                    kind: "path".into(),
9887                    name: String::new(),
9888                    value: "crates/eclipse-core/src/session.rs".into(),
9889                },
9890                Attachment {
9891                    kind: "url".into(),
9892                    name: String::new(),
9893                    value: "https://example.com/report".into(),
9894                },
9895            ],
9896        )
9897        .unwrap()
9898        .0;
9899        assert!(
9900            said.contains("attached path: crates/eclipse-core/src/session.rs"),
9901            "{said}"
9902        );
9903        assert!(
9904            said.contains("read_file"),
9905            "it says what to do with it: {said}"
9906        );
9907        assert!(
9908            said.contains("attached link: https://example.com/report"),
9909            "{said}"
9910        );
9911        assert!(said.contains("fetch"), "{said}");
9912        // No text, no words: the block is the whole turn, and it does not start with a blank line.
9913        assert!(said.starts_with("--- attached path:"), "{said:?}");
9914
9915        // `#346`: a picture is a part on the message, not a block in the text — the words say one
9916        // was attached, and the bytes travel where the API puts them.
9917        let (said, pictures) = compose_attachments(
9918            "look",
9919            &[Attachment {
9920                kind: "image".into(),
9921                name: "shot.png".into(),
9922                value: "data:image/png;base64,iVBORw0KGgo=".into(),
9923            }],
9924        )
9925        .unwrap();
9926        assert_eq!(pictures.len(), 1, "{pictures:?}");
9927        assert_eq!(pictures[0].name, "shot.png");
9928        assert_eq!(pictures[0].mime, "image/png");
9929        assert!(
9930            said.contains("--- attached picture: shot.png (image/png) ---"),
9931            "the words still read sensibly when a model is sent a description: {said}"
9932        );
9933        // Not a picture, not a `data:` URL, and too big: three refusals with a sentence each.
9934        assert!(compose_attachments(
9935            "x",
9936            &[Attachment {
9937                kind: "image".into(),
9938                name: "shot.svg".into(),
9939                value: "data:image/svg+xml;base64,iVBORw0KGgo=".into(),
9940            }]
9941        )
9942        .unwrap_err()
9943        .contains("not a picture this build can carry"));
9944        assert!(compose_attachments(
9945            "x",
9946            &[Attachment {
9947                kind: "image".into(),
9948                name: "shot.png".into(),
9949                value: "/tmp/shot.png".into(),
9950            }]
9951        )
9952        .unwrap_err()
9953        .contains("data: URL"));
9954
9955        // Bounded, and the sentence says which item and which number.
9956        let big = "x".repeat(MAX_ATTACHMENT_CHARS + 1);
9957        let refused = compose_attachments(
9958            "read this",
9959            &[Attachment {
9960                kind: "text".into(),
9961                name: "huge.log".into(),
9962                value: big,
9963            }],
9964        )
9965        .unwrap_err();
9966        assert!(refused.contains("huge.log"), "{refused}");
9967        assert!(
9968            refused.contains(&MAX_ATTACHMENT_CHARS.to_string()),
9969            "{refused}"
9970        );
9971        assert!(refused.contains("attach it as a path"), "{refused}");
9972
9973        // A "url" that is not one, and a path that is a paragraph.
9974        assert!(compose_attachments(
9975            "x",
9976            &[Attachment {
9977                kind: "url".into(),
9978                name: String::new(),
9979                value: "javascript:alert(1)".into(),
9980            }]
9981        )
9982        .is_err());
9983        assert!(compose_attachments(
9984            "x",
9985            &[Attachment {
9986                kind: "path".into(),
9987                name: String::new(),
9988                value: "a path\nwith a newline".into(),
9989            }]
9990        )
9991        .is_err());
9992
9993        // Nothing attached is the message, untouched — not the message plus a blank line.
9994        assert_eq!(
9995            compose_attachments("just words", &[]).unwrap().0,
9996            "just words"
9997        );
9998        let many: Vec<Attachment> = (0..=MAX_ATTACHMENTS)
9999            .map(|i| Attachment {
10000                kind: "url".into(),
10001                name: String::new(),
10002                value: format!("https://example.com/{i}"),
10003            })
10004            .collect();
10005        assert!(compose_attachments("x", &many)
10006            .unwrap_err()
10007            .contains("at most 8"));
10008    }
10009
10010    /// `#239` end to end through the router: the block the composer produced is the turn the model
10011    /// was given, and it is what the transcript keeps. A command line carrying a chip is refused
10012    /// rather than run with the chip quietly dropped.
10013    #[tokio::test]
10014    async fn an_attached_file_is_the_turn_the_model_read_and_the_text_the_store_keeps() {
10015        let dir = tempfile::tempdir().unwrap();
10016        let st = state(dir.path(), true);
10017        let store = st.agent.as_ref().unwrap().store().clone();
10018        let app = router(st);
10019
10020        let r = app
10021            .clone()
10022            .oneshot(chat_req(json!({
10023                "message": "what broke?",
10024                "attachments": [
10025                    { "kind": "text", "name": "trace.txt", "value": "ERROR: the pool was rebuilt" },
10026                    { "kind": "url", "value": "https://example.com/report" }
10027                ]
10028            })))
10029            .await
10030            .unwrap();
10031        assert_eq!(r.status(), StatusCode::OK, "a run, not a refusal");
10032        // The route answered a run, so this response is the run's stream; `notices` reads its
10033        // events, and the `session` event names the transcript the turn landed in.
10034        let events = notices(r).await;
10035        let session = events
10036            .iter()
10037            .find(|(kind, _)| kind == "session")
10038            .expect("a run opens a session");
10039        let id = session.1["session_id"].as_str().unwrap().to_string();
10040        let kept = store.load(&id).unwrap();
10041        let asked = kept
10042            .iter()
10043            .find(|m| m.role == eclipse_core::message::Role::User)
10044            .and_then(|m| m.content.clone())
10045            .expect("the turn is stored");
10046        assert!(asked.starts_with("what broke?"), "{asked}");
10047        assert!(asked.contains("--- attached file: trace.txt"), "{asked}");
10048        assert!(asked.contains("ERROR: the pool was rebuilt"), "{asked}");
10049        assert!(
10050            asked.contains("--- attached link: https://example.com/report"),
10051            "the link is a reference in the same turn: {asked}"
10052        );
10053
10054        // A verb runs on its own: a chip on a command line is refused, and nothing is stored.
10055        let r = app
10056            .clone()
10057            .oneshot(chat_req(json!({
10058                "message": "/help",
10059                "attachments": [{ "kind": "text", "name": "x.txt", "value": "hello" }]
10060            })))
10061            .await
10062            .unwrap();
10063        let events = notices(r).await;
10064        assert_eq!(events[0].0, "notice", "{events:?}");
10065        assert_eq!(events[0].1["kind"], json!("refusal"), "{events:?}");
10066        assert!(
10067            events[0].1["text"]
10068                .as_str()
10069                .unwrap()
10070                .contains("a command runs on its own"),
10071            "{events:?}"
10072        );
10073
10074        // `#346`: a picture that did not come from the file picker is a 400 with the sentence,
10075        // not a run that answers around it. The bytes have to be the page's own reading — a path
10076        // here would be a reference the model resolves, which is a different thing.
10077        let r = app
10078            .clone()
10079            .oneshot(chat_req(json!({
10080                "message": "look at this",
10081                "attachments": [{ "kind": "image", "name": "shot.png", "value": "AAAA" }]
10082            })))
10083            .await
10084            .unwrap();
10085        assert_eq!(r.status(), StatusCode::BAD_REQUEST);
10086        assert!(
10087            body_text(r).await.contains("data: URL"),
10088            "the refusal says what a picture has to be"
10089        );
10090
10091        // A kind nothing can carry is still refused by name.
10092        let r = app
10093            .clone()
10094            .oneshot(chat_req(json!({
10095                "message": "listen to this",
10096                "attachments": [{ "kind": "audio", "name": "clip.wav", "value": "AAAA" }]
10097            })))
10098            .await
10099            .unwrap();
10100        assert_eq!(r.status(), StatusCode::BAD_REQUEST);
10101        assert!(
10102            body_text(r).await.contains("cannot attach audio"),
10103            "the refusal names the kind"
10104        );
10105    }
10106
10107    /// `#239`, the page's half: the `+` control, its five rows with two disabled and saying why, a
10108    /// chip per item that can be removed, and a request body that carries exactly the chips.
10109    #[test]
10110    fn the_composer_has_a_plus_menu_and_sends_what_its_chips_say() {
10111        assert!(INDEX_HTML.contains("id=\"plus\""), "the control exists");
10112        assert!(
10113            INDEX_HTML.contains("aria-haspopup=\"menu\""),
10114            "and it says it opens a menu"
10115        );
10116        for kind in ["file", "path", "url", "image", "audio"] {
10117            assert!(
10118                INDEX_HTML.contains(&format!("data-attach=\"{kind}\"")),
10119                "the {kind} row exists"
10120            );
10121        }
10122        // `#346`: the picture row works now — it reads the file here and sends it with the turn —
10123        // and audio still says what has to land first. A row that disappears teaches nothing, and
10124        // one that works would be a lie.
10125        assert!(
10126            INDEX_HTML.contains("accept=\"image/png,image/jpeg,image/webp,image/gif\""),
10127            "the picture picker exists and is limited to what the wire carries"
10128        );
10129        assert!(
10130            INDEX_HTML.contains("readAsDataURL"),
10131            "and it reads the bytes here, because the page is the only thing that has them"
10132        );
10133        assert!(
10134            !INDEX_HTML.contains("data-attach=\"image\" disabled"),
10135            "the picture row is no longer a disabled row"
10136        );
10137        assert!(INDEX_HTML.contains("needs a transcription endpoint"));
10138        // A chip is removable, and the request is built from the chips rather than from anything
10139        // the page kept aside.
10140        assert!(INDEX_HTML.contains("function renderAttached()"));
10141        assert!(INDEX_HTML.contains("attached.splice(i, 1)"));
10142        assert!(
10143            INDEX_HTML.contains("const carrying = attached.map"),
10144            "the body is built from the chips at send time"
10145        );
10146        assert!(
10147            INDEX_HTML.contains("attachments: carrying"),
10148            "and travels in the same JSON body as the message"
10149        );
10150        // The picker's cap and the server's are the same number, and the page refuses before it
10151        // reads: a 40 MB file should not be a string in a browser tab.
10152        assert!(INDEX_HTML.contains("const ATTACH_MAX_CHARS = 65536;"));
10153        assert!(
10154            INDEX_HTML.contains("attach it as a path instead"),
10155            "an over-cap file is told what to do instead"
10156        );
10157        // Attaching alone is a turn: the words are not required when something is carried.
10158        assert!(INDEX_HTML.contains("(!text && attached.length === 0)"));
10159        // Escape closes and hands the keyboard back, the same contract as the `/` menu.
10160        assert!(INDEX_HTML.contains("closeAttach(); plus.focus();"));
10161    }
10162
10163    #[tokio::test]
10164    async fn session_endpoints() {
10165        let dir = tempfile::tempdir().unwrap();
10166        let st = state(dir.path(), true);
10167        st.store.append("s1", &Message::user("q")).unwrap();
10168        let app = router(st);
10169        let r = app
10170            .clone()
10171            .oneshot(get_req("/api/sessions", "127.0.0.1:1"))
10172            .await
10173            .unwrap();
10174        assert!(text(r).await.contains("\"s1\""));
10175        let r = app
10176            .clone()
10177            .oneshot(get_req("/api/sessions/s1", "127.0.0.1:1"))
10178            .await
10179            .unwrap();
10180        assert!(text(r).await.contains("\"q\""));
10181        let r = app
10182            .clone()
10183            .oneshot(get_req("/api/sessions/nope", "127.0.0.1:1"))
10184            .await
10185            .unwrap();
10186        assert_eq!(r.status(), StatusCode::NOT_FOUND);
10187        let r = app
10188            .clone()
10189            .oneshot(get_req("/api/sessions/a.b", "127.0.0.1:1"))
10190            .await
10191            .unwrap();
10192        assert_eq!(r.status(), StatusCode::BAD_REQUEST);
10193    }
10194
10195    #[test]
10196    fn loopback_host_parsing() {
10197        assert!(is_loopback_host("127.0.0.1:80"));
10198        assert!(is_loopback_host("localhost"));
10199        assert!(is_loopback_host("[::1]:8787"));
10200        assert!(!is_loopback_host("127.0.0.1.evil.com"));
10201        assert!(!is_loopback_host("example.com:80"));
10202        // The root label: `localhost.` is `localhost`, and a browser sends back what it was given.
10203        assert!(is_loopback_host("localhost.:8787"));
10204        assert!(is_loopback_host("127.0.0.1.:8787"));
10205        assert!(!is_loopback_host("localhost.evil.com:8787"));
10206    }
10207
10208    #[tokio::test]
10209    async fn stop_cancels_a_run_in_flight_and_ends_the_stream() {
10210        use futures_util::StreamExt;
10211        let dir = tempfile::tempdir().unwrap();
10212        let (st, entered, dropped) = hanging_state(dir.path());
10213
10214        let resp = router(st.clone())
10215            .oneshot(chat_req(json!({"message": "hang"})))
10216            .await
10217            .unwrap();
10218        assert_eq!(resp.status(), StatusCode::OK);
10219        let mut body = resp.into_body().into_data_stream();
10220        let first = String::from_utf8(body.next().await.unwrap().unwrap().to_vec()).unwrap();
10221        let run_id = first
10222            .split("run_id\":\"")
10223            .nth(1)
10224            .and_then(|rest| rest.split('"').next())
10225            .unwrap_or_else(|| panic!("no run_id in {first}"))
10226            .to_string();
10227        // Only stop once the model call is really in flight, otherwise this tests the
10228        // wrong path (a run cancelled before it starts).
10229        assert!(
10230            wait_for(&entered, 2000).await,
10231            "the model call never started"
10232        );
10233
10234        let r = router(st.clone())
10235            .oneshot(cancel_req(&run_id))
10236            .await
10237            .unwrap();
10238        assert_eq!(r.status(), StatusCode::OK);
10239        assert!(text(r).await.contains("\"cancelled\":true"));
10240
10241        let mut all = String::new();
10242        while let Ok(Some(Ok(chunk))) =
10243            tokio::time::timeout(Duration::from_secs(5), body.next()).await
10244        {
10245            all.push_str(&String::from_utf8_lossy(&chunk));
10246        }
10247        assert!(all.contains("event: cancelled"), "{all}");
10248        assert!(all.contains("event: done"), "{all}");
10249        assert!(
10250            !all.contains("event: error"),
10251            "cancelling is not a failure: {all}"
10252        );
10253        assert!(
10254            dropped.load(Ordering::SeqCst),
10255            "the provider request must be dropped, not waited out"
10256        );
10257        // The prompt stays in the session; no reply was invented for it.
10258        assert_eq!(st.store.list().unwrap()[0].messages, 1);
10259
10260        // The finished run is no longer cancellable.
10261        assert!(wait_for(&dropped, 1000).await);
10262        tokio::time::sleep(Duration::from_millis(100)).await;
10263        let again = router(st).oneshot(cancel_req(&run_id)).await.unwrap();
10264        assert_eq!(again.status(), StatusCode::NOT_FOUND);
10265    }
10266
10267    #[tokio::test]
10268    async fn closing_the_connection_cancels_the_run() {
10269        use futures_util::StreamExt;
10270        let dir = tempfile::tempdir().unwrap();
10271        let (st, entered, dropped) = hanging_state(dir.path());
10272        let resp = router(st.clone())
10273            .oneshot(chat_req(json!({"message": "hang"})))
10274            .await
10275            .unwrap();
10276        let mut body = resp.into_body().into_data_stream();
10277        body.next().await.unwrap().unwrap();
10278        assert!(
10279            wait_for(&entered, 2000).await,
10280            "the model call never started"
10281        );
10282        assert!(
10283            !dropped.load(Ordering::SeqCst),
10284            "the run must still be in flight"
10285        );
10286        // The browser closes the tab: the response body goes away.
10287        drop(body);
10288        assert!(
10289            wait_for(&dropped, 3000).await,
10290            "a closed connection must cancel the run, not leave it running"
10291        );
10292        tokio::time::sleep(Duration::from_millis(100)).await;
10293        assert_eq!(st.store.list().unwrap()[0].messages, 1);
10294    }
10295
10296    #[tokio::test]
10297    async fn cancel_rejects_malformed_and_unknown_run_ids() {
10298        let dir = tempfile::tempdir().unwrap();
10299        let st = state(dir.path(), true);
10300        for (uri, want) in [
10301            ("/api/runs/not-hex/cancel", StatusCode::BAD_REQUEST),
10302            ("/api/runs/deadbeef/cancel", StatusCode::NOT_FOUND),
10303        ] {
10304            let r = router(st.clone())
10305                .oneshot(
10306                    anon("POST", uri)
10307                        .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
10308                        .body(Body::empty())
10309                        .unwrap(),
10310                )
10311                .await
10312                .unwrap();
10313            assert_eq!(r.status(), want, "{uri}");
10314        }
10315    }
10316
10317    #[tokio::test]
10318    async fn a_chat_can_ask_for_its_own_turn_budget_and_hears_what_it_got() {
10319        let dir = tempfile::tempdir().unwrap();
10320        let st = state(dir.path(), true);
10321        let resp = router(st)
10322            .oneshot(chat_req(json!({"message": "hello", "max_iterations": 7})))
10323            .await
10324            .unwrap();
10325        assert_eq!(resp.status(), StatusCode::OK);
10326        let body = text(resp).await;
10327        assert!(
10328            body.contains("\"max_iterations\":7"),
10329            "the session event must report the budget that will apply: {body}"
10330        );
10331    }
10332
10333    /// `#425`: the browser chose the loop bound and only 0 was refused, so anything driving this
10334    /// route could ask for a bound that holds the model for as long as it liked. Refused, not
10335    /// clamped: the number in the session event is the number that runs.
10336    #[tokio::test]
10337    async fn a_chat_asking_for_a_turn_budget_past_the_ceiling_is_refused() {
10338        let dir = tempfile::tempdir().unwrap();
10339        let st = state(dir.path(), true);
10340        let resp = router(st)
10341            .oneshot(chat_req(json!({
10342                "message": "hello",
10343                "max_iterations": MAX_ITERATIONS_BOUND + 1
10344            })))
10345            .await
10346            .unwrap();
10347        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
10348        let body = text(resp).await;
10349        assert!(
10350            body.contains(&MAX_ITERATIONS_BOUND.to_string()),
10351            "the refusal names the ceiling: {body}"
10352        );
10353    }
10354
10355    #[tokio::test]
10356    async fn a_chat_asks_for_zero_turns_is_refused_rather_than_silently_corrected() {
10357        let dir = tempfile::tempdir().unwrap();
10358        let st = state(dir.path(), true);
10359        let resp = router(st)
10360            .oneshot(chat_req(json!({"message": "hello", "max_iterations": 0})))
10361            .await
10362            .unwrap();
10363        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
10364    }
10365
10366    /// A write on a session, as the page sends it: the session cookie, the CSRF token, and an
10367    /// `Origin: null` that only the token can rescue (a request with no origin at all is
10368    /// treated as same-origin, so it proves nothing about the guard).
10369    fn write_session(
10370        id: &str,
10371        act: &str,
10372        csrf: Option<&str>,
10373        body: Option<serde_json::Value>,
10374    ) -> HttpRequest<Body> {
10375        let mut b = HttpRequest::post(format!("/api/sessions/{id}/{act}"))
10376            .header("host", "127.0.0.1:8787")
10377            .header("origin", "null")
10378            .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"));
10379        if let Some(token) = csrf {
10380            b = b.header(CSRF_HEADER, token);
10381        }
10382        match body {
10383            Some(v) => b
10384                .header("content-type", "application/json")
10385                .body(Body::from(v.to_string()))
10386                .unwrap(),
10387            None => b.body(Body::empty()).unwrap(),
10388        }
10389    }
10390
10391    #[tokio::test]
10392    async fn a_rename_in_the_dashboard_is_the_rename_the_terminal_reads() {
10393        let dir = tempfile::tempdir().unwrap();
10394        let st = state(dir.path(), true);
10395        let store = st.agent.as_ref().unwrap().store().clone();
10396        let id = store.new_id();
10397        store.append(&id, &Message::user("the question")).unwrap();
10398        let app = router(st);
10399
10400        let r = app
10401            .clone()
10402            .oneshot(write_session(
10403                &id,
10404                "rename",
10405                Some(TEST_CSRF),
10406                Some(json!({"title": "named in the browser"})),
10407            ))
10408            .await
10409            .unwrap();
10410        assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
10411
10412        // One store function behind both surfaces: what the terminal would print is there.
10413        assert_eq!(
10414            store.title(&id).unwrap().as_deref(),
10415            Some("named in the browser")
10416        );
10417        let listed = body_text(
10418            app.oneshot(get_req("/api/sessions", "127.0.0.1:8787"))
10419                .await
10420                .unwrap(),
10421        )
10422        .await;
10423        assert!(listed.contains("named in the browser"), "{listed}");
10424        assert!(listed.contains(&format!("\"id\":\"{id}\"")), "{listed}");
10425    }
10426
10427    #[tokio::test]
10428    async fn a_pin_in_the_dashboard_puts_a_session_first_and_keeps_a_prune_off_it() {
10429        let dir = tempfile::tempdir().unwrap();
10430        let st = state(dir.path(), true);
10431        let store = st.agent.as_ref().unwrap().store().clone();
10432        let older = store.new_id();
10433        store
10434            .append(&older, &Message::user("the older one"))
10435            .unwrap();
10436        std::thread::sleep(std::time::Duration::from_millis(5));
10437        let newer = store.new_id();
10438        store
10439            .append(&newer, &Message::user("the newer one"))
10440            .unwrap();
10441        let app = router(st);
10442
10443        let r = app
10444            .clone()
10445            .oneshot(write_session(
10446                &older,
10447                "pin",
10448                Some(TEST_CSRF),
10449                Some(json!({"pinned": true})),
10450            ))
10451            .await
10452            .unwrap();
10453        assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
10454
10455        let listed = body_text(
10456            app.oneshot(get_req("/api/sessions", "127.0.0.1:8787"))
10457                .await
10458                .unwrap(),
10459        )
10460        .await;
10461        let rows: Vec<serde_json::Value> = serde_json::from_str(&listed).unwrap();
10462        assert_eq!(rows[0]["id"], json!(older), "pinned first: {listed}");
10463        assert_eq!(rows[0]["pinned"], json!(true));
10464        assert_eq!(rows[1]["id"], json!(newer));
10465
10466        // `keep only the newest one` would take the pinned one on age alone; the pin wins.
10467        let now = eclipse_core::session::now_ms();
10468        let plan = store.prune_candidates(0, 1, now, false).unwrap();
10469        assert!(!plan.candidates.contains(&older), "{:?}", plan.candidates);
10470        assert_eq!(plan.pinned_kept, 1);
10471    }
10472
10473    /// `#240` end to end through the dashboard: the row leaves `GET /api/sessions`, comes back
10474    /// marked under `?archived=1`, keeps its transcript and its place in the find box, and a
10475    /// prune leaves it alone.
10476    #[tokio::test]
10477    async fn an_archive_in_the_dashboard_is_the_archive_the_terminal_reads() {
10478        let dir = tempfile::tempdir().unwrap();
10479        let st = state(dir.path(), true);
10480        let store = st.agent.as_ref().unwrap().store().clone();
10481        let id = store.new_id();
10482        store
10483            .append(&id, &Message::user("the zfs pool was rebuilt"))
10484            .unwrap();
10485        store.rename(&id, "the nginx migration").unwrap();
10486        let app = router(st);
10487
10488        let r = app
10489            .clone()
10490            .oneshot(write_session(
10491                &id,
10492                "archive",
10493                Some(TEST_CSRF),
10494                Some(json!({"archived": true})),
10495            ))
10496            .await
10497            .unwrap();
10498        assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
10499
10500        // The store is the CLI's: the flag is on the row, and the default listing is empty.
10501        assert!(store.list().unwrap().is_empty());
10502        assert!(store.list_with_archived().unwrap()[0].archived);
10503
10504        let listed = body_text(
10505            app.clone()
10506                .oneshot(get_req("/api/sessions", "127.0.0.1:8787"))
10507                .await
10508                .unwrap(),
10509        )
10510        .await;
10511        assert_eq!(listed.trim(), "[]", "out of the list: {listed}");
10512
10513        // ...and back, marked, when the filter asks for it.
10514        let all = body_text(
10515            app.clone()
10516                .oneshot(get_req("/api/sessions?archived=1", "127.0.0.1:8787"))
10517                .await
10518                .unwrap(),
10519        )
10520        .await;
10521        let rows: Vec<serde_json::Value> = serde_json::from_str(&all).unwrap();
10522        assert_eq!(rows.len(), 1, "{all}");
10523        assert_eq!(rows[0]["archived"], json!(true), "{all}");
10524        assert_eq!(rows[0]["title"], json!("the nginx migration"), "{all}");
10525
10526        // Still found, still readable, and out of a prune's reach until it is asked for: a day
10527        // from now the age rule would take it, and the flag is what changes the answer.
10528        let hits = body_text(
10529            app.clone()
10530                .oneshot(get_req("/api/search?q=zfs", "127.0.0.1:8787"))
10531                .await
10532                .unwrap(),
10533        )
10534        .await;
10535        assert!(hits.contains(&id), "the find box still answers: {hits}");
10536        let transcript = body_text(
10537            app.clone()
10538                .oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
10539                .await
10540                .unwrap(),
10541        )
10542        .await;
10543        assert!(transcript.contains("zfs pool"), "{transcript}");
10544        let later = eclipse_core::session::now_ms() + 86_400_000;
10545        let plan = store.prune_candidates(1, 0, later, false).unwrap();
10546        assert!(plan.candidates.is_empty(), "{:?}", plan.candidates);
10547        assert_eq!(plan.archived_kept, 1);
10548        let asked = store.prune_candidates(1, 0, later, true).unwrap();
10549        assert_eq!(asked.candidates, vec![id.clone()]);
10550
10551        // Unarchiving is the same route the other way, and the row is back in the default list.
10552        let r = app
10553            .clone()
10554            .oneshot(write_session(
10555                &id,
10556                "archive",
10557                Some(TEST_CSRF),
10558                Some(json!({"archived": false})),
10559            ))
10560            .await
10561            .unwrap();
10562        assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
10563        let listed = body_text(
10564            app.oneshot(get_req("/api/sessions", "127.0.0.1:8787"))
10565                .await
10566                .unwrap(),
10567        )
10568        .await;
10569        assert!(listed.contains(&id), "{listed}");
10570    }
10571
10572    /// `#240` in the composer: the same three words the terminal answers, from the same store
10573    /// call — and a row in the transcript, not a turn.
10574    #[tokio::test]
10575    async fn the_composers_archive_verb_files_the_open_session_away() {
10576        let dir = tempfile::tempdir().unwrap();
10577        let st = state(dir.path(), true);
10578        let store = st.agent.as_ref().unwrap().store().clone();
10579        let id = store.new_id();
10580        store
10581            .append(&id, &Message::user("the nginx migration"))
10582            .unwrap();
10583        store.rename(&id, "the nginx migration").unwrap();
10584        let app = router(st);
10585
10586        let events = notices(
10587            app.clone()
10588                .oneshot(chat_req(json!({"message": "/archive", "session_id": id})))
10589                .await
10590                .unwrap(),
10591        )
10592        .await;
10593        assert_eq!(events[0].0, "notice", "{events:?}");
10594        assert_eq!(events[0].1["kind"], json!("command"));
10595        let said = events[0].1["text"].as_str().unwrap();
10596        assert!(said.contains("still in the find box"), "{said}");
10597        assert!(store.list().unwrap().is_empty(), "the row left the listing");
10598        assert!(store.list_with_archived().unwrap()[0].archived);
10599
10600        // `list` names what is filed away instead of claiming nothing is.
10601        let events = notices(
10602            app.clone()
10603                .oneshot(chat_req(json!({"message": "/archive list"})))
10604                .await
10605                .unwrap(),
10606        )
10607        .await;
10608        let said = events[0].1["text"].as_str().unwrap();
10609        assert!(
10610            said.contains(&id) && said.contains("the nginx migration"),
10611            "{said}"
10612        );
10613
10614        // `off` is the way back, and nothing was written to a session's transcript by either.
10615        let events = notices(
10616            app.clone()
10617                .oneshot(chat_req(
10618                    json!({"message": "/archive off", "session_id": id}),
10619                ))
10620                .await
10621                .unwrap(),
10622        )
10623        .await;
10624        let said = events[0].1["text"].as_str().unwrap();
10625        assert!(said.contains("back in the list"), "{said}");
10626        assert_eq!(store.list().unwrap().len(), 1);
10627        assert_eq!(store.load(&id).unwrap().len(), 1, "a verb is not a turn");
10628
10629        // And a word that is not one of the three is refused, with the two that are.
10630        let events = notices(
10631            app.oneshot(chat_req(
10632                json!({"message": "/archive everything", "session_id": id}),
10633            ))
10634            .await
10635            .unwrap(),
10636        )
10637        .await;
10638        assert_eq!(events[0].1["kind"], json!("refusal"));
10639        let said = events[0].1["text"].as_str().unwrap();
10640        assert!(said.contains("`list` or `off`"), "{said}");
10641    }
10642
10643    #[tokio::test]
10644    async fn deleting_from_the_dashboard_takes_the_transcript_title_and_memory() {
10645        let dir = tempfile::tempdir().unwrap();
10646        let st = state(dir.path(), true);
10647        let store = st.agent.as_ref().unwrap().store().clone();
10648        let id = store.new_id();
10649        store.append(&id, &Message::user("doomed")).unwrap();
10650        store.rename(&id, "a name").unwrap();
10651        let app = router(st);
10652
10653        let r = app
10654            .clone()
10655            .oneshot(write_session(&id, "delete", Some(TEST_CSRF), None))
10656            .await
10657            .unwrap();
10658        assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
10659        assert!(!store.exists(&id), "the whole session, not just the row");
10660        assert!(store.load(&id).is_err(), "the transcript went with it");
10661
10662        let r = app
10663            .clone()
10664            .oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
10665            .await
10666            .unwrap();
10667        assert_eq!(r.status(), StatusCode::NOT_FOUND);
10668    }
10669
10670    #[tokio::test]
10671    async fn every_session_write_is_refused_without_the_csrf_token() {
10672        let dir = tempfile::tempdir().unwrap();
10673        let st = state(dir.path(), true);
10674        let store = st.agent.as_ref().unwrap().store().clone();
10675        let id = store.new_id();
10676        store.append(&id, &Message::user("untouched")).unwrap();
10677        let app = router(st);
10678
10679        for (act, body) in [
10680            ("rename", Some(json!({"title": "should not land"}))),
10681            ("pin", Some(json!({"pinned": true}))),
10682            ("archive", Some(json!({"archived": true}))),
10683            ("delete", None),
10684        ] {
10685            let r = app
10686                .clone()
10687                .oneshot(write_session(&id, act, None, body))
10688                .await
10689                .unwrap();
10690            assert_eq!(r.status(), StatusCode::FORBIDDEN, "{act}");
10691            let said = body_text(r).await;
10692            assert!(said.contains(CSRF_HEADER), "{act}: {said}");
10693        }
10694        // Nothing ran: the title is unset, the pin is off, the row is still in the list, the
10695        // transcript is still there.
10696        assert_eq!(store.title(&id).unwrap(), None);
10697        assert!(!store.list().unwrap()[0].pinned);
10698        assert!(!store.list().unwrap()[0].archived);
10699        assert!(store.exists(&id));
10700    }
10701
10702    #[tokio::test]
10703    async fn a_session_write_names_an_unknown_session_rather_than_creating_one() {
10704        let dir = tempfile::tempdir().unwrap();
10705        let app = router(state(dir.path(), true));
10706        let r = app
10707            .clone()
10708            .oneshot(write_session(
10709                "no-such-session",
10710                "pin",
10711                Some(TEST_CSRF),
10712                Some(json!({"pinned": true})),
10713            ))
10714            .await
10715            .unwrap();
10716        assert_eq!(r.status(), StatusCode::NOT_FOUND);
10717    }
10718
10719    // -----------------------------------------------------------------------------------------
10720    // Cron: the same jobs the timer runs
10721    // -----------------------------------------------------------------------------------------
10722
10723    /// A dashboard whose cron root is the temp directory the test writes jobs into.
10724    fn cron_state(dir: &std::path::Path) -> Shared {
10725        match Arc::try_unwrap(state(dir, true)) {
10726            Ok(st) => Arc::new(st.with_cron_root(dir.to_path_buf())),
10727            Err(_) => panic!("a state built here is not shared yet"),
10728        }
10729    }
10730
10731    /// `ECLIPSE_BIN` is process-wide while cargo runs these tests as threads of one process, so the
10732    /// tests that point it at a stand-in take this first — the same reason the release tests
10733    /// serialise their scratch directories. A `tokio` mutex rather than a `std` one because the
10734    /// guard is held across awaits, and clippy is right to refuse that with a std lock.
10735    fn cron_env() -> &'static tokio::sync::Mutex<()> {
10736        static LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
10737        &LOCK
10738    }
10739
10740    fn cron_req(
10741        method: &str,
10742        path: &str,
10743        csrf: Option<&str>,
10744        body: Option<serde_json::Value>,
10745    ) -> HttpRequest<Body> {
10746        let mut b = HttpRequest::builder()
10747            .method(method)
10748            .uri(path)
10749            .header("host", "127.0.0.1:8787")
10750            // A page in an embedded pane reports an opaque origin, and the guard treats that as
10751            // foreign unless the request carries the token it read from this page.
10752            .header("origin", "null")
10753            .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"));
10754        if let Some(token) = csrf {
10755            b = b.header(CSRF_HEADER, token);
10756        }
10757        match body {
10758            Some(v) => b
10759                .header("content-type", "application/json")
10760                .body(Body::from(v.to_string()))
10761                .unwrap(),
10762            None => b.body(Body::empty()).unwrap(),
10763        }
10764    }
10765
10766    fn seed_job(dir: &std::path::Path, name: &str, prompt: &str) {
10767        let job = eclipse_core::cron::Draft {
10768            name: name.to_string(),
10769            schedule: "every 30m".to_string(),
10770            prompt: prompt.to_string(),
10771            ..Default::default()
10772        }
10773        .to_job()
10774        .unwrap();
10775        eclipse_core::cron::append_job(dir, &job).unwrap();
10776    }
10777
10778    #[tokio::test]
10779    async fn the_cron_list_is_the_same_job_the_cli_prints() {
10780        let dir = tempfile::tempdir().unwrap();
10781        seed_job(dir.path(), "brief", "summarise yesterday");
10782        let app = router(cron_state(dir.path()));
10783        let body = body_text(
10784            app.oneshot(cron_req("GET", "/api/cron", None, None))
10785                .await
10786                .unwrap(),
10787        )
10788        .await;
10789        let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
10790        assert!(parsed["now_ms"].as_i64().unwrap_or(0) > 0, "{body}");
10791        let jobs = parsed["jobs"].as_array().expect("a jobs array");
10792        assert_eq!(jobs.len(), 1, "{body}");
10793        assert_eq!(jobs[0]["name"], "brief");
10794        // The schedule goes out in the form an editor can submit back, not as a struct the page
10795        // would have to know how to print.
10796        assert_eq!(jobs[0]["schedule"], "every 30m");
10797        assert_eq!(jobs[0]["prompt"], "summarise yesterday");
10798        assert_eq!(jobs[0]["enabled"], true);
10799        assert!(jobs[0]["next_ms"].as_i64().is_some(), "{body}");
10800        assert_eq!(jobs[0]["runs"], 0);
10801    }
10802
10803    #[tokio::test]
10804    async fn a_cron_write_without_the_token_is_refused_and_changes_nothing() {
10805        let dir = tempfile::tempdir().unwrap();
10806        let app = router(cron_state(dir.path()));
10807        let r = app
10808            .clone()
10809            .oneshot(cron_req(
10810                "POST",
10811                "/api/cron",
10812                None,
10813                Some(json!({"name": "brief", "schedule": "hourly", "prompt": "x"})),
10814            ))
10815            .await
10816            .unwrap();
10817        assert_eq!(r.status(), StatusCode::FORBIDDEN);
10818        let left = eclipse_core::cron::load(dir.path()).unwrap();
10819        assert!(left.is_empty(), "a refused write wrote {:?}", left.len());
10820    }
10821
10822    #[tokio::test]
10823    async fn a_new_job_is_written_into_the_file_the_timer_reads() {
10824        let dir = tempfile::tempdir().unwrap();
10825        let app = router(cron_state(dir.path()));
10826        let r = app
10827            .clone()
10828            .oneshot(cron_req(
10829                "POST",
10830                "/api/cron",
10831                Some(TEST_CSRF),
10832                Some(json!({
10833                    "name": "brief",
10834                    "schedule": "daily 07:30",
10835                    "prompt": "what happened yesterday",
10836                })),
10837            ))
10838            .await
10839            .unwrap();
10840        assert_eq!(r.status(), StatusCode::CREATED);
10841        let body = body_text(r).await;
10842        let created: serde_json::Value = serde_json::from_str(&body).expect("json");
10843        assert_eq!(created["schedule"], "daily 07:30", "{body}");
10844        // Through the store, not a second writer: `cron::load` is what `cron list` and the tick
10845        // both read, so a file it can read is a job the timer will run.
10846        let jobs = eclipse_core::cron::load(dir.path()).unwrap();
10847        assert_eq!(jobs.len(), 1);
10848        assert_eq!(jobs[0].name, "brief");
10849        assert_eq!(jobs[0].prompt, "what happened yesterday");
10850        assert!(jobs[0].enabled);
10851    }
10852
10853    #[tokio::test]
10854    async fn a_schedule_the_parser_refuses_is_refused_in_the_parsers_words() {
10855        let dir = tempfile::tempdir().unwrap();
10856        let app = router(cron_state(dir.path()));
10857        let r = app
10858            .clone()
10859            .oneshot(cron_req(
10860                "POST",
10861                "/api/cron",
10862                Some(TEST_CSRF),
10863                Some(json!({"name": "brief", "schedule": "every tuesday-ish", "prompt": "x"})),
10864            ))
10865            .await
10866            .unwrap();
10867        assert_eq!(r.status(), StatusCode::BAD_REQUEST);
10868        let body = body_text(r).await;
10869        // The same sentence `cron add` gives, because it is the same parser saying it — compared
10870        // decoded, since the JSON escapes the quotes the sentence is built from.
10871        let from_parser = eclipse_core::cron::Schedule::parse("every tuesday-ish")
10872            .unwrap_err()
10873            .to_string();
10874        let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
10875        assert_eq!(parsed["error"], from_parser.as_str(), "{body}");
10876    }
10877
10878    #[tokio::test]
10879    async fn a_job_whose_name_is_taken_is_a_conflict_rather_than_a_second_block() {
10880        let dir = tempfile::tempdir().unwrap();
10881        seed_job(dir.path(), "brief", "the first one");
10882        let app = router(cron_state(dir.path()));
10883        let r = app
10884            .clone()
10885            .oneshot(cron_req(
10886                "POST",
10887                "/api/cron",
10888                Some(TEST_CSRF),
10889                Some(json!({"name": "brief", "schedule": "hourly", "prompt": "the second"})),
10890            ))
10891            .await
10892            .unwrap();
10893        assert_eq!(r.status(), StatusCode::CONFLICT);
10894        let jobs = eclipse_core::cron::load(dir.path()).unwrap();
10895        assert_eq!(jobs.len(), 1);
10896        assert_eq!(jobs[0].prompt, "the first one");
10897    }
10898
10899    #[tokio::test]
10900    async fn editing_a_job_rewrites_it_and_keeps_its_name() {
10901        let dir = tempfile::tempdir().unwrap();
10902        seed_job(dir.path(), "brief", "the old prompt");
10903        let app = router(cron_state(dir.path()));
10904        let r = app
10905            .clone()
10906            .oneshot(cron_req(
10907                "PUT",
10908                "/api/cron/brief",
10909                Some(TEST_CSRF),
10910                Some(json!({
10911                    "name": "brief",
10912                    "schedule": "weekly mon 09:00",
10913                    "prompt": "the new prompt",
10914                })),
10915            ))
10916            .await
10917            .unwrap();
10918        assert_eq!(r.status(), StatusCode::OK);
10919        let jobs = eclipse_core::cron::load(dir.path()).unwrap();
10920        assert_eq!(jobs.len(), 1, "an edit is not an append");
10921        assert_eq!(
10922            jobs[0].schedule,
10923            eclipse_core::cron::Schedule::parse("weekly mon 09:00").unwrap()
10924        );
10925        assert_eq!(jobs[0].prompt, "the new prompt");
10926    }
10927
10928    #[tokio::test]
10929    async fn a_rename_through_the_edit_route_is_refused() {
10930        let dir = tempfile::tempdir().unwrap();
10931        seed_job(dir.path(), "brief", "keep me");
10932        let app = router(cron_state(dir.path()));
10933        let r = app
10934            .clone()
10935            .oneshot(cron_req(
10936                "PUT",
10937                "/api/cron/brief",
10938                Some(TEST_CSRF),
10939                Some(json!({"name": "digest", "schedule": "hourly", "prompt": "moved"})),
10940            ))
10941            .await
10942            .unwrap();
10943        assert_eq!(r.status(), StatusCode::BAD_REQUEST);
10944        let jobs = eclipse_core::cron::load(dir.path()).unwrap();
10945        assert_eq!(jobs[0].name, "brief");
10946        assert_eq!(jobs[0].prompt, "keep me");
10947    }
10948
10949    #[tokio::test]
10950    async fn a_job_switched_off_stays_in_the_file_and_stops_firing() {
10951        let dir = tempfile::tempdir().unwrap();
10952        seed_job(dir.path(), "brief", "keep me");
10953        let app = router(cron_state(dir.path()));
10954        let r = app
10955            .clone()
10956            .oneshot(cron_req(
10957                "POST",
10958                "/api/cron/brief/enabled",
10959                Some(TEST_CSRF),
10960                Some(json!({"enabled": false})),
10961            ))
10962            .await
10963            .unwrap();
10964        assert_eq!(r.status(), StatusCode::OK);
10965        let body = body_text(r).await;
10966        let view: serde_json::Value = serde_json::from_str(&body).expect("json");
10967        assert_eq!(view["enabled"], false, "{body}");
10968        assert!(
10969            view["next_ms"].is_null(),
10970            "a disabled job has no next fire: {body}"
10971        );
10972        let jobs = eclipse_core::cron::load(dir.path()).unwrap();
10973        assert_eq!(jobs.len(), 1, "switching off is not deleting");
10974        assert_eq!(jobs[0].prompt, "keep me");
10975    }
10976
10977    #[tokio::test]
10978    async fn removing_a_job_keeps_its_run_logs() {
10979        let dir = tempfile::tempdir().unwrap();
10980        seed_job(dir.path(), "brief", "x");
10981        eclipse_core::cron::write_run(
10982            dir.path(),
10983            "brief",
10984            1_700_000_000_000,
10985            "# brief\n\n---\n\nit ran\n",
10986        )
10987        .unwrap();
10988        let app = router(cron_state(dir.path()));
10989        let r = app
10990            .clone()
10991            .oneshot(cron_req("DELETE", "/api/cron/brief", Some(TEST_CSRF), None))
10992            .await
10993            .unwrap();
10994        assert_eq!(r.status(), StatusCode::OK);
10995        assert!(eclipse_core::cron::load(dir.path()).unwrap().is_empty());
10996        assert_eq!(
10997            eclipse_core::cron::recent_runs(dir.path(), "brief", 5).len(),
10998            1,
10999            "the record of what ran outlives the job"
11000        );
11001        // And a second removal is a 404, not a silent success.
11002        let r = app
11003            .clone()
11004            .oneshot(cron_req("DELETE", "/api/cron/brief", Some(TEST_CSRF), None))
11005            .await
11006            .unwrap();
11007        assert_eq!(r.status(), StatusCode::NOT_FOUND);
11008    }
11009
11010    #[tokio::test]
11011    async fn the_logs_route_answers_with_the_text_after_the_header() {
11012        let dir = tempfile::tempdir().unwrap();
11013        seed_job(dir.path(), "brief", "x");
11014        eclipse_core::cron::write_run(
11015            dir.path(),
11016            "brief",
11017            1_700_000_000_000,
11018            "# brief — 2026-11-13 23:13\n\nschedule every 30m\n\n---\n\nthe answer\n",
11019        )
11020        .unwrap();
11021        let app = router(cron_state(dir.path()));
11022        let body = body_text(
11023            app.oneshot(cron_req("GET", "/api/cron/brief/logs?limit=3", None, None))
11024                .await
11025                .unwrap(),
11026        )
11027        .await;
11028        let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
11029        let runs = parsed["runs"].as_array().expect("runs");
11030        assert_eq!(runs.len(), 1, "{body}");
11031        assert_eq!(runs[0]["answer"], "the answer");
11032        assert_eq!(runs[0]["truncated"], false);
11033        assert!(runs[0]["text"].as_str().unwrap().contains("the answer"));
11034    }
11035
11036    #[tokio::test]
11037    async fn run_now_answers_before_the_tick_finishes() {
11038        let _env = cron_env().lock().await;
11039        // A stand-in for `eclipse`, in the tree rather than /tmp, that records its arguments and
11040        // takes a second — long enough that a handler waiting for it would time the request out.
11041        let dir = tempfile::tempdir().unwrap();
11042        let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
11043            .join("../../target/fixtures")
11044            .join(std::process::id().to_string())
11045            .join("cron-run");
11046        std::fs::create_dir_all(&fixture).unwrap();
11047        let stub = fixture.join("eclipse");
11048        let seen = fixture.join("seen.txt");
11049        let _ = std::fs::remove_file(&seen);
11050        std::fs::write(
11051            &stub,
11052            format!(
11053                "#!/bin/sh\nprintf '%s\\n' \"$*\" >> {}\nsleep 2\n",
11054                seen.display()
11055            ),
11056        )
11057        .unwrap();
11058        #[cfg(unix)]
11059        {
11060            use std::os::unix::fs::PermissionsExt;
11061            std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
11062        }
11063        seed_job(dir.path(), "brief", "x");
11064        // SAFETY-adjacent: the variable is read only by `eclipse_bin`, and this is the only test
11065        // that starts a process.
11066        std::env::set_var("ECLIPSE_BIN", &stub);
11067        let app = router(cron_state(dir.path()));
11068        let started = std::time::Instant::now();
11069        let r = app
11070            .clone()
11071            .oneshot(cron_req(
11072                "POST",
11073                "/api/cron/brief/run",
11074                Some(TEST_CSRF),
11075                None,
11076            ))
11077            .await
11078            .unwrap();
11079        let took = started.elapsed();
11080        std::env::remove_var("ECLIPSE_BIN");
11081        let status = r.status();
11082        let answer = body_text(r).await;
11083        assert_eq!(status, StatusCode::ACCEPTED);
11084        assert!(
11085            took < std::time::Duration::from_millis(1500),
11086            "the handler waited for the tick ({took:?})"
11087        );
11088        // The process did start, with the arguments the tick takes.
11089        let mut seen_text = String::new();
11090        for _ in 0..50 {
11091            if let Ok(t) = std::fs::read_to_string(&seen) {
11092                if t.contains("cron run brief") {
11093                    seen_text = t;
11094                    break;
11095                }
11096            }
11097            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
11098        }
11099        assert!(
11100            seen_text.contains("cron run brief"),
11101            "the stub saw: {seen_text:?}"
11102        );
11103
11104        // `#397`: the answer names the pid, and a `Child` that is dropped is never reaped — so the
11105        // finished tick stayed a zombie for as long as the dashboard ran, one per click. The stub
11106        // exits on its own; a process still under /proc well after that is one nobody waited for.
11107        let parsed: serde_json::Value = serde_json::from_str(&answer).expect("the answer is json");
11108        let pid = parsed["pid"].as_u64().expect("the answer names the pid");
11109        let mut reaped = false;
11110        for _ in 0..40 {
11111            if !std::path::Path::new(&format!("/proc/{pid}")).exists() {
11112                reaped = true;
11113                break;
11114            }
11115            tokio::time::sleep(std::time::Duration::from_millis(250)).await;
11116        }
11117        assert!(
11118            reaped,
11119            "/proc/{pid} is still there: the spawned tick was never reaped"
11120        );
11121    }
11122
11123    /// `#398`: the job was found in *this* dashboard's profile, so the tick has to be started in it.
11124    /// A child that resolves the default profile instead answers 202 with a pid and runs a job the
11125    /// page is not polling — the run never appears where the operator is looking.
11126    #[tokio::test]
11127    async fn the_started_tick_is_told_the_profile_and_config_this_dashboard_uses() {
11128        let _env = cron_env().lock().await;
11129        let dir = tempfile::tempdir().unwrap();
11130        let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
11131            .join("../../target/fixtures")
11132            .join(std::process::id().to_string())
11133            .join("cron-profile");
11134        std::fs::create_dir_all(&fixture).unwrap();
11135        let stub = fixture.join("eclipse");
11136        let seen = fixture.join("seen.txt");
11137        let _ = std::fs::remove_file(&seen);
11138        std::fs::write(
11139            &stub,
11140            format!("#!/bin/sh\nprintf '%s\\n' \"$*\" >> {}\n", seen.display()),
11141        )
11142        .unwrap();
11143        #[cfg(unix)]
11144        {
11145            use std::os::unix::fs::PermissionsExt;
11146            std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
11147        }
11148        seed_job(dir.path(), "brief", "x");
11149        let config = dir.path().join("config.toml");
11150        let st = Arc::try_unwrap(state(dir.path(), true))
11151            .unwrap_or_else(|_| panic!("a state built here is not shared yet"))
11152            .with_cron_root(dir.path().to_path_buf())
11153            .with_config_path(Some(config.clone()), Some("work".into()));
11154        std::env::set_var("ECLIPSE_BIN", &stub);
11155        let r = router(Arc::new(st))
11156            .oneshot(cron_req(
11157                "POST",
11158                "/api/cron/brief/run",
11159                Some(TEST_CSRF),
11160                None,
11161            ))
11162            .await
11163            .unwrap();
11164        std::env::remove_var("ECLIPSE_BIN");
11165        assert_eq!(r.status(), StatusCode::ACCEPTED);
11166
11167        let mut said = String::new();
11168        for _ in 0..50 {
11169            if let Ok(t) = std::fs::read_to_string(&seen) {
11170                if t.contains("cron run brief") {
11171                    said = t;
11172                    break;
11173                }
11174            }
11175            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
11176        }
11177        assert!(said.contains("cron run brief"), "the stub saw: {said:?}");
11178        assert!(
11179            said.contains("--profile work"),
11180            "the tick was started without this dashboard's profile: {said:?}"
11181        );
11182        assert!(
11183            said.contains(&format!("--config {}", config.display())),
11184            "the tick was started without this dashboard's config: {said:?}"
11185        );
11186    }
11187
11188    /// `#379`: an unnamed picture used to fall back to `item.value` for its name, so a 2 MB
11189    /// screenshot's whole data URL landed in the message text — and from there in the store, the
11190    /// preview column, the FTS row and the naming call.
11191    #[test]
11192    fn an_unnamed_picture_does_not_put_its_data_url_in_the_text() {
11193        let (said, pictures) = compose_attachments(
11194            "what is this?",
11195            &[Attachment {
11196                kind: "image".into(),
11197                name: String::new(),
11198                value: "data:image/png;base64,iVBORw0KGgo=".into(),
11199            }],
11200        )
11201        .unwrap();
11202        assert_eq!(pictures.len(), 1);
11203        assert_eq!(pictures[0].name, "picture");
11204        assert!(
11205            said.contains("--- attached picture: picture (image/png) ---"),
11206            "{said}"
11207        );
11208        assert!(!said.contains("base64"), "the data URL is not text: {said}");
11209    }
11210
11211    /// `#382`: the body cap is derived from what the attachment rules allow. It used to be 4 MiB
11212    /// while 8 × 2 MiB pictures were promised, so two honest 2 MiB pictures (5.6 MB of base64) were
11213    /// refused with advice that does not apply to a picture.
11214    #[test]
11215    fn the_body_cap_fits_the_pictures_the_rules_allow() {
11216        let picture_in_base64 = eclipse_core::message::MAX_PICTURE_BYTES / 3 * 4;
11217        assert!(
11218            CHAT_BODY_LIMIT > 2 * picture_in_base64,
11219            "two 2 MiB pictures are {pictures} of data URL and the cap is {CHAT_BODY_LIMIT}",
11220            pictures = 2 * picture_in_base64
11221        );
11222        assert!(
11223            CHAT_BODY_LIMIT > MAX_ATTACHMENTS / 2 * picture_in_base64,
11224            "half a turn of pictures must fit: {CHAT_BODY_LIMIT}"
11225        );
11226    }
11227
11228    // -----------------------------------------------------------------------------------------
11229    // MCP: the same `[[mcp]]` entries `eclipse mcp list` prints
11230    // -----------------------------------------------------------------------------------------
11231
11232    /// A dashboard whose `config.toml` is the temp directory's, holding exactly `text`.
11233    fn mcp_state(dir: &std::path::Path, text: &str) -> Shared {
11234        std::fs::write(dir.join("config.toml"), text).unwrap();
11235        state_with(dir, true, Some(dir.join("config.toml")))
11236    }
11237
11238    /// The core `mcp.rs` test server, cut down to what a listing needs: it answers `initialize`
11239    /// and lists two tools, so the pane can show a real handshake and a real count.
11240    const FAKE_MCP: &str = r#"#!/usr/bin/env python3
11241import json, sys
11242
11243def send(obj):
11244    sys.stdout.write(json.dumps(obj) + "\n"); sys.stdout.flush()
11245
11246for line in sys.stdin:
11247    line = line.strip()
11248    if not line:
11249        continue
11250    msg = json.loads(line)
11251    mid, method = msg.get("id"), msg.get("method")
11252    if method == "initialize":
11253        send({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": "2024-11-05",
11254              "capabilities": {"tools": {}}, "serverInfo": {"name": "fake", "version": "0"}}})
11255    elif method == "tools/list":
11256        send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
11257            {"name": "echo_text", "description": "Echo", "inputSchema": {"type": "object"}},
11258            {"name": "read_note", "description": "Read", "inputSchema": {"type": "object"}}]}})
11259"#;
11260
11261    fn fake_mcp(dir: &std::path::Path) -> String {
11262        let path = dir.join("fake_mcp.py");
11263        std::fs::write(&path, FAKE_MCP).unwrap();
11264        path.to_string_lossy().into_owned()
11265    }
11266
11267    fn servers_of(body: &str) -> Vec<serde_json::Value> {
11268        let parsed: serde_json::Value = serde_json::from_str(body).expect("json");
11269        parsed["servers"]
11270            .as_array()
11271            .expect("a servers array")
11272            .clone()
11273    }
11274
11275    /// `#505`: the endpoint the problems pane reads. Its shape is the contract with the page —
11276    /// `summary`, `problems[]` with a kind, and `checked[]` so an empty list is visibly a search
11277    /// that found nothing rather than one that never ran.
11278    #[tokio::test]
11279    async fn the_problems_endpoint_answers_the_shape_the_pane_renders() {
11280        let dir = tempfile::tempdir().unwrap();
11281        let app = router(mcp_state(dir.path(), "[provider]\nmodel = \"m\"\n"));
11282        let body = body_text(
11283            app.oneshot(cron_req("GET", "/api/problems", None, None))
11284                .await
11285                .unwrap(),
11286        )
11287        .await;
11288        let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
11289        assert!(parsed["summary"].is_string(), "{body}");
11290        assert!(parsed["problems"].is_array(), "{body}");
11291        let checked = parsed["checked"].as_array().expect("checked is an array");
11292        assert!(
11293            checked
11294                .iter()
11295                .any(|c| c.as_str().is_some_and(|s| s.starts_with("skill root:"))),
11296            "the readout says what was searched: {body}"
11297        );
11298        // Every problem that is there carries the two fields the table has columns for.
11299        for problem in parsed["problems"].as_array().expect("an array") {
11300            assert!(problem["kind"].is_string(), "{problem}");
11301            assert!(problem["text"].is_string(), "{problem}");
11302        }
11303    }
11304
11305    /// A config this process could not load is the loudest problem of all, and it is not one of
11306    /// the loaders': it stopped them from running. The pane puts it first, so it is its own field.
11307    #[tokio::test]
11308    async fn a_config_that_did_not_load_is_reported_beside_the_loader_problems() {
11309        let dir = tempfile::tempdir().unwrap();
11310        let store = SessionStore::new(dir.path().join("sessions"));
11311        let app = router(Arc::new(authed(
11312            None,
11313            store,
11314            "test-<model>",
11315            Some("provider.base_url is not set".into()),
11316        )));
11317        let body = body_text(
11318            app.oneshot(cron_req("GET", "/api/problems", None, None))
11319                .await
11320                .unwrap(),
11321        )
11322        .await;
11323        assert!(
11324            body.contains("provider.base_url is not set"),
11325            "the loader line is carried: {body}"
11326        );
11327    }
11328
11329    #[tokio::test]
11330    async fn an_mcp_entry_in_the_file_is_listed_with_its_source_and_tools() {
11331        let dir = tempfile::tempdir().unwrap();
11332        let script = fake_mcp(dir.path());
11333        let app = router(mcp_state(
11334            dir.path(),
11335            &format!(
11336                "[[mcp]]\nname = \"docs\"\ncommand = \"python3\"\nargs = [\"{script}\"]\n\
11337                 timeout_secs = 20\n"
11338            ),
11339        ));
11340        let body = body_text(
11341            app.oneshot(cron_req("GET", "/api/mcp", None, None))
11342                .await
11343                .unwrap(),
11344        )
11345        .await;
11346        let row = servers_of(&body)
11347            .into_iter()
11348            .find(|r| r["name"] == "docs")
11349            .unwrap_or_else(|| panic!("the entry is not in the list: {body}"));
11350        // The source says which file the row came from — the fact the issue was filed about.
11351        assert_eq!(row["source"], "config:mcp:docs", "{body}");
11352        assert_eq!(row["tools"], 2, "{body}");
11353        assert_eq!(row["started"], true, "{body}");
11354        // The listing reports what the server answered, not what the file promised.
11355        assert_eq!(row["protocol"], "2024-11-05", "{body}");
11356        assert_eq!(row["server_name"], "fake", "{body}");
11357    }
11358
11359    #[tokio::test]
11360    async fn switching_an_mcp_server_off_reaches_the_file_and_the_list_agrees() {
11361        let dir = tempfile::tempdir().unwrap();
11362        let app = router(mcp_state(
11363            dir.path(),
11364            "[[mcp]]\nname = \"ghost\"\ncommand = \"/nonexistent/eclipse-test-mcp\"\n",
11365        ));
11366        let r = app
11367            .clone()
11368            .oneshot(cron_req(
11369                "POST",
11370                "/api/mcp/ghost/enabled",
11371                Some(TEST_CSRF),
11372                Some(json!({"enabled": false})),
11373            ))
11374            .await
11375            .unwrap();
11376        assert_eq!(r.status(), StatusCode::OK);
11377        let body = body_text(r).await;
11378        let row: serde_json::Value = serde_json::from_str(&body).expect("json");
11379        assert_eq!(row["disabled"], true, "{body}");
11380        // Switched off means *not started*: it must not read as a green row it never earned.
11381        assert_eq!(row["started"], false, "{body}");
11382        assert_eq!(row["tools"], 0, "{body}");
11383        // The file, not the page, is what the next run loads.
11384        let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
11385        assert!(text.contains("disabled = true"), "{text}");
11386        // And a listing built from that file agrees with the row the toggle answered.
11387        let listed = body_text(
11388            app.clone()
11389                .oneshot(cron_req("GET", "/api/mcp", None, None))
11390                .await
11391                .unwrap(),
11392        )
11393        .await;
11394        let row = servers_of(&listed)
11395            .into_iter()
11396            .find(|r| r["name"] == "ghost")
11397            .expect("switching off is not deleting");
11398        assert_eq!(row["disabled"], true, "{listed}");
11399        // Back on: the writer's counterpart, and the list follows the file again.
11400        let r = app
11401            .clone()
11402            .oneshot(cron_req(
11403                "POST",
11404                "/api/mcp/ghost/enabled",
11405                Some(TEST_CSRF),
11406                Some(json!({"enabled": true})),
11407            ))
11408            .await
11409            .unwrap();
11410        assert_eq!(r.status(), StatusCode::OK);
11411        let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
11412        assert!(text.contains("disabled = false"), "{text}");
11413    }
11414
11415    #[tokio::test]
11416    async fn adding_a_server_writes_the_entry_a_duplicate_refuses_and_a_removal_takes() {
11417        let dir = tempfile::tempdir().unwrap();
11418        let script = fake_mcp(dir.path());
11419        let app = router(mcp_state(
11420            dir.path(),
11421            "# mcp servers live below this note\n",
11422        ));
11423        let add = json!({"name": "docs", "command": "python3", "args": [script], "policy": "ask"});
11424        let r = app
11425            .clone()
11426            .oneshot(cron_req(
11427                "POST",
11428                "/api/mcp",
11429                Some(TEST_CSRF),
11430                Some(add.clone()),
11431            ))
11432            .await
11433            .unwrap();
11434        assert_eq!(r.status(), StatusCode::CREATED);
11435        let body = body_text(r).await;
11436        let row: serde_json::Value = serde_json::from_str(&body).expect("json");
11437        assert_eq!(row["source"], "config:mcp:docs", "{body}");
11438        assert_eq!(row["tools"], 2, "{body}");
11439        let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
11440        assert!(
11441            text.contains("# mcp servers live below this note"),
11442            "{text}"
11443        );
11444
11445        // The same name again is the writer's own refusal, in its own words.
11446        let r = app
11447            .clone()
11448            .oneshot(cron_req("POST", "/api/mcp", Some(TEST_CSRF), Some(add)))
11449            .await
11450            .unwrap();
11451        assert_eq!(r.status(), StatusCode::CONFLICT);
11452        let body = body_text(r).await;
11453        assert!(body.contains("is already declared at line"), "{body}");
11454        let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
11455        assert_eq!(text.matches("[[mcp]]").count(), 1, "{text}");
11456
11457        // An entry that mixes the transports is refused by the check the loader runs.
11458        let r = app
11459            .clone()
11460            .oneshot(cron_req(
11461                "POST",
11462                "/api/mcp",
11463                Some(TEST_CSRF),
11464                Some(json!({"name": "mixed", "transport": "http", "command": "python3"})),
11465            ))
11466            .await
11467            .unwrap();
11468        assert_eq!(r.status(), StatusCode::BAD_REQUEST);
11469        let body = body_text(r).await;
11470        assert!(body.contains("that entry is not usable"), "{body}");
11471
11472        // Remove: the block goes, and the list no longer sees a server.
11473        let r = app
11474            .clone()
11475            .oneshot(cron_req("DELETE", "/api/mcp/docs", Some(TEST_CSRF), None))
11476            .await
11477            .unwrap();
11478        assert_eq!(r.status(), StatusCode::OK);
11479        let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
11480        assert!(!text.contains("[[mcp]]"), "{text}");
11481        let listed = body_text(
11482            app.clone()
11483                .oneshot(cron_req("GET", "/api/mcp", None, None))
11484                .await
11485                .unwrap(),
11486        )
11487        .await;
11488        assert!(servers_of(&listed).is_empty(), "{listed}");
11489
11490        // And removing what is not there is the writer's sentence, not silence.
11491        let r = app
11492            .oneshot(cron_req("DELETE", "/api/mcp/docs", Some(TEST_CSRF), None))
11493            .await
11494            .unwrap();
11495        assert_eq!(r.status(), StatusCode::NOT_FOUND);
11496    }
11497
11498    /// `#517`: the pane calls itself an editor and can now edit. One field changes, and every
11499    /// other byte of the file — the neighbouring entry, both comments, the entry's own policy
11500    /// line — is what it was.
11501    #[tokio::test]
11502    async fn editing_an_entry_changes_one_field_and_leaves_the_neighbours_byte_identical() {
11503        let dir = tempfile::tempdir().unwrap();
11504        let before = "# the ghost\n[[mcp]]\nname = \"ghost\"\ncommand = \"/nonexistent/one\"\n\n\
11505                      # the other one\n[[mcp]]\nname = \"other\"\n\
11506                      command = \"/nonexistent/two\"\npolicy = \"allow\"\n";
11507        let app = router(mcp_state(dir.path(), before));
11508        let r = app
11509            .clone()
11510            .oneshot(cron_req(
11511                "PUT",
11512                "/api/mcp/other",
11513                Some(TEST_CSRF),
11514                Some(json!({
11515                    "name": "other",
11516                    "command": "/nonexistent/three",
11517                    "policy": "allow",
11518                })),
11519            ))
11520            .await
11521            .unwrap();
11522        assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
11523        let after = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
11524        assert_eq!(
11525            after,
11526            before.replace("/nonexistent/two", "/nonexistent/three"),
11527            "an edit is not a remove and an add:\n{after}"
11528        );
11529
11530        // The row the page adopts is the row the listing gives.
11531        let listed = body_text(
11532            app.clone()
11533                .oneshot(cron_req("GET", "/api/mcp", None, None))
11534                .await
11535                .unwrap(),
11536        )
11537        .await;
11538        let row = servers_of(&listed)
11539            .into_iter()
11540            .find(|r| r["name"] == "other")
11541            .expect("the edited entry is still listed");
11542        assert_eq!(row["program"], "/nonexistent/three", "{listed}");
11543        assert_eq!(row["args"], json!([]), "{listed}");
11544    }
11545
11546    /// `token_env` is a field of the form now, and the value written is the *variable name*. The
11547    /// listing says in one word whether that variable resolves — this is where a server that
11548    /// cannot authenticate is visible without pressing anything.
11549    #[tokio::test]
11550    async fn a_token_env_typed_in_the_form_is_written_and_the_listing_says_whether_it_resolves() {
11551        let dir = tempfile::tempdir().unwrap();
11552        // The variable lives in the process environment: that is the half of the lookup a test can
11553        // set without touching the machine's own `~/.eclipse`. The `.env` half is `mcp.rs`'s.
11554        // A name built at runtime keeps this a test detail rather than a variable the build reads.
11555        let key = format!("ECLIPSE_TEST_WEB_MCP_TOKEN{}", "_SET");
11556        std::env::set_var(&key, "kept-here");
11557        let before = "[[mcp]]\nname = \"ha\"\ntransport = \"http\"\n\
11558                      url = \"http://127.0.0.1:9/api/mcp\"\n";
11559        let app = router(mcp_state(dir.path(), before));
11560        let put = |token: String| {
11561            json!({
11562                "name": "ha",
11563                "transport": "http",
11564                "url": "http://127.0.0.1:9/api/mcp",
11565                "token_env": token,
11566            })
11567        };
11568        let r = app
11569            .clone()
11570            .oneshot(cron_req(
11571                "PUT",
11572                "/api/mcp/ha",
11573                Some(TEST_CSRF),
11574                Some(put(key.clone())),
11575            ))
11576            .await
11577            .unwrap();
11578        assert_eq!(r.status(), StatusCode::OK);
11579        let body = body_text(r).await;
11580        let row: serde_json::Value = serde_json::from_str(&body).expect("json");
11581        assert_eq!(row["token_env"], key.as_str(), "{body}");
11582        assert_eq!(row["token"], "env", "it resolves: {body}");
11583        assert!(
11584            !body.contains("kept-here"),
11585            "the row carries the word, never the value: {body}"
11586        );
11587        let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
11588        assert!(
11589            text.contains(&format!("token_env = \"{key}\"")),
11590            "the variable name is what the file carries: {text}"
11591        );
11592
11593        // A variable nothing sets is `unset` in the row, beside the entry it dooms.
11594        let absent = format!("{key}_UNSET");
11595        let r = app
11596            .clone()
11597            .oneshot(cron_req(
11598                "PUT",
11599                "/api/mcp/ha",
11600                Some(TEST_CSRF),
11601                Some(put(absent.clone())),
11602            ))
11603            .await
11604            .unwrap();
11605        assert_eq!(r.status(), StatusCode::OK);
11606        let body = body_text(r).await;
11607        let row: serde_json::Value = serde_json::from_str(&body).expect("json");
11608        assert_eq!(row["token"], "unset", "{body}");
11609        assert_eq!(row["token_env"], absent.as_str(), "{body}");
11610        std::env::remove_var(&key);
11611    }
11612
11613    /// An edit that names nothing is a 404 with a sentence, a body that is not JSON never reaches
11614    /// the writer, and a rename is refused rather than done — none of the three touches the file.
11615    #[tokio::test]
11616    async fn an_unknown_entry_is_a_404_a_bad_body_and_a_rename_change_nothing() {
11617        let dir = tempfile::tempdir().unwrap();
11618        let before = "[[mcp]]\nname = \"ghost\"\ncommand = \"/nonexistent/one\"\n";
11619        let app = router(mcp_state(dir.path(), before));
11620        let config = dir.path().join("config.toml");
11621
11622        let r = app
11623            .clone()
11624            .oneshot(cron_req(
11625                "PUT",
11626                "/api/mcp/nope",
11627                Some(TEST_CSRF),
11628                Some(json!({"command": "/nonexistent/any"})),
11629            ))
11630            .await
11631            .unwrap();
11632        assert_eq!(r.status(), StatusCode::NOT_FOUND);
11633        let body = body_text(r).await;
11634        assert!(body.contains("no `[[mcp]]` entry for `nope`"), "{body}");
11635
11636        // A body axum cannot parse: the handler never runs, so the writer cannot have run either.
11637        let r = app
11638            .clone()
11639            .oneshot(
11640                HttpRequest::builder()
11641                    .method("PUT")
11642                    .uri("/api/mcp/ghost")
11643                    .header("host", "127.0.0.1:8787")
11644                    .header("origin", "null")
11645                    .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
11646                    .header(CSRF_HEADER, TEST_CSRF)
11647                    .header("content-type", "application/json")
11648                    .body(Body::from("{\"command\": "))
11649                    .unwrap(),
11650            )
11651            .await
11652            .unwrap();
11653        assert!(
11654            !r.status().is_success(),
11655            "a malformed body is not a saved entry: {}",
11656            body_text(r).await
11657        );
11658
11659        let r = app
11660            .clone()
11661            .oneshot(cron_req(
11662                "PUT",
11663                "/api/mcp/ghost",
11664                Some(TEST_CSRF),
11665                Some(json!({"name": "renamed", "command": "/nonexistent/one"})),
11666            ))
11667            .await
11668            .unwrap();
11669        assert_eq!(r.status(), StatusCode::BAD_REQUEST);
11670        let body = body_text(r).await;
11671        assert!(body.contains("an edit does not rename"), "{body}");
11672
11673        assert_eq!(
11674            std::fs::read_to_string(&config).unwrap(),
11675            before,
11676            "three refusals, and the file is exactly what it was"
11677        );
11678    }
11679
11680    // ---------------------------------------------------------------------------------------
11681    // `#509`: the Bots tab. A bot is a declaration plus one conversation; these hold the three
11682    // things the page promises — the tab exists only when a bot does, opening one reuses its
11683    // session with `origin = bot:<name>`, and that session is not in the human's own list.
11684    // ---------------------------------------------------------------------------------------
11685
11686    /// A config with one bot, written to `dir/config.toml`, and the state that serves it. The
11687    /// instructions are a real file, so the prompt view reads disk rather than a remembered copy.
11688    fn bot_state(dir: &std::path::Path) -> (Shared, std::path::PathBuf) {
11689        let ws = dir.join("ws");
11690        std::fs::create_dir_all(ws.join(".eclipse/skills/one")).unwrap();
11691        std::fs::write(
11692            ws.join(".eclipse/skills/one/SKILL.md"),
11693            "---\nname: one\ndescription: the skill this bot declared\n---\nbody one\n",
11694        )
11695        .unwrap();
11696        let instructions = dir.join("nox.md");
11697        std::fs::write(&instructions, "you are nox, and this is your own prompt\n").unwrap();
11698        let config = dir.join("config.toml");
11699        std::fs::write(
11700            &config,
11701            format!(
11702                r#"
11703[provider]
11704base_url = "http://127.0.0.1:1/v1"
11705model = "test"
11706api_key = "k"
11707
11708[sessions]
11709dir = {sessions:?}
11710
11711[tools]
11712workspace_root = {workspace:?}
11713
11714[bots.nox]
11715instructions = {instructions:?}
11716skills = ["one"]
11717adapter = "telegram"
11718"#,
11719                sessions = dir.join("sessions").display().to_string(),
11720                workspace = ws.display().to_string(),
11721                instructions = instructions.display().to_string(),
11722            ),
11723        )
11724        .unwrap();
11725        let cfg = eclipse_core::config::Config::from_file(&config).unwrap();
11726        let home = dir.join("home");
11727        std::fs::create_dir_all(&home).unwrap();
11728        let env = |key: &str| (key == "HOME").then(|| home.display().to_string());
11729        let store = SessionStore::new(cfg.sessions_dir(&env).unwrap());
11730        let agent = Arc::new(Agent::new(
11731            Arc::new(Canned),
11732            Arc::new(ToolRegistry::default()),
11733            store.clone(),
11734            "sys".into(),
11735            3,
11736        ));
11737        let mut st =
11738            authed(Some(agent), store, "test-<model>", None).with_config_path(Some(config), None);
11739        st.bots = crate::bots::Bots::build(&cfg, &env);
11740        (Arc::new(st), instructions)
11741    }
11742
11743    #[tokio::test]
11744    async fn a_page_with_no_bots_carries_no_bots_tab() {
11745        let dir = tempfile::tempdir().unwrap();
11746        let app = router(state(dir.path(), true));
11747        let page = body_text(app.oneshot(get_req("/", "127.0.0.1:8787")).await.unwrap()).await;
11748        assert!(
11749            !page.contains("id=\"bots\""),
11750            "a config with no bots grew a Bots button: the Sessions tab is not unchanged"
11751        );
11752        assert!(
11753            !page.contains("<section id=\"botspane\""),
11754            "the pane is in the page with no bots"
11755        );
11756        assert!(
11757            page.contains("<ul id=\"sessions\">"),
11758            "the session list is still there"
11759        );
11760    }
11761
11762    #[tokio::test]
11763    async fn a_declared_bot_lists_and_opens_one_session_with_its_own_origin() {
11764        let dir = tempfile::tempdir().unwrap();
11765        let (st, _) = bot_state(dir.path());
11766        let app = router(st.clone());
11767
11768        let listed = body_text(
11769            app.clone()
11770                .oneshot(get_req("/api/bots", "127.0.0.1:8787"))
11771                .await
11772                .unwrap(),
11773        )
11774        .await;
11775        let rows: Vec<serde_json::Value> = serde_json::from_str(&listed).unwrap();
11776        assert_eq!(rows.len(), 1, "{listed}");
11777        assert_eq!(rows[0]["name"], "nox");
11778        assert_eq!(
11779            rows[0]["lane"], "telegram",
11780            "the declaration's lane is what the row says"
11781        );
11782        assert!(rows[0]["last_session"].is_null(), "it has not spoken yet");
11783        assert!(rows[0]["problem"].is_null(), "{listed}");
11784
11785        let open = |app: axum::Router| async move {
11786            body_text(
11787                app.oneshot(
11788                    HttpRequest::post("/api/bots/nox/open")
11789                        .header("host", "127.0.0.1:8787")
11790                        .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
11791                        .header("content-type", "application/json")
11792                        .body(Body::from("{}"))
11793                        .unwrap(),
11794                )
11795                .await
11796                .unwrap(),
11797            )
11798            .await
11799        };
11800        let first = open(app.clone()).await;
11801        let second = open(app.clone()).await;
11802        let first: serde_json::Value = serde_json::from_str(&first).unwrap();
11803        let second: serde_json::Value = serde_json::from_str(&second).unwrap();
11804        let id = first["session_id"].as_str().unwrap().to_string();
11805        assert_eq!(
11806            second["session_id"], first["session_id"],
11807            "opening a bot twice made two conversations"
11808        );
11809        assert_eq!(
11810            st.store.origin(&id).unwrap().as_deref(),
11811            Some("bot:nox"),
11812            "the row the send path reads its identity from"
11813        );
11814
11815        // The human's own list does not carry it — the promise the Sessions tab is built on.
11816        let mine = body_text(
11817            app.clone()
11818                .oneshot(get_req("/api/sessions", "127.0.0.1:8787"))
11819                .await
11820                .unwrap(),
11821        )
11822        .await;
11823        assert!(
11824            !mine.contains(&id),
11825            "a bot's conversation reached the sidebar: {mine}"
11826        );
11827
11828        // And the bot itself has an agent with its own prompt, which is what makes the turn run
11829        // under its instructions rather than the dashboard's.
11830        let agent = st.bots.agent("nox").unwrap().as_ref().unwrap();
11831        assert!(agent.system_prompt().contains("you are nox"));
11832    }
11833
11834    #[tokio::test]
11835    async fn a_bot_conversation_is_cleared_not_deleted() {
11836        let dir = tempfile::tempdir().unwrap();
11837        let (st, _) = bot_state(dir.path());
11838        let app = router(st.clone());
11839        let open = |app: axum::Router, uri: &'static str| async move {
11840            let r = app
11841                .oneshot(
11842                    HttpRequest::post(uri)
11843                        .header("host", "127.0.0.1:8787")
11844                        .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
11845                        .header("content-type", "application/json")
11846                        .body(Body::from("{}"))
11847                        .unwrap(),
11848                )
11849                .await
11850                .unwrap();
11851            (r.status(), body_text(r).await)
11852        };
11853        let (_, body) = open(app.clone(), "/api/bots/nox/open").await;
11854        let first: serde_json::Value = serde_json::from_str(&body).unwrap();
11855        let first = first["session_id"].as_str().unwrap().to_string();
11856
11857        let (status, body) = open(app.clone(), "/api/bots/nox/clear").await;
11858        assert_eq!(status, StatusCode::OK, "{body}");
11859        let cleared: serde_json::Value = serde_json::from_str(&body).unwrap();
11860        assert_eq!(cleared["archived"], 1);
11861        let fresh = cleared["session_id"].as_str().unwrap();
11862        assert_ne!(
11863            fresh, first,
11864            "a cleared bot kept the conversation it was told to file away"
11865        );
11866
11867        // Filed away, not deleted: the old row is still there and says it is archived.
11868        assert!(st.store.exists(&first), "clearing deleted the transcript");
11869        let bots = st.store.list_bots().unwrap();
11870        assert_eq!(bots[0].sessions, 2, "both conversations are counted");
11871        assert_eq!(bots[0].last_session, fresh);
11872    }
11873
11874    #[tokio::test]
11875    async fn the_prompt_view_reads_the_instructions_file_from_disk() {
11876        let dir = tempfile::tempdir().unwrap();
11877        let (st, instructions) = bot_state(dir.path());
11878        // Edited after startup: the pane answers "who is this bot" as it is now, not as it was
11879        // when the process was built.
11880        std::fs::write(
11881            &instructions,
11882            "you are nox, rewritten after the process started\n",
11883        )
11884        .unwrap();
11885        let app = router(st);
11886        let body = body_text(
11887            app.oneshot(get_req("/api/bots/nox/prompt", "127.0.0.1:8787"))
11888                .await
11889                .unwrap(),
11890        )
11891        .await;
11892        let data: serde_json::Value = serde_json::from_str(&body).unwrap();
11893        assert_eq!(data["name"], "nox");
11894        assert!(
11895            data["instructions"]["body"]
11896                .as_str()
11897                .unwrap_or_default()
11898                .contains("rewritten after the process started"),
11899            "{body}"
11900        );
11901        assert_eq!(data["skills"], serde_json::json!(["one"]));
11902        assert_eq!(data["adapter"], "telegram");
11903    }
11904
11905    /// `#171`: a person who has never fanned a task out gets the page they had — no button, no
11906    /// pane, no `main.flares`. The same rule the Bots tab keeps, decided the same way: the server
11907    /// leaves the markup out, so there is no CSS rule to remember and nothing to reach.
11908    #[tokio::test]
11909    async fn a_page_with_no_flare_runs_carries_no_flares_tab() {
11910        let dir = tempfile::tempdir().unwrap();
11911        let app = router(state(dir.path(), true));
11912        let page = body_text(app.oneshot(get_req("/", "127.0.0.1:8787")).await.unwrap()).await;
11913        assert!(
11914            !page.contains("id=\"flares\""),
11915            "a person with no flare runs grew a Flares button"
11916        );
11917        assert!(
11918            !page.contains("<section id=\"flarespane\""),
11919            "the pane is in the page with no runs to show"
11920        );
11921        // The stylesheet is one block for every view and stays: it is inert without the pane, the
11922        // same way the Bots tab's rules are. What must not be there is anything to reach.
11923        assert!(
11924            page.contains("main.flares #flarespane"),
11925            "the tab's styles are part of the page, not spliced with it"
11926        );
11927        assert!(
11928            page.contains("<ul id=\"sessions\">"),
11929            "the session list is still there"
11930        );
11931    }
11932
11933    /// `#171`: the tab is the run ledger read back — a run, its children, and the one write the
11934    /// page is allowed. Both child shapes are here, because drawing them the same way is the bug
11935    /// this test exists for: one that ran (a session, a cost) and one that was **dropped** (no
11936    /// session, no cost, a reason). A dropped child's tokens are `null`, never `0` — a zero would
11937    /// read as a flare that ran for free.
11938    #[tokio::test]
11939    async fn a_flare_run_lists_its_children_and_a_cancel_reaches_the_store() {
11940        let dir = tempfile::tempdir().unwrap();
11941        let st = state(dir.path(), true);
11942        let store = st.store.clone();
11943        store
11944            .begin_flare_run(
11945                "run-1",
11946                "audit the retry paths",
11947                &["local".to_string(), "cloud".to_string()],
11948                2,
11949                "web",
11950            )
11951            .unwrap();
11952        store.begin_flare("flare-child-1", "run-1", 1).unwrap();
11953        store
11954            .flare_job_running("run-1", 1, "local", "flare-child-1")
11955            .unwrap();
11956        store
11957            .flare_job_done(&FlareJobRow {
11958                run_id: "run-1".into(),
11959                n: 1,
11960                route: "local".into(),
11961                session_id: Some("flare-child-1".into()),
11962                state: "done".into(),
11963                prompt_tokens: Some(1200),
11964                completion_tokens: Some(340),
11965                iterations: 2,
11966                why: None,
11967            })
11968            .unwrap();
11969        store
11970            .flare_job_done(&FlareJobRow {
11971                run_id: "run-1".into(),
11972                n: 2,
11973                route: "cloud".into(),
11974                session_id: None,
11975                state: "dropped".into(),
11976                prompt_tokens: None,
11977                completion_tokens: None,
11978                iterations: 0,
11979                why: Some("the run was cancelled before it started".into()),
11980            })
11981            .unwrap();
11982        store
11983            .finish_flare_run("run-1", "cancelled", Some(1200), Some(340), 2)
11984            .unwrap();
11985        let app = router(st);
11986
11987        // The other half of the rule above: with a run on the ledger, the button and the pane are
11988        // in the page. The tab is a class on `<main>`, like every other view.
11989        let page = body_text(
11990            app.clone()
11991                .oneshot(get_req("/", "127.0.0.1:8787"))
11992                .await
11993                .unwrap(),
11994        )
11995        .await;
11996        assert!(
11997            page.contains("id=\"flares\""),
11998            "the sidebar has no Flares button"
11999        );
12000        assert!(
12001            page.contains("<section id=\"flarespane\""),
12002            "the pane is missing"
12003        );
12004        assert!(
12005            page.contains("main.flares #flarespane"),
12006            "the pane's styles came with the page"
12007        );
12008
12009        let listed = body_text(
12010            app.clone()
12011                .oneshot(get_req("/api/flares", "127.0.0.1:8787"))
12012                .await
12013                .unwrap(),
12014        )
12015        .await;
12016        let rows: Vec<serde_json::Value> = serde_json::from_str(&listed).unwrap();
12017        assert_eq!(rows.len(), 1, "{listed}");
12018        assert_eq!(rows[0]["id"], "run-1");
12019        assert_eq!(
12020            rows[0]["jobs"], 2,
12021            "the count the run planned, not the children that started"
12022        );
12023        assert_eq!(
12024            rows[0]["routes"],
12025            serde_json::json!(["local", "cloud"]),
12026            "the routes the run named"
12027        );
12028        assert_eq!(rows[0]["state"], "cancelled");
12029        assert_eq!(rows[0]["running"], false);
12030        assert_eq!(rows[0]["prompt_tokens"], 1200);
12031
12032        let one = body_text(
12033            app.clone()
12034                .oneshot(get_req("/api/flares/run-1", "127.0.0.1:8787"))
12035                .await
12036                .unwrap(),
12037        )
12038        .await;
12039        let one: serde_json::Value = serde_json::from_str(&one).unwrap();
12040        assert_eq!(
12041            one["jobs"][0]["session_id"], "flare-child-1",
12042            "the session a click opens in the transcript view"
12043        );
12044        assert_eq!(one["jobs"][0]["completion_tokens"], 340);
12045        assert!(
12046            one["jobs"][1]["session_id"].is_null(),
12047            "a dropped child has no transcript"
12048        );
12049        assert!(
12050            one["jobs"][1]["prompt_tokens"].is_null(),
12051            "a dropped child costs nothing, and `null` is what the page turns into `?`"
12052        );
12053        assert_eq!(
12054            one["jobs"][1]["why"],
12055            "the run was cancelled before it started"
12056        );
12057
12058        // The one write: the same flag `eclipse flares cancel` sets, answered with the sentence
12059        // that says what the flag does rather than claiming the children have stopped.
12060        let cancelled = app
12061            .clone()
12062            .oneshot(
12063                HttpRequest::post("/api/flares/run-1/cancel")
12064                    .header("host", "127.0.0.1:8787")
12065                    .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
12066                    .header("content-type", "application/json")
12067                    .body(Body::from("{}"))
12068                    .unwrap(),
12069            )
12070            .await
12071            .unwrap();
12072        let status = cancelled.status();
12073        let body = body_text(cancelled).await;
12074        assert_eq!(status, StatusCode::OK, "{body}");
12075        assert!(
12076            body.contains("next boundary"),
12077            "the answer says what a cancel does, not that it is done: {body}"
12078        );
12079        assert!(
12080            store.flare_cancel_requested("run-1").unwrap(),
12081            "the flag the run checks between children"
12082        );
12083
12084        // A run nobody has is a 404 with a sentence, on the read as on the write.
12085        let missing = app
12086            .oneshot(get_req("/api/flares/nope", "127.0.0.1:8787"))
12087            .await
12088            .unwrap();
12089        assert_eq!(missing.status(), StatusCode::NOT_FOUND);
12090    }
12091}