1use 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
17pub const MIN_TOKEN_LEN: usize = 32;
25
26pub const MAX_TTL_HOURS: u64 = 24 * 365;
29
30#[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
39pub struct Prepared {
41 pub cfg: Config,
42 pub state: Shared,
43 pub addr: SocketAddr,
44}
45
46pub 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 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
71pub 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
93pub 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
108pub 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
122pub 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 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 if let Some(first) = a.route_infos().into_iter().next() {
157 model_name = first.model;
158 }
159 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 .with_bots(&cfg, &process_env)
178 .with_config_path(
181 opts.config
182 .clone()
183 .or_else(|| eclipse_core::config::config_path(&process_env)),
184 Some(cfg.profile_name().to_string()).filter(|p| p != "default"),
187 )
188 .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 state = state.with_cron_root(root);
197 }
198 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
211pub async fn serve(prepared: Prepared, router: axum::Router, banner: &str) -> Result<()> {
214 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
228async fn shutdown_signal() {
235 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 eprintln!("stopping: no new requests, in-flight runs are draining");
260}
261
262#[cfg(test)]
263mod tests {
264 use super::*;
265
266 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 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 cfg.web.auth_token = Some(" 0123456789abcdef0123456789abcde ".into()); assert!(auth_token(&cfg)
339 .unwrap_err()
340 .to_string()
341 .contains("too short"));
342 cfg.web.auth_token = Some(" 0123456789abcdef0123456789abcdef ".into()); 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}