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;
pub const MIN_TOKEN_LEN: usize = 32;
pub const MAX_TTL_HOURS: u64 = 24 * 365;
#[derive(Debug, Clone, Default)]
pub struct Options {
pub config: Option<PathBuf>,
pub host: Option<String>,
pub port: Option<u16>,
pub profile: Option<String>,
}
pub struct Prepared {
pub cfg: Config,
pub state: Shared,
pub addr: SocketAddr,
}
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)?;
let named = profile.map(str::trim).is_some_and(|p| !p.is_empty())
|| env("ECLIPSE_PROFILE").is_some_and(|p| !p.trim().is_empty());
if named {
return Ok(cfg);
}
match (cfg.profile.as_deref(), cfg.web.default_profile.clone()) {
(None, Some(wanted)) => Ok(Config::load_with_profile(path, Some(&wanted), env)?),
_ => Ok(cfg),
}
}
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]"
),
}
}
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))
}
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}"))
}
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();
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}");
}
if let Some(first) = a.route_infos().into_iter().next() {
model_name = first.model;
}
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)
.with_bots(&cfg, &process_env)
.with_config_path(
opts.config
.clone()
.or_else(|| eclipse_core::config::config_path(&process_env)),
Some(cfg.profile_name().to_string()).filter(|p| p != "default"),
)
.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) {
state = state.with_cron_root(root);
}
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,
})
}
pub async fn serve(prepared: Prepared, router: axum::Router, banner: &str) -> Result<()> {
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(())
}
async fn shutdown_signal() {
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 => {}
}
eprintln!("stopping: no new requests, in-flight runs are draining");
}
#[cfg(test)]
mod tests {
use super::*;
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(), None);
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"));
cfg.web.auth_token = Some(" 0123456789abcdef0123456789abcde ".into()); assert!(auth_token(&cfg)
.unwrap_err()
.to_string()
.contains("too short"));
cfg.web.auth_token = Some(" 0123456789abcdef0123456789abcdef ".into()); assert_eq!(
auth_token(&cfg).unwrap(),
"0123456789abcdef0123456789abcdef",
"32 characters is the floor, and the padding is trimmed before it is measured"
);
}
}