Skip to main content

eclipse_web/
startup.rs

1//! Startup shared by both binaries: the dashboard (`eclipse-web`) and the gateway
2//! (`eclipse-gateway`, which serves the same dashboard plus the `/v1` API and the scheduled
3//! upgrade check).
4//!
5//! Nothing here decides *what* to serve — only what config to load, which port to bind and
6//! what state the router gets. The routers are the binaries' business.
7
8use crate::app::{AppState, Shared};
9use anyhow::{bail, Context, Result};
10use eclipse_core::config::{process_env, Config};
11use eclipse_core::runtime::Agent;
12use eclipse_core::session::SessionStore;
13use std::net::{IpAddr, SocketAddr};
14use std::path::PathBuf;
15use std::sync::Arc;
16
17/// Shorter tokens are guessable; `config init` issues 64 hex characters (`token::generate` is 32
18/// random bytes in hex), so this floor only ever bites a token typed by hand.
19///
20/// 32 is Hermes's number — its dashboard session-token provider warns below
21/// `len(token) < 32` — and it is the strictest of the two tools in the house (Pi ships no
22/// dashboard and so has no floor to copy). Hermes warns at that length; this refuses, because a
23/// dashboard that will not start tells you before the browser does.
24pub const MIN_TOKEN_LEN: usize = 32;
25
26/// A year. A login that outlives the process is pointless — sessions live in memory — and a
27/// typo like `session_ttl_hours = 999999` should not mint a cookie that never expires.
28pub const MAX_TTL_HOURS: u64 = 24 * 365;
29
30/// What the command line said. Both binaries take the same flags.
31#[derive(Debug, Clone, Default)]
32pub struct Options {
33    pub config: Option<PathBuf>,
34    pub host: Option<String>,
35    pub port: Option<u16>,
36    pub profile: Option<String>,
37}
38
39/// Everything a server needs before it can serve.
40pub struct Prepared {
41    pub cfg: Config,
42    pub state: Shared,
43    pub addr: SocketAddr,
44}
45
46/// The config the dashboard serves: `[web] default_profile` decides which profile when the
47/// command line names none, resolved by loading again with it named so the overlay, session
48/// directories and plugins are exactly what a `--profile` run would get. An explicit
49/// `--profile`/`ECLIPSE_PROFILE` always wins.
50pub fn dashboard_config(
51    path: Option<&std::path::Path>,
52    profile: Option<&str>,
53    env: eclipse_core::config::EnvFn<'_>,
54) -> Result<Config> {
55    let cfg = Config::load_with_profile(path, profile, env)?;
56    match (cfg.profile.as_deref(), cfg.web.default_profile.clone()) {
57        (None, Some(wanted)) => Ok(Config::load_with_profile(path, Some(&wanted), env)?),
58        _ => Ok(cfg),
59    }
60}
61
62/// The login token the dashboard and the API share: one secret, no second credential to keep.
63pub fn auth_token(cfg: &Config) -> Result<String> {
64    match cfg
65        .web
66        .auth_token
67        .as_deref()
68        .map(str::trim)
69        .filter(|t| !t.is_empty())
70    {
71        Some(t) if t.len() >= MIN_TOKEN_LEN => Ok(t.to_string()),
72        Some(_) => bail!(
73            "web.auth_token is too short (need at least {MIN_TOKEN_LEN} characters); \
74             run `eclipse config init --force` to generate a new config with a random token"
75        ),
76        None => bail!(
77            "web.auth_token is not set, and the dashboard will not start without a login \
78             token; run `eclipse config init` (add --force to replace an existing config) \
79             or set auth_token under [web]"
80        ),
81    }
82}
83
84/// The dashboard is plain HTTP behind a single shared token, so it only binds to
85/// loopback addresses.
86pub fn bind_addr(host: &str, port: u16) -> Result<SocketAddr> {
87    let ip: IpAddr = if host == "localhost" {
88        IpAddr::from([127, 0, 0, 1])
89    } else {
90        host.parse()
91            .with_context(|| format!("invalid host {host:?}"))?
92    };
93    if !ip.is_loopback() {
94        bail!("refusing to bind to non-loopback address {ip}: the dashboard is plain HTTP and loopback-only");
95    }
96    Ok(SocketAddr::new(ip, port))
97}
98
99/// Who may sign in (`#266`): a username and a password hash from `.env`, or — on an install that
100/// has no hash yet — the shared token, which keeps working until `eclipse web passwd` runs.
101///
102/// The lookup order is the config loader's: a real environment variable beats `.env`, so exporting
103/// one to try something appears to work, exactly as `${ECLIPSE_WEB_AUTH_TOKEN}` does for the token.
104/// A hash that does not parse refuses to start: quietly falling back to the token would be a
105/// security decision taken by a typo.
106pub fn credentials(cfg: &Config) -> Result<eclipse_core::auth::Credentials> {
107    eclipse_core::auth::Credentials::resolve(|name| {
108        process_env(name).or_else(|| cfg.dotenv.values.get(name).cloned())
109    })
110    .map_err(|e| anyhow::anyhow!("{e}"))
111}
112
113/// Load the config, build the agent and the store, and decide the address. Shared by the
114/// dashboard and the gateway so the two can never disagree about what a profile means.
115pub async fn prepare(opts: &Options) -> Result<Prepared> {
116    let cfg = dashboard_config(
117        opts.config.as_deref(),
118        opts.profile.as_deref(),
119        &process_env,
120    )?;
121    let token = auth_token(&cfg)?;
122    let credentials = credentials(&cfg)?;
123    let ttl_hours = match cfg.web.session_ttl_hours {
124        0 => eclipse_core::config::DEFAULT_SESSION_TTL_HOURS,
125        h => h.min(MAX_TTL_HOURS),
126    };
127    let login_ttl = std::time::Duration::from_secs(ttl_hours * 60 * 60);
128    let addr = bind_addr(
129        opts.host.as_deref().unwrap_or(&cfg.web.host),
130        opts.port.unwrap_or(cfg.web.port),
131    )?;
132
133    let store = SessionStore::new(cfg.sessions_dir(&process_env)?);
134    let mut model_name = cfg.provider.model.clone();
135    // One long-lived process serves every run, so the hooks' report is said once, not once per
136    // run: the same sentence for each prompt would teach whoever reads stderr to skip it.
137    let (agent, config_error) = match Agent::from_config_reporting(
138        &cfg,
139        &process_env,
140        eclipse_core::hooks::Reporting::stderr_once_per_process(),
141    ) {
142        Ok(a) => {
143            for problem in &a.plugins().problems {
144                eprintln!("plugin: {problem}");
145            }
146            // `[provider]` may be absent when `fallback` names routes: show the first route's model.
147            if let Some(first) = a.route_infos().into_iter().next() {
148                model_name = first.model;
149            }
150            // One probe for the life of the process: without a window `compact_at` has no share
151            // to take, and a long conversation in the browser would never be compacted while the
152            // same conversation in the terminal would be. Capped at 2 s and best effort, so a
153            // server that is down costs startup one timeout and nothing else.
154            a.probe_advertised_window(&cfg, std::time::Duration::from_secs(2))
155                .await;
156            (Some(Arc::new(a)), None)
157        }
158        Err(e) => {
159            eprintln!("warning: {e}; chat is disabled until the config is fixed");
160            (None, Some(e.to_string()))
161        }
162    };
163    let mut state = AppState::new(agent, store, model_name, config_error, token, login_ttl)
164        .with_credentials(credentials)
165        // `#509`: one agent per declared bot. A bot's declaration is read with the same config the
166        // rest of the process runs on — same provider, same store, same permissions — so a bot
167        // differs in its instructions, its memory file and its skills and in nothing else.
168        .with_bots(&cfg, &process_env)
169        // The settings page reads and writes this file, so the process has to say which one
170        // it was started with — including the overlay, which is where a profile's writes go.
171        .with_config_path(
172            opts.config
173                .clone()
174                .or_else(|| eclipse_core::config::config_path(&process_env)),
175            // The profile actually served: `default_profile` may have chosen it, and a write
176            // belongs in the overlay of the profile whose settings the page is showing.
177            Some(cfg.profile_name().to_string()).filter(|p| p != "default"),
178        )
179        // `#571`: a path that came from `--config` is the file a write lands in, as it is for
180        // `config set`; a path this process defaulted to is not, and then the profile decides.
181        .with_config_targets(
182            opts.config.is_some(),
183            eclipse_core::config::home_root(&process_env),
184        );
185    if let Some(root) = eclipse_core::config::home_root(&process_env) {
186        // The cron state the health check reads.
187        state = state.with_cron_root(root);
188    }
189    // The install marker and the update cache live in the plain state directory, never a
190    // profile's: an install belongs to the machine user. A read only — the gateway's schedule
191    // is what asks the repository.
192    if let Some(dir) = eclipse_core::config::state_dir(&process_env) {
193        state.update = Some(eclipse_core::update::Watch::at(dir, &cfg.update));
194    }
195    Ok(Prepared {
196        cfg,
197        state: Arc::new(state),
198        addr,
199    })
200}
201
202/// Bind and serve until Ctrl-C. The router is the caller's: the dashboard passes the
203/// dashboard router, the gateway passes the dashboard router with the API merged on.
204pub async fn serve(prepared: Prepared, router: axum::Router, banner: &str) -> Result<()> {
205    // `#173`: a loop started from the browser belongs to this process, not to the tab. The
206    // sweeper is started with the server and lives as long as it does, which is what makes
207    // `/loop` here a timer rather than a promise the window has to keep open.
208    crate::loops_gateway::spawn(prepared.state.clone());
209    let listener = tokio::net::TcpListener::bind(prepared.addr)
210        .await
211        .with_context(|| format!("cannot bind {}", prepared.addr))?;
212    println!("{} on http://{}", banner, listener.local_addr()?);
213    axum::serve(listener, router)
214        .with_graceful_shutdown(shutdown_signal())
215        .await?;
216    Ok(())
217}
218
219/// Resolve when the process is asked to stop, so the server drains instead of dying.
220///
221/// `SIGINT` was the only arm (`#425`). `systemctl stop`, `docker stop` and a `kill` all send
222/// `SIGTERM`, and a process with no handler for it is terminated immediately — an in-flight run
223/// loses its `RunScope` cleanup, its tool process groups and its session write, and the operator
224/// sees a clean stop that left the state directory mid-turn.
225async fn shutdown_signal() {
226    // On a platform without unix signals there is nothing to listen for beyond Ctrl-C.
227    let signalled = async {
228        #[cfg(unix)]
229        {
230            use tokio::signal::unix::{signal, SignalKind};
231            match signal(SignalKind::terminate()) {
232                Ok(mut term) => {
233                    term.recv().await;
234                }
235                Err(e) => {
236                    eprintln!("cannot listen for SIGTERM ({e}); Ctrl-C still stops the server");
237                    std::future::pending::<()>().await;
238                }
239            }
240        }
241        #[cfg(not(unix))]
242        std::future::pending::<()>().await;
243    };
244    tokio::select! {
245        _ = tokio::signal::ctrl_c() => {}
246        _ = signalled => {}
247    }
248    // Straight to stderr: the point of the message is that a stop is not a crash, and a log line
249    // through the usual sink is the one thing that may not have been flushed yet.
250    eprintln!("stopping: no new requests, in-flight runs are draining");
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256
257    /// A temp home whose base config names `default_profile = "work"`, with the overlay that
258    /// profile carries. Returns the config path and the env closure's input.
259    fn home_with_default_profile() -> (tempfile::TempDir, std::path::PathBuf) {
260        let home = tempfile::tempdir().unwrap();
261        let dir = home.path().join(".eclipse");
262        std::fs::create_dir_all(dir.join("profiles/work")).unwrap();
263        let cfg = dir.join("config.toml");
264        std::fs::write(
265            &cfg,
266            "[provider]\nbase_url = \"http://x/v1\"\nmodel = \"base-model\"\n\
267             [web]\ndefault_profile = \"work\"\n",
268        )
269        .unwrap();
270        std::fs::write(
271            dir.join("profiles/work/config.toml"),
272            "[provider]\nmodel = \"work-model\"\n",
273        )
274        .unwrap();
275        (home, cfg)
276    }
277
278    #[test]
279    fn default_profile_decides_when_the_command_line_names_none() {
280        let (home, cfg) = home_with_default_profile();
281        let env = |k: &str| match k {
282            "HOME" => Some(home.path().to_string_lossy().into_owned()),
283            _ => None,
284        };
285        let loaded = dashboard_config(Some(&cfg), None, &env).unwrap();
286        assert_eq!(loaded.profile.as_deref(), Some("work"));
287        assert_eq!(loaded.provider.model, "work-model", "the overlay applied");
288    }
289
290    #[test]
291    fn an_explicit_profile_beats_the_configured_default() {
292        let (home, cfg) = home_with_default_profile();
293        let env = |k: &str| match k {
294            "HOME" => Some(home.path().to_string_lossy().into_owned()),
295            _ => None,
296        };
297        let loaded = dashboard_config(Some(&cfg), Some("default"), &env).unwrap();
298        assert_eq!(loaded.profile.as_deref(), Some("default"));
299        assert_eq!(
300            loaded.provider.model, "base-model",
301            "no overlay was applied"
302        );
303    }
304
305    #[test]
306    fn only_loopback_binds_are_allowed() {
307        assert!(bind_addr("127.0.0.1", 1).is_ok());
308        assert!(bind_addr("localhost", 1).is_ok());
309        assert!(bind_addr("::1", 1).is_ok());
310        assert!(bind_addr("0.0.0.0", 1).is_err());
311        assert!(bind_addr("192.168.1.5", 1).is_err());
312        assert!(bind_addr("nonsense", 1).is_err());
313    }
314
315    #[test]
316    fn startup_requires_a_long_enough_token() {
317        let mut cfg = Config::default();
318        let err = auth_token(&cfg).unwrap_err().to_string();
319        assert!(err.contains("auth_token") && err.contains("config init"));
320        cfg.web.auth_token = Some("short".into());
321        assert!(auth_token(&cfg)
322            .unwrap_err()
323            .to_string()
324            .contains("too short"));
325        // The boundary, both sides of it, with the padding a pasted value carries.
326        cfg.web.auth_token = Some(" 0123456789abcdef0123456789abcde ".into()); // 31
327        assert!(auth_token(&cfg)
328            .unwrap_err()
329            .to_string()
330            .contains("too short"));
331        cfg.web.auth_token = Some(" 0123456789abcdef0123456789abcdef ".into()); // 32
332        assert_eq!(
333            auth_token(&cfg).unwrap(),
334            "0123456789abcdef0123456789abcdef",
335            "32 characters is the floor, and the padding is trimmed before it is measured"
336        );
337    }
338}