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