eclipse-web 0.13.3

Local web dashboard for eclipse
Documentation
//! Startup shared by both binaries: the dashboard (`eclipse-web`) and the gateway
//! (`eclipse-gateway`, which serves the same dashboard plus the `/v1` API and the scheduled
//! upgrade check).
//!
//! Nothing here decides *what* to serve — only what config to load, which port to bind and
//! what state the router gets. The routers are the binaries' business.

use crate::app::{AppState, Shared};
use anyhow::{bail, Context, Result};
use eclipse_core::config::{process_env, Config};
use eclipse_core::runtime::Agent;
use eclipse_core::session::SessionStore;
use std::net::{IpAddr, SocketAddr};
use std::path::PathBuf;
use std::sync::Arc;

/// Shorter tokens are guessable; `config init` issues 64 hex characters (`token::generate` is 32
/// random bytes in hex), so this floor only ever bites a token typed by hand.
///
/// 32 is Hermes's number — its dashboard session-token provider warns below
/// `len(token) < 32` — and it is the strictest of the two tools in the house (Pi ships no
/// dashboard and so has no floor to copy). Hermes warns at that length; this refuses, because a
/// dashboard that will not start tells you before the browser does.
pub const MIN_TOKEN_LEN: usize = 32;

/// A year. A login that outlives the process is pointless — sessions live in memory — and a
/// typo like `session_ttl_hours = 999999` should not mint a cookie that never expires.
pub const MAX_TTL_HOURS: u64 = 24 * 365;

/// What the command line said. Both binaries take the same flags.
#[derive(Debug, Clone, Default)]
pub struct Options {
    pub config: Option<PathBuf>,
    pub host: Option<String>,
    pub port: Option<u16>,
    pub profile: Option<String>,
}

/// Everything a server needs before it can serve.
pub struct Prepared {
    pub cfg: Config,
    pub state: Shared,
    pub addr: SocketAddr,
}

/// The config the dashboard serves: `[web] default_profile` decides which profile when the
/// command line names none, resolved by loading again with it named so the overlay, session
/// directories and plugins are exactly what a `--profile` run would get. An explicit
/// `--profile`/`ECLIPSE_PROFILE` always wins.
pub fn dashboard_config(
    path: Option<&std::path::Path>,
    profile: Option<&str>,
    env: eclipse_core::config::EnvFn<'_>,
) -> Result<Config> {
    let cfg = Config::load_with_profile(path, profile, env)?;
    match (cfg.profile.as_deref(), cfg.web.default_profile.clone()) {
        (None, Some(wanted)) => Ok(Config::load_with_profile(path, Some(&wanted), env)?),
        _ => Ok(cfg),
    }
}

/// The login token the dashboard and the API share: one secret, no second credential to keep.
pub fn auth_token(cfg: &Config) -> Result<String> {
    match cfg
        .web
        .auth_token
        .as_deref()
        .map(str::trim)
        .filter(|t| !t.is_empty())
    {
        Some(t) if t.len() >= MIN_TOKEN_LEN => Ok(t.to_string()),
        Some(_) => bail!(
            "web.auth_token is too short (need at least {MIN_TOKEN_LEN} characters); \
             run `eclipse config init --force` to generate a new config with a random token"
        ),
        None => bail!(
            "web.auth_token is not set, and the dashboard will not start without a login \
             token; run `eclipse config init` (add --force to replace an existing config) \
             or set auth_token under [web]"
        ),
    }
}

/// The dashboard is plain HTTP behind a single shared token, so it only binds to
/// loopback addresses.
pub fn bind_addr(host: &str, port: u16) -> Result<SocketAddr> {
    let ip: IpAddr = if host == "localhost" {
        IpAddr::from([127, 0, 0, 1])
    } else {
        host.parse()
            .with_context(|| format!("invalid host {host:?}"))?
    };
    if !ip.is_loopback() {
        bail!("refusing to bind to non-loopback address {ip}: the dashboard is plain HTTP and loopback-only");
    }
    Ok(SocketAddr::new(ip, port))
}

/// Who may sign in (`#266`): a username and a password hash from `.env`, or — on an install that
/// has no hash yet — the shared token, which keeps working until `eclipse web passwd` runs.
///
/// The lookup order is the config loader's: a real environment variable beats `.env`, so exporting
/// one to try something appears to work, exactly as `${ECLIPSE_WEB_AUTH_TOKEN}` does for the token.
/// A hash that does not parse refuses to start: quietly falling back to the token would be a
/// security decision taken by a typo.
pub fn credentials(cfg: &Config) -> Result<eclipse_core::auth::Credentials> {
    eclipse_core::auth::Credentials::resolve(|name| {
        process_env(name).or_else(|| cfg.dotenv.values.get(name).cloned())
    })
    .map_err(|e| anyhow::anyhow!("{e}"))
}

/// Load the config, build the agent and the store, and decide the address. Shared by the
/// dashboard and the gateway so the two can never disagree about what a profile means.
pub async fn prepare(opts: &Options) -> Result<Prepared> {
    let cfg = dashboard_config(
        opts.config.as_deref(),
        opts.profile.as_deref(),
        &process_env,
    )?;
    let token = auth_token(&cfg)?;
    let credentials = credentials(&cfg)?;
    let ttl_hours = match cfg.web.session_ttl_hours {
        0 => eclipse_core::config::DEFAULT_SESSION_TTL_HOURS,
        h => h.min(MAX_TTL_HOURS),
    };
    let login_ttl = std::time::Duration::from_secs(ttl_hours * 60 * 60);
    let addr = bind_addr(
        opts.host.as_deref().unwrap_or(&cfg.web.host),
        opts.port.unwrap_or(cfg.web.port),
    )?;

    let store = SessionStore::new(cfg.sessions_dir(&process_env)?);
    let mut model_name = cfg.provider.model.clone();
    // One long-lived process serves every run, so the hooks' report is said once, not once per
    // run: the same sentence for each prompt would teach whoever reads stderr to skip it.
    let (agent, config_error) = match Agent::from_config_reporting(
        &cfg,
        &process_env,
        eclipse_core::hooks::Reporting::stderr_once_per_process(),
    ) {
        Ok(a) => {
            for problem in &a.plugins().problems {
                eprintln!("plugin: {problem}");
            }
            // `[provider]` may be absent when `fallback` names routes: show the first route's model.
            if let Some(first) = a.route_infos().into_iter().next() {
                model_name = first.model;
            }
            // One probe for the life of the process: without a window `compact_at` has no share
            // to take, and a long conversation in the browser would never be compacted while the
            // same conversation in the terminal would be. Capped at 2 s and best effort, so a
            // server that is down costs startup one timeout and nothing else.
            a.probe_advertised_window(&cfg, std::time::Duration::from_secs(2))
                .await;
            (Some(Arc::new(a)), None)
        }
        Err(e) => {
            eprintln!("warning: {e}; chat is disabled until the config is fixed");
            (None, Some(e.to_string()))
        }
    };
    let mut state = AppState::new(agent, store, model_name, config_error, token, login_ttl)
        .with_credentials(credentials)
        // `#509`: one agent per declared bot. A bot's declaration is read with the same config the
        // rest of the process runs on — same provider, same store, same permissions — so a bot
        // differs in its instructions, its memory file and its skills and in nothing else.
        .with_bots(&cfg, &process_env)
        // The settings page reads and writes this file, so the process has to say which one
        // it was started with — including the overlay, which is where a profile's writes go.
        .with_config_path(
            opts.config
                .clone()
                .or_else(|| eclipse_core::config::config_path(&process_env)),
            // The profile actually served: `default_profile` may have chosen it, and a write
            // belongs in the overlay of the profile whose settings the page is showing.
            Some(cfg.profile_name().to_string()).filter(|p| p != "default"),
        )
        // `#571`: a path that came from `--config` is the file a write lands in, as it is for
        // `config set`; a path this process defaulted to is not, and then the profile decides.
        .with_config_targets(
            opts.config.is_some(),
            eclipse_core::config::home_root(&process_env),
        );
    if let Some(root) = eclipse_core::config::home_root(&process_env) {
        // The cron state the health check reads.
        state = state.with_cron_root(root);
    }
    // The install marker and the update cache live in the plain state directory, never a
    // profile's: an install belongs to the machine user. A read only — the gateway's schedule
    // is what asks the repository.
    if let Some(dir) = eclipse_core::config::state_dir(&process_env) {
        state.update = Some(eclipse_core::update::Watch::at(dir, &cfg.update));
    }
    Ok(Prepared {
        cfg,
        state: Arc::new(state),
        addr,
    })
}

/// Bind and serve until Ctrl-C. The router is the caller's: the dashboard passes the
/// dashboard router, the gateway passes the dashboard router with the API merged on.
pub async fn serve(prepared: Prepared, router: axum::Router, banner: &str) -> Result<()> {
    // `#173`: a loop started from the browser belongs to this process, not to the tab. The
    // sweeper is started with the server and lives as long as it does, which is what makes
    // `/loop` here a timer rather than a promise the window has to keep open.
    crate::loops_gateway::spawn(prepared.state.clone());
    let listener = tokio::net::TcpListener::bind(prepared.addr)
        .await
        .with_context(|| format!("cannot bind {}", prepared.addr))?;
    println!("{} on http://{}", banner, listener.local_addr()?);
    axum::serve(listener, router)
        .with_graceful_shutdown(shutdown_signal())
        .await?;
    Ok(())
}

/// Resolve when the process is asked to stop, so the server drains instead of dying.
///
/// `SIGINT` was the only arm (`#425`). `systemctl stop`, `docker stop` and a `kill` all send
/// `SIGTERM`, and a process with no handler for it is terminated immediately — an in-flight run
/// loses its `RunScope` cleanup, its tool process groups and its session write, and the operator
/// sees a clean stop that left the state directory mid-turn.
async fn shutdown_signal() {
    // On a platform without unix signals there is nothing to listen for beyond Ctrl-C.
    let signalled = async {
        #[cfg(unix)]
        {
            use tokio::signal::unix::{signal, SignalKind};
            match signal(SignalKind::terminate()) {
                Ok(mut term) => {
                    term.recv().await;
                }
                Err(e) => {
                    eprintln!("cannot listen for SIGTERM ({e}); Ctrl-C still stops the server");
                    std::future::pending::<()>().await;
                }
            }
        }
        #[cfg(not(unix))]
        std::future::pending::<()>().await;
    };
    tokio::select! {
        _ = tokio::signal::ctrl_c() => {}
        _ = signalled => {}
    }
    // Straight to stderr: the point of the message is that a stop is not a crash, and a log line
    // through the usual sink is the one thing that may not have been flushed yet.
    eprintln!("stopping: no new requests, in-flight runs are draining");
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A temp home whose base config names `default_profile = "work"`, with the overlay that
    /// profile carries. Returns the config path and the env closure's input.
    fn home_with_default_profile() -> (tempfile::TempDir, std::path::PathBuf) {
        let home = tempfile::tempdir().unwrap();
        let dir = home.path().join(".eclipse");
        std::fs::create_dir_all(dir.join("profiles/work")).unwrap();
        let cfg = dir.join("config.toml");
        std::fs::write(
            &cfg,
            "[provider]\nbase_url = \"http://x/v1\"\nmodel = \"base-model\"\n\
             [web]\ndefault_profile = \"work\"\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("profiles/work/config.toml"),
            "[provider]\nmodel = \"work-model\"\n",
        )
        .unwrap();
        (home, cfg)
    }

    #[test]
    fn default_profile_decides_when_the_command_line_names_none() {
        let (home, cfg) = home_with_default_profile();
        let env = |k: &str| match k {
            "HOME" => Some(home.path().to_string_lossy().into_owned()),
            _ => None,
        };
        let loaded = dashboard_config(Some(&cfg), None, &env).unwrap();
        assert_eq!(loaded.profile.as_deref(), Some("work"));
        assert_eq!(loaded.provider.model, "work-model", "the overlay applied");
    }

    #[test]
    fn an_explicit_profile_beats_the_configured_default() {
        let (home, cfg) = home_with_default_profile();
        let env = |k: &str| match k {
            "HOME" => Some(home.path().to_string_lossy().into_owned()),
            _ => None,
        };
        let loaded = dashboard_config(Some(&cfg), Some("default"), &env).unwrap();
        assert_eq!(loaded.profile.as_deref(), Some("default"));
        assert_eq!(
            loaded.provider.model, "base-model",
            "no overlay was applied"
        );
    }

    #[test]
    fn only_loopback_binds_are_allowed() {
        assert!(bind_addr("127.0.0.1", 1).is_ok());
        assert!(bind_addr("localhost", 1).is_ok());
        assert!(bind_addr("::1", 1).is_ok());
        assert!(bind_addr("0.0.0.0", 1).is_err());
        assert!(bind_addr("192.168.1.5", 1).is_err());
        assert!(bind_addr("nonsense", 1).is_err());
    }

    #[test]
    fn startup_requires_a_long_enough_token() {
        let mut cfg = Config::default();
        let err = auth_token(&cfg).unwrap_err().to_string();
        assert!(err.contains("auth_token") && err.contains("config init"));
        cfg.web.auth_token = Some("short".into());
        assert!(auth_token(&cfg)
            .unwrap_err()
            .to_string()
            .contains("too short"));
        // The boundary, both sides of it, with the padding a pasted value carries.
        cfg.web.auth_token = Some(" 0123456789abcdef0123456789abcde ".into()); // 31
        assert!(auth_token(&cfg)
            .unwrap_err()
            .to_string()
            .contains("too short"));
        cfg.web.auth_token = Some(" 0123456789abcdef0123456789abcdef ".into()); // 32
        assert_eq!(
            auth_token(&cfg).unwrap(),
            "0123456789abcdef0123456789abcdef",
            "32 characters is the floor, and the padding is trimmed before it is measured"
        );
    }
}