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 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
62pub 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
84pub 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
99pub 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
113pub 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 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 if let Some(first) = a.route_infos().into_iter().next() {
148 model_name = first.model;
149 }
150 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 .with_bots(&cfg, &process_env)
169 .with_config_path(
172 opts.config
173 .clone()
174 .or_else(|| eclipse_core::config::config_path(&process_env)),
175 Some(cfg.profile_name().to_string()).filter(|p| p != "default"),
178 )
179 .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 state = state.with_cron_root(root);
188 }
189 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
202pub async fn serve(prepared: Prepared, router: axum::Router, banner: &str) -> Result<()> {
205 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
219async fn shutdown_signal() {
226 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 eprintln!("stopping: no new requests, in-flight runs are draining");
251}
252
253#[cfg(test)]
254mod tests {
255 use super::*;
256
257 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 cfg.web.auth_token = Some(" 0123456789abcdef0123456789abcde ".into()); assert!(auth_token(&cfg)
328 .unwrap_err()
329 .to_string()
330 .contains("too short"));
331 cfg.web.auth_token = Some(" 0123456789abcdef0123456789abcdef ".into()); 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}