use crate::calls;
use crate::verb::{self, Answer};
use async_trait::async_trait;
use axum::extract::{DefaultBodyLimit, Path, Query, Request, State};
use axum::http::{header, HeaderMap, HeaderValue, Method, StatusCode};
use axum::middleware::{self, Next};
use axum::response::sse::{Event, KeepAlive, Sse};
use axum::response::{Html, IntoResponse, Response};
use axum::routing::{get, post, put};
use axum::{Form, Json, Router};
use eclipse_core::cancel::Cancel;
use eclipse_core::commands::{Front, Parsed};
use eclipse_core::contextbar::Reading;
use eclipse_core::runtime::{Agent, AgentEvent, RunOptions};
use eclipse_core::session::{FlareJobRow, FlareRunRow};
use eclipse_core::tools::Approver;
use futures_util::stream::{self, Stream};
use futures_util::StreamExt;
use serde::Deserialize;
use serde_json::json;
use std::collections::HashMap;
use std::convert::Infallible;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::sync::{mpsc, oneshot, Semaphore};
const INDEX_HTML: &str = include_str!("index.html");
const BOTS_PANE: &str = r#" <section id="botspane" hidden aria-label="bots">
<header>
<h2>bots</h2>
<small id="botsfile"></small>
<span class="grow"></span>
<button id="botsrefresh" type="button">refresh</button>
</header>
<div id="botsmsg"></div>
<table id="botstable">
<thead><tr><th>bot</th><th>lane</th><th>last</th><th>said</th><th></th></tr></thead>
<tbody id="botsrows"></tbody>
</table>
<div id="botsprompt" hidden></div>
</section>
"#;
const FLARES_PANE: &str = r#" <section id="flarespane" hidden aria-label="flare runs">
<header>
<h2>flare runs</h2>
<small id="flaresfile"></small>
<span class="grow"></span>
<button id="flaresrefresh" type="button">refresh</button>
</header>
<div id="flaresmsg"></div>
<table id="flaretable">
<thead><tr><th>run</th><th>state</th><th>age</th><th>routes</th><th>jobs</th><th>cost</th><th></th></tr></thead>
<tbody id="flarerows"></tbody>
</table>
</section>
"#;
pub const CHAT_BODY_LIMIT: usize = MAX_ATTACHMENTS
* (eclipse_core::message::MAX_PICTURE_BYTES / 3 * 4 + 1024)
+ MAX_ATTACHED_CHARS;
const MARK_SVG: &str = include_str!("../static/eclipse-mark.svg");
const FAVICON_ICO: &[u8] = include_bytes!("../static/eclipse.ico");
fn mark_svg() -> String {
use eclipse_core::palette as p;
let hex = |c: (u8, u8, u8)| format!("#{:02X}{:02X}{:02X}", c.0, c.1, c.2);
MARK_SVG
.replace("#FF8A2B", &hex(p::ACCENT))
.replace("#FFB45E", &hex(p::ACCENT))
.replace("#FFF7E8", &hex(p::WORDMARK_TOP))
.replace("#05060D", &hex(p::BG))
}
const LOGIN_HTML: &str = include_str!("login.html");
const SESSION_COOKIE: &str = "eclipse_session";
const MAX_LOGINS: usize = 32;
pub const MAX_CONCURRENT_CHATS: usize = 4;
const APPROVAL_TIMEOUT: Duration = Duration::from_secs(120);
struct Pending {
run: u64,
decide: oneshot::Sender<bool>,
}
#[derive(Default)]
struct Approvals {
pending: Mutex<HashMap<String, Pending>>,
next_run: AtomicU64,
}
impl Approvals {
fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, Pending>> {
self.pending.lock().unwrap_or_else(|e| e.into_inner())
}
fn resolve(&self, id: &str, approved: bool) -> bool {
match self.lock().remove(id) {
Some(p) => {
let _ = p.decide.send(approved);
true
}
None => false,
}
}
#[cfg(test)]
fn len(&self) -> usize {
self.lock().len()
}
}
struct RunScope {
state: Shared,
run: u64,
token: String,
}
impl Drop for RunScope {
fn drop(&mut self) {
self.state.approvals.lock().retain(|_, p| p.run != self.run);
self.state
.cancels
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&self.token);
}
}
struct DisconnectGuard {
cancel: Cancel,
}
impl Drop for DisconnectGuard {
fn drop(&mut self) {
self.cancel.cancel();
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Verdict {
Approved,
Denied,
TimedOut,
Cancelled,
}
impl Verdict {
fn as_str(self) -> &'static str {
match self {
Verdict::Approved => "approved",
Verdict::Denied => "denied",
Verdict::TimedOut => "timeout",
Verdict::Cancelled => "cancelled",
}
}
}
struct WebApprover {
state: Shared,
run: u64,
events: mpsc::UnboundedSender<Out>,
}
#[async_trait]
impl Approver for WebApprover {
async fn decide(
&self,
call: &eclipse_core::approvals::Pending,
) -> eclipse_core::approvals::Decision {
use eclipse_core::approvals::Decision;
let (tool, summary) = (call.tool.as_str(), call.summary.as_str());
let Ok(id) = eclipse_core::token::random_hex(16) else {
return Decision::Defer;
};
if self.state.yolo.on() {
self.state
.unasked
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
return Decision::Allow;
}
let (decide, answer) = oneshot::channel();
self.state.approvals.lock().insert(
id.clone(),
Pending {
run: self.run,
decide,
},
);
let request = Out::ApprovalRequest {
id: id.clone(),
tool: tool.to_string(),
summary: summary.to_string(),
timeout_secs: self.state.approval_timeout.as_secs(),
};
let verdict = if self.events.send(request).is_err() {
Verdict::Cancelled
} else {
tokio::select! {
r = answer => match r {
Ok(true) => Verdict::Approved,
Ok(false) => Verdict::Denied,
Err(_) => Verdict::Cancelled,
},
_ = tokio::time::sleep(self.state.approval_timeout) => Verdict::TimedOut,
_ = self.events.closed() => Verdict::Cancelled,
}
};
self.state.approvals.lock().remove(&id);
let _ = self.events.send(Out::ApprovalResolved { id, verdict });
match verdict {
Verdict::Approved => Decision::Allow,
Verdict::TimedOut => Decision::Deny("the approval request timed out".to_string()),
Verdict::Cancelled => Decision::Defer,
Verdict::Denied => Decision::Deny("declined in the panel".to_string()),
}
}
}
struct Session {
expires: Instant,
csrf: String,
}
struct Logins {
sessions: Mutex<HashMap<String, Session>>,
ttl: Duration,
}
impl Logins {
fn new(ttl: Duration) -> Self {
Self {
sessions: Mutex::default(),
ttl,
}
}
fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, Session>> {
self.sessions.lock().unwrap_or_else(|e| e.into_inner())
}
fn create(&self) -> Option<(String, String)> {
let id = eclipse_core::token::random_hex(32).ok()?;
let csrf = eclipse_core::token::random_hex(32).ok()?;
let now = Instant::now();
let mut map = self.lock();
map.retain(|_, s| s.expires > now);
while map.len() >= MAX_LOGINS {
let oldest = map
.iter()
.min_by_key(|(_, s)| s.expires)
.map(|(k, _)| k.clone())?;
map.remove(&oldest);
}
map.insert(
id.clone(),
Session {
expires: now + self.ttl,
csrf: csrf.clone(),
},
);
Some((id, csrf))
}
fn is_valid(&self, id: &str) -> bool {
let mut map = self.lock();
match map.get(id) {
Some(s) if s.expires > Instant::now() => true,
Some(_) => {
map.remove(id);
false
}
None => false,
}
}
fn csrf_for(&self, id: &str) -> Option<String> {
let now = Instant::now();
self.lock()
.get(id)
.filter(|s| s.expires > now)
.map(|s| s.csrf.clone())
}
fn csrf_ok(&self, id: &str, presented: &str) -> bool {
self.csrf_for(id)
.is_some_and(|want| eclipse_core::token::constant_time_eq(presented, &want))
}
fn remove(&self, id: &str) {
self.lock().remove(id);
}
}
pub struct AppState {
pub agent: Option<Arc<Agent>>,
pub store: eclipse_core::session::SessionStore,
pub model: String,
pub config_error: Option<String>,
chat_slots: Arc<Semaphore>,
approvals: Approvals,
cancels: Mutex<HashMap<String, Cancel>>,
approval_timeout: Duration,
pub yolo: eclipse_core::yolo::Yolo,
pub unasked: std::sync::atomic::AtomicUsize,
auth_token: String,
auth: eclipse_core::auth::Credentials,
login_ttl: Duration,
logins: Logins,
throttle: LoginThrottle,
pub config_path: Option<std::path::PathBuf>,
pub profile: Option<String>,
pub config_explicit: bool,
pub profiles_root: Option<std::path::PathBuf>,
pub cron_root: Option<std::path::PathBuf>,
pub config_writes: Arc<std::sync::Mutex<()>>,
pub model_probe: Arc<std::sync::Mutex<Option<(std::time::Instant, bool)>>>,
ticking: Mutex<std::collections::HashSet<String>>,
pub update: Option<eclipse_core::update::Watch>,
pub bots: crate::bots::Bots,
}
impl AppState {
pub fn new(
agent: Option<Arc<Agent>>,
store: eclipse_core::session::SessionStore,
model: String,
config_error: Option<String>,
auth_token: String,
login_ttl: Duration,
) -> Self {
Self {
agent,
store,
model,
config_error,
chat_slots: Arc::new(Semaphore::new(MAX_CONCURRENT_CHATS)),
approvals: Approvals::default(),
cancels: Mutex::default(),
approval_timeout: APPROVAL_TIMEOUT,
yolo: eclipse_core::yolo::Yolo::new(false),
unasked: std::sync::atomic::AtomicUsize::new(0),
auth_token,
auth: eclipse_core::auth::Credentials::Token,
login_ttl,
logins: Logins::new(login_ttl),
throttle: LoginThrottle::default(),
config_path: None,
profile: None,
config_explicit: false,
profiles_root: None,
cron_root: None,
config_writes: Arc::new(std::sync::Mutex::new(())),
model_probe: Arc::new(std::sync::Mutex::default()),
ticking: Mutex::default(),
update: None,
bots: crate::bots::Bots::empty(),
}
}
pub fn with_bots(
mut self,
cfg: &eclipse_core::config::Config,
env: eclipse_core::config::EnvFn,
) -> Self {
self.bots = crate::bots::Bots::build(cfg, env);
self
}
fn agent_for(&self, session: &str) -> std::result::Result<Option<Arc<Agent>>, String> {
let origin = self.store.origin(session).ok().flatten();
let Some(name) = origin.as_deref().and_then(|o| o.strip_prefix("bot:")) else {
return Ok(self.agent.clone());
};
match self.bots.agent(name) {
Some(Ok(agent)) => Ok(Some(Arc::clone(agent))),
Some(Err(why)) => Err(format!("bot `{name}` cannot run: {why}")),
None => Err(format!(
"this session belongs to bot `{name}`, which is no longer declared in `[bots]`"
)),
}
}
pub fn claim_tick(&self, session: &str) -> bool {
self.ticking
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(session.to_string())
}
pub fn release_tick(&self, session: &str) {
self.ticking
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(session);
}
pub fn try_chat_slot(&self) -> Option<tokio::sync::OwnedSemaphorePermit> {
self.chat_slots.clone().try_acquire_owned().ok()
}
pub fn token(&self) -> &str {
&self.auth_token
}
pub fn with_credentials(mut self, auth: eclipse_core::auth::Credentials) -> Self {
self.auth = auth;
self
}
pub fn auth_mode(&self) -> &'static str {
self.auth.mode()
}
pub fn with_cron_root(mut self, root: std::path::PathBuf) -> Self {
self.cron_root = Some(root);
self
}
pub fn with_config_path(
mut self,
path: Option<std::path::PathBuf>,
profile: Option<String>,
) -> Self {
self.config_path = path;
self.profile = profile;
self
}
pub fn with_config_targets(
mut self,
explicit: bool,
profiles_root: Option<std::path::PathBuf>,
) -> Self {
self.config_explicit = explicit;
self.profiles_root = profiles_root;
self
}
pub(crate) fn write_path(&self) -> Option<std::path::PathBuf> {
let explicit = if self.config_explicit {
self.config_path.as_deref()
} else {
None
};
eclipse_core::config::write_target(
self.profiles_root.as_deref(),
explicit,
self.config_path.as_deref(),
self.profile.as_deref(),
)
.or_else(|| self.config_path.clone())
}
pub(crate) fn reload_config(&self) -> Result<eclipse_core::config::Config, String> {
let path = self
.config_path
.as_ref()
.ok_or_else(|| "this dashboard was started without a config file".to_string())?;
eclipse_core::config::Config::load_with_profile(
Some(path),
self.profile.as_deref(),
&eclipse_core::config::process_env,
)
.map_err(|e| e.to_string())
}
pub fn current_model(&self) -> Option<String> {
self.agent
.as_ref()
.and_then(|a| a.model())
.or_else(|| (!self.model.is_empty()).then(|| self.model.clone()))
}
pub(crate) fn configured_model(&self) -> Option<String> {
(!self.model.is_empty()).then(|| self.model.clone())
}
#[cfg(test)]
fn with_login(self, id: &str) -> Self {
self.logins.lock().insert(
id.to_string(),
Session {
expires: Instant::now() + self.login_ttl,
csrf: TEST_CSRF.to_string(),
},
);
self
}
#[cfg(test)]
fn with_approval_timeout(mut self, timeout: Duration) -> Self {
self.approval_timeout = timeout;
self
}
}
pub type Shared = Arc<AppState>;
pub fn routes(state: Shared) -> Router<Shared> {
Router::new()
.route("/", get(index))
.route("/login", get(login_page).post(login))
.route("/logout", post(logout))
.route("/healthz", get(health))
.route("/api/update", get(update_state))
.route("/api/sessions", get(list_sessions))
.route("/api/bots", get(list_bots))
.route("/api/bots/:name/open", post(open_bot))
.route("/api/bots/:name/rename", post(rename_bot))
.route("/api/bots/:name/clear", post(clear_bot))
.route("/api/bots/:name/prompt", get(bot_prompt))
.route("/api/flares", get(list_flares))
.route("/api/flares/:run", get(read_flare))
.route("/api/flares/:run/cancel", post(cancel_flare))
.route("/api/sessions/:id", get(get_session))
.route("/api/sessions/:id/rename", post(rename_session))
.route("/api/sessions/:id/pin", post(pin_session))
.route("/api/sessions/:id/archive", post(archive_session))
.route("/api/sessions/:id/delete", post(delete_session))
.route("/api/search", get(search_sessions))
.route("/api/settings", get(list_settings).post(write_setting))
.route("/api/context", get(list_context).post(write_context))
.route("/api/models", get(list_models))
.route("/api/commands", get(list_commands))
.route("/api/model", post(choose_model))
.route("/api/reasoning", get(read_reasoning).post(choose_reasoning))
.route("/api/chat", post(chat))
.route("/api/approvals/:id", post(decide_approval))
.route("/api/runs/:id/cancel", post(cancel_run))
.route("/logo.svg", get(logo))
.route("/favicon.ico", get(favicon))
.route("/api/cron", get(list_cron).post(create_cron))
.route("/api/cron/:name", put(update_cron).delete(delete_cron))
.route("/api/cron/:name/enabled", post(set_cron_enabled))
.route("/api/cron/:name/run", post(run_cron_now))
.route("/api/cron/:name/logs", get(cron_logs))
.route("/api/problems", get(list_problems))
.route("/api/mcp", get(list_mcp).post(add_mcp))
.route("/api/mcp/:name", put(update_mcp).delete(remove_mcp))
.route("/api/mcp/:name/enabled", post(set_mcp_enabled))
.route("/api/mcp/:name/test", post(test_mcp))
.layer(middleware::from_fn(refuse_oversized))
.layer(DefaultBodyLimit::max(CHAT_BODY_LIMIT))
.layer(middleware::from_fn_with_state(state.clone(), require_login))
.layer(middleware::from_fn_with_state(
state.clone(),
guard_local_origin,
))
}
async fn refuse_oversized(req: Request, next: Next) -> Response {
if req.method() == Method::POST && req.uri().path() == "/api/chat" {
let declared = req
.headers()
.get(header::CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<usize>().ok());
if let Some(len) = declared {
if len > CHAT_BODY_LIMIT {
let mb = |n: usize| format!("{:.1} MB", n as f64 / (1024.0 * 1024.0));
let sentence = format!(
"that message is {} ({} over the {} limit for one turn) — attach fewer or \
smaller pictures, or write the text to a file and send its path",
mb(len),
mb(len - CHAT_BODY_LIMIT),
mb(CHAT_BODY_LIMIT),
);
return error(StatusCode::PAYLOAD_TOO_LARGE, &sentence).into_response();
}
}
}
next.run(req).await
}
pub fn router(state: Shared) -> Router {
routes(state.clone()).with_state(state)
}
fn cookie_value<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
headers
.get_all(header::COOKIE)
.iter()
.filter_map(|v| v.to_str().ok())
.flat_map(|v| v.split(';'))
.find_map(|pair| {
let (k, v) = pair.trim().split_once('=')?;
(k == name).then_some(v)
})
}
fn is_logged_in(st: &AppState, headers: &HeaderMap) -> bool {
cookie_value(headers, SESSION_COOKIE).is_some_and(|id| st.logins.is_valid(id))
}
fn session_cookie(value: &str, max_age_secs: u64) -> HeaderValue {
HeaderValue::from_str(&format!(
"{SESSION_COOKIE}={value}; HttpOnly; SameSite=Strict; Path=/; Max-Age={max_age_secs}"
))
.expect("cookie is ascii")
}
fn login_html(mode: &str, error: &str, hint: &str) -> Html<String> {
let intro = match mode {
"password" => {
"Sign in with the user from <code>ECLIPSE_WEB_USER</code> in <code>.env</code>, and \
the password <code>eclipse web passwd</code> set for it."
}
_ => "Enter the dashboard token from <code>auth_token</code> in your config file.",
};
Html(
LOGIN_HTML
.replace("{{PALETTE}}", &palette_css())
.replace("{{VERSION}}", env!("CARGO_PKG_VERSION"))
.replace("{{AUTH_MODE}}", mode)
.replace("{{AUTH_INTRO}}", intro)
.replace("{{ERROR}}", &escape_html(error))
.replace("{{HINT}}", &escape_html(hint)),
)
}
async fn require_login(State(st): State<Shared>, req: Request, next: Next) -> Response {
let path = req.uri().path();
if matches!(
path,
"/healthz" | "/login" | "/logout" | "/logo.svg" | "/favicon.ico"
) || is_logged_in(&st, req.headers())
{
return next.run(req).await;
}
if path == "/" {
return (StatusCode::UNAUTHORIZED, login_html(st.auth_mode(), "", "")).into_response();
}
error(StatusCode::UNAUTHORIZED, "login required").into_response()
}
async fn login_page(State(st): State<Shared>, headers: HeaderMap) -> Response {
if is_logged_in(&st, &headers) {
return redirect_home(None);
}
login_html(st.auth_mode(), "", frame_hint(&headers)).into_response()
}
fn frame_hint(headers: &HeaderMap) -> &'static str {
let dest = headers
.get("sec-fetch-dest")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
if dest == "iframe" || dest == "frame" || dest == "embed" || dest == "object" {
"This page is inside a frame. A frame that cannot name its origin cannot keep the session \
cookie either, so signing in will return you here — open the dashboard in its own browser \
tab instead."
} else {
""
}
}
pub struct LoginThrottle {
inner: Mutex<Attempts>,
free: u32,
base: Duration,
cap: Duration,
}
#[derive(Default)]
struct Attempts {
wrong: u32,
until: Option<Instant>,
}
impl Default for LoginThrottle {
fn default() -> Self {
Self::new(2, Duration::from_secs(1), Duration::from_secs(60))
}
}
impl LoginThrottle {
fn new(free: u32, base: Duration, cap: Duration) -> Self {
Self {
inner: Mutex::new(Attempts::default()),
free,
base,
cap,
}
}
fn wait_for(&self) -> Option<u64> {
let g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
let until = g.until?;
let now = Instant::now();
if now >= until {
return None;
}
Some((until - now).as_secs().max(1))
}
fn fail(&self) {
let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
g.wrong = g.wrong.saturating_add(1);
if g.wrong <= self.free {
return;
}
let step = g.wrong - self.free - 1;
let delay = self
.base
.saturating_mul(1u32.checked_shl(step.min(16)).unwrap_or(u32::MAX))
.min(self.cap);
g.until = Some(Instant::now() + delay);
}
fn reset(&self) {
let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
*g = Attempts::default();
}
}
fn redirect_home(cookie: Option<HeaderValue>) -> Response {
let mut resp = (StatusCode::SEE_OTHER, [(header::LOCATION, "/")]).into_response();
if let Some(c) = cookie {
resp.headers_mut().insert(header::SET_COOKIE, c);
}
resp
}
#[derive(Deserialize)]
struct LoginForm {
#[serde(default)]
username: String,
#[serde(default)]
password: String,
#[serde(default)]
token: String,
}
#[derive(Deserialize)]
struct Find {
q: Option<String>,
limit: Option<usize>,
}
async fn login(
State(st): State<Shared>,
headers: HeaderMap,
Form(form): Form<LoginForm>,
) -> Response {
if let Some(secs) = st.throttle.wait_for() {
let mut resp = (
StatusCode::TOO_MANY_REQUESTS,
login_html(
st.auth_mode(),
&format!("Too many wrong sign-ins. Try again in {secs} s."),
"Each wrong sign-in makes the next attempt wait longer. Nothing is locked for good: \
wait it out, or restart the dashboard to clear the counter.",
),
)
.into_response();
resp.headers_mut().insert(
header::RETRY_AFTER,
HeaderValue::from_str(&secs.to_string()).unwrap_or(HeaderValue::from_static("1")),
);
return resp;
}
let secret = if form.password.is_empty() {
form.token.as_str()
} else {
form.password.as_str()
};
let auth = st.auth.clone();
let (user, token, secret) = (
form.username.clone(),
st.auth_token.clone(),
secret.to_string(),
);
let passed = blocking(move || auth.check(&user, &secret, &token))
.await
.unwrap_or(false);
if !passed {
st.throttle.fail();
let hint = match frame_hint(&headers) {
"" if headers.contains_key(header::ORIGIN) => {
"Your browser sent Origin: null, so it will not say which page submitted this \
form (a sandboxed frame, an embedded pane, a file:// page, or an extension that \
rewrites headers). If the credential is right and you land back here, open the \
dashboard in its own tab."
}
other => other,
};
let wrong = match st.auth_mode() {
"password" => "Wrong user or password.",
_ => "Wrong token.",
};
return (
StatusCode::UNAUTHORIZED,
login_html(st.auth_mode(), wrong, hint),
)
.into_response();
}
st.throttle.reset();
match st.logins.create() {
Some((id, _csrf)) => redirect_home(Some(session_cookie(&id, st.login_ttl.as_secs()))),
None => error(StatusCode::INTERNAL_SERVER_ERROR, "cannot create a session").into_response(),
}
}
async fn logout(State(st): State<Shared>, headers: HeaderMap) -> Response {
if let Some(id) = cookie_value(&headers, SESSION_COOKIE) {
st.logins.remove(id);
}
let mut resp = (StatusCode::SEE_OTHER, [(header::LOCATION, "/")]).into_response();
resp.headers_mut()
.insert(header::SET_COOKIE, session_cookie("", 0));
resp
}
fn is_loopback_host(authority: &str) -> bool {
let host = if let Some(rest) = authority.strip_prefix('[') {
rest.split(']').next().unwrap_or("")
} else {
authority.split(':').next().unwrap_or("")
};
let host = host.trim_end_matches('.');
host == "127.0.0.1" || host == "::1" || host.eq_ignore_ascii_case("localhost")
}
const CSRF_HEADER: &str = "x-eclipse-csrf";
#[cfg(test)]
const TEST_CSRF: &str = "test-csrf-token";
fn header_text(req: &Request, name: &str) -> Option<String> {
req.headers()
.get(name)
.and_then(|v| v.to_str().ok())
.map(str::to_string)
}
fn authority_of(origin: &str) -> &str {
origin.split_once("://").map_or(origin, |(_, rest)| rest)
}
fn arrival_refusal(
logins: &Logins,
method: &Method,
path: &str,
host: Option<&str>,
origin: Option<&str>,
csrf: Option<&str>,
session: Option<&str>,
) -> Option<String> {
let Some(host) = host else {
return Some("the request carried no Host header".to_string());
};
if !is_loopback_host(host) {
return Some(format!(
"Host {host:?} is not 127.0.0.1, ::1 or localhost. Open the dashboard on this \
machine's own address, http://127.0.0.1:<port>; from another machine use an SSH \
tunnel, which keeps the header local. A reverse proxy or a LAN name in front of the \
dashboard is refused by design, because the token is the only thing guarding it"
));
}
if matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS) {
return None;
}
let stated = origin.map(authority_of);
let same_origin = match stated {
None => true, Some(authority) => authority.eq_ignore_ascii_case(host),
};
if same_origin {
return None;
}
let anonymous_but_harmless = path == "/login" && stated == Some("null");
if anonymous_but_harmless {
return None;
}
if let (Some(id), Some(presented)) = (session, csrf) {
if logins.csrf_ok(id, presented) {
return None;
}
}
let what = match stated {
Some("null") => {
"Origin \"null\" means the browser would not name the page that sent this request: a \
sandboxed frame, an embedded preview pane, a file:// page, or an extension that \
rewrites headers all look like this"
.to_string()
}
Some(authority) => format!(
"Origin {authority:?} is not this dashboard ({host:?}); that mismatch is what a \
cross-site request looks like, or a proxy that rewrote the Host header"
),
None => "the request says nothing about where it came from".to_string(),
};
Some(format!(
"{what}. This request also carried no valid {CSRF_HEADER} token for its session, and a page \
served from here always does. Open the dashboard in a normal browser tab at \
http://127.0.0.1:<port>: a frame that cannot name its origin cannot keep the session \
cookie either, so signing in from one would bounce straight back to the form"
))
}
pub async fn guard_local_origin(State(st): State<Shared>, req: Request, next: Next) -> Response {
let method = req.method().clone();
let path = req.uri().path().to_string();
let host = header_text(&req, "host");
let origin = header_text(&req, "origin");
let csrf = header_text(&req, CSRF_HEADER);
let session = cookie_value(req.headers(), SESSION_COOKIE).map(str::to_string);
let refusal = arrival_refusal(
&st.logins,
&method,
&path,
host.as_deref(),
origin.as_deref(),
csrf.as_deref(),
session.as_deref(),
);
let mut resp = match refusal {
None => next.run(req).await,
Some(why) => (StatusCode::FORBIDDEN, format!("forbidden: {why}")).into_response(),
};
let h = resp.headers_mut();
h.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static(
"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; \
img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'self'; \
frame-ancestors 'none'",
),
);
h.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
h.insert(
header::REFERRER_POLICY,
HeaderValue::from_static("no-referrer"),
);
resp
}
async fn blocking<T, F>(work: F) -> Option<T>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
tokio::task::spawn_blocking(work).await.ok()
}
fn escape_html(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
.replace('\'', "'")
}
fn palette_css() -> String {
use eclipse_core::palette as p;
let rgb = |c: (u8, u8, u8)| format!("rgb({}, {}, {})", c.0, c.1, c.2);
format!(
":root {{ color-scheme: dark; \
--bg:{}; --panel:{}; --line:{}; --hover:{}; \
--fg:{}; --dim:{}; --faint:{}; --rule:{}; \
--accent:{}; --user:{}; --ok:{}; --warn:{}; --bad:{}; --ink:{}; }}",
rgb(p::BG),
rgb(p::PANEL),
rgb(p::LINE),
rgb(p::HOVER),
rgb(p::FG),
rgb(p::MUTED),
rgb(p::FAINT),
rgb(p::RULE),
rgb(p::ACCENT),
rgb(p::USER),
rgb(p::OK),
rgb(p::WARN),
rgb(p::BAD),
rgb(p::INK),
)
}
async fn index(State(st): State<Shared>, headers: HeaderMap) -> Html<String> {
let csrf = cookie_value(&headers, SESSION_COOKIE)
.and_then(|id| st.logins.csrf_for(id))
.unwrap_or_default();
let store = st.store.clone();
let sessions = blocking(move || store.list().unwrap_or_default())
.await
.unwrap_or_default()
.into_iter()
.map(|s| {
let cost = s
.cost
.as_ref()
.and_then(|c| serde_json::to_string(c).ok())
.map(|json| escape_html(&json))
.unwrap_or_default();
format!(
"<li class=\"session\" data-id=\"{}\" data-updated=\"{}\" data-pinned=\"{}\" data-archived=\"{}\" data-cost=\"{}\"><div class=\"name\">{}{}</div></li>",
escape_html(&s.id),
s.updated_ms,
if s.pinned { "1" } else { "0" },
if s.archived { "1" } else { "0" },
cost,
if s.pinned { "\u{2605} " } else { "" },
escape_html(&s.tagged_label())
)
})
.collect::<String>();
let status = st.config_error.as_deref().unwrap_or("");
let judged = st
.reload_config()
.map(|c| c.cli.approval == eclipse_core::config::Approval::Smart)
.unwrap_or(false);
let model = st.current_model();
let model = model.as_deref().unwrap_or("(not configured)");
let (effort, effort_detail, effort_session) = match st.agent.as_deref() {
Some(agent) => {
let report = agent.reasoning_report();
let sentence = report.sentence();
(report.label, sentence, report.session)
}
None => (
eclipse_core::reasoning::NOT_SENT.to_string(),
"no provider is configured: there is no effort to be in force".to_string(),
false,
),
};
let probe = st.store.clone();
let has_flares = matches!(
blocking(move || probe.flare_runs(1)).await,
Some(Ok(runs)) if !runs.is_empty()
);
Html(
INDEX_HTML
.replace("{{PALETTE}}", &palette_css())
.replace("{{CSRF}}", &escape_html(&csrf))
.replace("{{MODEL}}", &escape_html(model))
.replace("{{EFFORT}}", &escape_html(&effort))
.replace("{{EFFORT_DETAIL}}", &escape_html(&effort_detail))
.replace(
"{{EFFORT_CLASS}}",
if effort_session { "session" } else { "" },
)
.replace("{{YOLO_ATTR}}", if st.yolo.on() { "" } else { "hidden" })
.replace(
"{{YOLO_DETAIL}}",
&escape_html(&eclipse_core::yolo::announce(st.yolo.on())),
)
.replace("{{JUDGE_ATTR}}", if judged { "" } else { "hidden" })
.replace("{{VERSION}}", env!("CARGO_PKG_VERSION"))
.replace(
"{{PASTE_LIMIT}}",
&eclipse_core::paste::PASTE_INLINE_LIMIT.to_string(),
)
.replace("{{STATUS}}", &escape_html(status))
.replace("{{SESSIONS}}", &sessions)
.replace(
"{{BOTS_BUTTON}}",
&if st.bots.is_empty() {
String::new()
} else {
format!(
" <button id=\"bots\" type=\"button\" aria-expanded=\"false\" \
title=\"the bots this config declared — open one and talk to it in its own conversation\">bots ({})</button>",
st.bots.declared().count()
)
},
)
.replace(
"{{BOTS_PANE}}",
if st.bots.is_empty() { "" } else { BOTS_PANE },
)
.replace(
"{{FLARES_BUTTON}}",
&if has_flares {
" <button id=\"flares\" type=\"button\" aria-expanded=\"false\" \
title=\"the flare runs this install has started — one task split across N read-only agents\">flares</button>"
.to_string()
} else {
String::new()
},
)
.replace(
"{{FLARES_PANE}}",
if has_flares { FLARES_PANE } else { "" },
),
)
}
async fn logo() -> impl IntoResponse {
(
[
("content-type", "image/svg+xml; charset=utf-8"),
("cache-control", "public, max-age=3600"),
],
mark_svg(),
)
}
async fn favicon() -> impl IntoResponse {
(
[
("content-type", "image/x-icon"),
("cache-control", "public, max-age=3600"),
],
FAVICON_ICO,
)
}
async fn health(
State(st): State<Shared>,
headers: axum::http::HeaderMap,
) -> Json<serde_json::Value> {
if !is_logged_in(&st, &headers) {
return Json(json!({"status": "ok"}));
}
let model_probe = (*st.model_probe.lock().unwrap_or_else(|e| e.into_inner()))
.map(|(when, ok)| json!({"reachable": ok, "at_secs_ago": when.elapsed().as_secs()}));
let cron_root = st.cron_root.clone();
let cron = match blocking(move || {
cron_root.and_then(|root| eclipse_core::cron::load_state(&root).ok())
})
.await
.flatten()
{
Some(state) => {
let failed: Vec<&str> = state
.jobs
.iter()
.filter(|(_, j)| j.last_outcome.as_deref() == Some("failed"))
.map(|(name, _)| name.as_str())
.collect();
let last_tick = state.jobs.values().filter_map(|j| j.last_started_ms).max();
Some(json!({
"failed_jobs": failed,
"last_tick_ms": last_tick,
}))
}
None => None,
};
Json(json!({
"status": "ok",
"version": env!("CARGO_PKG_VERSION"),
"configured": st.agent.is_some(),
"model_reachable": model_probe,
"cron": cron,
}))
}
async fn update_state(State(st): State<Shared>) -> Json<eclipse_core::update::Snapshot> {
let Some(watch) = st.update.clone() else {
return Json(eclipse_core::update::Snapshot::default());
};
let now = eclipse_core::session::now_ms() / 1000;
match blocking(move || watch.snapshot(now)).await {
Some(snapshot) => Json(snapshot),
None => Json(eclipse_core::update::Snapshot::default()),
}
}
async fn list_sessions(State(st): State<Shared>, Query(list): Query<ListQuery>) -> Response {
let store = st.store.clone();
let all = list.archived.unwrap_or(0) != 0;
let Some(listed) = blocking(move || {
if all {
store.list_with_archived()
} else {
store.list()
}
})
.await
else {
return error(
StatusCode::INTERNAL_SERVER_ERROR,
"the store did not answer",
)
.into_response();
};
match listed {
Ok(list) => Json(
list.into_iter()
.map(|s| {
json!({
"id": s.id, "messages": s.messages, "updated_ms": s.updated_ms,
"preview": s.preview, "title": s.title, "pinned": s.pinned,
"archived": s.archived,
"cost": s.cost,
"subagent": s.subagent().map(|o| json!({"parent": o.parent, "route": o.route})),
})
})
.collect::<Vec<_>>(),
)
.into_response(),
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
#[derive(Deserialize)]
struct ListQuery {
archived: Option<u8>,
}
async fn list_bots(State(st): State<Shared>) -> Response {
let store = st.store.clone();
let conversations = match blocking(move || store.list_bots()).await {
Some(Ok(list)) => list,
Some(Err(e)) => {
return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
}
None => {
return error(
StatusCode::INTERNAL_SERVER_ERROR,
"the store did not answer",
)
.into_response()
}
};
let rows: Vec<serde_json::Value> = st
.bots
.declared()
.map(|(name, bot)| {
let live = conversations.iter().find(|c| c.name == name);
let problem = match st.bots.agent(name) {
Some(Err(why)) => serde_json::Value::String(why.clone()),
_ => serde_json::Value::Null,
};
json!({
"name": name,
"lane": bot.adapter.clone().unwrap_or_else(|| "web".to_string()),
"sessions": live.map(|c| c.sessions).unwrap_or(0),
"messages": live.map(|c| c.messages).unwrap_or(0),
"last_session": live.map(|c| c.last_session.clone()),
"last_activity_ms": live.map(|c| c.last_activity_ms).unwrap_or(0),
"archived": live.map(|c| c.archived).unwrap_or(false),
"problem": problem,
})
})
.collect();
Json(rows).into_response()
}
async fn open_bot(State(st): State<Shared>, Path(name): Path<String>) -> Response {
if !st.bots.declares(&name) {
return error(
StatusCode::NOT_FOUND,
format!("no bot `{name}` is declared"),
)
.into_response();
}
if let Some(Err(why)) = st.bots.agent(&name) {
return error(
StatusCode::SERVICE_UNAVAILABLE,
format!("bot `{name}` cannot run: {why}"),
)
.into_response();
}
let store = st.store.clone();
let wanted = name.clone();
let opened = blocking(move || store.bot_session(&wanted)).await;
match opened {
Some(Ok(session_id)) => {
Json(json!({ "name": name, "session_id": session_id })).into_response()
}
Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
None => error(
StatusCode::INTERNAL_SERVER_ERROR,
"the store did not answer",
)
.into_response(),
}
}
async fn rename_bot(
State(st): State<Shared>,
Path(name): Path<String>,
Json(body): Json<RenameBody>,
) -> Response {
if !st.bots.declares(&name) {
return error(
StatusCode::NOT_FOUND,
format!("no bot `{name}` is declared"),
)
.into_response();
}
let title = body.title.trim().to_string();
if title.is_empty() {
return error(StatusCode::BAD_REQUEST, "title is empty").into_response();
}
let store = st.store.clone();
let wanted = name.clone();
let named = title.clone();
let renamed = blocking(move || {
let id = store.bot_session(&wanted)?;
store.set_title(&id, &named, eclipse_core::session::TitleSource::User)
})
.await;
match renamed {
Some(Ok(_)) => Json(json!({ "name": name, "title": title })).into_response(),
Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
None => error(
StatusCode::INTERNAL_SERVER_ERROR,
"the store did not answer",
)
.into_response(),
}
}
async fn clear_bot(State(st): State<Shared>, Path(name): Path<String>) -> Response {
if !st.bots.declares(&name) {
return error(
StatusCode::NOT_FOUND,
format!("no bot `{name}` is declared"),
)
.into_response();
}
let store = st.store.clone();
let wanted = name.clone();
let cleared = blocking(move || {
let mut filed = 0usize;
for id in store.bot_sessions(&wanted)? {
store.set_archived(&id, true)?;
filed += 1;
}
let fresh = store.bot_session(&wanted)?;
Ok::<_, eclipse_core::Error>((filed, fresh))
})
.await;
match cleared {
Some(Ok((filed, session_id))) => {
Json(json!({ "name": name, "archived": filed, "session_id": session_id }))
.into_response()
}
Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
None => error(
StatusCode::INTERNAL_SERVER_ERROR,
"the store did not answer",
)
.into_response(),
}
}
async fn bot_prompt(State(st): State<Shared>, Path(name): Path<String>) -> Response {
let Some((bot, ..)) = st
.bots
.declared()
.find(|(declared, _)| *declared == name)
.map(|(n, b)| (b.clone(), n))
else {
return error(
StatusCode::NOT_FOUND,
format!("no bot `{name}` is declared"),
)
.into_response();
};
let env: eclipse_core::config::EnvFn = &eclipse_core::config::process_env;
let read = bot
.instructions
.as_deref()
.filter(|p| !p.trim().is_empty())
.map(|declared| {
let Some(path) = st
.reload_config()
.ok()
.and_then(|cfg| cfg.bot_file(env, declared))
else {
return (
None,
format!("cannot resolve `instructions = {declared:?}`"),
);
};
match std::fs::read_to_string(&path) {
Ok(text) => (Some((path, text)), String::new()),
Err(e) => (None, format!("cannot read {}: {e}", path.display())),
}
});
let (instructions, why) = match read {
Some((Some((path, text)), _)) => (
json!({ "path": path.display().to_string(), "body": text }),
String::new(),
),
Some((None, why)) => (serde_json::Value::Null, why),
None => (serde_json::Value::Null, String::new()),
};
let memory = st
.reload_config()
.ok()
.and_then(|cfg| cfg.bot_memory(env, &name, &bot))
.map(|p| p.display().to_string());
Json(json!({
"name": name,
"instructions": instructions,
"skills": bot.skills,
"memory": memory,
"adapter": bot.adapter,
"problem": match st.bots.agent(&name) { Some(Err(why)) => json!(why), _ => serde_json::Value::Null },
"why": why,
}))
.into_response()
}
fn flare_json(run: &FlareRunRow) -> serde_json::Value {
json!({
"id": run.id,
"task": run.task,
"state": run.state,
"routes": run.routes,
"jobs": run.jobs,
"parent": run.parent,
"started_ms": run.started_ms,
"finished_ms": run.finished_ms,
"prompt_tokens": run.prompt_tokens,
"completion_tokens": run.completion_tokens,
"iterations": run.iterations,
"running": !run.finished(),
})
}
fn flare_job_json(job: &FlareJobRow) -> serde_json::Value {
json!({
"n": job.n,
"route": job.route,
"session_id": job.session_id,
"state": job.state,
"prompt_tokens": job.prompt_tokens,
"completion_tokens": job.completion_tokens,
"iterations": job.iterations,
"why": job.why,
})
}
#[derive(Deserialize)]
struct FlaresQuery {
limit: Option<usize>,
}
async fn list_flares(State(st): State<Shared>, Query(q): Query<FlaresQuery>) -> Response {
let limit = q.limit.unwrap_or(50);
let store = st.store.clone();
match blocking(move || store.flare_runs(limit)).await {
Some(Ok(runs)) => Json(
runs.iter()
.map(flare_json)
.collect::<Vec<serde_json::Value>>(),
)
.into_response(),
Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
None => error(
StatusCode::INTERNAL_SERVER_ERROR,
"the store did not answer",
)
.into_response(),
}
}
async fn read_flare(State(st): State<Shared>, Path(run): Path<String>) -> Response {
let store = st.store.clone();
let wanted = run.clone();
match blocking(move || store.flare_run(&wanted)).await {
Some(Ok(Some((row, jobs)))) => {
let jobs: Vec<serde_json::Value> = jobs.iter().map(flare_job_json).collect();
Json(json!({ "run": flare_json(&row), "jobs": jobs })).into_response()
}
Some(Ok(None)) => {
error(StatusCode::NOT_FOUND, format!("no flare run `{run}`")).into_response()
}
Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
None => error(
StatusCode::INTERNAL_SERVER_ERROR,
"the store did not answer",
)
.into_response(),
}
}
async fn cancel_flare(State(st): State<Shared>, Path(run): Path<String>) -> Response {
let store = st.store.clone();
let wanted = run.clone();
match blocking(move || store.cancel_flare_run(&wanted)).await {
Some(Ok(true)) => Json(json!({
"run": run,
"cancel_requested": true,
"note": "cancel requested: queued flares are dropped, running ones stop at their next boundary",
}))
.into_response(),
Some(Ok(false)) => {
error(StatusCode::NOT_FOUND, format!("no flare run `{run}`")).into_response()
}
Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
None => error(
StatusCode::INTERNAL_SERVER_ERROR,
"the store did not answer",
)
.into_response(),
}
}
async fn search_sessions(State(st): State<Shared>, Query(find): Query<Find>) -> Response {
let term = find.q.unwrap_or_default();
let term = term.trim();
if term.is_empty() {
return Json(Vec::<serde_json::Value>::new()).into_response();
}
let limit = find.limit.unwrap_or(20).clamp(1, 100);
let store = st.store.clone();
let term = term.to_string();
let Some(found) = blocking(move || {
let hits = store.search(&term, limit);
let named: HashMap<String, (Option<String>, u64)> = store
.list()
.map(|list| {
list.into_iter()
.map(|s| (s.id, (s.title, s.updated_ms)))
.collect()
})
.unwrap_or_default();
(hits, named)
})
.await
else {
return error(
StatusCode::INTERNAL_SERVER_ERROR,
"the store did not answer",
)
.into_response();
};
let (hits, named) = found;
let hits = match hits {
Ok(hits) => hits,
Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
};
Json(
hits.into_iter()
.map(|h| {
let (title, updated_ms) = named.get(&h.session_id).cloned().unwrap_or((None, 0));
json!({
"session_id": h.session_id,
"seq": h.seq,
"at_ms": h.at_ms,
"role": h.role,
"snippet": h.snippet,
"title": title,
"updated_ms": updated_ms,
})
})
.collect::<Vec<_>>(),
)
.into_response()
}
async fn list_commands() -> Json<serde_json::Value> {
use eclipse_core::commands::{Args, Command, Front, COMMANDS};
let row = |c: &Command| {
json!({
"name": c.name,
"aliases": c.aliases,
"label": c.label(),
"args": match c.args {
Args::Shown(args) => json!(args),
Args::None | Args::Unshown => serde_json::Value::Null,
},
"takes_arg": c.args.takes(),
"help": c.help,
})
};
Json(json!({
"commands": COMMANDS
.iter()
.filter(|c| c.serves(Front::Web))
.map(row)
.collect::<Vec<_>>(),
}))
}
async fn list_models(State(st): State<Shared>) -> Response {
let Some(agent) = st.agent.clone() else {
return error(StatusCode::SERVICE_UNAVAILABLE, unconfigured(&st)).into_response();
};
match agent.list_models().await {
Ok(models) => Json(json!({
"model": st.current_model(),
"configured": st.configured_model(),
"models": models,
}))
.into_response(),
Err(e) => error(StatusCode::BAD_GATEWAY, e.to_string()).into_response(),
}
}
#[derive(Deserialize)]
struct ModelChoice {
#[serde(default, deserialize_with = "some_option")]
model: Option<Option<String>>,
}
fn some_option<'de, D>(d: D) -> Result<Option<Option<String>>, D::Error>
where
D: serde::Deserializer<'de>,
{
Option::<String>::deserialize(d).map(Some)
}
async fn list_settings(State(st): State<Shared>) -> Response {
match st.reload_config() {
Ok(cfg) => Json(json!({
"profile": cfg.profile_name(),
"settings": cfg.settings().iter().map(setting_json).collect::<Vec<_>>(),
}))
.into_response(),
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
}
}
fn setting_json(s: &eclipse_core::config::Setting) -> serde_json::Value {
json!({
"key": s.path(),
"section": s.section,
"value": if s.secret { serde_json::Value::Null } else { json!(s.rendered()) },
"default": s.default.as_ref().map(std::string::ToString::to_string),
"is_default": s.is_default(),
"secret": s.secret,
"set": s.value.is_some(),
"applies": s.applies.as_str(),
"kind": s.kind.as_str(),
"about": s.about,
"choices": s.choices,
})
}
#[derive(Deserialize)]
struct SettingWrite {
key: String,
#[serde(default, deserialize_with = "some_option")]
value: Option<Option<String>>,
}
async fn write_setting(State(st): State<Shared>, Json(body): Json<SettingWrite>) -> Response {
let Some(value) = body.value else {
return error(
StatusCode::BAD_REQUEST,
"name a value: {\"value\": \"text\"} to set it, or {\"value\": null} to go back to the \
default",
)
.into_response();
};
match apply_setting(&st, &body.key, value.as_deref()).await {
Ok(setting) => Json(setting).into_response(),
Err((code, why)) => error(code, why).into_response(),
}
}
pub(crate) async fn apply_setting(
st: &AppState,
key: &str,
value: Option<&str>,
) -> Result<serde_json::Value, (StatusCode, String)> {
let Some(path) = st.write_path() else {
return Err((
StatusCode::SERVICE_UNAVAILABLE,
"this dashboard was started without a config file".to_string(),
));
};
let base = st.config_path.clone();
let (key, value) = (key.to_string(), value.map(str::to_string));
let edited_key = key.clone();
let profile = st.profile.clone();
let writes = st.config_writes.clone();
let written = blocking(
move || -> Result<eclipse_core::config::Config, (StatusCode, String)> {
let _one_writer = writes
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("{}: {e}", path.display()),
))
}
};
let edited = match &value {
Some(raw) => {
let typed = eclipse_core::config::parse_value(raw);
eclipse_core::config::set_in_text(&text, &edited_key, &typed)
}
None => eclipse_core::config::unset_in_text(&text, &edited_key),
}
.map_err(|why| (StatusCode::BAD_REQUEST, why))?;
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("{}: {e}", dir.display()),
)
})?;
}
eclipse_core::config::save_config_text(&path, &edited)
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
eclipse_core::config::Config::load_with_profile(
base.as_deref(),
profile.as_deref(),
&eclipse_core::config::process_env,
)
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
},
)
.await;
let Some(written) = written else {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
"the write did not finish".to_string(),
));
};
match written {
Ok(cfg) => match cfg.setting(&key) {
Some(setting) => Ok(setting_json(&setting)),
None => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("`{key}` is not in the file it was just written to"),
)),
},
Err((code, why)) => Err((code, why)),
}
}
fn context_json(
e: &eclipse_core::context_files::Editable,
home: Option<&std::path::Path>,
) -> serde_json::Value {
json!({
"name": e.which.id(),
"file": e.file,
"path": short_path(&e.path, home),
"exists": e.exists,
"chars": e.chars,
"kept": e.kept,
"truncated": e.truncated(),
"max_chars": e.max_chars,
"own_budget": e.own_budget,
"total": e.total,
"total_budget": e.total_budget,
"position": e.position,
"others": e.others,
"kind": match e.which {
eclipse_core::context_files::Which::Memory => "memory",
_ => "prose",
},
"text": e.text,
})
}
fn short_path(path: &std::path::Path, home: Option<&std::path::Path>) -> String {
let shown = path.to_string_lossy().into_owned();
match home {
Some(home) => {
let home = home.to_string_lossy();
match shown.strip_prefix(home.as_ref()) {
Some(rest) => format!("~{rest}"),
None => shown,
}
}
None => shown,
}
}
async fn list_context(State(st): State<Shared>) -> Response {
let cfg = match st.reload_config() {
Ok(cfg) => cfg,
Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
};
let home = cfg.home(&eclipse_core::config::process_env);
let files = blocking(move || {
eclipse_core::context_files::editable(&cfg, &eclipse_core::config::process_env)
})
.await;
match files {
Some(files) => Json(json!({
"profile": st.profile.clone(),
"files": files.iter().map(|e| context_json(e, home.as_deref())).collect::<Vec<_>>(),
}))
.into_response(),
None => error(
StatusCode::INTERNAL_SERVER_ERROR,
"the context files took too long to read",
)
.into_response(),
}
}
#[derive(Deserialize)]
struct ContextWrite {
name: String,
text: String,
}
async fn write_context(State(st): State<Shared>, Json(body): Json<ContextWrite>) -> Response {
let Some(which) = eclipse_core::context_files::Which::from_id(&body.name) else {
return error(
StatusCode::BAD_REQUEST,
format!(
"name one of the three context files: \"agent\", \"user\" or \"memory\" — not {:?}",
body.name
),
)
.into_response();
};
let cfg = match st.reload_config() {
Ok(cfg) => cfg,
Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
};
let home = cfg.home(&eclipse_core::config::process_env);
let text = body.text;
let written = blocking(move || {
eclipse_core::context_files::write_file(
&cfg,
&eclipse_core::config::process_env,
which,
&text,
)
})
.await;
match written {
Some(Ok(row)) => Json(json!({
"file": context_json(&row, home.as_deref()),
"applies": "the next run uses it",
}))
.into_response(),
Some(Err(e)) => error(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
None => error(
StatusCode::INTERNAL_SERVER_ERROR,
"the write did not finish",
)
.into_response(),
}
}
async fn choose_model(State(st): State<Shared>, Json(choice): Json<ModelChoice>) -> Response {
let Some(choice) = choice.model else {
return error(
StatusCode::BAD_REQUEST,
"name a model: {\"model\": \"name\"}, or {\"model\": null} to go back to the configured one",
)
.into_response();
};
match apply_model(&st, choice).await {
Ok(answer) => Json(answer).into_response(),
Err((code, why)) => error(code, why).into_response(),
}
}
pub(crate) async fn apply_model(
st: &AppState,
picked: Option<String>,
) -> Result<serde_json::Value, (StatusCode, String)> {
let Some(agent) = st.agent.clone() else {
return Err((StatusCode::SERVICE_UNAVAILABLE, unconfigured(st)));
};
let picked = match picked {
Some(name) => {
let name = name.trim().to_string();
if name.is_empty() {
return Err((StatusCode::BAD_REQUEST, "model is empty".to_string()));
}
Some(name)
}
None => None,
};
match agent.set_model(picked) {
Ok(()) => {
let probe = agent.clone();
tokio::spawn(async move {
if let Some(window) = probe
.advertised_context_window(Duration::from_secs(2))
.await
{
probe.set_advertised_window(window);
}
});
Ok(json!({
"model": st.current_model(),
"configured": st.configured_model(),
}))
}
Err(e) => Err((StatusCode::BAD_REQUEST, e.to_string())),
}
}
pub(crate) fn unconfigured(st: &AppState) -> String {
st.config_error
.clone()
.unwrap_or_else(|| "agent is not configured".into())
}
fn reasoning_json(agent: &Agent) -> serde_json::Value {
use eclipse_core::provider::Reasoning;
let report = agent.reasoning_report();
let control = agent.reasoning_control();
let (levels, described, note): (Vec<String>, serde_json::Value, String) = match &control {
Some(Reasoning::Policy(policy)) => {
let levels = policy.vocabulary();
let said: serde_json::Map<String, serde_json::Value> = levels
.iter()
.map(|level| (level.clone(), json!(policy.describe(Some(level)))))
.collect();
(levels, serde_json::Value::Object(said), String::new())
}
Some(Reasoning::Off) => (
Vec::new(),
json!({}),
"no reasoning control on this model".to_string(),
),
Some(Reasoning::Undeclared) => (
Vec::new(),
json!({}),
"this backend declares no reasoning control, so a level goes out verbatim and only \
`/reasoning` in the terminal can set one"
.to_string(),
),
None => (
Vec::new(),
json!({}),
"this dashboard has no provider configuration to describe".to_string(),
),
};
let (off_word, off_why) = match &control {
Some(Reasoning::Policy(policy)) if policy.has_off() => (json!("none"), String::new()),
Some(Reasoning::Policy(policy)) => (
json!(null),
format!(
"this route has no off switch: nothing at {} turns thinking off on it",
policy.field
),
),
Some(Reasoning::Off) => (
json!(null),
"this model has no reasoning field, so there is nothing to switch off".to_string(),
),
Some(Reasoning::Undeclared) => (
json!(null),
"this backend declares no reasoning control, so a level goes out verbatim: \
`/reasoning none` in the terminal is the only off"
.to_string(),
),
None => (
json!(null),
"this dashboard has no provider configuration, so there is nothing to switch"
.to_string(),
),
};
json!({
"off_word": off_word,
"off_why": off_why,
"effort": report.label,
"effort_detail": report.sentence(),
"effort_session": report.session,
"effort_default": report.by_default,
"in_force": report.in_force,
"resolved": report.resolved,
"configured": agent.reasoning().configured(),
"levels": levels,
"described": described,
"note": note,
})
}
async fn read_reasoning(State(st): State<Shared>) -> Response {
let Some(agent) = st.agent.clone() else {
return error(StatusCode::SERVICE_UNAVAILABLE, unconfigured(&st)).into_response();
};
Json(reasoning_json(&agent)).into_response()
}
#[derive(Deserialize)]
struct ReasoningChoice {
#[serde(default, deserialize_with = "some_option")]
level: Option<Option<String>>,
}
async fn choose_reasoning(
State(st): State<Shared>,
Json(choice): Json<ReasoningChoice>,
) -> Response {
let Some(level) = choice.level else {
return error(
StatusCode::BAD_REQUEST,
"name a level: {\"level\": \"high\"}, or {\"level\": null} to go back to the file",
)
.into_response();
};
match apply_reasoning(&st, level).await {
Ok(answer) => Json(answer).into_response(),
Err((code, why)) => error(code, why).into_response(),
}
}
pub(crate) async fn apply_reasoning(
st: &AppState,
level: Option<String>,
) -> Result<serde_json::Value, (StatusCode, String)> {
use eclipse_core::provider::Reasoning;
use eclipse_core::reasoning::Wire;
let Some(agent) = st.agent.clone() else {
return Err((StatusCode::SERVICE_UNAVAILABLE, unconfigured(st)));
};
match level {
Some(level) => {
let level = level.trim().to_lowercase();
if level.is_empty() {
return Err((StatusCode::BAD_REQUEST, "level is empty".to_string()));
}
let omit = eclipse_core::reasoning::is_omit(&level);
match agent.reasoning_control() {
Some(Reasoning::Policy(policy)) => {
if !omit && matches!(policy.resolve(Some(&level)), Wire::Omit(_)) {
return Err((
StatusCode::BAD_REQUEST,
format!(
"{} — this route takes: {}",
policy.describe(Some(&level)),
policy.vocabulary().join(" · ")
),
));
}
}
Some(Reasoning::Off) => {
if !omit {
return Err((
StatusCode::BAD_REQUEST,
"no reasoning control on this model: it has no field to carry a level"
.to_string(),
));
}
}
Some(Reasoning::Undeclared) => {
if !omit && !eclipse_core::reasoning::is_level(&level) {
return Err((
StatusCode::BAD_REQUEST,
format!(
"{level:?} is not a level; the ladder is {}",
eclipse_core::reasoning::LADDER.join(" · ")
),
));
}
}
None => {
return Err((
StatusCode::SERVICE_UNAVAILABLE,
"this dashboard has no provider configuration, so there is no dial to turn"
.to_string(),
));
}
}
agent.reasoning().set_session(Some(level));
}
None => agent.reasoning().clear_session(),
}
Ok(reasoning_json(&agent))
}
async fn get_session(State(st): State<Shared>, Path(id): Path<String>) -> Response {
if eclipse_core::session::validate_id(&id).is_err() {
return error(StatusCode::BAD_REQUEST, "invalid session id").into_response();
}
let store = st.store.clone();
let Some(loaded) = blocking(move || {
if !store.exists(&id) {
return Err(None::<eclipse_core::Error>);
}
let msgs = store.load(&id).map_err(Some)?;
let marks = store.tool_outcomes(&id).map_err(Some)?;
Ok((msgs, marks))
})
.await
else {
return error(
StatusCode::INTERNAL_SERVER_ERROR,
"the store did not answer",
)
.into_response();
};
match loaded {
Ok((msgs, marks)) => {
let mut results: std::collections::HashMap<&str, (&str, Option<bool>)> =
std::collections::HashMap::new();
for m in &msgs {
if let (Some(id), Some(text)) = (m.tool_call_id.as_deref(), m.content.as_deref()) {
let mark = marks.get(id).copied();
results.entry(id).or_insert((text, mark));
}
}
let shown: Vec<serde_json::Value> = msgs
.iter()
.filter_map(|m| {
let mut v = serde_json::to_value(m).ok()?;
let calls: Vec<serde_json::Value> = m
.tool_calls
.iter()
.map(|c| {
let state = results
.get(c.id.as_str())
.map(|(text, mark)| calls::outcome(text, *mark))
.unwrap_or(calls::Outcome::Running);
serde_json::json!({
"summary": calls::statement(&c.function.name, &c.function.arguments),
"state": state.as_str(),
})
})
.collect();
if !calls.is_empty() {
v["calls"] = serde_json::Value::Array(calls);
}
Some(v)
})
.collect();
Json(shown).into_response()
}
Err(None) => error(StatusCode::NOT_FOUND, "no such session").into_response(),
Err(Some(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
type ApiError = (StatusCode, Json<serde_json::Value>);
fn session_id_ok(id: &str, st: &AppState) -> Option<ApiError> {
if eclipse_core::session::validate_id(id).is_err() {
return Some(error(StatusCode::BAD_REQUEST, "invalid session id"));
}
if !st.store.exists(id) {
return Some(error(StatusCode::NOT_FOUND, "no such session"));
}
None
}
#[derive(Deserialize)]
struct RenameBody {
title: String,
}
async fn rename_session(
State(st): State<Shared>,
Path(id): Path<String>,
Json(body): Json<RenameBody>,
) -> Response {
if let Some(refusal) = session_id_ok(&id, &st) {
return refusal.into_response();
}
match st.store.rename(&id, &body.title) {
Ok(()) => Json(json!({ "id": id, "title": body.title.trim() })).into_response(),
Err(e) => error(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
}
}
#[derive(Deserialize)]
struct PinBody {
pinned: bool,
}
async fn pin_session(
State(st): State<Shared>,
Path(id): Path<String>,
Json(body): Json<PinBody>,
) -> Response {
if let Some(refusal) = session_id_ok(&id, &st) {
return refusal.into_response();
}
match st.store.set_pinned(&id, body.pinned) {
Ok(()) => Json(json!({ "id": id, "pinned": body.pinned })).into_response(),
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
#[derive(Deserialize)]
struct ArchiveBody {
archived: bool,
}
async fn archive_session(
State(st): State<Shared>,
Path(id): Path<String>,
Json(body): Json<ArchiveBody>,
) -> Response {
if let Some(refusal) = session_id_ok(&id, &st) {
return refusal.into_response();
}
match st.store.set_archived(&id, body.archived) {
Ok(()) => Json(json!({ "id": id, "archived": body.archived })).into_response(),
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
async fn delete_session(State(st): State<Shared>, Path(id): Path<String>) -> Response {
if let Some(refusal) = session_id_ok(&id, &st) {
return refusal.into_response();
}
match st.store.delete(&id) {
Ok(()) => Json(json!({ "id": id, "deleted": true })).into_response(),
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
const MAX_ITERATIONS_BOUND: usize = 200;
fn error(status: StatusCode, msg: impl Into<String>) -> ApiError {
(status, Json(json!({"error": msg.into()})))
}
type Refusal = (StatusCode, String);
fn cron_root(st: &AppState) -> Result<std::path::PathBuf, Refusal> {
st.cron_root.clone().ok_or((
StatusCode::SERVICE_UNAVAILABLE,
"this dashboard was started without an install root, so it has no cron files to show"
.to_string(),
))
}
fn cron_job(root: &std::path::Path, name: &str) -> Result<eclipse_core::cron::Job, Refusal> {
let jobs = eclipse_core::cron::load(root)
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
jobs.into_iter().find(|j| j.name == name).ok_or((
StatusCode::NOT_FOUND,
format!("no job named `{name}`; the list shows the names"),
))
}
async fn list_cron(State(st): State<Shared>) -> Response {
let root = match cron_root(&st) {
Ok(root) => root,
Err((status, why)) => return error(status, why).into_response(),
};
let now = eclipse_core::session::now_ms() as i64;
let reader = {
let root = root.clone();
move || eclipse_core::cron::views(&root, now)
};
let Some(listing) = blocking(reader).await else {
return error(
StatusCode::SERVICE_UNAVAILABLE,
"the blocking pool did not take the read; try again",
)
.into_response();
};
match listing {
Ok(jobs) => Json(json!({
"now_ms": now,
"jobs_file": eclipse_core::cron::jobs_path(&root).display().to_string(),
"runs_dir": eclipse_core::cron::runs_root(&root).display().to_string(),
"jobs": jobs,
}))
.into_response(),
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
async fn create_cron(
State(st): State<Shared>,
Json(draft): Json<eclipse_core::cron::Draft>,
) -> Response {
let root = match cron_root(&st) {
Ok(root) => root,
Err((status, why)) => return error(status, why).into_response(),
};
let job = match draft.to_job() {
Ok(job) => job,
Err(e) => return error(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
};
let existing = match eclipse_core::cron::load(&root) {
Ok(jobs) => jobs,
Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
};
if existing.iter().any(|j| j.name == job.name) {
return error(
StatusCode::CONFLICT,
format!("a job named `{}` already exists", job.name),
)
.into_response();
}
if let Err(e) = eclipse_core::cron::append_job(&root, &job) {
return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
}
let now = eclipse_core::session::now_ms() as i64;
match eclipse_core::cron::views(&root, now)
.map(|all| all.into_iter().find(|v| v.name == job.name))
{
Ok(Some(view)) => (StatusCode::CREATED, Json(view)).into_response(),
Ok(None) => error(
StatusCode::INTERNAL_SERVER_ERROR,
"the job was written but does not read back",
)
.into_response(),
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
async fn update_cron(
State(st): State<Shared>,
Path(name): Path<String>,
Json(draft): Json<eclipse_core::cron::Draft>,
) -> Response {
let root = match cron_root(&st) {
Ok(root) => root,
Err((status, why)) => return error(status, why).into_response(),
};
if draft.name != name {
return error(
StatusCode::BAD_REQUEST,
"a job's name is its identity: remove this one and add the new name",
)
.into_response();
}
if let Err((status, why)) = cron_job(&root, &name) {
return error(status, why).into_response();
}
let job = match draft.to_job() {
Ok(job) => job,
Err(e) => return error(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
};
if let Err(e) = eclipse_core::cron::replace_job(&root, &job) {
return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
}
let now = eclipse_core::session::now_ms() as i64;
match eclipse_core::cron::views(&root, now).map(|all| all.into_iter().find(|v| v.name == name))
{
Ok(Some(view)) => Json(view).into_response(),
Ok(None) => error(
StatusCode::INTERNAL_SERVER_ERROR,
"the job was written but does not read back",
)
.into_response(),
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
#[derive(Deserialize)]
struct EnabledBody {
enabled: bool,
}
async fn set_cron_enabled(
State(st): State<Shared>,
Path(name): Path<String>,
Json(body): Json<EnabledBody>,
) -> Response {
let root = match cron_root(&st) {
Ok(root) => root,
Err((status, why)) => return error(status, why).into_response(),
};
let job = match eclipse_core::cron::set_enabled(&root, &name, body.enabled) {
Ok(Some(job)) => job,
Ok(None) => {
return error(StatusCode::NOT_FOUND, format!("no job named `{name}`")).into_response()
}
Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
};
let now = eclipse_core::session::now_ms() as i64;
let state = eclipse_core::cron::load_state(&root).unwrap_or_default();
Json(eclipse_core::cron::view(&job, &state, now)).into_response()
}
async fn delete_cron(State(st): State<Shared>, Path(name): Path<String>) -> Response {
let root = match cron_root(&st) {
Ok(root) => root,
Err((status, why)) => return error(status, why).into_response(),
};
match eclipse_core::cron::remove_job(&root, &name) {
Ok(true) => Json(json!({ "name": name, "removed": true })).into_response(),
Ok(false) => error(StatusCode::NOT_FOUND, format!("no job named `{name}`")).into_response(),
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
fn eclipse_bin() -> std::path::PathBuf {
if let Some(path) = std::env::var_os("ECLIPSE_BIN") {
return std::path::PathBuf::from(path);
}
if let Ok(exe) = std::env::current_exe() {
if let Some(dir) = exe.parent() {
let beside = dir.join("eclipse");
if beside.is_file() {
return beside;
}
}
}
std::path::PathBuf::from("eclipse")
}
async fn run_cron_now(State(st): State<Shared>, Path(name): Path<String>) -> Response {
let root = match cron_root(&st) {
Ok(root) => root,
Err((status, why)) => return error(status, why).into_response(),
};
let job = match cron_job(&root, &name) {
Ok(job) => job,
Err((status, why)) => return error(status, why).into_response(),
};
let mut command = std::process::Command::new(eclipse_bin());
if let Some(profile) = st.profile.as_deref() {
command.arg("--profile").arg(profile);
}
if let Some(config) = st.config_path.as_deref() {
command.arg("--config").arg(config);
}
let spawned = command
.arg("cron")
.arg("run")
.arg(&name)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn();
match spawned {
Ok(mut child) => {
let pid = child.id();
tokio::task::spawn_blocking(move || {
let _ = child.wait();
});
(
StatusCode::ACCEPTED,
Json(json!({
"name": name,
"started": true,
"pid": pid,
"enabled": job.enabled,
})),
)
.into_response()
}
Err(e) => error(
StatusCode::INTERNAL_SERVER_ERROR,
format!(
"could not start `{} cron run {name}`: {e}",
eclipse_bin().display()
),
)
.into_response(),
}
}
async fn cron_logs(
State(st): State<Shared>,
Path(name): Path<String>,
Query(q): Query<LogsQuery>,
) -> Response {
let root = match cron_root(&st) {
Ok(root) => root,
Err((status, why)) => return error(status, why).into_response(),
};
if let Err((status, why)) = cron_job(&root, &name) {
return error(status, why).into_response();
}
let limit = q.limit.unwrap_or(3).clamp(1, 20);
Json(json!({
"job": name,
"runs_dir": eclipse_core::cron::runs_dir(&root, &name).display().to_string(),
"runs": eclipse_core::cron::runs(&root, &name, limit),
}))
.into_response()
}
#[derive(Deserialize)]
struct LogsQuery {
limit: Option<usize>,
}
fn mcp_config_path(st: &AppState) -> Result<std::path::PathBuf, Refusal> {
st.write_path().ok_or((
StatusCode::SERVICE_UNAVAILABLE,
"this dashboard was started without a config file, so it has no `[[mcp]]` entries to \
show or edit"
.to_string(),
))
}
fn mcp_row(s: &eclipse_core::plugins::McpServerState) -> serde_json::Value {
json!({
"name": s.name,
"source": s.source.label(),
"owner": s.owner,
"command": s.command,
"policy": format!("{:?}", s.policy).to_lowercase(),
"prefix": s.prefix,
"timeout_secs": s.timeout_secs,
"disabled": s.disabled,
"transport": s.transport.as_str(),
"program": s.program,
"args": s.args,
"url": s.url,
"token_env": s.token_env,
"token": s.token.as_str(),
"tools": s.tools,
"started": s.error.is_none() && !s.disabled,
"error": s.error,
"protocol": s.protocol,
"server_name": s.server_name,
"server_version": s.server_version,
})
}
fn mcp_listing(cfg: &eclipse_core::config::Config) -> (Vec<serde_json::Value>, Vec<String>) {
let loaded = eclipse_core::plugins::load(
&cfg.plugins_dirs(&eclipse_core::config::process_env),
&cfg.plugins.enabled,
)
.with_mcp(eclipse_core::plugins::McpSettings::from_config(cfg))
.with_config_mcp(cfg);
let workspace = cfg.workspace_root(&eclipse_core::config::process_env);
let (servers, problems) = loaded.mcp_report(&workspace);
(servers.iter().map(mcp_row).collect(), problems)
}
fn mcp_writer_error(why: String) -> (StatusCode, String) {
let status = if why.starts_with("no `[[mcp]]` entry") {
StatusCode::NOT_FOUND
} else if why.contains("is already declared at line") {
StatusCode::CONFLICT
} else if why.starts_with("that entry is not usable") {
StatusCode::BAD_REQUEST
} else {
StatusCode::INTERNAL_SERVER_ERROR
};
(status, why)
}
async fn mcp_edit(
st: &AppState,
edit: impl FnOnce(&str) -> Result<String, (StatusCode, String)> + Send + 'static,
) -> Result<eclipse_core::config::Config, (StatusCode, String)> {
let path = mcp_config_path(st)?;
let base = st.config_path.clone();
let profile = st.profile.clone();
let writes = st.config_writes.clone();
let written = blocking(move || -> Result<_, (StatusCode, String)> {
let _one_writer = writes
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("{}: {e}", path.display()),
))
}
};
let edited = edit(&text)?;
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("{}: {e}", dir.display()),
)
})?;
}
eclipse_core::config::save_config_text(&path, &edited)
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
eclipse_core::config::Config::load_with_profile(
base.as_deref(),
profile.as_deref(),
&eclipse_core::config::process_env,
)
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
})
.await;
let Some(written) = written else {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
"the write did not finish".to_string(),
));
};
written
}
async fn mcp_row_after(
cfg: eclipse_core::config::Config,
name: &str,
) -> Result<serde_json::Value, (StatusCode, String)> {
let Some(rows) = blocking(move || mcp_listing(&cfg)).await else {
return Err((
StatusCode::SERVICE_UNAVAILABLE,
"the blocking pool did not take the read; try again".to_string(),
));
};
rows.0
.into_iter()
.find(|r| r["name"] == name)
.ok_or_else(|| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("the entry was written but `{name}` does not read back"),
)
})
}
async fn list_problems(State(st): State<Shared>) -> Response {
let cfg = match st.reload_config() {
Ok(cfg) => cfg,
Err(e) => {
return Json(json!({
"summary": format!("the config could not be loaded: {e}"),
"config_error": st.config_error.clone().unwrap_or_else(|| e.clone()),
"problems": [],
"checked": [],
}))
.into_response()
}
};
let report =
blocking(move || eclipse_core::problems::collect(&cfg, &eclipse_core::config::process_env))
.await;
let Some(report) = report else {
return error(
StatusCode::SERVICE_UNAVAILABLE,
"the blocking pool did not take the read; try again",
)
.into_response();
};
let problems: Vec<serde_json::Value> = report
.problems
.iter()
.map(|p| {
json!({
"kind": p.kind.as_str(),
"text": p.text,
"path": p.path.as_ref().map(|p| p.display().to_string()),
})
})
.collect();
Json(json!({
"summary": report.summary(),
"config_error": st.config_error.clone(),
"problems": problems,
"checked": report.checked,
}))
.into_response()
}
async fn list_mcp(State(st): State<Shared>) -> Response {
let path = match mcp_config_path(&st) {
Ok(path) => path,
Err((status, why)) => return error(status, why).into_response(),
};
let cfg = match st.reload_config() {
Ok(cfg) => cfg,
Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
};
let Some(listing) = blocking(move || mcp_listing(&cfg)).await else {
return error(
StatusCode::SERVICE_UNAVAILABLE,
"the blocking pool did not take the read; try again",
)
.into_response();
};
Json(json!({
"config_path": path.display().to_string(),
"servers": listing.0,
"problems": listing.1,
}))
.into_response()
}
type TokenEnv = Option<String>;
#[derive(Deserialize)]
struct McpEntry {
#[serde(default)]
name: Option<String>,
#[serde(default)]
transport: Option<String>,
#[serde(default)]
command: Option<String>,
#[serde(default)]
args: Option<Vec<String>>,
#[serde(default)]
url: Option<String>,
#[serde(default)]
prefix: Option<String>,
#[serde(default)]
policy: Option<String>,
#[serde(default)]
token_env: TokenEnv,
#[serde(default)]
timeout_secs: Option<u64>,
}
fn filled(v: Option<&String>) -> bool {
v.is_some_and(|s| !s.trim().is_empty())
}
async fn add_mcp(State(st): State<Shared>, Json(body): Json<McpEntry>) -> Response {
let name = body.name.clone().unwrap_or_default().trim().to_string();
if name.is_empty() {
return error(
StatusCode::BAD_REQUEST,
"a server needs a name — it is what `eclipse mcp test` and the tool names use",
)
.into_response();
}
let transport = match mcp_transport(&body) {
Ok(transport) => transport,
Err((status, why)) => return error(status, why).into_response(),
};
let policy = match mcp_policy(&body) {
Ok(policy) => policy,
Err((status, why)) => return error(status, why).into_response(),
};
let spec = eclipse_core::mcp::Spec {
name: name.clone(),
transport,
command: body.command.unwrap_or_default(),
args: body.args.unwrap_or_default(),
env: Vec::new(),
cwd: Default::default(),
url: body.url.filter(|u| !u.trim().is_empty()),
token_env: body.token_env.filter(|t| !t.trim().is_empty()),
timeout_secs: body.timeout_secs,
policy,
policies: Default::default(),
prefix: body.prefix.unwrap_or_default(),
override_builtin: false,
disabled: false,
};
let wrote = mcp_edit(&st, move |text| {
eclipse_core::config::mcp_add(text, &spec).map_err(mcp_writer_error)
})
.await;
let cfg = match wrote {
Ok(cfg) => cfg,
Err((status, why)) => return error(status, why).into_response(),
};
match mcp_row_after(cfg, &name).await {
Ok(row) => (StatusCode::CREATED, Json(row)).into_response(),
Err((status, why)) => error(status, why).into_response(),
}
}
fn mcp_transport(body: &McpEntry) -> Result<eclipse_core::mcp::Transport, (StatusCode, String)> {
match body.transport.as_deref() {
None | Some("") => {
if filled(body.url.as_ref()) && !filled(body.command.as_ref()) {
Ok(eclipse_core::mcp::Transport::Http)
} else {
Ok(eclipse_core::mcp::Transport::Stdio)
}
}
Some("stdio") => Ok(eclipse_core::mcp::Transport::Stdio),
Some("http") => Ok(eclipse_core::mcp::Transport::Http),
Some(other) => Err((
StatusCode::BAD_REQUEST,
format!("`{other}` is not a transport: this build speaks `stdio` and `http`"),
)),
}
}
fn mcp_policy(body: &McpEntry) -> Result<eclipse_core::config::Policy, (StatusCode, String)> {
match body.policy.as_deref() {
None | Some("") => Ok(eclipse_core::config::Policy::Ask),
Some(raw) => {
serde_json::from_value::<eclipse_core::config::Policy>(json!(raw)).map_err(|_| {
(
StatusCode::BAD_REQUEST,
format!("`{raw}` is not a policy: `ask`, `allow` or `deny`"),
)
})
}
}
}
struct McpFields {
transport: eclipse_core::mcp::Transport,
command: String,
args: Vec<String>,
url: Option<String>,
prefix: String,
policy: eclipse_core::config::Policy,
token_env: Option<String>,
timeout_secs: Option<u64>,
}
async fn update_mcp(
State(st): State<Shared>,
Path(name): Path<String>,
Json(body): Json<McpEntry>,
) -> Response {
if let Some(named) = body
.name
.as_deref()
.map(str::trim)
.filter(|n| !n.is_empty())
{
if named != name {
return error(
StatusCode::BAD_REQUEST,
format!(
"this is the entry for `{name}`, and an edit does not rename it — remove it and add `{named}` instead"
),
)
.into_response();
}
}
let transport = match mcp_transport(&body) {
Ok(transport) => transport,
Err((status, why)) => return error(status, why).into_response(),
};
let policy = match mcp_policy(&body) {
Ok(policy) => policy,
Err((status, why)) => return error(status, why).into_response(),
};
let edit = McpFields {
transport,
command: body.command.unwrap_or_default(),
args: body.args.unwrap_or_default(),
url: body.url.filter(|u| !u.trim().is_empty()),
prefix: body.prefix.unwrap_or_default(),
policy,
token_env: body.token_env.filter(|t| !t.trim().is_empty()),
timeout_secs: body.timeout_secs,
};
let for_writer = name.clone();
let wrote = mcp_edit(&st, move |text| {
eclipse_core::config::mcp_update(text, &for_writer, move |spec| {
spec.transport = edit.transport;
spec.command = edit.command;
spec.args = edit.args;
spec.url = edit.url;
spec.prefix = edit.prefix;
spec.policy = edit.policy;
spec.token_env = edit.token_env;
if edit.timeout_secs.is_some() {
spec.timeout_secs = edit.timeout_secs;
}
})
.map_err(mcp_writer_error)
})
.await;
let cfg = match wrote {
Ok(cfg) => cfg,
Err((status, why)) => return error(status, why).into_response(),
};
match mcp_row_after(cfg, &name).await {
Ok(row) => Json(row).into_response(),
Err((status, why)) => error(status, why).into_response(),
}
}
async fn set_mcp_enabled(
State(st): State<Shared>,
Path(name): Path<String>,
Json(body): Json<EnabledBody>,
) -> Response {
let for_writer = name.clone();
let wrote = mcp_edit(&st, move |text| {
eclipse_core::config::mcp_set_disabled(text, &for_writer, !body.enabled)
.map_err(mcp_writer_error)
})
.await;
let cfg = match wrote {
Ok(cfg) => cfg,
Err((status, why)) => return error(status, why).into_response(),
};
match mcp_row_after(cfg, &name).await {
Ok(row) => Json(row).into_response(),
Err((status, why)) => error(status, why).into_response(),
}
}
async fn test_mcp(State(st): State<Shared>, Path(name): Path<String>) -> Response {
if let Err((status, why)) = mcp_config_path(&st) {
return error(status, why).into_response();
}
let cfg = match st.reload_config() {
Ok(cfg) => cfg,
Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
};
let wanted = name.clone();
let Some(rows) = blocking(move || mcp_listing(&cfg)).await else {
return error(
StatusCode::SERVICE_UNAVAILABLE,
"the blocking pool did not take the run; try again",
)
.into_response();
};
match rows.0.into_iter().find(|r| r["name"] == wanted) {
Some(row) => Json(row).into_response(),
None => error(
StatusCode::NOT_FOUND,
format!("no MCP server is called `{name}` — the list shows the names this build sees"),
)
.into_response(),
}
}
async fn remove_mcp(State(st): State<Shared>, Path(name): Path<String>) -> Response {
let for_writer = name.clone();
let wrote = mcp_edit(&st, move |text| {
eclipse_core::config::mcp_remove(text, &for_writer).map_err(mcp_writer_error)
})
.await;
match wrote {
Ok(_) => Json(json!({ "name": name, "removed": true })).into_response(),
Err((status, why)) => error(status, why).into_response(),
}
}
#[derive(Deserialize)]
struct ChatRequest {
#[serde(default)]
message: String,
session_id: Option<String>,
max_iterations: Option<usize>,
#[serde(default)]
attachments: Vec<Attachment>,
}
#[derive(Debug, Deserialize)]
struct Attachment {
kind: String,
#[serde(default)]
name: String,
#[serde(default)]
value: String,
}
const MAX_ATTACHMENTS: usize = 8;
const MAX_ATTACHMENT_CHARS: usize = 64 * 1024;
const MAX_ATTACHED_CHARS: usize = 192 * 1024;
fn compose_attachments(
message: &str,
items: &[Attachment],
) -> Result<(String, Vec<eclipse_core::message::ImagePart>), String> {
if items.is_empty() {
return Ok((message.to_string(), Vec::new()));
}
if items.len() > MAX_ATTACHMENTS {
return Err(format!(
"at most {MAX_ATTACHMENTS} attachments per turn; this one has {}",
items.len()
));
}
let mut blocks: Vec<String> = Vec::new();
let mut pictures: Vec<eclipse_core::message::ImagePart> = Vec::new();
let mut added = 0usize;
for item in items {
let name = if item.name.trim().is_empty() {
item.value.trim().to_string()
} else {
item.name.trim().to_string()
};
let block = match item.kind.as_str() {
"text" => {
let body = item.value.trim_end_matches('\n');
let chars = body.chars().count();
if chars > MAX_ATTACHMENT_CHARS {
return Err(format!(
"{name} is {chars} characters and the limit is {MAX_ATTACHMENT_CHARS}: \
attach it as a path and let the agent read the part it needs"
));
}
added = added.saturating_add(chars);
format!("--- attached file: {name} ({chars} chars) ---\n{body}\n--- end of {name} ---")
}
"path" => {
let path = item.value.trim();
if path.is_empty() || path.chars().count() > 512 || path.chars().any(char::is_control) {
return Err(format!(
"cannot attach {path:?} as a path: a path is one line, at most 512 characters"
));
}
format!(
"--- attached path: {path} (not inlined; read it with read_file if you need it) ---"
)
}
"url" => {
let url = item.value.trim();
let ok = (url.starts_with("http://") || url.starts_with("https://"))
&& url.chars().count() <= 2048
&& !url.chars().any(|c| c.is_whitespace() || c.is_control());
if !ok {
return Err(format!(
"cannot attach {url:?} as a link: it has to start with http:// or https:// and hold no spaces"
));
}
format!("--- attached link: {url} (fetch it if you need it) ---")
}
"image" => {
let parts = image_parts(std::slice::from_ref(item))?;
let part = parts.into_iter().next().expect("one item, one part");
let label = part.name.clone();
pictures.push(part.clone());
format!("--- attached picture: {label} ({}) ---", part.mime)
}
other => {
return Err(format!(
"this page cannot attach {other} yet: the request has no part for one, so it would \
be dropped rather than read. Attach a file, a picture, a path or a link."
))
}
};
blocks.push(block);
}
if added > MAX_ATTACHED_CHARS {
return Err(format!(
"the attachments add {added} characters and the limit is {MAX_ATTACHED_CHARS}: \
send fewer, or attach the paths instead"
));
}
let blocks = blocks.join("\n\n");
let head = message.trim_end();
let text = if head.is_empty() {
blocks
} else {
format!("{head}\n\n{blocks}")
};
Ok((text, pictures))
}
fn image_parts(items: &[Attachment]) -> Result<Vec<eclipse_core::message::ImagePart>, String> {
items
.iter()
.map(|item| {
eclipse_core::message::ImagePart::from_data_url(item.name.trim(), item.value.trim())
})
.collect()
}
enum Out {
Event(AgentEvent),
ApprovalRequest {
id: String,
tool: String,
summary: String,
timeout_secs: u64,
},
ApprovalResolved {
id: String,
verdict: Verdict,
},
Cancelled,
Failed(String),
Done,
}
#[derive(Deserialize)]
struct Decision {
approved: bool,
}
async fn cancel_run(State(st): State<Shared>, Path(id): Path<String>) -> Response {
if id.is_empty() || id.len() > 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
return error(StatusCode::BAD_REQUEST, "invalid run id").into_response();
}
let cancel = st
.cancels
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&id)
.cloned();
match cancel {
Some(cancel) => {
cancel.cancel();
Json(json!({"cancelled": true})).into_response()
}
None => error(StatusCode::NOT_FOUND, "no such run").into_response(),
}
}
async fn decide_approval(
State(st): State<Shared>,
Path(id): Path<String>,
Json(decision): Json<Decision>,
) -> Response {
if id.is_empty() || id.len() > 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
return error(StatusCode::BAD_REQUEST, "invalid approval id").into_response();
}
if st.approvals.resolve(&id, decision.approved) {
Json(json!({"ok": true})).into_response()
} else {
error(
StatusCode::NOT_FOUND,
"no such pending approval (already answered or expired)",
)
.into_response()
}
}
fn sse(name: &str, data: serde_json::Value) -> Event {
Event::default().event(name).data(data.to_string())
}
type EventStream = Sse<std::pin::Pin<Box<dyn Stream<Item = Result<Event, Infallible>> + Send>>>;
fn notice_stream(answer: Answer) -> EventStream {
let events = vec![
Ok(sse(
"notice",
json!({
"text": answer.text,
"kind": if answer.refused { "refusal" } else { "command" },
"clear_session": answer.clear_session,
"yolo": answer.yolo,
}),
)),
Ok(sse("done", json!({}))),
];
Sse::new(stream::iter(events).boxed())
}
async fn chat(
State(st): State<Shared>,
Json(req): Json<ChatRequest>,
) -> Result<EventStream, ApiError> {
if req.message.trim().is_empty() && req.attachments.is_empty() {
return Err(error(StatusCode::BAD_REQUEST, "message is empty"));
}
if let Some(answer) = verb::bang_refusal(&req.message) {
return Ok(notice_stream(answer));
}
let parsed = eclipse_core::commands::parse(&req.message, Front::Web);
let command_line = matches!(parsed, Parsed::Run(..) | Parsed::Elsewhere(..))
|| matches!(&parsed, Parsed::Unknown(line) if line.starts_with('/'));
if command_line && !req.attachments.is_empty() {
return Ok(notice_stream(Answer::refused(
"a command runs on its own: remove the attachment, or send it with a message",
)));
}
match parsed {
Parsed::Run(command, arg) => {
let answer = verb::serve(&st, command, arg, req.session_id.as_deref()).await;
return Ok(notice_stream(answer));
}
Parsed::Elsewhere(command) => {
return Ok(notice_stream(Answer::refused(
command.unavailable_in(Front::Web),
)))
}
Parsed::Unknown(line) if line.starts_with('/') => {
return Ok(notice_stream(Answer::refused("unknown command; try /help")))
}
Parsed::Unknown(_) => {}
}
let (message, pictures) = compose_attachments(&req.message, &req.attachments)
.map_err(|e| error(StatusCode::BAD_REQUEST, e))?;
let Some(_) = st.agent.clone() else {
return Err(error(StatusCode::SERVICE_UNAVAILABLE, unconfigured(&st)));
};
if req.max_iterations == Some(0) {
return Err(error(
StatusCode::BAD_REQUEST,
"max_iterations must be at least 1: a run allowed no request is not a run",
));
}
if let Some(n) = req.max_iterations.filter(|n| *n > MAX_ITERATIONS_BOUND) {
return Err(error(
StatusCode::BAD_REQUEST,
format!(
"max_iterations is at most {MAX_ITERATIONS_BOUND} (asked for {n}): a bound that \
large is a request for the model, not a turn"
),
));
}
let session_id = match req.session_id.filter(|s| !s.is_empty()) {
Some(id) => {
eclipse_core::session::validate_id(&id)
.map_err(|e| error(StatusCode::BAD_REQUEST, e.to_string()))?;
id
}
None => st.store.new_id(),
};
let agent = match st.agent_for(&session_id) {
Ok(Some(agent)) => agent,
Ok(None) => return Err(error(StatusCode::SERVICE_UNAVAILABLE, unconfigured(&st))),
Err(why) => return Err(error(StatusCode::SERVICE_UNAVAILABLE, why)),
};
let Some(permit) = st.try_chat_slot() else {
return Err(error(
StatusCode::TOO_MANY_REQUESTS,
"too many chats in progress; try again shortly",
));
};
let (tx, rx) = mpsc::unbounded_channel::<Out>();
let sid = session_id.clone();
let run = st.approvals.next_run.fetch_add(1, Ordering::Relaxed);
let run_id = eclipse_core::token::random_hex(16)
.map_err(|e| error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
let cancel = Cancel::new();
st.cancels
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(run_id.clone(), cancel.clone());
let run_token = run_id.clone();
let guard_cancel = cancel.clone();
let budget = req.max_iterations.unwrap_or_else(|| agent.max_iterations());
let opts = RunOptions {
max_iterations: req.max_iterations,
resume: false,
output_schema: None,
title: true,
images: pictures,
};
let rail = agent.context_reading(None);
let report = agent.reasoning_report();
tokio::spawn(async move {
let _permit = permit;
let _scope = RunScope {
state: st.clone(),
run,
token: run_token,
};
let events = tx.clone();
let sink = move |e: AgentEvent| {
let _ = events.send(Out::Event(e));
};
let approver = WebApprover {
state: st.clone(),
run,
events: tx.clone(),
};
match agent
.run_cancellable_with(Some(&sid), &message, &approver, &sink, &cancel, &opts)
.await
{
Ok(_) => {}
Err(eclipse_core::Error::Cancelled) => {
let _ = tx.send(Out::Cancelled);
}
Err(e) => {
let _ = tx.send(Out::Failed(e.to_string()));
}
}
let _ = tx.send(Out::Done);
});
let first = stream::once(async move {
Ok::<_, Infallible>(sse(
"session",
json!({"session_id": session_id, "run_id": run_id, "max_iterations": budget}),
))
});
let guard = DisconnectGuard {
cancel: guard_cancel,
};
let state = (rx, guard, rail, report);
let rest = stream::unfold(state, |(mut rx, guard, rail, report)| async move {
let item = rx.recv().await?;
let ev = match item {
Out::Event(AgentEvent::ToolCall {
call_id,
name,
arguments,
}) => {
let summary = calls::statement(&name, &arguments);
sse(
"tool_call",
json!({
"call_id": call_id,
"name": name,
"arguments": arguments,
"summary": summary,
}),
)
}
Out::Event(AgentEvent::ToolResult {
call_id,
name,
output,
is_error,
}) => sse(
"tool_result",
json!({
"call_id": call_id,
"name": name,
"state": calls::outcome(&output, Some(is_error)).as_str(),
"output": output,
"is_error": is_error,
}),
),
Out::Event(AgentEvent::Delta(text)) => sse("delta", json!({"text": text})),
Out::Event(AgentEvent::ReasoningDelta(text)) => sse("reasoning", json!({"text": text})),
Out::Event(AgentEvent::ToolCallDelta { index, json }) => {
sse("tool_call_delta", json!({"index": index, "json": json}))
}
Out::Event(AgentEvent::Message(text)) => sse("message", json!({"text": text})),
Out::Event(AgentEvent::TurnStats {
usage,
context_tokens,
budget_tokens,
}) => sse(
"stats",
json!({
"prompt_tokens": usage.prompt_tokens,
"completion_tokens": usage.completion_tokens,
"total_tokens": usage.total_tokens,
"cached_tokens": usage.cached_tokens,
"prompt_ms": usage.prompt_ms,
"completion_ms": usage.completion_ms,
"latency_ms": usage.latency_ms,
"ttft_ms": usage.ttft_ms,
"tokens_per_sec": usage.tokens_per_sec(),
"context_tokens": context_tokens,
"budget_tokens": budget_tokens,
"window_tokens": rail.denominator,
"ctx": Reading::new(
usage
.prompt_tokens
.or((context_tokens > 0).then_some(context_tokens as u64)),
rail.denominator,
rail.marker,
)
.text(12),
"effort": report.label.clone(),
"effort_detail": report.sentence(),
"effort_session": report.session,
}),
),
Out::Event(AgentEvent::SchemaRejected { error, retrying }) => sse(
"schema_rejected",
json!({ "error": error, "retrying": retrying }),
),
Out::Event(AgentEvent::ContextTrimmed {
turns,
messages,
memory,
judgement,
}) => {
let (memory, memory_error) = match memory {
eclipse_core::MemoryStatus::NotUsed => ("not_used", None),
eclipse_core::MemoryStatus::Reused => ("reused", None),
eclipse_core::MemoryStatus::Saved => ("saved", None),
eclipse_core::MemoryStatus::SaveFailed(e) => ("save_failed", Some(e)),
};
let (judgement, judgement_bullets, judgement_error) = match judgement {
eclipse_core::JudgementStatus::Off => ("off", 0, None),
eclipse_core::JudgementStatus::Used { bullets } => ("used", bullets, None),
eclipse_core::JudgementStatus::Rejected(e) => ("rejected", 0, Some(e)),
eclipse_core::JudgementStatus::Failed(e) => ("failed", 0, Some(e)),
};
sse(
"context_trimmed",
json!({
"turns": turns,
"messages": messages,
"memory": memory,
"memory_error": memory_error,
"judgement": judgement,
"judgement_bullets": judgement_bullets,
"judgement_error": judgement_error,
}),
)
}
Out::ApprovalRequest {
id,
tool,
summary,
timeout_secs,
} => sse(
"approval_request",
json!({"id": id, "tool": tool, "summary": summary, "timeout_secs": timeout_secs}),
),
Out::ApprovalResolved { id, verdict } => sse(
"approval_resolved",
json!({"id": id, "outcome": verdict.as_str()}),
),
Out::Cancelled => sse("cancelled", json!({})),
Out::Failed(message) => sse("error", json!({"message": message})),
Out::Done => sse("done", json!({})),
};
Some((Ok::<_, Infallible>(ev), (rx, guard, rail, report)))
});
Ok(Sse::new(first.chain(rest).boxed()).keep_alive(KeepAlive::default()))
}
#[cfg(test)]
mod tests {
use super::*;
use async_trait::async_trait;
use axum::body::Body;
use axum::http::Request as HttpRequest;
use eclipse_core::error::Result as CoreResult;
use eclipse_core::message::Message;
use eclipse_core::provider::ChatProvider;
use eclipse_core::session::SessionStore;
use eclipse_core::tools::{ToolRegistry, ToolSpec};
use eclipse_core::usage::TurnUsage;
use tower::ServiceExt;
struct Canned;
#[async_trait]
impl ChatProvider for Canned {
async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
Ok(Message::assistant("canned reply"))
}
}
struct Measured;
#[async_trait]
impl ChatProvider for Measured {
async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
unreachable!()
}
async fn chat_stream(
&self,
_: &[Message],
_: &[ToolSpec],
on_delta: eclipse_core::stream::DeltaFn<'_>,
) -> CoreResult<Message> {
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
on_delta(eclipse_core::stream::Delta::Text("measured ".into()));
on_delta(eclipse_core::stream::Delta::Text("reply".into()));
Ok(Message::assistant("measured reply"))
}
fn take_usage(&self) -> Option<TurnUsage> {
let prompt = 30_000_u64;
let total = 30_120_u64;
let cached = 19_000_u64;
Some(TurnUsage {
prompt_tokens: Some(prompt),
completion_tokens: Some(120),
total_tokens: Some(total),
cached_tokens: Some(cached),
prompt_ms: Some(300),
completion_ms: Some(2_500),
latency_ms: 2_900,
ttft_ms: Some(1_500),
})
}
}
struct Scripted(Mutex<Vec<Message>>);
impl Scripted {
fn new(mut replies: Vec<Message>) -> Arc<Self> {
replies.reverse();
Arc::new(Self(Mutex::new(replies)))
}
}
#[async_trait]
impl ChatProvider for Scripted {
async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
Ok(self.0.lock().unwrap().pop().expect("script exhausted"))
}
}
struct Streaming;
#[async_trait]
impl ChatProvider for Streaming {
async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
unreachable!()
}
async fn chat_stream(
&self,
_: &[Message],
_: &[ToolSpec],
on_delta: eclipse_core::stream::DeltaFn<'_>,
) -> CoreResult<Message> {
on_delta(eclipse_core::stream::Delta::Text("tok".into()));
on_delta(eclipse_core::stream::Delta::Text("ens".into()));
Ok(Message::assistant("tokens"))
}
}
struct Hangs {
entered: Arc<std::sync::atomic::AtomicBool>,
dropped: Arc<std::sync::atomic::AtomicBool>,
}
struct MarkDropped(Arc<std::sync::atomic::AtomicBool>);
impl Drop for MarkDropped {
fn drop(&mut self) {
self.0.store(true, Ordering::SeqCst);
}
}
#[async_trait]
impl ChatProvider for Hangs {
async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
unreachable!()
}
async fn chat_stream(
&self,
_: &[Message],
_: &[ToolSpec],
_: eclipse_core::stream::DeltaFn<'_>,
) -> CoreResult<Message> {
self.entered.store(true, Ordering::SeqCst);
let _dropped = MarkDropped(self.dropped.clone());
tokio::time::sleep(Duration::from_secs(600)).await;
Ok(Message::assistant("too late"))
}
}
fn hanging_state(
dir: &std::path::Path,
) -> (
Shared,
Arc<std::sync::atomic::AtomicBool>,
Arc<std::sync::atomic::AtomicBool>,
) {
let store = SessionStore::new(dir.join("sessions"));
let entered = Arc::new(std::sync::atomic::AtomicBool::new(false));
let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false));
let agent = Agent::new(
Arc::new(Hangs {
entered: entered.clone(),
dropped: dropped.clone(),
}),
Arc::new(ToolRegistry::default()),
store.clone(),
"sys".into(),
3,
);
let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
(st, entered, dropped)
}
async fn wait_for(flag: &Arc<std::sync::atomic::AtomicBool>, ms: u64) -> bool {
for _ in 0..(ms / 20) {
if flag.load(Ordering::SeqCst) {
return true;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
flag.load(Ordering::SeqCst)
}
fn cancel_req(run_id: &str) -> HttpRequest<Body> {
HttpRequest::post(format!("/api/runs/{run_id}/cancel"))
.header("host", "127.0.0.1:8787")
.header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
.body(Body::empty())
.unwrap()
}
const TOKEN: &str = "0123456789abcdef0123456789abcdef";
const LOGIN_ID: &str = "test-login-id";
fn authed(
agent: Option<Arc<Agent>>,
store: SessionStore,
model: &str,
config_error: Option<String>,
) -> AppState {
AppState::new(
agent,
store,
model.into(),
config_error,
TOKEN.into(),
std::time::Duration::from_secs(
eclipse_core::config::DEFAULT_SESSION_TTL_HOURS * 60 * 60,
),
)
.with_login(LOGIN_ID)
}
fn state(dir: &std::path::Path, configured: bool) -> Shared {
state_with(dir, configured, None)
}
fn state_throttled(dir: &std::path::Path, throttle: LoginThrottle) -> Shared {
match Arc::try_unwrap(state(dir, true)) {
Ok(mut st) => {
st.throttle = throttle;
Arc::new(st)
}
Err(_) => panic!("a state built here is not shared yet"),
}
}
fn state_with(
dir: &std::path::Path,
configured: bool,
config: Option<std::path::PathBuf>,
) -> Shared {
let store = SessionStore::new(dir.join("sessions"));
let agent = configured.then(|| {
Arc::new(Agent::new(
Arc::new(Canned),
Arc::new(ToolRegistry::default()),
store.clone(),
"sys".into(),
3,
))
});
Arc::new(
authed(
agent,
store,
"test-<model>",
(!configured).then(|| "provider.base_url is not set".into()),
)
.with_config_path(config, None),
)
}
async fn body_text(r: Response) -> String {
let bytes = axum::body::to_bytes(r.into_body(), 512 * 1024)
.await
.unwrap_or_default();
String::from_utf8_lossy(&bytes).into_owned()
}
fn state_watching(dir: &std::path::Path, check: eclipse_core::config::UpdateCheck) -> Shared {
let store = SessionStore::new(dir.join("sessions"));
let mut st = authed(None, store, "test-<model>", None);
st.update = Some(eclipse_core::update::Watch::at(
dir.join("state"),
&eclipse_core::config::UpdateConfig {
check,
track: eclipse_core::config::Track::Release,
remote: None,
releases: Some("http://127.0.0.1:1/latest".into()),
},
));
Arc::new(st)
}
#[tokio::test]
async fn api_update_reports_the_cache_the_cli_would_show() {
let dir = tempfile::tempdir().unwrap();
let state = dir.path().join("state");
std::fs::create_dir_all(&state).unwrap();
std::fs::write(
state.join("install.json"),
r#"{"channel":"release","prefix":"/x","installed_at":"t","version":"0.2.0"}"#,
)
.unwrap();
let now = eclipse_core::session::now_ms() / 1000;
std::fs::write(
state.join("update.json"),
format!(r#"{{"checked_at":{now},"latest":"v0.3.0"}}"#),
)
.unwrap();
let app = router(state_watching(
dir.path(),
eclipse_core::config::UpdateCheck::Daily,
));
let resp = app
.clone()
.oneshot(get_req("/api/update", "127.0.0.1:8787"))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body: serde_json::Value = serde_json::from_str(&text(resp).await).unwrap();
assert_eq!(body["installed"], "0.2.0");
assert_eq!(body["latest"], "v0.3.0");
assert_eq!(body["behind"], true, "the same answer the CLI badges");
assert_eq!(body["channel"], "release");
assert_eq!(body["checked_at"], now);
let post = HttpRequest::post("/api/update")
.header("host", "127.0.0.1:8787")
.header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
.header("origin", "http://127.0.0.1:8787")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(post).await.unwrap();
assert_eq!(
resp.status(),
StatusCode::METHOD_NOT_ALLOWED,
"nothing writes this endpoint"
);
}
#[tokio::test]
async fn api_update_shows_nothing_when_the_check_is_off() {
let dir = tempfile::tempdir().unwrap();
let state = dir.path().join("state");
std::fs::create_dir_all(&state).unwrap();
std::fs::write(
state.join("install.json"),
r#"{"channel":"release","prefix":"/x","installed_at":"t","version":"0.2.0"}"#,
)
.unwrap();
let now = eclipse_core::session::now_ms() / 1000;
std::fs::write(
state.join("update.json"),
format!(r#"{{"checked_at":{now},"latest":"v0.3.0"}}"#),
)
.unwrap();
let app = router(state_watching(
dir.path(),
eclipse_core::config::UpdateCheck::Off,
));
let resp = app
.oneshot(get_req("/api/update", "127.0.0.1:8787"))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body: serde_json::Value = serde_json::from_str(&text(resp).await).unwrap();
assert_eq!(body["behind"], false, "the user said not to be told");
assert_eq!(body["latest"], serde_json::Value::Null);
}
#[tokio::test]
async fn a_stored_session_carries_a_statement_beside_each_call() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let store = st.agent.as_ref().unwrap().store().clone();
let id = store.new_id();
let arguments = r#"{"path":"crates/x/src/session.rs","content":"abc"}"#;
store.append(&id, &Message::user("write it")).unwrap();
store
.append(
&id,
&Message::assistant_tool_calls(
None,
vec![eclipse_core::message::ToolCall {
id: "c1".into(),
kind: "function".into(),
function: eclipse_core::message::FunctionCall {
name: "write_file".into(),
arguments: arguments.into(),
},
}],
),
)
.unwrap();
store
.append(&id, &Message::tool_result("c1", "wrote it"))
.unwrap();
let app = router(st);
let r = app
.clone()
.oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
let body: Vec<serde_json::Value> = serde_json::from_str(&text(r).await).unwrap();
assert_eq!(body.len(), 3, "the whole transcript, oldest first");
assert!(
body[0].get("calls").is_none(),
"a message with no calls grows no array"
);
assert_eq!(
body[1]["calls"][0]["summary"], "write_file crates/x/src/session.rs · 3 B",
"the statement the page puts on the row"
);
assert_eq!(
body[1]["calls"][0]["state"], "ok",
"and the verdict, so the row's mark is right on replay and not only live"
);
assert_eq!(
body[1]["tool_calls"][0]["function"]["arguments"], arguments,
"and the arguments are exactly what the store holds, for the toggle"
);
assert_eq!(body[2]["content"], "wrote it", "a result is unaffected");
}
#[tokio::test]
async fn a_replayed_session_marks_each_call_the_way_it_ended() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let store = st.agent.as_ref().unwrap().store().clone();
let id = store.new_id();
let call = |id: &str| eclipse_core::message::ToolCall {
id: id.into(),
kind: "function".into(),
function: eclipse_core::message::FunctionCall {
name: "shell".into(),
arguments: r#"{"command":"date"}"#.into(),
},
};
store.append(&id, &Message::user("three of them")).unwrap();
store
.append(
&id,
&Message::assistant_tool_calls(None, vec![call("a"), call("b"), call("c")]),
)
.unwrap();
store
.append(
&id,
&Message::tool_result("a", "exit code: 0\nstdout:\nMon Nov 30\n"),
)
.unwrap();
store
.append(
&id,
&Message::tool_result("b", "exit code: 2\nstdout:\n\nstderr:\nno\n"),
)
.unwrap();
store
.append(
&id,
&Message::tool_result("c", "the user declined to run `shell`: that is a delete"),
)
.unwrap();
let app = router(st);
let r = app
.clone()
.oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
.await
.unwrap();
let body: Vec<serde_json::Value> = serde_json::from_str(&text(r).await).unwrap();
let states: Vec<&str> = body[1]["calls"]
.as_array()
.unwrap()
.iter()
.map(|c| c["state"].as_str().unwrap())
.collect();
assert_eq!(
states,
["ok", "failed", "refused"],
"the exit code and the refusal are read off the text, one mark each"
);
assert_eq!(
body[1]["calls"][2]["summary"], "shell date",
"and every row still has its statement"
);
}
#[tokio::test]
async fn a_replayed_failure_with_no_exit_code_is_marked_failed() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let store = st.agent.as_ref().unwrap().store().clone();
let id = store.new_id();
let call = |call_id: &str| eclipse_core::message::ToolCall {
id: call_id.into(),
kind: "function".into(),
function: eclipse_core::message::FunctionCall {
name: "read_file".into(),
arguments: r#"{"path":"gone.txt"}"#.into(),
},
};
store.append(&id, &Message::user("read two files")).unwrap();
store
.append(
&id,
&Message::assistant_tool_calls(None, vec![call("a"), call("b")]),
)
.unwrap();
store
.append(&id, &Message::tool_result("a", "no such file: gone.txt"))
.unwrap();
store.set_tool_outcome(&id, "a", true).unwrap();
store
.append(&id, &Message::tool_result("b", "no such file: gone.txt"))
.unwrap();
let app = router(st);
let r = app
.oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
.await
.unwrap();
let body: Vec<serde_json::Value> = serde_json::from_str(&text(r).await).unwrap();
let states: Vec<&str> = body[1]["calls"]
.as_array()
.unwrap()
.iter()
.map(|c| c["state"].as_str().unwrap())
.collect();
assert_eq!(
states,
["failed", "ok"],
"the record decides when there is one; without it the text still guesses"
);
}
#[tokio::test]
async fn a_call_with_no_result_is_still_running() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let store = st.agent.as_ref().unwrap().store().clone();
let id = store.new_id();
store
.append(
&id,
&Message::assistant_tool_calls(
None,
vec![eclipse_core::message::ToolCall {
id: "c1".into(),
kind: "function".into(),
function: eclipse_core::message::FunctionCall {
name: "shell".into(),
arguments: r#"{"command":"sleep 900"}"#.into(),
},
}],
),
)
.unwrap();
let app = router(st);
let r = app
.clone()
.oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
.await
.unwrap();
let body: Vec<serde_json::Value> = serde_json::from_str(&text(r).await).unwrap();
assert_eq!(body[0]["calls"][0]["state"], "running");
}
#[test]
fn the_refusal_names_which_check_failed_and_what_arrived() {
let logins = Logins::new(Duration::from_secs(60));
let post = Method::POST;
let at = |h: Option<&str>, o: Option<&str>| {
arrival_refusal(&logins, &post, "/api/chat", h, o, None, None)
};
let no_host = at(None, None).expect("refused");
assert!(no_host.contains("no Host header"), "{no_host}");
let foreign = at(Some("dash.example.com"), None).expect("refused");
assert!(foreign.contains("dash.example.com"), "{foreign}");
let cross_site =
at(Some("127.0.0.1:8787"), Some("http://127.0.0.1:9999")).expect("refused");
assert!(
cross_site.contains("Origin") && cross_site.contains("9999"),
"{cross_site}"
);
let anonymous = at(Some("127.0.0.1:8787"), Some("null")).expect("refused");
assert!(anonymous.contains("Origin \"null\""), "{anonymous}");
assert!(
anonymous.contains(CSRF_HEADER),
"and names the token that would have let it through: {anonymous}"
);
assert!(at(Some("localhost:8787"), None).is_none());
assert!(at(Some("127.0.0.1:8787"), Some("http://127.0.0.1:8787")).is_none());
assert!(at(Some("127.0.0.1:8787"), Some("https://127.0.0.1:8787")).is_none());
assert!(at(Some("localhost.:8787"), Some("http://localhost.:8787")).is_none());
}
#[test]
fn reading_is_never_refused_and_signing_in_survives_a_null_origin() {
let logins = Logins::new(Duration::from_secs(60));
let at = |m: Method, path: &str, o: Option<&str>| {
arrival_refusal(&logins, &m, path, Some("127.0.0.1:8787"), o, None, None)
};
assert!(at(Method::GET, "/api/sessions", Some("https://evil.example")).is_none());
assert!(at(Method::POST, "/login", Some("null")).is_none());
assert!(at(Method::POST, "/login", Some("https://evil.example")).is_some());
}
#[test]
fn the_csrf_token_is_what_lets_an_anonymous_origin_change_something() {
let logins = Logins::new(Duration::from_secs(60));
let (id, csrf) = logins.create().expect("session");
let at = |o: &str, presented: Option<&str>, session: &str| {
arrival_refusal(
&logins,
&Method::POST,
"/api/chat",
Some("127.0.0.1:8787"),
Some(o),
presented,
Some(session),
)
};
assert!(
at("null", Some(&csrf), &id).is_none(),
"the session token is the second lock"
);
assert!(at("https://evil.example", Some(&csrf), &id).is_none());
assert!(at("null", None, &id).is_some(), "no token, no entry");
assert!(at("null", Some("not-the-token"), &id).is_some());
assert!(at("null", Some(&csrf), "some-other-session").is_some());
let (other, other_csrf) = logins.create().expect("session");
assert_ne!(other, id);
assert!(at("null", Some(&other_csrf), &id).is_some());
}
async fn sign_in(app: &axum::Router) -> (String, String) {
let r = app
.clone()
.oneshot(
HttpRequest::post("/login")
.header("host", "127.0.0.1:8787")
.header("content-type", "application/x-www-form-urlencoded")
.body(Body::from(format!("token={TOKEN}")))
.unwrap(),
)
.await
.unwrap();
assert_eq!(r.status(), StatusCode::SEE_OTHER, "signed in");
let cookie = r
.headers()
.get(header::SET_COOKIE)
.and_then(|v| v.to_str().ok())
.expect("a session cookie")
.to_string();
let jar = cookie.split(';').next().unwrap().to_string();
let page = body_text(
app.clone()
.oneshot(
HttpRequest::get("/")
.header("host", "127.0.0.1:8787")
.header("cookie", &jar)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap(),
)
.await;
let csrf = csrf_of(&page);
(jar, csrf)
}
#[tokio::test]
async fn the_settings_endpoints_read_the_file_write_it_and_never_show_a_secret() {
let dir = tempfile::tempdir().unwrap();
let config_path = dir.path().join("config.toml");
std::fs::write(
&config_path,
"[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"seed\"\n",
)
.unwrap();
let app = router(state_with(dir.path(), true, Some(config_path.clone())));
let (jar, csrf) = sign_in(&app).await;
let body = body_text(
app.clone()
.oneshot(
HttpRequest::get("/api/settings")
.header("host", "127.0.0.1:8787")
.header("cookie", &jar)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap(),
)
.await;
let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
let keys: Vec<&str> = parsed["settings"]
.as_array()
.expect("a settings array")
.iter()
.filter_map(|s| s["key"].as_str())
.collect();
assert!(keys.contains(&"provider.model"), "{keys:?}");
let written = body_text(
app.clone()
.oneshot(
HttpRequest::post("/api/settings")
.header("host", "127.0.0.1:8787")
.header("cookie", &jar)
.header("x-eclipse-csrf", &csrf)
.header("content-type", "application/json")
.body(Body::from(
r#"{"key":"provider.model","value":"qwen3-coder"}"#,
))
.unwrap(),
)
.await
.unwrap(),
)
.await;
let parsed: serde_json::Value = serde_json::from_str(&written).expect("json");
assert_eq!(parsed["key"], "provider.model");
assert_eq!(parsed["value"], "\"qwen3-coder\"");
assert_eq!(parsed["is_default"], false);
let on_disk = std::fs::read_to_string(&config_path).unwrap();
assert!(on_disk.contains("qwen3-coder"), "{on_disk}");
}
#[tokio::test]
async fn a_settings_write_under_a_profile_lands_in_that_profiles_overlay() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("home/.eclipse");
std::fs::create_dir_all(&root).unwrap();
let base = root.join("config.toml");
let before = "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"seed\"\n";
std::fs::write(&base, before).unwrap();
let overlay = root.join("profiles/work/config.toml");
let st = match Arc::try_unwrap(state(dir.path(), true)) {
Ok(st) => st,
Err(_) => panic!("a state built here is not shared yet"),
}
.with_config_path(Some(base.clone()), Some("work".into()))
.with_config_targets(false, Some(root.clone()));
let app = router(Arc::new(st));
let (jar, csrf) = sign_in(&app).await;
let written = body_text(
app.clone()
.oneshot(
HttpRequest::post("/api/settings")
.header("host", "127.0.0.1:8787")
.header("cookie", &jar)
.header("x-eclipse-csrf", &csrf)
.header("content-type", "application/json")
.body(Body::from(
r#"{"key":"provider.model","value":"work-model"}"#,
))
.unwrap(),
)
.await
.unwrap(),
)
.await;
assert_eq!(
serde_json::from_str::<serde_json::Value>(&written).expect("json")["key"],
"provider.model",
"the write answered for the key it was given: {written}"
);
let overlay_text = std::fs::read_to_string(&overlay).expect("the overlay was written");
assert!(overlay_text.contains("work-model"), "{overlay_text}");
assert_eq!(
std::fs::read_to_string(&base).unwrap(),
before,
"the shared base file was not touched"
);
let home = root.parent().unwrap().display().to_string();
let env = |key: &str| match key {
"HOME" => Some(home.clone()),
_ => None,
};
let loaded =
eclipse_core::config::Config::load_with_profile(Some(&base), Some("work"), &env)
.expect("the profile loads");
assert_eq!(loaded.provider.model, "work-model");
let listing = body_text(
app.clone()
.oneshot(
HttpRequest::get("/api/mcp")
.header("host", "127.0.0.1:8787")
.header("cookie", &jar)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap(),
)
.await;
let parsed: serde_json::Value = serde_json::from_str(&listing).expect("json");
assert_eq!(parsed["config_path"], overlay.display().to_string());
}
#[tokio::test]
async fn a_settings_write_with_no_profile_still_lands_in_the_file_it_was_started_with() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("home/.eclipse");
std::fs::create_dir_all(&root).unwrap();
let base = root.join("config.toml");
std::fs::write(
&base,
"[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"seed\"\n",
)
.unwrap();
let st = match Arc::try_unwrap(state(dir.path(), true)) {
Ok(st) => st,
Err(_) => panic!("a state built here is not shared yet"),
}
.with_config_path(Some(base.clone()), None)
.with_config_targets(false, Some(root.clone()));
let st = Arc::new(st);
let _app = router(st.clone());
let written = apply_setting(&st, "provider.model", Some("base-model")).await;
assert!(written.is_ok(), "{written:?}");
let on_disk = std::fs::read_to_string(&base).unwrap();
assert!(on_disk.contains("base-model"), "{on_disk}");
assert!(
!root.join("profiles").exists(),
"nothing was created for a profile nobody serves"
);
}
#[tokio::test]
async fn a_settings_write_waits_for_the_one_already_in_flight() {
let dir = tempfile::tempdir().unwrap();
let config_path = dir.path().join("config.toml");
std::fs::write(
&config_path,
"[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"seed\"\n",
)
.unwrap();
let st = state_with(dir.path(), true, Some(config_path.clone()));
let writes = st.config_writes.clone();
let holder = tokio::task::spawn_blocking(move || {
let guard = writes
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
std::thread::sleep(std::time::Duration::from_millis(1000));
drop(guard);
});
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
let finished = done.clone();
let writer = tokio::spawn(async move {
let written = apply_setting(&st, "provider.model", Some("waited")).await;
finished.store(true, std::sync::atomic::Ordering::SeqCst);
written
});
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
assert!(
!done.load(std::sync::atomic::Ordering::SeqCst),
"the second write finished while the first one held the file"
);
holder.await.unwrap();
let written = writer.await.unwrap();
assert!(written.is_ok(), "the write failed: {written:?}");
let on_disk = std::fs::read_to_string(&config_path).unwrap();
assert!(on_disk.contains("waited"), "{on_disk}");
}
#[tokio::test]
async fn a_key_nothing_reads_is_refused_rather_than_written() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, "[provider]\nmodel = \"seed\"\n").unwrap();
let app = router(state_with(dir.path(), true, Some(path.clone())));
let (jar, csrf) = sign_in(&app).await;
let r = app
.clone()
.oneshot(
HttpRequest::post("/api/settings")
.header("host", "127.0.0.1:8787")
.header("cookie", &jar)
.header("x-eclipse-csrf", &csrf)
.header("content-type", "application/json")
.body(Body::from(r#"{"key":"nope.nope","value":"1"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(r.status(), StatusCode::BAD_REQUEST);
let on_disk = std::fs::read_to_string(&path).unwrap();
assert!(!on_disk.contains("nope"), "{on_disk}");
}
#[tokio::test]
async fn a_secret_setting_is_listed_without_its_value() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(
&path,
"[provider]\napi_key = \"sk-live-0123456789abcdef\"\n",
)
.unwrap();
let app = router(state_with(dir.path(), true, Some(path)));
let (jar, _csrf) = sign_in(&app).await;
let page = body_text(
app.clone()
.oneshot(
HttpRequest::get("/api/settings")
.header("host", "127.0.0.1:8787")
.header("cookie", &jar)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap(),
)
.await;
assert!(!page.contains("sk-live"), "the key leaked: {page}");
assert!(page.contains("\"secret\":true"), "{page}");
assert!(page.contains("\"set\":true"), "{page}");
}
#[tokio::test]
async fn a_setting_row_carries_its_type_its_words_and_its_choices() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, "[provider]\nmodel = \"seed\"\n").unwrap();
let app = router(state_with(dir.path(), true, Some(path)));
let (jar, _csrf) = sign_in(&app).await;
let body = body_text(
app.oneshot(
HttpRequest::get("/api/settings")
.header("host", "127.0.0.1:8787")
.header("cookie", &jar)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap(),
)
.await;
let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
let rows = parsed["settings"].as_array().expect("an array");
let row = |key: &str| {
rows.iter()
.find(|r| r["key"] == json!(key))
.unwrap_or_else(|| panic!("{key} is in the catalogue"))
};
assert_eq!(row("agent.trace_content")["kind"], json!("bool"));
assert_eq!(row("provider.temperature")["kind"], json!("float"));
assert_eq!(row("provider.model")["kind"], json!("str"));
assert_eq!(row("tools.deferred")["kind"], json!("list"));
assert_eq!(row("cli.approval")["choices"], json!(["ask", "auto"]));
assert_eq!(
row("tools.shell")["choices"],
json!(["deny", "ask", "allow"])
);
assert_eq!(
row("update.check")["choices"],
json!(["daily", "weekly", "off"])
);
assert_eq!(row("provider.model")["choices"], json!([]));
for r in rows {
let about = r["about"].as_str().unwrap_or("");
assert!(
!about.trim().is_empty(),
"{} has no description: {}",
r["key"],
r
);
}
}
#[tokio::test]
async fn a_null_value_puts_a_key_back_to_its_default_and_a_missing_one_is_refused() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, "[agent]\nmax_iterations = 3\n").unwrap();
let app = router(state_with(dir.path(), true, Some(path.clone())));
let (jar, csrf) = sign_in(&app).await;
let write = |body: &'static str| {
let app = app.clone();
let jar = jar.clone();
let csrf = csrf.clone();
async move {
app.oneshot(
HttpRequest::post("/api/settings")
.header("host", "127.0.0.1:8787")
.header("cookie", &jar)
.header("x-eclipse-csrf", &csrf)
.header("content-type", "application/json")
.body(Body::from(body))
.unwrap(),
)
.await
.unwrap()
}
};
let r = write(r#"{"key":"agent.max_iterations","value":"42"}"#).await;
assert_eq!(r.status(), StatusCode::OK);
assert!(std::fs::read_to_string(&path).unwrap().contains("42"));
let r = write(r#"{"key":"agent.max_iterations","value":null}"#).await;
assert_eq!(r.status(), StatusCode::OK);
let said = body_text(r).await;
let row: serde_json::Value = serde_json::from_str(&said).expect("json");
assert_eq!(row["is_default"], json!(true), "{row}");
assert_eq!(row["value"], json!("\"unlimited\""), "{row}");
let on_disk = std::fs::read_to_string(&path).unwrap();
assert!(
!on_disk
.lines()
.any(|l| l.trim_start().starts_with("max_iterations")),
"the line is gone or commented: {on_disk}"
);
let r = write(r#"{"key":"agent.max_iterations"}"#).await;
assert_eq!(r.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn a_boolean_is_written_as_a_boolean() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, "[agent]\nmax_iterations = 3\n").unwrap();
let app = router(state_with(dir.path(), true, Some(path.clone())));
let (jar, csrf) = sign_in(&app).await;
let r = app
.clone()
.oneshot(
HttpRequest::post("/api/settings")
.header("host", "127.0.0.1:8787")
.header("cookie", &jar)
.header("x-eclipse-csrf", &csrf)
.header("content-type", "application/json")
.body(Body::from(
r#"{"key":"agent.trace_content","value":"true"}"#,
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
let on_disk = std::fs::read_to_string(&path).unwrap();
assert!(
on_disk.contains("trace_content = true"),
"a boolean, not a string: {on_disk}"
);
}
fn context_fixture(dir: &std::path::Path) -> std::path::PathBuf {
let workspace = dir.join("work");
std::fs::create_dir_all(&workspace).unwrap();
std::fs::write(workspace.join("AGENT.md"), "RULE: in the tree\n").unwrap();
let memory = dir.join("memory");
std::fs::create_dir_all(&memory).unwrap();
std::fs::write(memory.join("USER.md"), "USER FACT: one line").unwrap();
let path = dir.join(".eclipse/config.toml");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(
&path,
format!(
"[provider]\nmodel = \"m\"\n[tools]\nworkspace_root = \"{ws}\"\n\
[user]\nfile = \"{user}\"\nmemory_file = \"{mem}\"\n",
ws = workspace.display(),
user = memory.join("USER.md").display(),
mem = memory.join("MEMORY.md").display(),
),
)
.unwrap();
path
}
#[tokio::test]
async fn the_context_list_resolves_three_files_from_the_config_not_the_request() {
let dir = tempfile::tempdir().unwrap();
let workspace = dir.path().join("work");
let memory = dir.path().join("memory");
let path = context_fixture(dir.path());
let app = router(state_with(dir.path(), true, Some(path)));
let (jar, _csrf) = sign_in(&app).await;
let body = body_text(
app.oneshot(
HttpRequest::get("/api/context")
.header("host", "127.0.0.1:8787")
.header("cookie", &jar)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap(),
)
.await;
let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
let files = parsed["files"].as_array().expect("an array");
assert_eq!(
files
.iter()
.map(|f| f["name"].as_str().unwrap())
.collect::<Vec<_>>(),
vec!["agent", "user", "memory"]
);
let user = &files[1];
assert_eq!(user["file"], json!("USER.md"));
assert_eq!(user["exists"], json!(true));
assert_eq!(user["chars"], json!(19));
assert_eq!(user["text"], json!("USER FACT: one line"));
assert_eq!(user["kind"], json!("prose"));
assert!(
user["path"].as_str().unwrap().ends_with("memory/USER.md"),
"{user}"
);
assert_eq!(files[0]["exists"], json!(true));
assert!(
files[0]["path"]
.as_str()
.unwrap()
.ends_with("work/AGENT.md"),
"{}",
files[0]["path"]
);
assert!(files[0]["others"].as_u64().is_some(), "{}", files[0]);
assert_eq!(files[2]["own_budget"], json!(3000));
assert_eq!(user["own_budget"], serde_json::Value::Null);
assert_eq!(files[2]["exists"], json!(false));
assert!(
files[2]["path"]
.as_str()
.unwrap()
.ends_with("memory/MEMORY.md"),
"{}",
files[2]["path"]
);
for f in files {
let shown = f["path"].as_str().unwrap();
assert!(!shown.contains("/home/mmhorda/.eclipse"), "{shown}");
}
let _ = (&workspace, &memory);
}
#[tokio::test]
async fn a_context_write_may_not_name_a_path_and_lands_where_the_file_belongs() {
let dir = tempfile::tempdir().unwrap();
let memory = dir.path().join("memory");
let path = context_fixture(dir.path());
let app = router(state_with(dir.path(), true, Some(path)));
let (jar, csrf) = sign_in(&app).await;
let write = |body: &'static str| {
let app = app.clone();
let jar = jar.clone();
let csrf = csrf.clone();
async move {
app.oneshot(
HttpRequest::post("/api/context")
.header("host", "127.0.0.1:8787")
.header("cookie", &jar)
.header("x-eclipse-csrf", &csrf)
.header("content-type", "application/json")
.body(Body::from(body))
.unwrap(),
)
.await
.unwrap()
}
};
for bad in [
r#"{"name":"../../../etc/passwd","text":"x"}"#,
r#"{"name":"/etc/passwd","text":"x"}"#,
r#"{"name":"AGENT.md","text":"x"}"#,
r#"{"name":"skill","text":"x"}"#,
] {
let r = write(Box::leak(bad.to_string().into_boxed_str())).await;
assert_eq!(r.status(), StatusCode::BAD_REQUEST, "{bad}");
let said = body_text(r).await;
assert!(
said.contains("agent"),
"the refusal names the legal ones: {said}"
);
}
assert!(!dir.path().join("etc/passwd").exists());
let r = write(r#"{"name":"user","text":"USER FACT: written from the page"}"#).await;
assert_eq!(r.status(), StatusCode::OK);
let said: serde_json::Value = serde_json::from_str(&body_text(r).await).expect("json");
assert_eq!(said["file"]["name"], json!("user"));
assert_eq!(
said["file"]["text"],
json!("USER FACT: written from the page")
);
assert_eq!(said["applies"], json!("the next run uses it"));
assert_eq!(
std::fs::read_to_string(memory.join("USER.md")).unwrap(),
"USER FACT: written from the page"
);
let r = write(r#"{"name":"memory","text":"one\n§\ntwo"}"#).await;
assert_eq!(r.status(), StatusCode::OK);
let mem = eclipse_core::memory::Memory::new(memory.join("MEMORY.md"), 3000);
assert_eq!(mem.read().unwrap(), vec!["one", "two"]);
}
#[tokio::test]
async fn two_cookie_headers_are_read_the_same_way_by_the_guard_and_the_login_check() {
let dir = tempfile::tempdir().unwrap();
let app = router(state(dir.path(), true));
let r = app.clone().oneshot(login_req(TOKEN)).await.unwrap();
assert_eq!(r.status(), StatusCode::SEE_OTHER);
let jar = r
.headers()
.get(header::SET_COOKIE)
.and_then(|v| v.to_str().ok())
.expect("a session cookie")
.split(';')
.next()
.unwrap()
.to_string();
let page = body_text(
app.clone()
.oneshot(
HttpRequest::get("/")
.header("host", "127.0.0.1:8787")
.header("cookie", &jar)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap(),
)
.await;
let csrf = csrf_of(&page);
let r = app
.clone()
.oneshot(
HttpRequest::post("/api/chat")
.header("host", "127.0.0.1:8787")
.header("origin", "null")
.header("cookie", "theme=dark")
.header("cookie", &jar)
.header(CSRF_HEADER, &csrf)
.header("content-type", "application/json")
.body(Body::from(json!({ "message": "hi" }).to_string()))
.unwrap(),
)
.await
.unwrap();
assert_ne!(
r.status(),
StatusCode::FORBIDDEN,
"the second Cookie header carries the session; the guard must see it"
);
}
#[tokio::test]
async fn a_browser_that_reports_no_origin_can_sign_in_and_then_act() {
let dir = tempfile::tempdir().unwrap();
let app = router(state(dir.path(), true));
let r = app
.clone()
.oneshot(
HttpRequest::post("/login")
.header("host", "127.0.0.1:8787")
.header("origin", "null")
.header("content-type", "application/x-www-form-urlencoded")
.body(Body::from(format!("token={TOKEN}")))
.unwrap(),
)
.await
.unwrap();
assert_eq!(
r.status(),
StatusCode::SEE_OTHER,
"not refused at the guard"
);
let cookie = r
.headers()
.get(header::SET_COOKIE)
.and_then(|v| v.to_str().ok())
.expect("a session cookie")
.to_string();
let jar = cookie.split(';').next().unwrap().to_string();
let page = body_text(
app.clone()
.oneshot(
HttpRequest::get("/")
.header("host", "127.0.0.1:8787")
.header("cookie", &jar)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap(),
)
.await;
let csrf = csrf_of(&page);
assert_eq!(csrf.len(), 64, "a real token, not an empty meta tag");
let r = app
.clone()
.oneshot(
HttpRequest::post("/api/chat")
.header("host", "127.0.0.1:8787")
.header("origin", "null")
.header("cookie", &jar)
.header(CSRF_HEADER, &csrf)
.header("content-type", "application/json")
.body(Body::from(json!({ "message": "hi" }).to_string()))
.unwrap(),
)
.await
.unwrap();
assert_ne!(r.status(), StatusCode::FORBIDDEN, "the token opened it");
let r = app
.clone()
.oneshot(
HttpRequest::post("/api/chat")
.header("host", "127.0.0.1:8787")
.header("origin", "null")
.header("cookie", &jar)
.header(CSRF_HEADER, TEST_CSRF)
.header("content-type", "application/json")
.body(Body::from(json!({ "message": "hi" }).to_string()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(
r.status(),
StatusCode::FORBIDDEN,
"a foreign token is no token"
);
let r = app
.clone()
.oneshot(
HttpRequest::post("/api/model")
.header("host", "127.0.0.1:8787")
.header("origin", "null")
.header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
.header("content-type", "application/json")
.body(Body::from(json!({ "model": "picked" }).to_string()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(r.status(), StatusCode::FORBIDDEN);
let said = body_text(r).await;
assert!(said.contains(CSRF_HEADER), "{said}");
}
#[tokio::test]
async fn the_page_hands_the_token_to_every_request_it_makes() {
let dir = tempfile::tempdir().unwrap();
let app = router(state(dir.path(), true));
let page = body_text(
app.clone()
.oneshot(get_req("/", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
assert!(
page.contains(&format!("<meta name=\"csrf\" content=\"{TEST_CSRF}\">")),
"the meta tag the script reads"
);
assert_eq!(
page.matches("await post(").count(),
11,
"model, reasoning, settings, context, approval, chat, cancel, logout, the session \
writes, the bot writes and the flare cancel"
);
assert!(page.contains("'X-Eclipse-CSRF': CSRF"), "{page:.0}");
assert!(page.contains("id=\"logout\""), "sign-out is a fetch too");
}
#[test]
fn the_context_pane_edits_the_files_by_id_and_shows_their_budget() {
assert!(
INDEX_HTML.contains("area.id = 'filetext'")
&& INDEX_HTML.contains("const area = document.createElement('textarea')"),
"a textarea, because these are prose"
);
assert!(
INDEX_HTML.contains("fetch('/api/context')"),
"the list is the server's, not the page's"
);
assert!(
INDEX_HTML.contains("post('/api/context', { name: row.name, text: area.value })"),
"a save names an id and the text"
);
assert!(
INDEX_HTML.contains("row.own_budget === null"),
"MEMORY.md is measured against its own budget, not the per-file ceiling"
);
assert!(
INDEX_HTML.contains("a save applies to the next run"),
"what a save applies to is said once, in the same words the settings rows use"
);
assert!(
INDEX_HTML.contains("entries are separated by a line holding"),
"the `§` storage format is explained where it is edited"
);
for literal in [
"'USER.md'",
"'MEMORY.md'",
"\"USER.md\"",
".eclipse/memory",
"\"agent\"",
"\"memory\"",
] {
assert!(
!INDEX_HTML.contains(literal),
"the page spells {literal}: the names come from `GET /api/context`"
);
}
assert!(
INDEX_HTML.contains("for (const f of ctxFiles)"),
"the rail's file entries are built from the server's list"
);
}
#[tokio::test]
async fn the_sign_in_page_says_when_it_is_inside_a_frame() {
let dir = tempfile::tempdir().unwrap();
let app = router(state(dir.path(), false));
let framed = body_text(
app.clone()
.oneshot(
HttpRequest::get("/login")
.header("host", "127.0.0.1:8787")
.header("sec-fetch-dest", "iframe")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap(),
)
.await;
assert!(framed.contains("inside a frame"), "{framed}");
let plain = body_text(
app.oneshot(
HttpRequest::get("/login")
.header("host", "127.0.0.1:8787")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap(),
)
.await;
assert!(!plain.contains("inside a frame"), "{plain}");
}
fn csrf_of(page: &str) -> String {
const AT: &str = "name=\"csrf\" content=\"";
let start = page.find(AT).expect("the page carries a csrf token") + AT.len();
page[start..].split('"').next().unwrap_or("").to_string()
}
fn get_req(uri: &str, host: &str) -> HttpRequest<Body> {
HttpRequest::get(uri)
.header("host", host)
.header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
.body(Body::empty())
.unwrap()
}
fn model_req(body: serde_json::Value) -> HttpRequest<Body> {
HttpRequest::post("/api/model")
.header("host", "127.0.0.1:8787")
.header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap()
}
async fn serve_models(names: &[(&str, Option<u64>)]) -> String {
let rows: Vec<serde_json::Value> = names
.iter()
.map(|(n, window)| match window {
Some(w) => json!({ "id": n, "context_length": w }),
None => json!({ "id": n }),
})
.collect();
let app = Router::new().route(
"/v1/models",
get(move || {
let body = json!({ "data": rows });
async move { Json(body) }
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
let _ = axum::serve(listener, app).await;
});
format!("http://{addr}/v1")
}
fn provider_state(dir: &std::path::Path, base_url: &str, model: &str) -> (Shared, Arc<Agent>) {
let store = SessionStore::new(dir.join("sessions"));
let cfg = eclipse_core::config::ProviderConfig {
base_url: base_url.into(),
model: model.into(),
..Default::default()
};
let agent = Arc::new(
Agent::new(
Arc::new(Canned),
Arc::new(ToolRegistry::default()),
store.clone(),
"sys".into(),
3,
)
.with_provider_config(cfg),
);
(
Arc::new(authed(Some(agent.clone()), store, model, None)),
agent,
)
}
fn chat_req(body: serde_json::Value) -> HttpRequest<Body> {
HttpRequest::post("/api/chat")
.header("host", "127.0.0.1:8787")
.header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap()
}
async fn text(resp: Response) -> String {
let bytes = axum::body::to_bytes(resp.into_body(), 1 << 20)
.await
.unwrap();
String::from_utf8(bytes.to_vec()).unwrap()
}
fn anon(method: &str, uri: &str) -> axum::http::request::Builder {
HttpRequest::builder()
.method(method)
.uri(uri)
.header("host", "127.0.0.1:8787")
}
fn login_req(token: &str) -> HttpRequest<Body> {
anon("POST", "/login")
.header("content-type", "application/x-www-form-urlencoded")
.header("origin", "http://127.0.0.1:8787")
.body(Body::from(format!("token={token}")))
.unwrap()
}
fn pair_req(user: &str, password: &str) -> HttpRequest<Body> {
anon("POST", "/login")
.header("content-type", "application/x-www-form-urlencoded")
.header("origin", "http://127.0.0.1:8787")
.body(Body::from(format!("username={user}&password={password}")))
.unwrap()
}
fn state_with_password(dir: &std::path::Path, user: &str, password: &str) -> Arc<AppState> {
state_with_password_throttled(
dir,
user,
password,
LoginThrottle::new(100, Duration::from_millis(1), Duration::from_millis(1)),
)
}
fn state_with_password_throttled(
dir: &std::path::Path,
user: &str,
password: &str,
throttle: LoginThrottle,
) -> Arc<AppState> {
let mut st = match Arc::try_unwrap(state_with_password_inner(dir, user, password)) {
Ok(st) => st,
Err(_) => panic!("a state built here is not shared yet"),
};
st.throttle = throttle;
Arc::new(st)
}
fn state_with_password_inner(
dir: &std::path::Path,
user: &str,
password: &str,
) -> Arc<AppState> {
let hash = eclipse_core::auth::hash_password(password).unwrap();
Arc::new(
authed(None, SessionStore::new(dir.join("sessions")), "m", None).with_credentials(
eclipse_core::auth::Credentials::Password {
user: user.into(),
hash: eclipse_core::auth::Stored::parse(&hash).unwrap(),
},
),
)
}
#[tokio::test]
async fn a_username_and_password_sign_in_and_every_wrong_answer_is_the_same() {
let dir = tempfile::tempdir().unwrap();
let app = router(state_with_password(dir.path(), "max", "open sesame"));
let r = app
.clone()
.oneshot(pair_req("max", "open sesame"))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::SEE_OTHER, "the right pair");
assert!(
r.headers().get("set-cookie").is_some(),
"and it hands out the session cookie"
);
for (user, password) in [
("max", "open sesam"),
("mor", "open sesame"),
("", "open sesame"),
("max", ""),
] {
let r = app.clone().oneshot(pair_req(user, password)).await.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED, "{user}/{password}");
let body = text(r).await;
assert!(body.contains("Wrong user or password."), "{body}");
assert!(
!body.contains("Wrong token."),
"the page does not offer the old wording in this mode: {body}"
);
}
}
#[tokio::test]
async fn the_right_pair_gets_in_after_the_failed_attempt_wait() {
let dir = tempfile::tempdir().unwrap();
let app = router(state_with_password_throttled(
dir.path(),
"max",
"open sesame",
LoginThrottle::new(0, Duration::from_secs(2), Duration::from_secs(2)),
));
let wrong = app.clone().oneshot(pair_req("max", "nope")).await.unwrap();
assert_eq!(wrong.status(), StatusCode::UNAUTHORIZED);
let held = app
.clone()
.oneshot(pair_req("max", "open sesame"))
.await
.unwrap();
assert_eq!(held.status(), StatusCode::TOO_MANY_REQUESTS);
let wait: u64 = held
.headers()
.get("retry-after")
.expect("the wait says how long")
.to_str()
.unwrap()
.parse()
.unwrap();
assert!(wait >= 1, "at least a second: {wait}");
tokio::time::sleep(Duration::from_millis(2_100)).await;
let r = app.oneshot(pair_req("max", "open sesame")).await.unwrap();
assert_eq!(r.status(), StatusCode::SEE_OTHER);
}
#[tokio::test]
async fn a_token_only_install_still_signs_in_through_the_new_form() {
let dir = tempfile::tempdir().unwrap();
let app = router(state(dir.path(), true));
let r = app.clone().oneshot(pair_req("", TOKEN)).await.unwrap();
assert_eq!(r.status(), StatusCode::SEE_OTHER, "the token still works");
let r = router(state(dir.path(), true))
.oneshot(anon("GET", "/login").body(Body::empty()).unwrap())
.await
.unwrap();
let html = text(r).await;
assert!(html.contains("class=\"token\""), "token mode: {html:.0}");
assert!(html.contains("Enter the dashboard token from"), "{html:.0}");
assert!(!html.contains("ECLIPSE_WEB_USER"), "no password advice yet");
}
#[tokio::test]
async fn the_password_page_asks_for_a_user_and_a_password() {
let dir = tempfile::tempdir().unwrap();
let r = router(state_with_password(dir.path(), "max", "open sesame"))
.oneshot(anon("GET", "/login").body(Body::empty()).unwrap())
.await
.unwrap();
let html = text(r).await;
assert!(
html.contains("class=\"password\""),
"password mode: {html:.0}"
);
assert!(html.contains("autocomplete=\"username\""), "{html:.0}");
assert!(
html.contains("autocomplete=\"current-password\""),
"{html:.0}"
);
assert!(
html.contains("ECLIPSE_WEB_USER"),
"it names where the user comes from"
);
assert!(
!html.contains("auth_token"),
"the token is the machine credential; the page does not offer it as a human one"
);
}
#[tokio::test]
async fn blocking_runs_the_work_off_the_async_worker() {
let here = std::thread::current().id();
let there = blocking(move || std::thread::current().id()).await;
assert!(there.is_some(), "the work finished");
assert_ne!(
there.unwrap(),
here,
"a blocking call must not run on the async worker"
);
}
#[tokio::test]
async fn blocking_turns_a_panic_into_nothing() {
let died = blocking(|| -> usize { panic!("the disk went away") }).await;
assert!(
died.is_none(),
"a panic comes back as None, not a dropped request"
);
}
#[tokio::test]
async fn a_couple_of_wrong_tokens_is_not_an_attack() {
let dir = tempfile::tempdir().unwrap();
let app = router(state(dir.path(), true));
for attempt in 1..=2 {
let r = app
.clone()
.oneshot(login_req("not-the-token"))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED, "attempt {attempt}");
}
}
#[tokio::test]
async fn a_run_of_wrong_tokens_is_answered_429_and_even_the_right_one_waits() {
let dir = tempfile::tempdir().unwrap();
let app = router(state_throttled(
dir.path(),
LoginThrottle::new(2, Duration::from_secs(1), Duration::from_secs(30)),
));
for _ in 1..=2 {
let r = app
.clone()
.oneshot(login_req("not-the-token"))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
}
let r = app
.clone()
.oneshot(login_req("not-the-token"))
.await
.unwrap();
assert_eq!(
r.status(),
StatusCode::UNAUTHORIZED,
"the 2 free ones, then the wait"
);
let r = app.clone().oneshot(login_req(TOKEN)).await.unwrap();
assert_eq!(r.status(), StatusCode::TOO_MANY_REQUESTS);
assert!(
r.headers().contains_key("retry-after"),
"a 429 without Retry-After is a riddle"
);
}
#[tokio::test]
async fn the_wait_ends_and_a_right_token_clears_it() {
let dir = tempfile::tempdir().unwrap();
let app = router(state_throttled(
dir.path(),
LoginThrottle::new(1, Duration::from_millis(30), Duration::from_millis(60)),
));
for _ in 1..=2 {
let _ = app
.clone()
.oneshot(login_req("not-the-token"))
.await
.unwrap();
}
let r = app.clone().oneshot(login_req(TOKEN)).await.unwrap();
assert_eq!(r.status(), StatusCode::TOO_MANY_REQUESTS, "still waiting");
tokio::time::sleep(Duration::from_millis(70)).await;
let r = app.clone().oneshot(login_req(TOKEN)).await.unwrap();
assert_eq!(r.status(), StatusCode::SEE_OTHER, "the wait is over");
let r = app
.clone()
.oneshot(login_req("not-the-token"))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED, "free attempts again");
}
#[tokio::test]
async fn everything_but_healthz_and_login_needs_the_cookie() {
let dir = tempfile::tempdir().unwrap();
let app = router(state(dir.path(), true));
for (method, uri) in [
("GET", "/"),
("GET", "/api/sessions"),
("GET", "/api/sessions/s1"),
("GET", "/api/models"),
("GET", "/api/update"),
("POST", "/api/model"),
("POST", "/api/chat"),
("POST", "/api/approvals/deadbeef"),
("POST", "/api/runs/deadbeef/cancel"),
("GET", "/nonexistent"),
] {
let r = app
.clone()
.oneshot(anon(method, uri).body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED, "{method} {uri}");
}
let r = app
.clone()
.oneshot(
anon("GET", "/api/sessions")
.header("cookie", format!("{SESSION_COOKIE}=forged"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
let r = app
.clone()
.oneshot(
anon("GET", "/api/sessions")
.header("cookie", format!("{SESSION_COOKIE}={TOKEN}"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
for uri in ["/", "/api/sessions"] {
let r = app
.clone()
.oneshot(get_req(uri, "127.0.0.1:8787"))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK, "{uri} with cookie");
}
let r = app
.clone()
.oneshot(anon("GET", "/healthz").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
}
#[tokio::test]
async fn healthz_tells_an_anonymous_caller_only_that_it_is_up() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("state");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(
root.join("cron.json"),
r#"{"jobs": {"backup-everything": {"runs": 1, "last_outcome": "failed"}}}"#,
)
.unwrap();
let store = SessionStore::new(dir.path().join("sessions"));
let agent = Some(Arc::new(Agent::new(
Arc::new(Canned),
Arc::new(ToolRegistry::default()),
store.clone(),
"sys".into(),
3,
)));
let st = Arc::new(
authed(agent, store, "test-<model>", None).with_cron_root(dir.path().to_path_buf()),
);
let app = router(st);
let public: serde_json::Value = serde_json::from_str(
&text(
app.clone()
.oneshot(anon("GET", "/healthz").body(Body::empty()).unwrap())
.await
.unwrap(),
)
.await,
)
.unwrap();
assert_eq!(public, json!({"status": "ok"}), "one word and nothing else");
let signed_in: serde_json::Value = serde_json::from_str(
&text(
app.oneshot(get_req("/healthz", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await,
)
.unwrap();
assert_eq!(signed_in["status"], "ok");
assert!(signed_in.get("version").is_some(), "{signed_in}");
assert_eq!(
signed_in["cron"]["failed_jobs"][0], "backup-everything",
"the detail is still there for the person who is signed in"
);
}
#[tokio::test]
async fn unauthenticated_index_is_the_login_form_without_the_app() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
st.store
.append("s1", &Message::user("secret preview"))
.unwrap();
let r = router(st)
.oneshot(anon("GET", "/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
let html = text(r).await;
assert!(html.contains("name=\"username\"") && html.contains("name=\"password\""));
assert!(html.contains("method=\"post\"") && html.contains("class=\"token\""));
assert!(!html.contains("secret preview") && !html.contains("test-<model"));
let r = router(state(dir.path(), true))
.oneshot(anon("GET", "/login").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
assert!(text(r).await.contains("name=\"password\""));
}
#[tokio::test]
async fn login_with_the_token_sets_a_strict_httponly_cookie_that_works() {
let dir = tempfile::tempdir().unwrap();
let app = router(state(dir.path(), true));
let r = app.clone().oneshot(login_req(TOKEN)).await.unwrap();
assert_eq!(r.status(), StatusCode::SEE_OTHER);
assert_eq!(r.headers()[header::LOCATION], "/");
let set = r.headers()[header::SET_COOKIE]
.to_str()
.unwrap()
.to_string();
assert!(set.starts_with(&format!("{SESSION_COOKIE}=")));
assert!(set.contains("HttpOnly") && set.contains("SameSite=Strict"));
assert!(set.contains("Path=/") && set.contains("Max-Age="));
assert!(!set.contains(TOKEN), "the cookie must not carry the token");
let cookie = set.split(';').next().unwrap();
let r = app
.clone()
.oneshot(
anon("GET", "/api/sessions")
.header("cookie", cookie)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
let r = app
.clone()
.oneshot(
anon("POST", "/logout")
.header("cookie", cookie)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert!(r.headers()[header::SET_COOKIE]
.to_str()
.unwrap()
.contains("Max-Age=0"));
let r = app
.clone()
.oneshot(
anon("GET", "/api/sessions")
.header("cookie", cookie)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn wrong_or_empty_token_is_rejected_without_a_cookie() {
let dir = tempfile::tempdir().unwrap();
let app = router(state_throttled(
dir.path(),
LoginThrottle::new(8, Duration::from_secs(1), Duration::from_secs(1)),
));
for req in [
login_req("nope"),
login_req(""),
login_req(&TOKEN[..TOKEN.len() - 1]),
login_req(&format!("{TOKEN}x")),
] {
let r = app.clone().oneshot(req).await.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
assert!(r.headers().get(header::SET_COOKIE).is_none());
}
let malformed = anon("POST", "/login")
.header("content-type", "application/x-www-form-urlencoded")
.body(Body::from("other=1"))
.unwrap();
let r = app.oneshot(malformed).await.unwrap();
assert!(r.status().is_client_error());
assert!(r.headers().get(header::SET_COOKIE).is_none());
}
#[tokio::test]
async fn login_from_a_foreign_origin_is_forbidden() {
let dir = tempfile::tempdir().unwrap();
let req = anon("POST", "/login")
.header("content-type", "application/x-www-form-urlencoded")
.header("origin", "https://evil.example.com")
.body(Body::from(format!("token={TOKEN}")))
.unwrap();
let r = router(state(dir.path(), true)).oneshot(req).await.unwrap();
assert_eq!(r.status(), StatusCode::FORBIDDEN);
assert!(r.headers().get(header::SET_COOKIE).is_none());
}
#[tokio::test]
async fn the_login_cookie_lives_as_long_as_the_configured_ttl() {
let dir = tempfile::tempdir().unwrap();
let store = SessionStore::new(dir.path().join("sessions"));
let st = AppState::new(
None,
store,
"m".into(),
None,
TOKEN.into(),
Duration::from_secs(3600),
);
let req = login_req(TOKEN);
let r = router(Arc::new(st)).oneshot(req).await.unwrap();
assert_eq!(r.status(), StatusCode::SEE_OTHER);
let cookie = r
.headers()
.get(header::SET_COOKIE)
.expect("a login sets a cookie")
.to_str()
.unwrap()
.to_string();
assert!(cookie.contains("Max-Age=3600"), "{cookie}");
assert!(cookie.contains("HttpOnly"), "{cookie}");
}
#[test]
fn login_ids_expire_and_are_capped() {
let logins = Logins::new(Duration::from_secs(
eclipse_core::config::DEFAULT_SESSION_TTL_HOURS * 60 * 60,
));
let first = logins.create().unwrap().0;
assert!(logins.is_valid(&first));
for _ in 0..MAX_LOGINS + 5 {
logins.create().unwrap();
}
assert!(logins.lock().len() <= MAX_LOGINS);
logins.lock().insert(
"old".into(),
Session {
expires: Instant::now() - Duration::from_secs(1),
csrf: String::new(),
},
);
assert!(!logins.is_valid("old"));
assert!(!logins.is_valid(""));
}
#[tokio::test]
async fn health_reports_configuration() {
let dir = tempfile::tempdir().unwrap();
let resp = router(state(dir.path(), true))
.oneshot(get_req("/healthz", "127.0.0.1:8787"))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let v: serde_json::Value = serde_json::from_str(&text(resp).await).unwrap();
assert_eq!(v["status"], "ok");
assert_eq!(v["configured"], true);
}
#[tokio::test]
async fn health_reports_the_cron_state_when_a_root_is_set() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("state");
std::fs::create_dir_all(&root).unwrap();
let jobs = root.join("cron.json");
std::fs::write(
&jobs,
r#"{"jobs": {"brief": {"runs": 1, "last_started_ms": 1000, "last_finished_ms": 1100, "last_outcome": "failed"}}}"#,
).unwrap();
let store = SessionStore::new(dir.path().join("sessions"));
let agent = Some(Arc::new(Agent::new(
Arc::new(Canned),
Arc::new(ToolRegistry::default()),
store.clone(),
"sys".into(),
3,
)));
let st = Arc::new(
authed(agent, store, "test-<model>", None).with_cron_root(dir.path().to_path_buf()),
);
let resp = router(st)
.oneshot(get_req("/healthz", "127.0.0.1:8787"))
.await
.unwrap();
let v: serde_json::Value = serde_json::from_str(&text(resp).await).unwrap();
assert_eq!(v["cron"]["failed_jobs"][0], "brief");
assert_eq!(v["cron"]["last_tick_ms"], 1000);
}
#[tokio::test]
async fn index_is_server_rendered_and_escaped() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
st.store.append("s1", &Message::user("<b>hi</b>")).unwrap();
let html = text(
router(st)
.oneshot(get_req("/", "localhost:8787"))
.await
.unwrap(),
)
.await;
assert!(html.contains("test-<model>"));
assert!(html.contains("data-id=\"s1\""));
assert!(
html.contains("class=\"name\"><b>hi</b>"),
"the label is escaped text, not markup"
);
assert!(
html.contains("data-updated=") && html.contains("class=\"session\""),
"a row says when it last moved, which is what the page sections by"
);
assert!(!html.contains("{{"));
}
#[tokio::test]
async fn the_page_cannot_spell_a_colour_of_its_own() {
let dir = tempfile::tempdir().unwrap();
let html = text(
router(state(dir.path(), true))
.oneshot(get_req("/", "localhost:8787"))
.await
.unwrap(),
)
.await;
let accent = eclipse_core::palette::ACCENT;
assert!(
html.contains(&format!(
"--accent:rgb({}, {}, {})",
accent.0, accent.1, accent.2
)),
"the accent arrives as a custom property from the table"
);
assert!(
!html.to_lowercase().contains("#5aa9ff"),
"the blue the dashboard used to be is gone, not merely overridden"
);
let styles = html.split("</style>").next().unwrap_or_default();
assert!(
!styles.contains(":#") && !styles.contains(": #"),
"no colour literal in the stylesheet: {:?}",
styles
.match_indices(":#")
.map(|(i, _)| &styles[i..(i + 8).min(styles.len())])
.collect::<Vec<_>>()
);
}
#[test]
fn only_the_pane_decides_where_the_pane_is() {
let assignments: Vec<&str> = INDEX_HTML
.lines()
.filter(|l| !l.trim_start().starts_with("//"))
.filter(|l| l.contains("log.scrollTop ="))
.collect();
assert_eq!(
assignments.len(),
1,
"the pane is scrolled from `pin()` and nowhere else, found: {assignments:?}"
);
let pin = INDEX_HTML
.split("function pin()")
.nth(1)
.expect("the page has a `pin()`");
let body = pin.split("\n }").next().unwrap_or_default();
assert!(
body.contains("log.scrollTop = log.scrollHeight"),
"the single assignment lives in `pin()`: {body:?}"
);
assert!(
INDEX_HTML.contains("log.addEventListener('scroll'"),
"the page learns where the reader is by listening to the pane"
);
}
#[test]
fn the_way_back_down_is_a_button_on_the_stats_row() {
assert!(
INDEX_HTML.contains(r#"<button id="jump" type="button" hidden"#),
"the control starts hidden and says what it is"
);
let css = INDEX_HTML
.split("#statsrow #yolo[hidden] { display:none; }")
.nth(1)
.expect("the stats row's rules come before the button's");
assert!(
css.contains("#jump { position:absolute") && css.contains("bottom:calc(100% + 8px)"),
"it floats over the transcript's corner, the way the model menu does"
);
assert!(
INDEX_HTML.contains("jump.addEventListener('click'"),
"and clicking it is wired"
);
}
#[test]
fn every_token_a_page_asks_for_is_one_the_palette_emits() {
let css = palette_css();
let emitted: Vec<&str> = css
.match_indices("--")
.filter_map(|(i, _)| {
let rest = &css[i + 2..];
let end = rest.find(':')?;
let name = &rest[..end];
if name.chars().next()?.is_ascii_alphanumeric() {
Some(name)
} else {
None
}
})
.collect();
assert!(
emitted.len() >= 14,
"the palette block reads back as {emitted:?}"
);
for (name, page) in [("index.html", INDEX_HTML), ("login.html", LOGIN_HTML)] {
let mut asked = std::collections::BTreeSet::new();
for (i, _) in page.match_indices("var(--") {
let rest = &page[i + "var(--".len()..];
let end = rest
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '-'))
.unwrap_or(rest.len());
asked.insert(&rest[..end]);
}
assert!(
asked.len() >= 6,
"{name} asks for {asked:?} — the scan found almost nothing to check"
);
for token in asked {
assert!(
emitted.contains(&token),
"{name} uses var(--{token}) and the palette emits no --{token}: \
the declaration would be dropped and the property would inherit"
);
}
}
}
#[test]
fn the_sign_in_page_is_the_same_brand() {
use eclipse_core::palette as p;
let page = login_html("token", "", "").0;
assert!(
page.contains(&format!(
"--accent:rgb({}, {}, {})",
p::ACCENT.0,
p::ACCENT.1,
p::ACCENT.2
)),
"the accent arrives from the table, on this page too"
);
assert!(page.contains(&format!(
"--bad:rgb({}, {}, {})",
p::BAD.0,
p::BAD.1,
p::BAD.2
)));
assert!(page.contains(&format!(
"--ink:rgb({}, {}, {})",
p::INK.0,
p::INK.1,
p::INK.2
)));
assert!(page.contains("src=\"/logo.svg\""), "the mark is on it");
assert!(page.contains("class=\"version\""), "and the version");
assert!(
page.contains(&format!("v{}", env!("CARGO_PKG_VERSION"))),
"the version is this build's"
);
let styles = page.split("</style>").next().unwrap_or_default();
assert!(
!styles.contains(":#") && !styles.contains(": #"),
"no colour literal in the sign-in sheet: {:?}",
styles
.match_indices(":#")
.map(|(i, _)| &styles[i..(i + 8).min(styles.len())])
.collect::<Vec<_>>()
);
for gone in ["#5aa2ff", "#5aa9ff"] {
assert!(
!page.to_lowercase().contains(gone),
"{gone} is the blue this page used to be, and is not this brand"
);
}
assert!(
!page.contains("{{"),
"a placeholder was left unfilled, and would render literally"
);
}
#[tokio::test]
async fn the_mark_is_served_in_the_palettes_colours() {
use eclipse_core::palette as p;
let dir = tempfile::tempdir().unwrap();
let app = router(state(dir.path(), true));
let r = app
.clone()
.oneshot(get_req("/logo.svg", "localhost:8787"))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
assert!(
r.headers()["content-type"]
.to_str()
.unwrap_or_default()
.starts_with("image/svg+xml"),
"{:?}",
r.headers()["content-type"]
);
let svg = text(r).await;
let hex = |c: (u8, u8, u8)| format!("#{:02X}{:02X}{:02X}", c.0, c.1, c.2);
for (label, colour) in [
("the accent", p::ACCENT),
("the wordmark's hot end", p::WORDMARK_TOP),
("the page background", p::BG),
] {
assert!(
svg.contains(&hex(colour)),
"{label} is {} in the served mark",
hex(colour)
);
}
for literal in ["#FF8A2B", "#FFB45E", "#FFF7E8", "#05060D"] {
assert!(
!svg.contains(literal),
"{literal} is the file's, not the brand's"
);
}
assert!(
svg.contains("feGaussianBlur"),
"the corona's blur is the file's"
);
let ico = app
.clone()
.oneshot(get_req("/favicon.ico", "localhost:8787"))
.await
.unwrap();
assert_eq!(ico.status(), StatusCode::OK);
assert_eq!(ico.headers()["content-type"], "image/x-icon");
let bytes = axum::body::to_bytes(ico.into_body(), 1 << 20)
.await
.unwrap();
assert_eq!(
bytes.len(),
FAVICON_ICO.len(),
"the committed icon, byte for byte"
);
assert!(bytes.starts_with(&[0, 0, 1, 0]), "an ICO header");
let page = text(
app.clone()
.oneshot(get_req("/", "localhost:8787"))
.await
.unwrap(),
)
.await;
assert_eq!(page.matches("rel=\"icon\"").count(), 1, "one icon link");
assert!(page.contains("href=\"/favicon.ico\""), "{page:.0}");
let login = text(
app.oneshot(anon("GET", "/login").body(Body::empty()).unwrap())
.await
.unwrap(),
)
.await;
assert!(
login.contains("rel=\"icon\""),
"the sign-in page too: {:?}",
&login[..login.len().min(400)]
);
}
#[tokio::test]
async fn the_header_carries_the_mark_and_a_readable_name() {
let dir = tempfile::tempdir().unwrap();
let html = text(
router(state(dir.path(), true))
.oneshot(get_req("/", "localhost:8787"))
.await
.unwrap(),
)
.await;
let h1 = html
.split("<h1>")
.nth(1)
.and_then(|rest| rest.split("</h1>").next())
.expect("the header");
assert!(h1.contains("id=\"mark\""), "{h1}");
assert!(h1.contains("src=\"/logo.svg\""), "{h1}");
assert!(
h1.contains("aria-hidden=\"true\""),
"the picture is not the name: {h1}"
);
assert!(h1.contains("alt=\"\""), "{h1}");
assert!(h1.contains(">eclipse"), "the word is still there: {h1}");
assert!(
h1.contains(env!("CARGO_PKG_VERSION")),
"the version is the binary's: {h1}"
);
}
#[tokio::test]
async fn a_turn_that_never_started_gives_the_composer_back() {
let dir = tempfile::tempdir().unwrap();
let html = text(
router(state(dir.path(), true))
.oneshot(get_req("/", "localhost:8787"))
.await
.unwrap(),
)
.await;
let refused = html
.split("if (!resp.ok) {")
.nth(1)
.and_then(|rest| rest.split("let finished = false;").next())
.expect("the refusal branch");
assert!(
refused.contains("restoreComposer();"),
"what the press took goes back: {refused}"
);
assert!(
refused.contains("if (echo) echo.remove();"),
"and the bubble the press drew goes with it"
);
assert!(
html.contains("const restoreComposer = () => {"),
"the snapshot is taken before anything is cleared"
);
let end = html
.split("} finally {")
.nth(1)
.and_then(|rest| rest.split("busy = false;").next())
.expect("the finally block");
assert!(
end.contains("deferredLine = null;"),
"an unlanded command line is not echoed into the next turn: {end}"
);
assert!(
html.contains("try { handle(event, JSON.parse(data)); }"),
"one bad event is contained where it happens"
);
assert!(
html.contains("await reader.cancel()"),
"the connection is closed on the way out"
);
assert!(
html.contains("let reader = null;"),
"and `finally` can reach the reader to do it"
);
}
#[tokio::test]
async fn the_model_picker_lives_in_the_stats_row() {
let dir = tempfile::tempdir().unwrap();
let html = text(
router(state(dir.path(), true))
.oneshot(get_req("/", "localhost:8787"))
.await
.unwrap(),
)
.await;
let aside = html
.split("<aside>")
.nth(1)
.and_then(|rest| rest.split("</aside>").next())
.expect("the sidebar");
assert!(
!aside.contains("id=\"model\""),
"the sidebar no longer carries a model control: {aside:.0}"
);
let row = html
.split("id=\"statsrow\"")
.nth(1)
.and_then(|rest| rest.split("<form id=\"form\"").next())
.expect("the stats row");
assert!(
row.contains("id=\"model\""),
"the button is in the row: {row}"
);
assert!(
row.contains("id=\"models\""),
"and its panel is anchored to it"
);
assert!(row.contains("role=\"menu\""), "a menu, not a panel");
assert!(html.contains("showReasoning"), "the reasoning submenu");
assert!(
html.contains("fetch('/api/reasoning')"),
"the words on offer are served, not spelled here"
);
assert!(
!html.contains("const EFFORTS"),
"the page owns no level list of its own"
);
assert!(
!html.contains("the effort is fixed when eclipse-web starts"),
"the page is no longer ignorant of the level"
);
assert!(
html.contains("eclipse-web restarts. config.toml is not touched"),
"the note says what a pick lasts for and what it does not write"
);
assert!(
html.contains("modelRow('effort · '"),
"a head row that names the level and cannot be picked"
);
assert!(
html.contains("id=\"effort\""),
"the row carries the effort the next turn will ask for"
);
assert!(html.contains(">effort not sent</span>"), "{html:.0}");
assert!(
!html.contains("{{EFFORT}}"),
"every placeholder is filled on the way out"
);
assert!(
html.contains("const EFFORT0 = effortEl.dataset.label;")
&& html.contains("const EFFORT_DETAIL0 = effortEl.title;"),
"the level and its sentence are read from the element, not written into the script"
);
assert!(
!html.contains("const EFFORT0 = \""),
"an interpolated literal is escaped for HTML and then parsed as JavaScript"
);
assert!(
html.contains("data-label=\"not sent\""),
"the label the script reads rides on the element"
);
assert!(
!html.contains("{{CTX}}") && !html.contains("CTX0"),
"the page-load window is gone, not merely unfilled"
);
assert!(
html.contains("ctx -- · first --"),
"an unmeasured row states no denominator"
);
assert!(
html.contains("li.dataset.cost = s.cost"),
"the sidebar's rows carry what the session last cost, so a click needs no request"
);
assert!(html.contains("focusRow"), "arrows walk the rows");
assert!(
html.contains("if (!modelSub.hidden) showModelList();"),
"esc is one level"
);
assert!(html.contains("modelLabel.focus()"), "and focus returns");
assert!(
!html.contains("· current' : level"),
"no guessed current effort"
);
}
#[tokio::test]
async fn the_transcript_column_is_the_pane() {
let dir = tempfile::tempdir().unwrap();
let html = text(
router(state(dir.path(), true))
.oneshot(get_req("/", "localhost:8787"))
.await
.unwrap(),
)
.await;
let styles = html.split("</style>").next().unwrap_or_default();
let rule = |selector: &str| -> String {
styles
.split(selector)
.nth(1)
.and_then(|rest| rest.split('}').next())
.map(|body| body.to_string())
.unwrap_or_default()
};
for (selector, what) in [(".msg {", "the transcript"), ("#form {", "the composer")] {
let body = rule(selector);
assert!(!body.is_empty(), "{selector} is styled");
assert!(
!body.contains("max-width"),
"{what} reaches the pane's edges: {selector} {body}"
);
assert!(
!body.contains("margin:0 auto"),
"{what} is not centred in a wider row: {selector} {body}"
);
}
assert!(
rule("#log {").contains("padding:20px"),
"one gutter, on the box that scrolls"
);
let assistant = rule(".msg.assistant {");
assert!(!assistant.contains("background"), "{assistant}");
assert!(!assistant.contains("border"), "{assistant}");
let user = rule(".msg.user {");
assert!(user.contains("background:var(--panel)"), "{user}");
assert!(user.contains("border-left:3px solid var(--user)"), "{user}");
assert!(user.contains("padding"), "{user}");
assert!(
rule(".msg.approval {").contains("padding"),
"the approval card"
);
assert!(
rule(".msg.error {").contains("padding"),
"the error verdict"
);
}
#[tokio::test]
async fn the_composer_has_one_control_with_two_states() {
let dir = tempfile::tempdir().unwrap();
let html = text(
router(state(dir.path(), true))
.oneshot(get_req("/", "localhost:8787"))
.await
.unwrap(),
)
.await;
let form = html
.split("<form id=\"form\"")
.nth(1)
.and_then(|rest| rest.split("</form>").next())
.expect("the composer form");
assert_eq!(form.matches("class=\"go\"").count(), 1, "{form}");
assert!(form.contains("id=\"go\""), "{form}");
assert!(!html.contains("id=\"send\""), "the second button is gone");
assert!(!html.contains("id=\"stop\""), "not hidden, removed");
let styles = html.split("</style>").next().unwrap_or_default();
let go = styles
.split("button.go {")
.nth(1)
.and_then(|rest| rest.split('}').next())
.unwrap_or_default();
assert!(go.contains("align-self:center"), "{go}");
assert!(go.contains("height:34px"), "{go}");
assert!(
html.contains("setGo('starting')"),
"the press is acknowledged"
);
assert!(
html.contains("setGo('stop')"),
"a run with an id can be stopped"
);
assert!(html.contains("setGo('idle')"), "and the control comes back");
assert!(
html.contains("'Stop the run in flight'"),
"the accessible name changes with the state"
);
assert!(
html.contains("/cancel"),
"the Stop state posts the route the server has"
);
assert!(
html.contains("nothing to cancel yet"),
"a press in the gap says so instead of doing nothing"
);
}
#[tokio::test]
async fn every_view_switch_closes_the_cron_pane() {
let dir = tempfile::tempdir().unwrap();
let html = text(
router(state(dir.path(), true))
.oneshot(get_req("/", "localhost:8787"))
.await
.unwrap(),
)
.await;
let helper = function_body(&html, "setView").expect("setView is the one switch");
for bit in [
"main').classList.toggle('cron'",
"cronBtn.classList.toggle('on'",
"aria-expanded",
"cronPane.hidden",
] {
assert!(helper.contains(bit), "`setView` sets {bit}: {helper}");
}
let writers = html.matches("classList.toggle('cron'").count();
assert_eq!(writers, 1, "the class is written in one place, not two");
let wrapper = function_body(&html, "showCron").expect("showCron still exists");
assert!(
wrapper.contains("setView(open ? 'cron' : 'session')"),
"{wrapper}"
);
let loads = function_body(&html, "loadSession").expect("loadSession");
assert!(
loads.contains("setView('session')"),
"opening a session closes the pane: {loads}"
);
let new_session = html
.split("getElementById('new').addEventListener")
.nth(1)
.and_then(|rest| rest.split("\n });").next())
.expect("the + New session handler");
assert!(new_session.contains("setView('session')"), "{new_session}");
let stream = html
.split("case 'session':")
.nth(1)
.and_then(|rest| rest.split("break;").next())
.expect("the SSE session case");
assert!(
stream.contains("setView('session')"),
"a run that starts a session takes the column: {stream}"
);
}
#[tokio::test]
async fn a_closed_section_reads_its_state_from_outside_the_rebuild() {
let dir = tempfile::tempdir().unwrap();
let html = text(
router(state(dir.path(), true))
.oneshot(get_req("/", "localhost:8787"))
.await
.unwrap(),
)
.await;
let groups = function_body(&html, "groupList").expect("groupList is the one partition");
assert!(
groups.contains("collapsed.has"),
"the rebuild consults the closed set: {groups}"
);
assert!(
!groups.contains("saveCollapsed"),
"the rebuild never writes the set back: {groups}"
);
assert!(
!groups.contains("list.children"),
"rows come from `master`, not from what is currently on screen: {groups}"
);
assert!(
html.contains("closest('.grouptoggle')"),
"one delegated listener toggles any heading"
);
let head = function_body(&html, "header").expect("header builds every heading");
for bit in [
"createElement('button')",
"aria-expanded",
"grouptoggle",
"\\u00b7",
] {
assert!(head.contains(bit), "a heading carries {bit}: {head}");
}
assert!(
html.contains("localStorage.setItem(COLLAPSED_KEY"),
"the set persists"
);
assert!(
html.contains("localStorage.getItem(COLLAPSED_KEY"),
"and is read back"
);
let mark = function_body(&html, "markActive").expect("markActive");
assert!(
mark.contains("isConnected"),
"a row that is not in the DOM marks its heading instead: {mark}"
);
}
fn function_body<'a>(html: &'a str, name: &str) -> Option<&'a str> {
let start = html.find(&format!("function {name}("))?;
let rest = &html[start..];
if let Some(line) = rest.split('\n').next() {
if line.contains('}') {
return Some(line);
}
}
let end = rest.find("\n }")? + 3;
Some(&rest[..end])
}
#[tokio::test]
async fn rejects_foreign_host_and_origin() {
let dir = tempfile::tempdir().unwrap();
let app = router(state(dir.path(), true));
let r = app
.clone()
.oneshot(get_req("/healthz", "evil.example.com"))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::FORBIDDEN);
let said = body_text(r).await;
assert!(
said.contains("evil.example.com") && said.contains("127.0.0.1"),
"{said}"
);
assert!(said.contains("SSH tunnel"), "{said}");
let req = HttpRequest::get("/healthz")
.header("host", "127.0.0.1:8787")
.header("origin", "https://evil.example.com")
.body(Body::empty())
.unwrap();
assert_eq!(
app.clone().oneshot(req).await.unwrap().status(),
StatusCode::OK
);
let req = HttpRequest::post("/api/model")
.header("host", "127.0.0.1:8787")
.header("origin", "http://127.0.0.1:9999")
.header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
.header("content-type", "application/json")
.body(Body::from(json!({ "model": "picked" }).to_string()))
.unwrap();
let r = app.clone().oneshot(req).await.unwrap();
assert_eq!(r.status(), StatusCode::FORBIDDEN);
let said = body_text(r).await;
assert!(
said.contains("Origin") && said.contains("9999") && said.contains("8787"),
"the message names both sides: {said}"
);
assert!(
!said.contains("is not 127.0.0.1"),
"not the Host refusal: {said}"
);
let req = HttpRequest::get("/healthz")
.header("host", "localhost:8787")
.header("origin", "http://localhost:8787")
.body(Body::empty())
.unwrap();
assert_eq!(app.oneshot(req).await.unwrap().status(), StatusCode::OK);
}
#[tokio::test]
async fn responses_carry_hardening_headers() {
let dir = tempfile::tempdir().unwrap();
let r = router(state(dir.path(), true))
.oneshot(get_req("/", "127.0.0.1:8787"))
.await
.unwrap();
let csp = r.headers()[header::CONTENT_SECURITY_POLICY]
.to_str()
.unwrap();
assert!(csp.contains("frame-ancestors 'none'") && csp.contains("default-src 'none'"));
assert!(
csp.contains("img-src 'self' data:;"),
"the mark, the icon and a message's picture are loadable: {csp}"
);
assert!(!csp.contains("img-src 'self' https:"), "{csp}");
assert!(csp.contains("script-src 'unsafe-inline';"), "{csp}");
assert_eq!(r.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
}
#[tokio::test]
async fn chat_is_rejected_when_all_slots_are_busy() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let _held = st
.chat_slots
.clone()
.acquire_many_owned(MAX_CONCURRENT_CHATS as u32)
.await
.unwrap();
let r = router(st)
.oneshot(chat_req(json!({"message": "x"})))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::TOO_MANY_REQUESTS);
}
#[tokio::test]
async fn chat_streams_events_and_persists_session() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let resp = router(st.clone())
.oneshot(chat_req(json!({"message": "hello"})))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = text(resp).await;
let order: Vec<_> = ["event: session", "event: message", "event: done"]
.iter()
.map(|m| {
body.find(m)
.unwrap_or_else(|| panic!("missing {m} in {body}"))
})
.collect();
assert!(order.windows(2).all(|w| w[0] < w[1]));
assert!(body.contains("canned reply"));
let list = st.store.list().unwrap();
assert_eq!(list.len(), 1);
assert_eq!(list[0].messages, 2);
}
#[tokio::test]
async fn a_large_paste_is_one_chip_and_the_model_still_gets_the_text() {
use eclipse_core::paste::{chip_for, expand, fits_inline, Paste, PASTE_INLINE_LIMIT};
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let page = text(
router(st.clone())
.oneshot(get_req("/", "localhost:8787"))
.await
.unwrap(),
)
.await;
assert!(
page.contains(&format!("data-paste-limit=\"{PASTE_INLINE_LIMIT}\"")),
"the composer reads its limit from `eclipse_core::paste`"
);
assert!(
!page.contains("{{PASTE_LIMIT}}"),
"the placeholder was filled"
);
for needle in [
"function fitsInline",
"function chipFor",
"function expandPastes",
"addEventListener('paste'",
"function userMessage",
"PASTE_FOLD_LINES",
] {
assert!(page.contains(needle), "the composer's paste rule: {needle}");
}
let log: String = (1..=200).map(|i| format!("line {i}\n")).collect();
assert!(!fits_inline(&log));
let chip = chip_for(&log, 1);
assert_eq!(
chip,
format!("[Pasted #1: 200 line(s), {} chars]", log.chars().count())
);
assert_eq!(
expand(
&format!("why is this failing? {chip}"),
&[Paste {
chip: chip.clone(),
text: log.clone(),
}]
),
format!("why is this failing? {log}")
);
let message = format!("here is the log:\n{log}");
let resp = router(st.clone())
.oneshot(chat_req(json!({ "message": message })))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert!(text(resp).await.contains("event: done"));
let list = st.store.list().unwrap();
assert_eq!(list.len(), 1);
let stored = st.store.load(&list[0].id).unwrap();
let first = &stored[0];
assert_eq!(first.role, eclipse_core::message::Role::User);
let content = first.content.as_deref().unwrap_or_default();
assert_eq!(content, message, "every character, and no chip");
assert!(
!content.contains("[Pasted"),
"a chip is a display, not a message"
);
}
#[tokio::test]
async fn a_body_over_the_limit_is_refused_by_name() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let too_big = CHAT_BODY_LIMIT * 2;
let r = router(st)
.oneshot(
HttpRequest::post("/api/chat")
.header("host", "127.0.0.1:8787")
.header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
.header("content-type", "application/json")
.header("content-length", too_big.to_string())
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(r.status(), StatusCode::PAYLOAD_TOO_LARGE);
let body = text(r).await;
assert!(body.contains("that message is"), "{body}");
let named = format!("{:.1} MB limit", CHAT_BODY_LIMIT as f64 / (1024.0 * 1024.0));
assert!(
body.contains(&named),
"the limit is named in the sentence: {body}"
);
assert!(
body.contains("smaller pictures") && body.contains("send its path"),
"and so is what to do instead: {body}"
);
let r = router(state(dir.path(), true))
.oneshot(chat_req(json!({ "message": "small" })))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
}
#[tokio::test]
async fn chat_emits_a_delta_event_per_chunk_before_the_final_message() {
let dir = tempfile::tempdir().unwrap();
let store = SessionStore::new(dir.path().join("sessions"));
let agent = Agent::new(
Arc::new(Streaming),
Arc::new(ToolRegistry::default()),
store.clone(),
"sys".into(),
3,
);
let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
let body = text(
router(st)
.oneshot(chat_req(json!({"message": "hi"})))
.await
.unwrap(),
)
.await;
let at = |needle: &str| {
body.find(needle)
.unwrap_or_else(|| panic!("missing {needle} in {body}"))
};
assert_eq!(body.matches("event: delta").count(), 2);
assert!(at("data: {\"text\":\"tok\"}") < at("data: {\"text\":\"ens\"}"));
assert!(at("event: delta") < at("event: message"));
assert!(body.contains("data: {\"text\":\"tokens\"}"));
}
#[tokio::test]
async fn the_stats_event_carries_the_numbers_the_footer_prints() {
let dir = tempfile::tempdir().unwrap();
let store = SessionStore::new(dir.path().join("sessions"));
let agent = Agent::new(
Arc::new(Measured),
Arc::new(ToolRegistry::default()),
store.clone(),
"sys".into(),
3,
);
let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
let body = text(
router(st)
.oneshot(chat_req(json!({"message": "hi"})))
.await
.unwrap(),
)
.await;
assert!(body.contains("event: stats"), "{body}");
let stats = stats_payload(&body);
assert_eq!(stats["prompt_tokens"], json!(30000));
assert_eq!(stats["completion_tokens"], json!(120));
assert_eq!(stats["cached_tokens"], json!(19000));
assert_eq!(stats["latency_ms"], json!(2900));
assert_eq!(
stats["tokens_per_sec"],
json!(48.0),
"120 tokens over the 2.5 s the server timed"
);
assert!(
stats["ttft_ms"].as_u64().unwrap_or(0) >= 20,
"the client's own first-token time: {}",
stats["ttft_ms"]
);
assert!(
stats["context_tokens"].as_u64().unwrap() > 0,
"the assembled prompt is a size, not a placeholder"
);
assert_eq!(
stats["budget_tokens"],
json!(0),
"no budget set is 0, and the footer draws that as `ctx <used>` with no denominator"
);
assert_eq!(
stats["ctx"],
json!("ctx 30.0K tokens · no budget"),
"the page's context field is the shared reading: {}",
stats["ctx"]
);
assert_eq!(stats["window_tokens"], json!(0), "nobody stated a window");
assert_eq!(
stats["effort"],
json!("not sent"),
"this agent has no provider configuration, so nothing is sent — and the label says \
that rather than naming a level"
);
assert_eq!(stats["effort_session"], json!(false), "nothing overrode it");
assert!(
!stats["effort_detail"].as_str().unwrap_or("").is_empty(),
"the long sentence travels for the row's title: {}",
stats["effort_detail"]
);
assert!(
INDEX_HTML.contains(
"case 'stats':\n // A turn in flight is the one row that is current"
) && INDEX_HTML.contains("paintLive(data);")
&& INDEX_HTML.contains("if (data.effort) setEffort("),
"the page has to put the event in the bar, or the numbers go nowhere"
);
}
#[tokio::test]
async fn the_context_bar_ends_at_the_window_and_marks_the_threshold_inside_it() {
let dir = tempfile::tempdir().unwrap();
let store = SessionStore::new(dir.path().join("sessions"));
let agent = Agent::new(
Arc::new(Measured),
Arc::new(ToolRegistry::default()),
store.clone(),
"sys".into(),
3,
)
.with_context_policy(0.85, 20, 328_000, 120_000);
let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
let body = text(
router(st)
.oneshot(chat_req(json!({"message": "hi"})))
.await
.unwrap(),
)
.await;
let stats = stats_payload(&body);
assert_eq!(
stats["window_tokens"],
json!(328_000),
"the window is the end"
);
let ctx = stats["ctx"].as_str().unwrap_or_default();
assert!(
ctx.starts_with("ctx 30.0K/328K "),
"the prompt out of the window, not out of the rail: {ctx}"
);
assert!(
ctx.contains('│'),
"the compaction threshold is a mark inside the bar, not its end: {ctx}"
);
assert!(
ctx.ends_with(" 9%"),
"the same percentage the CLI prints: {ctx}"
);
assert!(!ctx.contains("compacts at"));
}
fn stats_payload(body: &str) -> serde_json::Value {
let data = body
.lines()
.skip_while(|l| *l != "event: stats")
.nth(1)
.and_then(|l| l.strip_prefix("data: "))
.unwrap_or_else(|| panic!("no stats event in {body}"));
serde_json::from_str(data).unwrap()
}
#[tokio::test]
async fn a_silent_server_sends_nulls_and_the_footer_draws_dashes_for_them() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let body = text(
router(st)
.oneshot(chat_req(json!({"message": "hi"})))
.await
.unwrap(),
)
.await;
for needle in [
"\"cached_tokens\":null",
"\"ttft_ms\":null",
"\"tokens_per_sec\":null",
"\"prompt_tokens\":null",
] {
assert!(
body.contains(needle),
"an unreported field is null, never a made-up number: {needle} in {body}"
);
}
for needle in [
"id=\"stats\"",
"const UNKNOWN = '--'",
"const ctx = d.ctx || 'ctx --';",
"'first ' + duration(d.ttft_ms)",
] {
assert!(INDEX_HTML.contains(needle), "the page draws {needle}");
}
}
#[tokio::test]
async fn reasoning_and_argument_fragments_are_their_own_events_before_the_reply() {
let dir = tempfile::tempdir().unwrap();
let store = SessionStore::new(dir.path().join("sessions"));
let agent = Agent::new(
Arc::new(ThinksAloud),
Arc::new(ToolRegistry::default()),
store.clone(),
"sys".into(),
3,
);
let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
let body = text(
router(st)
.oneshot(chat_req(json!({"message": "hi"})))
.await
.unwrap(),
)
.await;
let at = |needle: &str| {
body.find(needle)
.unwrap_or_else(|| panic!("missing {needle} in {body}"))
};
assert!(body.contains("event: reasoning"), "{body}");
assert!(
body.contains("data: {\"text\":\"weighing \"}")
&& body.contains("data: {\"text\":\"it\"}"),
"each reasoning fragment is its own event: {body}"
);
assert!(
body.contains("event: tool_call_delta")
&& body.contains("data: {\"index\":0,\"json\":\"{\\\"path\\\"\"}"),
"the argument fragment keeps its call index: {body}"
);
assert!(
at("event: reasoning") < at("event: tool_call_delta"),
"reasoning comes before the call it explains"
);
assert!(at("event: tool_call_delta") < at("event: message"));
for handler in [
"case 'reasoning'",
"case 'tool_call_delta'",
"addThinking(",
"addCall(",
] {
assert!(INDEX_HTML.contains(handler), "the page handles {handler}");
}
for rule in ["details.reasoning", "details.tool", "#thinkall"] {
assert!(INDEX_HTML.contains(rule), "the page styles {rule}");
}
assert!(
INDEX_HTML.contains("function addThinking") && INDEX_HTML.contains("function addCall"),
"a reload rebuilds the same folds the stream built"
);
assert!(
INDEX_HTML.contains("m.reasoning_content"),
"a reloaded session shows the reasoning it stored"
);
}
struct ThinksAloud;
#[async_trait]
impl ChatProvider for ThinksAloud {
async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
unreachable!()
}
async fn chat_stream(
&self,
_: &[Message],
_: &[ToolSpec],
on_delta: eclipse_core::stream::DeltaFn<'_>,
) -> CoreResult<Message> {
on_delta(eclipse_core::stream::Delta::Reasoning("weighing ".into()));
on_delta(eclipse_core::stream::Delta::Reasoning("it".into()));
on_delta(eclipse_core::stream::Delta::ToolCallArgs {
index: 0,
json: "{\"path\"".into(),
});
on_delta(eclipse_core::stream::Delta::Text("done".into()));
Ok(Message::assistant("done"))
}
}
#[tokio::test]
async fn context_trimmed_event_reports_the_judgement_pass_and_the_handoff() {
let dir = tempfile::tempdir().unwrap();
let store = SessionStore::new(dir.path().join("sessions"));
for i in 0..3 {
store
.append("s", &Message::user(format!("old{i} {}", "y".repeat(400))))
.unwrap();
store.append("s", &Message::assistant("ok")).unwrap();
}
let agent = Agent::new(
Arc::new(Canned),
Arc::new(ToolRegistry::default()),
store.clone(),
"sys".into(),
3,
)
.with_context_budget(150)
.with_judgement(false, std::time::Duration::from_secs(1));
let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
let body = text(
router(st)
.oneshot(chat_req(json!({"message": "hi", "session_id": "s"})))
.await
.unwrap(),
)
.await;
assert!(body.contains("event: context_trimmed"), "{body}");
assert!(
body.contains("\"judgement\":\"off\"")
&& body.contains("\"judgement_bullets\":0")
&& body.contains("\"judgement_error\":null"),
"{body}"
);
assert!(
body.contains("\"memory\":\"saved\"") && body.contains("\"memory_error\":null"),
"{body}"
);
assert!(
!body.contains("summarized") && !body.contains("summary_error"),
"the summary path is gone from the wire too: {body}"
);
assert!(body.contains("event: message"));
}
fn approval_app(dir: &std::path::Path, timeout: Duration) -> (Router, Shared) {
use eclipse_core::config::ToolsConfig;
std::fs::create_dir_all(dir.join("ws")).unwrap();
let store = SessionStore::new(dir.join("sessions"));
let call = Message::assistant_tool_calls(
None,
vec![eclipse_core::message::ToolCall {
id: "c1".into(),
kind: "function".into(),
function: eclipse_core::message::FunctionCall {
name: "write_file".into(),
arguments: r#"{"path":"o.txt","content":"x"}"#.into(),
},
}],
);
let cfg = ToolsConfig {
write_file: eclipse_core::config::Policy::Ask,
..ToolsConfig::default()
};
let agent = Agent::new(
Scripted::new(vec![call, Message::assistant("finished")]),
Arc::new(ToolRegistry::from_config(&cfg, dir.join("ws"))),
store.clone(),
"sys".into(),
4,
);
let st = Arc::new(
authed(Some(Arc::new(agent)), store, "m", None).with_approval_timeout(timeout),
);
(router(st.clone()), st)
}
async fn read_until(
body: &mut (impl Stream<Item = Result<axum::body::Bytes, axum::Error>> + Unpin),
seen: &mut String,
needle: &str,
) {
while !seen.contains(needle) {
let chunk = tokio::time::timeout(Duration::from_secs(5), body.next())
.await
.unwrap_or_else(|_| panic!("timed out waiting for {needle} in {seen}"))
.unwrap_or_else(|| panic!("stream ended before {needle}: {seen}"))
.unwrap();
seen.push_str(&String::from_utf8_lossy(&chunk));
}
}
fn request_id(seen: &str) -> String {
let at = seen.find("event: approval_request").unwrap();
let data = seen[at..]
.lines()
.nth(1)
.unwrap()
.trim_start_matches("data: ");
serde_json::from_str::<serde_json::Value>(data).unwrap()["id"]
.as_str()
.unwrap()
.to_string()
}
fn decision_req(id: &str, body: serde_json::Value) -> HttpRequest<Body> {
HttpRequest::post(format!("/api/approvals/{id}"))
.header("host", "127.0.0.1:8787")
.header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap()
}
async fn run_with_decision(approved: bool) -> (String, bool, usize) {
let dir = tempfile::tempdir().unwrap();
let (app, st) = approval_app(dir.path(), Duration::from_secs(30));
let resp = app
.clone()
.oneshot(chat_req(json!({"message": "write it"})))
.await
.unwrap();
let mut body = resp.into_body().into_data_stream();
let mut seen = String::new();
read_until(&mut body, &mut seen, "event: approval_request").await;
read_until(&mut body, &mut seen, "\"tool\":\"write_file\"}").await;
let id = request_id(&seen);
assert!(!dir.path().join("ws/o.txt").exists());
let r = app
.clone()
.oneshot(decision_req(&id, json!({"approved": approved})))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
while let Some(chunk) = body.next().await {
seen.push_str(&String::from_utf8_lossy(&chunk.unwrap()));
}
let again = app
.oneshot(decision_req(&id, json!({"approved": true})))
.await
.unwrap();
assert_eq!(again.status(), StatusCode::NOT_FOUND);
let written = dir.path().join("ws/o.txt").exists();
(seen, written, st.approvals.len())
}
#[tokio::test]
async fn approving_an_ask_tool_in_the_ui_runs_it() {
let (events, written, pending) = run_with_decision(true).await;
assert!(written, "{events}");
assert!(events.contains(r#""outcome":"approved""#), "{events}");
assert!(events.contains("event: done") && events.contains("finished"));
assert_eq!(pending, 0);
assert!(
events.contains(r#""summary":"write_file o.txt · 1 B""#),
"the call's statement travels with it: {events}"
);
}
#[tokio::test]
async fn denying_an_ask_tool_in_the_ui_declines_it_and_the_run_continues() {
let (events, written, pending) = run_with_decision(false).await;
assert!(!written, "{events}");
assert!(events.contains(r#""outcome":"denied""#), "{events}");
assert!(events.contains("declined"), "{events}");
assert!(events.contains("finished"));
assert_eq!(pending, 0);
}
#[tokio::test]
async fn unanswered_approval_times_out_declined_and_is_cleaned_up() {
let dir = tempfile::tempdir().unwrap();
let (app, st) = approval_app(dir.path(), Duration::from_millis(100));
let resp = app
.clone()
.oneshot(chat_req(json!({"message": "write it"})))
.await
.unwrap();
let events = text(resp).await;
assert!(events.contains(r#""outcome":"timeout""#), "{events}");
assert!(events.contains("declined") && events.contains("event: done"));
assert!(!dir.path().join("ws/o.txt").exists());
assert_eq!(st.approvals.len(), 0);
let id = request_id(&events);
let late = app
.oneshot(decision_req(&id, json!({"approved": true})))
.await
.unwrap();
assert_eq!(late.status(), StatusCode::NOT_FOUND);
assert!(!dir.path().join("ws/o.txt").exists());
}
#[tokio::test]
async fn disconnecting_while_an_approval_is_pending_frees_the_run() {
let dir = tempfile::tempdir().unwrap();
let (app, st) = approval_app(dir.path(), Duration::from_secs(60));
let resp = app
.oneshot(chat_req(json!({"message": "write it"})))
.await
.unwrap();
let mut body = resp.into_body().into_data_stream();
let mut seen = String::new();
read_until(&mut body, &mut seen, "event: approval_request").await;
assert_eq!(st.approvals.len(), 1);
drop(body);
for _ in 0..100 {
if st.approvals.len() == 0 && st.chat_slots.available_permits() == MAX_CONCURRENT_CHATS
{
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert_eq!(st.approvals.len(), 0);
assert_eq!(st.chat_slots.available_permits(), MAX_CONCURRENT_CHATS);
assert!(!dir.path().join("ws/o.txt").exists());
}
#[tokio::test]
async fn approval_endpoint_rejects_bad_ids_and_bodies() {
let dir = tempfile::tempdir().unwrap();
let (app, _) = approval_app(dir.path(), Duration::from_secs(1));
let r = app
.clone()
.oneshot(decision_req("deadbeef", json!({"approved": true})))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::NOT_FOUND);
let r = app
.clone()
.oneshot(decision_req("not-hex!", json!({"approved": true})))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::BAD_REQUEST);
let r = app
.clone()
.oneshot(decision_req("deadbeef", json!({"approve": true})))
.await
.unwrap();
assert!(r.status().is_client_error());
}
#[tokio::test]
async fn chat_validates_input_and_configuration() {
let dir = tempfile::tempdir().unwrap();
let app = router(state(dir.path(), true));
let r = app
.clone()
.oneshot(chat_req(json!({"message": " "})))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::BAD_REQUEST);
let r = app
.clone()
.oneshot(chat_req(json!({"message": "x", "session_id": "../x"})))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::BAD_REQUEST);
let r = app
.clone()
.oneshot(chat_req(json!({"message": "/bg count the files"})))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
let said = text(r).await;
assert!(
said.contains("only in the full-screen interface and the plain REPL"),
"{said}"
);
let r = router(state(dir.path(), false))
.oneshot(chat_req(json!({"message": "x"})))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::SERVICE_UNAVAILABLE);
assert!(text(r).await.contains("base_url"));
}
#[tokio::test]
async fn renamed_sessions_show_their_title() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
st.store
.append("s1", &Message::user("first words"))
.unwrap();
st.store.rename("s1", "Trip <plan>").unwrap();
let app = router(st);
let html = text(
app.clone()
.oneshot(get_req("/", "127.0.0.1:1"))
.await
.unwrap(),
)
.await;
assert!(
html.contains("data-id=\"s1\"") && html.contains("class=\"name\">Trip <plan>"),
"{html}"
);
let r = app
.clone()
.oneshot(get_req("/api/sessions", "127.0.0.1:1"))
.await
.unwrap();
let v: serde_json::Value = serde_json::from_str(&text(r).await).unwrap();
assert_eq!(v[0]["title"], "Trip <plan>");
assert_eq!(v[0]["preview"], "first words");
}
#[tokio::test]
async fn search_finds_the_message_and_names_its_session() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
st.store
.append("s1", &Message::user("the quick brown fox"))
.unwrap();
st.store
.append("s2", &Message::user("nothing here"))
.unwrap();
let app = router(st);
for path in ["/api/search", "/api/search?q=", "/api/search?q=%20%20"] {
let r = app
.clone()
.oneshot(get_req(path, "127.0.0.1:1"))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK, "{path}");
assert_eq!(text(r).await.trim(), "[]", "{path}");
}
let r = app
.clone()
.oneshot(get_req("/api/search?q=brown", "127.0.0.1:1"))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
let body = text(r).await;
assert!(body.contains("\"s1\""), "{body}");
assert!(
!body.contains("\"s2\""),
"only the matching session: {body}"
);
assert!(
body.contains("brown"),
"the snippet carries the match: {body}"
);
assert!(
body.contains("\"seq\":0"),
"the hit says where it is: {body}"
);
let r = app
.clone()
.oneshot(get_req("/api/search?q=zebra", "127.0.0.1:1"))
.await
.unwrap();
assert_eq!(text(r).await.trim(), "[]");
}
#[tokio::test]
async fn search_demands_a_login_like_everything_else() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), false);
let app = router(st);
let req = HttpRequest::get("/api/search?q=anything")
.header("host", "127.0.0.1:1")
.body(Body::empty())
.unwrap();
let r = app.oneshot(req).await.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
}
#[test]
fn the_page_has_a_cron_pane_that_talks_to_the_cron_routes() {
for needle in [
"id=\"cron\"",
"id=\"cronpane\"",
"id=\"cronrows\"",
"id=\"cronform\"",
"id=\"cr-schedule\"",
] {
assert!(INDEX_HTML.contains(needle), "the pane has {needle}");
}
for route in [
"'/api/cron'",
"'/api/cron/' + encodeURIComponent(name) + '/run'",
"'/api/cron/' + encodeURIComponent(name) + '/enabled'",
"'/api/cron/' + encodeURIComponent(name) + '/logs?limit=3'",
] {
assert!(INDEX_HTML.contains(route), "the pane calls {route}");
}
assert!(!INDEX_HTML.contains("cronRows.innerHTML"));
assert!(INDEX_HTML.contains("pre.textContent = body.trim()"));
}
#[test]
fn the_page_has_a_find_box_that_draws_hits_as_text() {
assert!(INDEX_HTML.contains("id=\"find\""), "a box to type in");
assert!(INDEX_HTML.contains("/api/search?q="), "wired to the route");
assert!(INDEX_HTML.contains("snip.textContent ="));
assert!(
!INDEX_HTML.contains("list.innerHTML"),
"no markup is rebuilt from data"
);
}
#[tokio::test]
async fn search_is_bounded_and_says_so() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
for i in 0..5 {
st.store
.append(&format!("s{i}"), &Message::user("repeated needle"))
.unwrap();
}
let app = router(st);
let r = app
.clone()
.oneshot(get_req("/api/search?q=needle&limit=2", "127.0.0.1:1"))
.await
.unwrap();
let body = text(r).await;
let hits: serde_json::Value = serde_json::from_str(&body).unwrap();
assert_eq!(hits.as_array().unwrap().len(), 2, "{body}");
let r = app
.clone()
.oneshot(get_req("/api/search?q=needle&limit=99999", "127.0.0.1:1"))
.await
.unwrap();
let body = text(r).await;
let hits: serde_json::Value = serde_json::from_str(&body).unwrap();
assert!(hits.as_array().unwrap().len() <= 100, "{body}");
}
#[tokio::test]
async fn the_picker_lists_what_the_endpoint_serves_and_names_the_one_in_use() {
let dir = tempfile::tempdir().unwrap();
let base = serve_models(&[("small", None), ("big", None)]).await;
let (st, _agent) = provider_state(dir.path(), &base, "small");
let app = router(st);
let r = app
.clone()
.oneshot(get_req("/api/models", "127.0.0.1:8787"))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
let body = text(r).await;
let v: serde_json::Value = serde_json::from_str(&body).unwrap();
assert_eq!(v["models"], json!(["small", "big"]), "{body}");
assert_eq!(v["model"], "small", "the one the next turn uses: {body}");
assert_eq!(v["configured"], "small", "{body}");
}
#[tokio::test]
async fn choosing_a_model_changes_the_next_turn_and_leaves_the_file_alone() {
let dir = tempfile::tempdir().unwrap();
let (st, agent) = provider_state(dir.path(), "http://127.0.0.1:9/v1", "configured");
let app = router(st);
let r = app
.clone()
.oneshot(model_req(json!({ "model": "picked" })))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
let body = text(r).await;
assert!(body.contains("\"model\":\"picked\""), "{body}");
assert_eq!(agent.model().as_deref(), Some("picked"));
let page = text(
app.clone()
.oneshot(get_req("/", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
assert!(
page.contains(">picked</button>") || page.contains(">picked\n"),
"the model button follows the choice: {page:.0}"
);
let r = app
.clone()
.oneshot(model_req(json!({ "model": null })))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
assert_eq!(agent.model().as_deref(), Some("configured"));
assert!(dir.path().join("sessions").exists(), "state untouched");
assert!(!dir.path().join("config.toml").exists());
}
#[tokio::test]
async fn a_body_that_names_no_model_is_refused_rather_than_read_as_a_reset() {
let dir = tempfile::tempdir().unwrap();
let (st, agent) = provider_state(dir.path(), "http://127.0.0.1:9/v1", "configured");
let app = router(st);
for body in [json!({}), json!({ "model": " " }), json!({ "model": "" })] {
let r = app.clone().oneshot(model_req(body.clone())).await.unwrap();
assert_eq!(r.status(), StatusCode::BAD_REQUEST, "{body}");
}
assert_eq!(agent.model().as_deref(), Some("configured"));
}
#[tokio::test]
async fn a_model_cannot_be_picked_on_an_agent_with_no_provider_configuration() {
let dir = tempfile::tempdir().unwrap();
let app = router(state(dir.path(), true));
let r = app
.clone()
.oneshot(model_req(json!({ "model": "picked" })))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::BAD_REQUEST);
assert!(
text(r)
.await
.contains("not built from a provider configuration"),
"the reason says what is missing"
);
}
#[tokio::test]
async fn an_endpoint_that_cannot_be_reached_says_so_instead_of_listing_nothing() {
let dir = tempfile::tempdir().unwrap();
let (st, _agent) = provider_state(dir.path(), "http://127.0.0.1:9/v1", "m");
let app = router(st);
let r = app
.clone()
.oneshot(get_req("/api/models", "127.0.0.1:8787"))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::BAD_GATEWAY);
let body = text(r).await;
assert!(body.contains("\"error\""), "{body}");
}
#[tokio::test]
async fn a_command_needs_no_provider() {
let dir = tempfile::tempdir().unwrap();
let app = router(state(dir.path(), false));
let events = notices(
app.clone()
.oneshot(chat_req(json!({"message": "/help"})))
.await
.unwrap(),
)
.await;
assert_eq!(events[0].1["kind"], json!("command"), "{events:?}");
assert!(events[0].1["text"].as_str().unwrap().contains("/settings"));
let events = notices(
app.clone()
.oneshot(chat_req(json!({"message": "/model"})))
.await
.unwrap(),
)
.await;
assert_eq!(events[0].1["kind"], json!("refusal"));
assert!(events[0].1["text"]
.as_str()
.unwrap()
.contains("provider.base_url"));
let r = app
.clone()
.oneshot(chat_req(json!({"message": "hello"})))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::SERVICE_UNAVAILABLE);
}
async fn notices(resp: Response) -> Vec<(String, serde_json::Value)> {
let body = text(resp).await;
let mut out = Vec::new();
for block in body.split("\n\n") {
let mut event = "message".to_string();
let mut data = String::new();
for line in block.split('\n') {
if let Some(rest) = line.strip_prefix("event:") {
event = rest.trim().to_string();
} else if let Some(rest) = line.strip_prefix("data:") {
data.push_str(rest.trim());
}
}
if !data.is_empty() {
out.push((event, serde_json::from_str(&data).unwrap_or_default()));
}
}
out
}
#[tokio::test]
async fn a_bang_line_is_refused_and_nothing_runs() {
let dir = tempfile::tempdir().unwrap();
let cfg = eclipse_core::config::ProviderConfig {
base_url: "http://127.0.0.1:9/v1".into(),
model: "m".into(),
..Default::default()
};
let (st, _agent) = agent_state(dir.path(), cfg, Default::default());
let app = router(st);
for line in ["!ls", " !rm -rf /", "!!echo hi"] {
let events = notices(
app.clone()
.oneshot(chat_req(json!({ "message": line })))
.await
.unwrap(),
)
.await;
assert_eq!(events.len(), 2, "{line}: {events:?}");
assert_eq!(events[0].0, "notice", "{line}");
assert_eq!(events[0].1["kind"], json!("refusal"), "{line}: {events:?}");
let said = events[0].1["text"].as_str().unwrap();
assert!(said.contains("terminal and nowhere else"), "{line}: {said}");
assert_eq!(events[1].0, "done", "{line}: the composer returns to idle");
assert!(
!events
.iter()
.any(|(kind, _)| kind == "session" || kind == "error"),
"{line}: nothing was started"
);
}
let r = app
.clone()
.oneshot(chat_req(json!({ "message": "fix the bug!" })))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK, "a message is a message");
let events = notices(r).await;
assert!(
!events
.iter()
.any(|(_, data)| data["kind"] == json!("refusal")),
"prose is not refused by the bang rule: {events:?}"
);
}
#[tokio::test]
async fn the_composer_speaks_the_table_and_a_command_is_a_row() {
let dir = tempfile::tempdir().unwrap();
let cfg = eclipse_core::config::ProviderConfig {
base_url: "http://127.0.0.1:9/v1".into(),
model: "m".into(),
..Default::default()
};
let (st, agent) = agent_state(dir.path(), cfg, Default::default());
let app = router(st);
let events = notices(
app.clone()
.oneshot(chat_req(json!({"message": "/help"})))
.await
.unwrap(),
)
.await;
assert_eq!(events.len(), 2, "{events:?}");
assert_eq!(events[0].0, "notice");
assert_eq!(events[1].0, "done", "the composer returns to idle");
let help = events[0].1["text"].as_str().unwrap();
assert_eq!(events[0].1["kind"], json!("command"));
assert!(help.contains("/reasoning"), "{help}");
assert!(!help.contains("!command"), "no bang in a browser: {help}");
assert!(
!help.contains("/resume"),
"a terminal-only verb is not in this list: {help}"
);
let events = notices(
app.clone()
.oneshot(chat_req(json!({"message": "/reasoning"})))
.await
.unwrap(),
)
.await;
assert!(events[0].1["text"]
.as_str()
.unwrap()
.contains("effort: medium"));
let events = notices(
app.clone()
.oneshot(chat_req(json!({"message": "/reasoning high"})))
.await
.unwrap(),
)
.await;
assert!(events[0].1["text"]
.as_str()
.unwrap()
.contains("effort: high"));
assert_eq!(agent.reasoning().effort(), Some("high".to_string()));
let events = notices(
app.clone()
.oneshot(chat_req(json!({"message": "/reasoning none"})))
.await
.unwrap(),
)
.await;
assert_eq!(events[0].1["kind"], json!("refusal"));
assert!(events[0].1["text"]
.as_str()
.unwrap()
.contains("this route takes"));
let events = notices(
app.clone()
.oneshot(chat_req(json!({"message": "/resume"})))
.await
.unwrap(),
)
.await;
assert_eq!(events[0].1["kind"], json!("refusal"));
assert!(events[0].1["text"]
.as_str()
.unwrap()
.contains("only in the full-screen interface"));
let events = notices(
app.clone()
.oneshot(chat_req(json!({"message": "/bg write me a poem"})))
.await
.unwrap(),
)
.await;
assert!(events[0].1["text"]
.as_str()
.unwrap()
.contains("only in the full-screen interface and the plain REPL"));
let events = notices(
app.clone()
.oneshot(chat_req(json!({"message": "/nope"})))
.await
.unwrap(),
)
.await;
assert_eq!(events[0].1["kind"], json!("refusal"));
assert_eq!(events[0].1["text"], json!("unknown command; try /help"));
let events = notices(
app.clone()
.oneshot(chat_req(json!({"message": "/new"})))
.await
.unwrap(),
)
.await;
assert_eq!(events[0].1["clear_session"], json!(true));
}
#[tokio::test]
async fn yolo_in_the_dashboard_is_a_switch_the_page_can_show() {
use eclipse_core::approvals::{Decision, Pending};
use eclipse_core::tools::Approver;
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("config.toml"),
"[provider]\nbase_url = \"http://h:1/v1\"\nmodel = \"m\"\n",
)
.unwrap();
let cfg = eclipse_core::config::ProviderConfig {
base_url: "http://h:1/v1".into(),
model: "m".into(),
..Default::default()
};
let (st, _agent) = agent_state(dir.path(), cfg, Default::default());
let st = match Arc::try_unwrap(st) {
Ok(st) => Arc::new(st.with_config_path(Some(dir.path().join("config.toml")), None)),
Err(_) => panic!("a state built here is not shared yet"),
};
let app = router(st.clone());
assert!(!st.yolo.on());
let Html(html) = index(State(st.clone()), HeaderMap::new()).await;
assert!(
html.contains("id=\"yolo\""),
"the chip exists: {html:.4000}"
);
assert!(
html.contains("id=\"yolo\" hidden"),
"and it is hidden while approvals are on: {html:.4000}"
);
let events = notices(
app.clone()
.oneshot(chat_req(json!({"message": "/yolo"})))
.await
.unwrap(),
)
.await;
assert_eq!(events[0].1["kind"], json!("command"));
let said = events[0].1["text"].as_str().unwrap();
assert!(said.contains("approvals: auto"), "{said}");
assert!(
said.contains("config.toml"),
"the promise is still there: {said}"
);
assert_eq!(
events[0].1["yolo"],
json!(true),
"the page learns the state"
);
let Html(html) = index(State(st.clone()), HeaderMap::new()).await;
assert!(
!html.contains("id=\"yolo\" hidden"),
"a reload shows a mode that is still in force: {html:.4000}"
);
let (tx, mut rx) = mpsc::unbounded_channel();
let approver = WebApprover {
state: st.clone(),
run: 1,
events: tx,
};
let call = Pending {
call_id: "c1".into(),
tool: "shell".into(),
summary: "echo hi".into(),
args: "{}".into(),
};
let decision = approver.decide(&call).await;
assert!(
matches!(decision, Decision::Allow),
"with yolo on the call runs: {decision:?}"
);
assert!(
rx.try_recv().is_err(),
"and nothing was sent to the browser to click"
);
assert_eq!(
st.unasked.load(std::sync::atomic::Ordering::Relaxed),
1,
"the count is the honest part"
);
assert!(st.approvals.lock().is_empty(), "nothing left waiting");
let events = notices(
app.clone()
.oneshot(chat_req(json!({"message": "/yolo off"})))
.await
.unwrap(),
)
.await;
let said = events[0].1["text"].as_str().unwrap();
assert!(said.contains("approvals: ask"), "{said}");
assert!(
said.contains("1 tool call"),
"the count rides along: {said}"
);
assert_eq!(events[0].1["yolo"], json!(false));
let (tx, mut rx) = mpsc::unbounded_channel();
let approver = WebApprover {
state: st.clone(),
run: 2,
events: tx,
};
let call = Pending {
call_id: "c2".into(),
tool: "shell".into(),
summary: "echo hi".into(),
args: "{}".into(),
};
let asked = tokio::spawn(async move { approver.decide(&call).await });
let id = match rx.recv().await.expect("an approval request") {
Out::ApprovalRequest { id, .. } => id,
Out::Event(_) | Out::Done | Out::Cancelled | Out::Failed(_) => {
panic!("the approver did not ask before running the call")
}
Out::ApprovalResolved { .. } => {
panic!("the approval resolved before it was sent")
}
};
assert_eq!(
st.unasked.load(std::sync::atomic::Ordering::Relaxed),
1,
"a parked call is not an unasked one"
);
let sender = st
.approvals
.lock()
.remove(&id)
.expect("the pending call")
.decide;
let _ = sender.send(true);
assert!(
matches!(asked.await.unwrap(), Decision::Allow),
"an explicit yes is still an allow"
);
}
#[tokio::test]
async fn a_verb_and_its_route_are_one_implementation() {
use eclipse_core::config::ProviderConfig;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(
&path,
"[provider]\nbase_url = \"http://h:1/v1\"\nmodel = \"m\"\n",
)
.unwrap();
let cfg = ProviderConfig {
base_url: "http://h:1/v1".into(),
model: "m".into(),
..Default::default()
};
let (st, agent) = agent_state(dir.path(), cfg, Default::default());
let st = match Arc::try_unwrap(st) {
Ok(st) => Arc::new(st.with_config_path(Some(path.clone()), None)),
Err(_) => panic!("a state built here is not shared yet"),
};
let app = router(st);
let _ = notices(
app.clone()
.oneshot(chat_req(json!({"message": "/reasoning low"})))
.await
.unwrap(),
)
.await;
let body = json_body(
app.clone()
.oneshot(get_req("/api/reasoning", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
assert_eq!(
body["effort"],
json!("low"),
"the route sees the command's pick"
);
let _ = notices(
app.clone()
.oneshot(chat_req(json!({"message": "/set provider.model other"})))
.await
.unwrap(),
)
.await;
let text = std::fs::read_to_string(&path).unwrap();
assert!(
text.contains("model = \"other\""),
"the file is the store: {text}"
);
let body = json_body(
app.clone()
.oneshot(get_req("/api/settings", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
let row = body["settings"]
.as_array()
.unwrap()
.iter()
.find(|r| r["key"] == json!("provider.model"))
.expect("the key");
assert_eq!(row["value"], json!("\"other\""));
let events = notices(
app.clone()
.oneshot(chat_req(json!({"message": "/model"})))
.await
.unwrap(),
)
.await;
assert!(events[0].1["text"]
.as_str()
.unwrap()
.contains("configured:"));
let _ = agent;
}
fn agent_state(
dir: &std::path::Path,
cfg: eclipse_core::config::ProviderConfig,
plugins: eclipse_core::plugins::Plugins,
) -> (Shared, Arc<Agent>) {
let store = SessionStore::new(dir.join("sessions"));
let agent = Arc::new(
Agent::new(
Arc::new(Canned),
Arc::new(ToolRegistry::default()),
store.clone(),
"sys".into(),
3,
)
.with_provider_config(cfg)
.with_plugins(plugins),
);
(
Arc::new(authed(Some(agent.clone()), store, "m", None)),
agent,
)
}
fn reasoning_req(body: serde_json::Value) -> HttpRequest<Body> {
HttpRequest::post("/api/reasoning")
.header("host", "127.0.0.1:8787")
.header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap()
}
async fn json_body(resp: Response) -> serde_json::Value {
serde_json::from_str(&text(resp).await).expect("a JSON reply")
}
#[tokio::test]
async fn the_submenu_is_served_the_levels_this_route_takes() {
use eclipse_core::config::ProviderConfig;
let dir = tempfile::tempdir().unwrap();
let openai = ProviderConfig {
base_url: "http://h:1/v1".into(),
model: "m".into(),
..Default::default()
};
let (st, _agent) = agent_state(dir.path(), openai, Default::default());
let body = json_body(
router(st)
.oneshot(get_req("/api/reasoning", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
assert_eq!(
body["levels"],
json!(["minimal", "low", "medium", "high"]),
"four rungs, and no off switch to offer"
);
assert_eq!(
body["effort"],
json!("medium"),
"the shipped default is what an unconfigured install reasons at"
);
assert_eq!(body["effort_default"], json!(true));
assert_eq!(body["effort_session"], json!(false));
assert!(
body["configured"].is_null(),
"the file sets nothing: {}",
body["configured"]
);
assert_eq!(
body["described"]["high"],
json!("sends high"),
"each row quotes the policy, so a clamp is visible before the click"
);
assert_eq!(body["off_word"], json!(null), "no off to offer");
assert!(
body["off_why"]
.as_str()
.unwrap_or_default()
.contains("no off switch"),
"and the switch's title carries the reason: {}",
body["off_why"]
);
let dir = tempfile::tempdir().unwrap();
let llama = ProviderConfig {
base_url: "http://h:1/v1".into(),
model: "mmnuc/inkling-2-mini".into(),
profile: Some("llamacpp".into()),
..Default::default()
};
let (st, _agent) = agent_state(dir.path(), llama, Default::default());
let body = json_body(
router(st)
.oneshot(get_req("/api/reasoning", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
assert_eq!(body["levels"], json!(["low", "medium", "high", "none"]));
assert_eq!(
body["described"]["none"],
json!("sends none"),
"the off switch is named as the wire takes it"
);
assert_eq!(
body["off_word"],
json!("none"),
"this route declares an off, so the switch is live"
);
assert_eq!(body["off_why"], json!(""));
let dir = tempfile::tempdir().unwrap();
let plugins_dir = dir.path().join("plugins").join("provider-profile-bare");
std::fs::create_dir_all(&plugins_dir).unwrap();
std::fs::write(
plugins_dir.join("plugin.toml"),
"name = \"provider-profile-bare\"\nversion = \"0.1.0\"\napi = 1\n\
description = \"a profile that declares no reasoning control\"\n\n\
[[provider_profile]]\nname = \"bare\"\n",
)
.unwrap();
let loaded = eclipse_core::plugins::load(&[dir.path().join("plugins")], &[]);
let bare = ProviderConfig {
base_url: "http://h:1/v1".into(),
model: "m".into(),
profile: Some("bare".into()),
..Default::default()
};
let (st, _agent) = agent_state(dir.path(), bare, loaded);
let body = json_body(
router(st)
.oneshot(get_req("/api/reasoning", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
assert_eq!(
body["levels"],
json!([]),
"nothing to offer is the honest list for this backend"
);
assert!(
body["note"]
.as_str()
.unwrap_or_default()
.contains("declares no reasoning control"),
"and the menu says why: {}",
body["note"]
);
}
#[tokio::test]
async fn a_pick_changes_the_next_request_body_and_nothing_else() {
use eclipse_core::config::ProviderConfig;
let seen: Arc<Mutex<Vec<serde_json::Value>>> = Arc::new(Mutex::new(Vec::new()));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let recorder = {
let seen = Arc::clone(&seen);
Router::new().route(
"/v1/chat/completions",
post(move |Json(body): Json<serde_json::Value>| {
let seen = Arc::clone(&seen);
async move {
seen.lock().unwrap().push(body);
Json(json!({
"choices": [{"message": {"role": "assistant", "content": "ok"}}]
}))
}
}),
)
};
tokio::spawn(async move {
let _ = axum::serve(listener, recorder).await;
});
let dir = tempfile::tempdir().unwrap();
let cfg = ProviderConfig {
base_url: format!("http://{addr}/v1"),
model: "m".into(),
stream: false,
retry_base_delay_ms: 20,
..Default::default()
};
let (st, agent) = agent_state(dir.path(), cfg, Default::default());
let app = router(st);
let r = app
.clone()
.oneshot(model_req(json!({ "model": "m" })))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
for level in ["low", "high"] {
let r = app
.clone()
.oneshot(reasoning_req(json!({ "level": level })))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK, "{level}");
let body = json_body(r).await;
assert_eq!(body["effort"], json!(level));
assert_eq!(body["effort_session"], json!(true), "and it says why");
let r = app
.clone()
.oneshot(chat_req(json!({ "message": "same prompt" })))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
let _ = text(r).await; }
let seen = seen.lock().unwrap().clone();
assert_eq!(seen.len(), 2, "one request per turn: {seen:?}");
assert_eq!(seen[0]["reasoning_effort"], json!("low"), "{:?}", seen[0]);
assert_eq!(seen[1]["reasoning_effort"], json!("high"), "{:?}", seen[1]);
let strip = |mut body: serde_json::Value| {
body.as_object_mut().unwrap().remove("reasoning_effort");
body
};
assert_eq!(
strip(seen[0].clone()),
strip(seen[1].clone()),
"two identical prompts, and only the level differs"
);
assert!(agent.reasoning().overridden(), "a session dial, not a file");
}
#[tokio::test]
async fn the_off_switch_reaches_the_wire_as_this_route_spells_it() {
use eclipse_core::config::ProviderConfig;
let seen: Arc<Mutex<Vec<serde_json::Value>>> = Arc::new(Mutex::new(Vec::new()));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let recorder = {
let seen = Arc::clone(&seen);
Router::new().route(
"/v1/chat/completions",
post(move |Json(body): Json<serde_json::Value>| {
let seen = Arc::clone(&seen);
async move {
seen.lock().unwrap().push(body);
Json(json!({
"choices": [{"message": {"role": "assistant", "content": "ok"}}]
}))
}
}),
)
};
tokio::spawn(async move {
let _ = axum::serve(listener, recorder).await;
});
let dir = tempfile::tempdir().unwrap();
let cfg = ProviderConfig {
base_url: format!("http://{addr}/v1"),
model: "mmnuc/inkling-2-mini".into(),
profile: Some("llamacpp".into()),
stream: false,
retry_base_delay_ms: 20,
..Default::default()
};
let (st, agent) = agent_state(dir.path(), cfg, Default::default());
let app = router(st);
let r = app
.clone()
.oneshot(model_req(json!({ "model": "mmnuc/inkling-2-mini" })))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
for level in ["high", "none"] {
let r = app
.clone()
.oneshot(reasoning_req(json!({ "level": level })))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK, "{level}");
}
let r = app
.clone()
.oneshot(chat_req(json!({ "message": "same prompt" })))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
let _ = text(r).await;
let first = seen.lock().unwrap().clone();
assert_eq!(first.len(), 1, "one request for the turn: {first:?}");
assert_eq!(
first[0]["reasoning_effort"],
json!("none"),
"the off is the policy's own word on this wire: {:?}",
first[0]
);
assert!(agent.reasoning().overridden(), "still a session dial");
let r = app
.clone()
.oneshot(reasoning_req(json!({ "level": "omit" })))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK, "omit on the route with a dial");
let r = app
.clone()
.oneshot(chat_req(json!({ "message": "now quiet" })))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
let _ = text(r).await;
let bodies = seen.lock().unwrap().clone();
assert_eq!(bodies.len(), 2, "one request per turn: {bodies:?}");
assert!(
bodies[1].get("reasoning_effort").is_none(),
"asked for no field, and none is sent: {:?}",
bodies[1]
);
let dir = tempfile::tempdir().unwrap();
let openai = ProviderConfig {
base_url: format!("http://{addr}/v1"),
model: "m".into(),
stream: false,
retry_base_delay_ms: 20,
..Default::default()
};
let (st, _agent) = agent_state(dir.path(), openai, Default::default());
let app = router(st);
let r = app
.clone()
.oneshot(reasoning_req(json!({ "level": "none" })))
.await
.unwrap();
assert_eq!(
r.status(),
StatusCode::BAD_REQUEST,
"there is no off to ask for on this route"
);
let why = text(r).await;
assert!(why.contains("not a level this backend takes"), "{why}");
let r = app
.clone()
.oneshot(reasoning_req(json!({ "level": "omit" })))
.await
.unwrap();
assert_eq!(
r.status(),
StatusCode::OK,
"a route with no off switch can still be told to send nothing"
);
}
#[test]
fn the_reasoning_row_is_a_switch_and_never_a_renamed_verb() {
for verb in ["show reasoning", "hide reasoning"] {
assert!(
!INDEX_HTML.contains(verb),
"the row is not a phrase that changes {verb:?}"
);
}
assert!(
INDEX_HTML.contains("switchRow('Reasoning'"),
"one row, labelled with the setting"
);
assert!(
INDEX_HTML.contains("b.setAttribute('role', 'switch')")
&& INDEX_HTML.contains("b.setAttribute('aria-checked'"),
"a switch with a state on the control, so Up/Down still reaches it"
);
assert!(
INDEX_HTML.contains("pickEffort(isOff ? restore : offWord)"),
"the flip posts the route's off word, never a sentinel"
);
assert!(
INDEX_HTML.contains("onClick: offWord ?"),
"a route with no off gets a switch with no handler"
);
assert!(
INDEX_HTML.contains("if (word === offWord) continue;"),
"the off word is not also a level row: one dial, one control"
);
let submenu = INDEX_HTML
.split("function renderReasoning(")
.nth(1)
.and_then(|rest| rest.split("async function showReasoning(").next())
.expect("the submenu's renderer");
assert!(
!submenu.contains("setThinking"),
"the menu row must not fold a single block: {submenu:.0}"
);
assert!(
INDEX_HTML.contains("id=\"thinkall\""),
"the fold control is where it was"
);
}
#[tokio::test]
async fn a_pick_never_writes_the_config_file() {
use eclipse_core::config::ProviderConfig;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(
&path,
"[provider]\nbase_url = \"http://h:1/v1\"\nmodel = \"m\"\nreasoning_effort = \"low\"\n",
)
.unwrap();
let before = std::fs::read(&path).unwrap();
let cfg = ProviderConfig {
base_url: "http://h:1/v1".into(),
model: "m".into(),
reasoning_effort: Some("low".into()),
..Default::default()
};
let (st, agent) = agent_state(dir.path(), cfg, Default::default());
let st = match Arc::try_unwrap(st) {
Ok(st) => Arc::new(st.with_config_path(Some(path.clone()), None)),
Err(_) => panic!("a state built here is not shared yet"),
};
let app = router(st);
let body = json_body(
app.clone()
.oneshot(reasoning_req(json!({ "level": "high" })))
.await
.unwrap(),
)
.await;
assert_eq!(body["effort"], json!("high"));
assert_eq!(
body["configured"],
json!("low"),
"the row that goes back to the file says what it would go back to"
);
assert_eq!(
std::fs::read(&path).unwrap(),
before,
"a click is not a `config set`"
);
assert_eq!(
agent.reasoning().configured(),
Some("low"),
"the agent still holds the file's level underneath"
);
let body = json_body(
app.clone()
.oneshot(get_req("/api/settings", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
let rows = body["settings"]
.as_array()
.unwrap_or_else(|| panic!("the settings page answers rows: {body}"));
let row = rows
.iter()
.find(|r| r["key"] == json!("provider.reasoning_effort"))
.expect("the key is on the settings page");
assert_eq!(
row["value"],
json!("\"low\""),
"the page reports the file, not the dashboard's dial"
);
}
#[tokio::test]
async fn default_goes_back_to_the_file_and_a_level_the_route_lacks_is_refused() {
use eclipse_core::config::ProviderConfig;
let dir = tempfile::tempdir().unwrap();
let cfg = ProviderConfig {
base_url: "http://h:1/v1".into(),
model: "m".into(),
reasoning_effort: Some("low".into()),
..Default::default()
};
let (st, agent) = agent_state(dir.path(), cfg, Default::default());
let app = router(st);
let body = json_body(
app.clone()
.oneshot(reasoning_req(json!({ "level": "high" })))
.await
.unwrap(),
)
.await;
assert_eq!(body["effort_session"], json!(true));
let body = json_body(
app.clone()
.oneshot(reasoning_req(json!({ "level": null })))
.await
.unwrap(),
)
.await;
assert_eq!(body["effort"], json!("low"));
assert_eq!(body["effort_session"], json!(false));
assert!(!agent.reasoning().overridden());
let r = app
.clone()
.oneshot(reasoning_req(json!({ "level": "none" })))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::BAD_REQUEST);
let said = text(r).await;
assert!(
said.contains("not sent") && said.contains("this route takes"),
"the refusal is the policy's sentence plus the vocabulary: {said}"
);
assert!(!agent.reasoning().overridden(), "a refusal changes nothing");
let r = app.clone().oneshot(reasoning_req(json!({}))).await.unwrap();
assert_eq!(r.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn a_pick_moves_the_context_window_to_the_new_model() {
let dir = tempfile::tempdir().unwrap();
let base = serve_models(&[("small", Some(4_096)), ("big", Some(131_072))]).await;
let (st, agent) = provider_state(dir.path(), &base, "small");
assert_eq!(agent.context_window(), 0, "nothing probed yet");
let app = router(st);
let r = app
.clone()
.oneshot(model_req(json!({ "model": "big" })))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
for _ in 0..100 {
if agent.context_window() == 131_072 {
return;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
panic!(
"the window still reads {} after a pick",
agent.context_window()
);
}
#[test]
fn the_pane_names_the_session_that_is_open() {
assert!(
INDEX_HTML.contains("id=\"openname\"") && INDEX_HTML.contains("id=\"openid\""),
"a name and its id, above the transcript"
);
let script = INDEX_HTML.split("<script>").nth(1).unwrap_or_default();
assert!(
script.contains("row.querySelector('.name')"),
"the name is read off the row the list already drew, not fetched again"
);
assert!(
script.contains("showOpen(parked)"),
"and it follows every rebuild of the list, naming the row the list may not be showing \
(#345: the section holding the open session can be closed)"
);
assert!(
INDEX_HTML.contains("#open[hidden] { display:none; }"),
"an empty bar takes no height"
);
}
#[test]
fn the_page_has_the_archive_filter_and_the_row_menu_word() {
assert!(
INDEX_HTML.contains("id=\"showarchived\""),
"the filter exists"
);
assert!(
INDEX_HTML.contains("?archived=1"),
"and it is the server's list with the filed rows back in it"
);
assert!(
INDEX_HTML.contains("li.dataset.archived"),
"a row says whether it is filed away"
);
assert!(
INDEX_HTML.contains("data-archived=\""),
"and the first paint says so too"
);
assert!(
INDEX_HTML.contains("'archive'") && INDEX_HTML.contains("'unarchive'"),
"the menu offers the write and its undo"
);
assert!(
INDEX_HTML.contains("add('Archived', archived)"),
"filed rows get their own heading, not a date bucket"
);
assert!(INDEX_HTML.contains("out of the list, still in the find box"));
assert!(
INDEX_HTML.contains("'delete the transcript, its title and its memory', 'danger'"),
"delete is still the only irreversible row"
);
}
#[test]
fn the_page_has_a_model_picker_wired_to_its_routes() {
assert!(INDEX_HTML.contains("id=\"model\""), "the label is a button");
assert!(INDEX_HTML.contains("/api/models"), "asked for the list");
assert!(
INDEX_HTML.contains("'/api/model'"),
"and tells the server a choice"
);
assert!(INDEX_HTML.contains("b.textContent = text"));
assert!(!INDEX_HTML.contains("innerHTML"));
assert!(
INDEX_HTML.contains("/api/settings"),
"the catalogue is asked for"
);
assert!(
INDEX_HTML.contains("name.textContent = row.key"),
"a key is text, not markup"
);
assert!(
INDEX_HTML.contains("about.textContent = row.about"),
"a description is text too — it comes from the catalogue"
);
}
#[tokio::test]
async fn the_commands_route_is_the_table() {
use eclipse_core::commands::{Args, Front, COMMANDS};
let dir = tempfile::tempdir().unwrap();
let app = router(state(dir.path(), true));
let body = json_body(
app.oneshot(get_req("/api/commands", "127.0.0.1:1"))
.await
.unwrap(),
)
.await;
let served: Vec<&str> = body["commands"]
.as_array()
.expect("a list")
.iter()
.map(|r| r["name"].as_str().expect("a name"))
.collect();
let expected: Vec<&str> = COMMANDS
.iter()
.filter(|c| c.serves(Front::Web))
.map(|c| c.name)
.collect();
assert_eq!(served, expected, "the route is the table, in table order");
assert!(
!served.contains(&"/resume"),
"a terminal-only verb is not offered: {served:?}"
);
for row in body["commands"].as_array().unwrap() {
let name = row["name"].as_str().unwrap();
let command = COMMANDS.iter().find(|c| c.name == name).unwrap();
assert_eq!(row["label"], json!(command.label()));
assert_eq!(row["help"], json!(command.help));
assert_eq!(row["aliases"], json!(command.aliases));
assert_eq!(row["takes_arg"], json!(command.args.takes()));
match command.args {
Args::Shown(args) => assert_eq!(row["args"], json!(args)),
Args::None | Args::Unshown => assert_eq!(row["args"], serde_json::Value::Null),
}
}
let set = body["commands"]
.as_array()
.unwrap()
.iter()
.find(|r| r["name"] == json!("/set"))
.expect("/set");
assert_eq!(set["label"], json!("/set <key> <value>"));
}
#[test]
fn the_command_menu_is_the_servers_list_not_the_pages() {
use eclipse_core::commands::{Front, COMMANDS};
assert!(
INDEX_HTML.contains("fetch('/api/commands')"),
"the menu asks the server"
);
for c in COMMANDS.iter().filter(|c| c.serves(Front::Web)) {
for quoted in [format!("'{}'", c.name), format!("\"{}\"", c.name)] {
assert!(
!INDEX_HTML.contains("ed),
"the page spells {} — the menu must come from the table",
c.name
);
}
}
for key in ["ArrowDown", "ArrowUp", "'Tab'", "'Escape'"] {
assert!(
INDEX_HTML.contains(key),
"{key} is handled: the menu owns {key}"
);
}
assert!(INDEX_HTML.contains("role=\"listbox\""));
assert!(INDEX_HTML.contains("aria-activedescendant"));
}
#[test]
fn the_settings_window_draws_its_rows_from_the_catalogue() {
use eclipse_core::commands::COMMANDS;
assert!(
INDEX_HTML.contains("<dialog id=\"settingswindow\""),
"a dialog, not a box in the sidebar"
);
assert!(INDEX_HTML.contains("setWin.showModal()"));
assert!(
INDEX_HTML.contains("for (const choice of row.choices)"),
"a select's options are the server's words"
);
assert!(
INDEX_HTML.contains("row.kind === 'bool'"),
"a boolean is a toggle, chosen by kind"
);
assert!(
INDEX_HTML.contains("send(null)"),
"reset is a null, which the route reads as \"comment the line out\""
);
for key in [
"provider.model",
"agent.max_iterations",
"tools.shell",
"web.port",
"cli.approval",
] {
assert!(
!INDEX_HTML.contains(key),
"the page spells {key} — the rows must come from the catalogue"
);
}
assert!(COMMANDS.iter().any(|c| c.name == "/settings"));
}
#[test]
fn the_settings_window_keeps_its_frame_whatever_section_is_picked() {
assert!(
INDEX_HTML.contains("height:min(760px, 84vh)"),
"the dialog states a height rather than a maximum, so it cannot be as small as its rows"
);
assert!(
INDEX_HTML.contains("#settingswindow[open] { display:flex; flex-direction:column; }"),
"and the body is a column that fills it — `[open]`, or the dialog would draw closed"
);
assert!(
INDEX_HTML.contains("scrollbar-gutter:stable"),
"the rows pane reserves its scrollbar, so picking a long section does not shift the text"
);
assert!(
!INDEX_HTML.contains("max-height:62vh"),
"the old cap is what let the window collapse: the rows pane scrolls instead"
);
assert!(
INDEX_HTML.contains("ctl.appendChild(where)"),
"`now: …` is on the control's line, not a fourth line under it"
);
assert!(
INDEX_HTML.contains("setAttribute('role', 'switch')"),
"a boolean is a switch, not a button shaped like `set`"
);
assert!(
INDEX_HTML.contains(".srow .switch[aria-checked=\"true\"] .track"),
"and the switch has a drawn on-state"
);
assert!(INDEX_HTML.contains("SET_SECTION_ABOUT"));
for section in ["agent", "provider", "web", "tools"] {
assert!(
INDEX_HTML.contains(&format!(" {section}: '")),
"the {section} section has a sentence"
);
}
}
#[test]
fn an_attachment_becomes_a_block_the_model_can_tell_from_the_sentence() {
let said = compose_attachments(
"here is the trace",
&[Attachment {
kind: "text".into(),
name: "trace.txt".into(),
value: "ERROR: the pool was rebuilt\n".into(),
}],
)
.unwrap()
.0;
assert!(said.starts_with("here is the trace"), "{said}");
assert!(
said.contains("--- attached file: trace.txt (27 chars) ---"),
"the block names the file and its size: {said}"
);
assert!(said.contains("ERROR: the pool was rebuilt"), "{said}");
assert!(
said.contains("--- end of trace.txt ---"),
"and says where the file stopped, so the model does not read on: {said}"
);
let said = compose_attachments(
"",
&[
Attachment {
kind: "path".into(),
name: String::new(),
value: "crates/eclipse-core/src/session.rs".into(),
},
Attachment {
kind: "url".into(),
name: String::new(),
value: "https://example.com/report".into(),
},
],
)
.unwrap()
.0;
assert!(
said.contains("attached path: crates/eclipse-core/src/session.rs"),
"{said}"
);
assert!(
said.contains("read_file"),
"it says what to do with it: {said}"
);
assert!(
said.contains("attached link: https://example.com/report"),
"{said}"
);
assert!(said.contains("fetch"), "{said}");
assert!(said.starts_with("--- attached path:"), "{said:?}");
let (said, pictures) = compose_attachments(
"look",
&[Attachment {
kind: "image".into(),
name: "shot.png".into(),
value: "data:image/png;base64,iVBORw0KGgo=".into(),
}],
)
.unwrap();
assert_eq!(pictures.len(), 1, "{pictures:?}");
assert_eq!(pictures[0].name, "shot.png");
assert_eq!(pictures[0].mime, "image/png");
assert!(
said.contains("--- attached picture: shot.png (image/png) ---"),
"the words still read sensibly when a model is sent a description: {said}"
);
assert!(compose_attachments(
"x",
&[Attachment {
kind: "image".into(),
name: "shot.svg".into(),
value: "data:image/svg+xml;base64,iVBORw0KGgo=".into(),
}]
)
.unwrap_err()
.contains("not a picture this build can carry"));
assert!(compose_attachments(
"x",
&[Attachment {
kind: "image".into(),
name: "shot.png".into(),
value: "/tmp/shot.png".into(),
}]
)
.unwrap_err()
.contains("data: URL"));
let big = "x".repeat(MAX_ATTACHMENT_CHARS + 1);
let refused = compose_attachments(
"read this",
&[Attachment {
kind: "text".into(),
name: "huge.log".into(),
value: big,
}],
)
.unwrap_err();
assert!(refused.contains("huge.log"), "{refused}");
assert!(
refused.contains(&MAX_ATTACHMENT_CHARS.to_string()),
"{refused}"
);
assert!(refused.contains("attach it as a path"), "{refused}");
assert!(compose_attachments(
"x",
&[Attachment {
kind: "url".into(),
name: String::new(),
value: "javascript:alert(1)".into(),
}]
)
.is_err());
assert!(compose_attachments(
"x",
&[Attachment {
kind: "path".into(),
name: String::new(),
value: "a path\nwith a newline".into(),
}]
)
.is_err());
assert_eq!(
compose_attachments("just words", &[]).unwrap().0,
"just words"
);
let many: Vec<Attachment> = (0..=MAX_ATTACHMENTS)
.map(|i| Attachment {
kind: "url".into(),
name: String::new(),
value: format!("https://example.com/{i}"),
})
.collect();
assert!(compose_attachments("x", &many)
.unwrap_err()
.contains("at most 8"));
}
#[tokio::test]
async fn an_attached_file_is_the_turn_the_model_read_and_the_text_the_store_keeps() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let store = st.agent.as_ref().unwrap().store().clone();
let app = router(st);
let r = app
.clone()
.oneshot(chat_req(json!({
"message": "what broke?",
"attachments": [
{ "kind": "text", "name": "trace.txt", "value": "ERROR: the pool was rebuilt" },
{ "kind": "url", "value": "https://example.com/report" }
]
})))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK, "a run, not a refusal");
let events = notices(r).await;
let session = events
.iter()
.find(|(kind, _)| kind == "session")
.expect("a run opens a session");
let id = session.1["session_id"].as_str().unwrap().to_string();
let kept = store.load(&id).unwrap();
let asked = kept
.iter()
.find(|m| m.role == eclipse_core::message::Role::User)
.and_then(|m| m.content.clone())
.expect("the turn is stored");
assert!(asked.starts_with("what broke?"), "{asked}");
assert!(asked.contains("--- attached file: trace.txt"), "{asked}");
assert!(asked.contains("ERROR: the pool was rebuilt"), "{asked}");
assert!(
asked.contains("--- attached link: https://example.com/report"),
"the link is a reference in the same turn: {asked}"
);
let r = app
.clone()
.oneshot(chat_req(json!({
"message": "/help",
"attachments": [{ "kind": "text", "name": "x.txt", "value": "hello" }]
})))
.await
.unwrap();
let events = notices(r).await;
assert_eq!(events[0].0, "notice", "{events:?}");
assert_eq!(events[0].1["kind"], json!("refusal"), "{events:?}");
assert!(
events[0].1["text"]
.as_str()
.unwrap()
.contains("a command runs on its own"),
"{events:?}"
);
let r = app
.clone()
.oneshot(chat_req(json!({
"message": "look at this",
"attachments": [{ "kind": "image", "name": "shot.png", "value": "AAAA" }]
})))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::BAD_REQUEST);
assert!(
body_text(r).await.contains("data: URL"),
"the refusal says what a picture has to be"
);
let r = app
.clone()
.oneshot(chat_req(json!({
"message": "listen to this",
"attachments": [{ "kind": "audio", "name": "clip.wav", "value": "AAAA" }]
})))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::BAD_REQUEST);
assert!(
body_text(r).await.contains("cannot attach audio"),
"the refusal names the kind"
);
}
#[test]
fn the_composer_has_a_plus_menu_and_sends_what_its_chips_say() {
assert!(INDEX_HTML.contains("id=\"plus\""), "the control exists");
assert!(
INDEX_HTML.contains("aria-haspopup=\"menu\""),
"and it says it opens a menu"
);
for kind in ["file", "path", "url", "image", "audio"] {
assert!(
INDEX_HTML.contains(&format!("data-attach=\"{kind}\"")),
"the {kind} row exists"
);
}
assert!(
INDEX_HTML.contains("accept=\"image/png,image/jpeg,image/webp,image/gif\""),
"the picture picker exists and is limited to what the wire carries"
);
assert!(
INDEX_HTML.contains("readAsDataURL"),
"and it reads the bytes here, because the page is the only thing that has them"
);
assert!(
!INDEX_HTML.contains("data-attach=\"image\" disabled"),
"the picture row is no longer a disabled row"
);
assert!(INDEX_HTML.contains("needs a transcription endpoint"));
assert!(INDEX_HTML.contains("function renderAttached()"));
assert!(INDEX_HTML.contains("attached.splice(i, 1)"));
assert!(
INDEX_HTML.contains("const carrying = attached.map"),
"the body is built from the chips at send time"
);
assert!(
INDEX_HTML.contains("attachments: carrying"),
"and travels in the same JSON body as the message"
);
assert!(INDEX_HTML.contains("const ATTACH_MAX_CHARS = 65536;"));
assert!(
INDEX_HTML.contains("attach it as a path instead"),
"an over-cap file is told what to do instead"
);
assert!(INDEX_HTML.contains("(!text && attached.length === 0)"));
assert!(INDEX_HTML.contains("closeAttach(); plus.focus();"));
}
#[tokio::test]
async fn session_endpoints() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
st.store.append("s1", &Message::user("q")).unwrap();
let app = router(st);
let r = app
.clone()
.oneshot(get_req("/api/sessions", "127.0.0.1:1"))
.await
.unwrap();
assert!(text(r).await.contains("\"s1\""));
let r = app
.clone()
.oneshot(get_req("/api/sessions/s1", "127.0.0.1:1"))
.await
.unwrap();
assert!(text(r).await.contains("\"q\""));
let r = app
.clone()
.oneshot(get_req("/api/sessions/nope", "127.0.0.1:1"))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::NOT_FOUND);
let r = app
.clone()
.oneshot(get_req("/api/sessions/a.b", "127.0.0.1:1"))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::BAD_REQUEST);
}
#[test]
fn loopback_host_parsing() {
assert!(is_loopback_host("127.0.0.1:80"));
assert!(is_loopback_host("localhost"));
assert!(is_loopback_host("[::1]:8787"));
assert!(!is_loopback_host("127.0.0.1.evil.com"));
assert!(!is_loopback_host("example.com:80"));
assert!(is_loopback_host("localhost.:8787"));
assert!(is_loopback_host("127.0.0.1.:8787"));
assert!(!is_loopback_host("localhost.evil.com:8787"));
}
#[tokio::test]
async fn stop_cancels_a_run_in_flight_and_ends_the_stream() {
use futures_util::StreamExt;
let dir = tempfile::tempdir().unwrap();
let (st, entered, dropped) = hanging_state(dir.path());
let resp = router(st.clone())
.oneshot(chat_req(json!({"message": "hang"})))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let mut body = resp.into_body().into_data_stream();
let first = String::from_utf8(body.next().await.unwrap().unwrap().to_vec()).unwrap();
let run_id = first
.split("run_id\":\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.unwrap_or_else(|| panic!("no run_id in {first}"))
.to_string();
assert!(
wait_for(&entered, 2000).await,
"the model call never started"
);
let r = router(st.clone())
.oneshot(cancel_req(&run_id))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
assert!(text(r).await.contains("\"cancelled\":true"));
let mut all = String::new();
while let Ok(Some(Ok(chunk))) =
tokio::time::timeout(Duration::from_secs(5), body.next()).await
{
all.push_str(&String::from_utf8_lossy(&chunk));
}
assert!(all.contains("event: cancelled"), "{all}");
assert!(all.contains("event: done"), "{all}");
assert!(
!all.contains("event: error"),
"cancelling is not a failure: {all}"
);
assert!(
dropped.load(Ordering::SeqCst),
"the provider request must be dropped, not waited out"
);
assert_eq!(st.store.list().unwrap()[0].messages, 1);
assert!(wait_for(&dropped, 1000).await);
tokio::time::sleep(Duration::from_millis(100)).await;
let again = router(st).oneshot(cancel_req(&run_id)).await.unwrap();
assert_eq!(again.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn closing_the_connection_cancels_the_run() {
use futures_util::StreamExt;
let dir = tempfile::tempdir().unwrap();
let (st, entered, dropped) = hanging_state(dir.path());
let resp = router(st.clone())
.oneshot(chat_req(json!({"message": "hang"})))
.await
.unwrap();
let mut body = resp.into_body().into_data_stream();
body.next().await.unwrap().unwrap();
assert!(
wait_for(&entered, 2000).await,
"the model call never started"
);
assert!(
!dropped.load(Ordering::SeqCst),
"the run must still be in flight"
);
drop(body);
assert!(
wait_for(&dropped, 3000).await,
"a closed connection must cancel the run, not leave it running"
);
tokio::time::sleep(Duration::from_millis(100)).await;
assert_eq!(st.store.list().unwrap()[0].messages, 1);
}
#[tokio::test]
async fn cancel_rejects_malformed_and_unknown_run_ids() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
for (uri, want) in [
("/api/runs/not-hex/cancel", StatusCode::BAD_REQUEST),
("/api/runs/deadbeef/cancel", StatusCode::NOT_FOUND),
] {
let r = router(st.clone())
.oneshot(
anon("POST", uri)
.header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(r.status(), want, "{uri}");
}
}
#[tokio::test]
async fn a_chat_can_ask_for_its_own_turn_budget_and_hears_what_it_got() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let resp = router(st)
.oneshot(chat_req(json!({"message": "hello", "max_iterations": 7})))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = text(resp).await;
assert!(
body.contains("\"max_iterations\":7"),
"the session event must report the budget that will apply: {body}"
);
}
#[tokio::test]
async fn a_chat_asking_for_a_turn_budget_past_the_ceiling_is_refused() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let resp = router(st)
.oneshot(chat_req(json!({
"message": "hello",
"max_iterations": MAX_ITERATIONS_BOUND + 1
})))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let body = text(resp).await;
assert!(
body.contains(&MAX_ITERATIONS_BOUND.to_string()),
"the refusal names the ceiling: {body}"
);
}
#[tokio::test]
async fn a_chat_asks_for_zero_turns_is_refused_rather_than_silently_corrected() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let resp = router(st)
.oneshot(chat_req(json!({"message": "hello", "max_iterations": 0})))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
fn write_session(
id: &str,
act: &str,
csrf: Option<&str>,
body: Option<serde_json::Value>,
) -> HttpRequest<Body> {
let mut b = HttpRequest::post(format!("/api/sessions/{id}/{act}"))
.header("host", "127.0.0.1:8787")
.header("origin", "null")
.header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"));
if let Some(token) = csrf {
b = b.header(CSRF_HEADER, token);
}
match body {
Some(v) => b
.header("content-type", "application/json")
.body(Body::from(v.to_string()))
.unwrap(),
None => b.body(Body::empty()).unwrap(),
}
}
#[tokio::test]
async fn a_rename_in_the_dashboard_is_the_rename_the_terminal_reads() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let store = st.agent.as_ref().unwrap().store().clone();
let id = store.new_id();
store.append(&id, &Message::user("the question")).unwrap();
let app = router(st);
let r = app
.clone()
.oneshot(write_session(
&id,
"rename",
Some(TEST_CSRF),
Some(json!({"title": "named in the browser"})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
assert_eq!(
store.title(&id).unwrap().as_deref(),
Some("named in the browser")
);
let listed = body_text(
app.oneshot(get_req("/api/sessions", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
assert!(listed.contains("named in the browser"), "{listed}");
assert!(listed.contains(&format!("\"id\":\"{id}\"")), "{listed}");
}
#[tokio::test]
async fn a_pin_in_the_dashboard_puts_a_session_first_and_keeps_a_prune_off_it() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let store = st.agent.as_ref().unwrap().store().clone();
let older = store.new_id();
store
.append(&older, &Message::user("the older one"))
.unwrap();
std::thread::sleep(std::time::Duration::from_millis(5));
let newer = store.new_id();
store
.append(&newer, &Message::user("the newer one"))
.unwrap();
let app = router(st);
let r = app
.clone()
.oneshot(write_session(
&older,
"pin",
Some(TEST_CSRF),
Some(json!({"pinned": true})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
let listed = body_text(
app.oneshot(get_req("/api/sessions", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
let rows: Vec<serde_json::Value> = serde_json::from_str(&listed).unwrap();
assert_eq!(rows[0]["id"], json!(older), "pinned first: {listed}");
assert_eq!(rows[0]["pinned"], json!(true));
assert_eq!(rows[1]["id"], json!(newer));
let now = eclipse_core::session::now_ms();
let plan = store.prune_candidates(0, 1, now, false).unwrap();
assert!(!plan.candidates.contains(&older), "{:?}", plan.candidates);
assert_eq!(plan.pinned_kept, 1);
}
#[tokio::test]
async fn an_archive_in_the_dashboard_is_the_archive_the_terminal_reads() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let store = st.agent.as_ref().unwrap().store().clone();
let id = store.new_id();
store
.append(&id, &Message::user("the zfs pool was rebuilt"))
.unwrap();
store.rename(&id, "the nginx migration").unwrap();
let app = router(st);
let r = app
.clone()
.oneshot(write_session(
&id,
"archive",
Some(TEST_CSRF),
Some(json!({"archived": true})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
assert!(store.list().unwrap().is_empty());
assert!(store.list_with_archived().unwrap()[0].archived);
let listed = body_text(
app.clone()
.oneshot(get_req("/api/sessions", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
assert_eq!(listed.trim(), "[]", "out of the list: {listed}");
let all = body_text(
app.clone()
.oneshot(get_req("/api/sessions?archived=1", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
let rows: Vec<serde_json::Value> = serde_json::from_str(&all).unwrap();
assert_eq!(rows.len(), 1, "{all}");
assert_eq!(rows[0]["archived"], json!(true), "{all}");
assert_eq!(rows[0]["title"], json!("the nginx migration"), "{all}");
let hits = body_text(
app.clone()
.oneshot(get_req("/api/search?q=zfs", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
assert!(hits.contains(&id), "the find box still answers: {hits}");
let transcript = body_text(
app.clone()
.oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
assert!(transcript.contains("zfs pool"), "{transcript}");
let later = eclipse_core::session::now_ms() + 86_400_000;
let plan = store.prune_candidates(1, 0, later, false).unwrap();
assert!(plan.candidates.is_empty(), "{:?}", plan.candidates);
assert_eq!(plan.archived_kept, 1);
let asked = store.prune_candidates(1, 0, later, true).unwrap();
assert_eq!(asked.candidates, vec![id.clone()]);
let r = app
.clone()
.oneshot(write_session(
&id,
"archive",
Some(TEST_CSRF),
Some(json!({"archived": false})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
let listed = body_text(
app.oneshot(get_req("/api/sessions", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
assert!(listed.contains(&id), "{listed}");
}
#[tokio::test]
async fn the_composers_archive_verb_files_the_open_session_away() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let store = st.agent.as_ref().unwrap().store().clone();
let id = store.new_id();
store
.append(&id, &Message::user("the nginx migration"))
.unwrap();
store.rename(&id, "the nginx migration").unwrap();
let app = router(st);
let events = notices(
app.clone()
.oneshot(chat_req(json!({"message": "/archive", "session_id": id})))
.await
.unwrap(),
)
.await;
assert_eq!(events[0].0, "notice", "{events:?}");
assert_eq!(events[0].1["kind"], json!("command"));
let said = events[0].1["text"].as_str().unwrap();
assert!(said.contains("still in the find box"), "{said}");
assert!(store.list().unwrap().is_empty(), "the row left the listing");
assert!(store.list_with_archived().unwrap()[0].archived);
let events = notices(
app.clone()
.oneshot(chat_req(json!({"message": "/archive list"})))
.await
.unwrap(),
)
.await;
let said = events[0].1["text"].as_str().unwrap();
assert!(
said.contains(&id) && said.contains("the nginx migration"),
"{said}"
);
let events = notices(
app.clone()
.oneshot(chat_req(
json!({"message": "/archive off", "session_id": id}),
))
.await
.unwrap(),
)
.await;
let said = events[0].1["text"].as_str().unwrap();
assert!(said.contains("back in the list"), "{said}");
assert_eq!(store.list().unwrap().len(), 1);
assert_eq!(store.load(&id).unwrap().len(), 1, "a verb is not a turn");
let events = notices(
app.oneshot(chat_req(
json!({"message": "/archive everything", "session_id": id}),
))
.await
.unwrap(),
)
.await;
assert_eq!(events[0].1["kind"], json!("refusal"));
let said = events[0].1["text"].as_str().unwrap();
assert!(said.contains("`list` or `off`"), "{said}");
}
#[tokio::test]
async fn deleting_from_the_dashboard_takes_the_transcript_title_and_memory() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let store = st.agent.as_ref().unwrap().store().clone();
let id = store.new_id();
store.append(&id, &Message::user("doomed")).unwrap();
store.rename(&id, "a name").unwrap();
let app = router(st);
let r = app
.clone()
.oneshot(write_session(&id, "delete", Some(TEST_CSRF), None))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
assert!(!store.exists(&id), "the whole session, not just the row");
assert!(store.load(&id).is_err(), "the transcript went with it");
let r = app
.clone()
.oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn every_session_write_is_refused_without_the_csrf_token() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let store = st.agent.as_ref().unwrap().store().clone();
let id = store.new_id();
store.append(&id, &Message::user("untouched")).unwrap();
let app = router(st);
for (act, body) in [
("rename", Some(json!({"title": "should not land"}))),
("pin", Some(json!({"pinned": true}))),
("archive", Some(json!({"archived": true}))),
("delete", None),
] {
let r = app
.clone()
.oneshot(write_session(&id, act, None, body))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::FORBIDDEN, "{act}");
let said = body_text(r).await;
assert!(said.contains(CSRF_HEADER), "{act}: {said}");
}
assert_eq!(store.title(&id).unwrap(), None);
assert!(!store.list().unwrap()[0].pinned);
assert!(!store.list().unwrap()[0].archived);
assert!(store.exists(&id));
}
#[tokio::test]
async fn a_session_write_names_an_unknown_session_rather_than_creating_one() {
let dir = tempfile::tempdir().unwrap();
let app = router(state(dir.path(), true));
let r = app
.clone()
.oneshot(write_session(
"no-such-session",
"pin",
Some(TEST_CSRF),
Some(json!({"pinned": true})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::NOT_FOUND);
}
fn cron_state(dir: &std::path::Path) -> Shared {
match Arc::try_unwrap(state(dir, true)) {
Ok(st) => Arc::new(st.with_cron_root(dir.to_path_buf())),
Err(_) => panic!("a state built here is not shared yet"),
}
}
fn cron_env() -> &'static tokio::sync::Mutex<()> {
static LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
&LOCK
}
fn cron_req(
method: &str,
path: &str,
csrf: Option<&str>,
body: Option<serde_json::Value>,
) -> HttpRequest<Body> {
let mut b = HttpRequest::builder()
.method(method)
.uri(path)
.header("host", "127.0.0.1:8787")
.header("origin", "null")
.header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"));
if let Some(token) = csrf {
b = b.header(CSRF_HEADER, token);
}
match body {
Some(v) => b
.header("content-type", "application/json")
.body(Body::from(v.to_string()))
.unwrap(),
None => b.body(Body::empty()).unwrap(),
}
}
fn seed_job(dir: &std::path::Path, name: &str, prompt: &str) {
let job = eclipse_core::cron::Draft {
name: name.to_string(),
schedule: "every 30m".to_string(),
prompt: prompt.to_string(),
..Default::default()
}
.to_job()
.unwrap();
eclipse_core::cron::append_job(dir, &job).unwrap();
}
#[tokio::test]
async fn the_cron_list_is_the_same_job_the_cli_prints() {
let dir = tempfile::tempdir().unwrap();
seed_job(dir.path(), "brief", "summarise yesterday");
let app = router(cron_state(dir.path()));
let body = body_text(
app.oneshot(cron_req("GET", "/api/cron", None, None))
.await
.unwrap(),
)
.await;
let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
assert!(parsed["now_ms"].as_i64().unwrap_or(0) > 0, "{body}");
let jobs = parsed["jobs"].as_array().expect("a jobs array");
assert_eq!(jobs.len(), 1, "{body}");
assert_eq!(jobs[0]["name"], "brief");
assert_eq!(jobs[0]["schedule"], "every 30m");
assert_eq!(jobs[0]["prompt"], "summarise yesterday");
assert_eq!(jobs[0]["enabled"], true);
assert!(jobs[0]["next_ms"].as_i64().is_some(), "{body}");
assert_eq!(jobs[0]["runs"], 0);
}
#[tokio::test]
async fn a_cron_write_without_the_token_is_refused_and_changes_nothing() {
let dir = tempfile::tempdir().unwrap();
let app = router(cron_state(dir.path()));
let r = app
.clone()
.oneshot(cron_req(
"POST",
"/api/cron",
None,
Some(json!({"name": "brief", "schedule": "hourly", "prompt": "x"})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::FORBIDDEN);
let left = eclipse_core::cron::load(dir.path()).unwrap();
assert!(left.is_empty(), "a refused write wrote {:?}", left.len());
}
#[tokio::test]
async fn a_new_job_is_written_into_the_file_the_timer_reads() {
let dir = tempfile::tempdir().unwrap();
let app = router(cron_state(dir.path()));
let r = app
.clone()
.oneshot(cron_req(
"POST",
"/api/cron",
Some(TEST_CSRF),
Some(json!({
"name": "brief",
"schedule": "daily 07:30",
"prompt": "what happened yesterday",
})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::CREATED);
let body = body_text(r).await;
let created: serde_json::Value = serde_json::from_str(&body).expect("json");
assert_eq!(created["schedule"], "daily 07:30", "{body}");
let jobs = eclipse_core::cron::load(dir.path()).unwrap();
assert_eq!(jobs.len(), 1);
assert_eq!(jobs[0].name, "brief");
assert_eq!(jobs[0].prompt, "what happened yesterday");
assert!(jobs[0].enabled);
}
#[tokio::test]
async fn a_schedule_the_parser_refuses_is_refused_in_the_parsers_words() {
let dir = tempfile::tempdir().unwrap();
let app = router(cron_state(dir.path()));
let r = app
.clone()
.oneshot(cron_req(
"POST",
"/api/cron",
Some(TEST_CSRF),
Some(json!({"name": "brief", "schedule": "every tuesday-ish", "prompt": "x"})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::BAD_REQUEST);
let body = body_text(r).await;
let from_parser = eclipse_core::cron::Schedule::parse("every tuesday-ish")
.unwrap_err()
.to_string();
let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
assert_eq!(parsed["error"], from_parser.as_str(), "{body}");
}
#[tokio::test]
async fn a_job_whose_name_is_taken_is_a_conflict_rather_than_a_second_block() {
let dir = tempfile::tempdir().unwrap();
seed_job(dir.path(), "brief", "the first one");
let app = router(cron_state(dir.path()));
let r = app
.clone()
.oneshot(cron_req(
"POST",
"/api/cron",
Some(TEST_CSRF),
Some(json!({"name": "brief", "schedule": "hourly", "prompt": "the second"})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::CONFLICT);
let jobs = eclipse_core::cron::load(dir.path()).unwrap();
assert_eq!(jobs.len(), 1);
assert_eq!(jobs[0].prompt, "the first one");
}
#[tokio::test]
async fn editing_a_job_rewrites_it_and_keeps_its_name() {
let dir = tempfile::tempdir().unwrap();
seed_job(dir.path(), "brief", "the old prompt");
let app = router(cron_state(dir.path()));
let r = app
.clone()
.oneshot(cron_req(
"PUT",
"/api/cron/brief",
Some(TEST_CSRF),
Some(json!({
"name": "brief",
"schedule": "weekly mon 09:00",
"prompt": "the new prompt",
})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
let jobs = eclipse_core::cron::load(dir.path()).unwrap();
assert_eq!(jobs.len(), 1, "an edit is not an append");
assert_eq!(
jobs[0].schedule,
eclipse_core::cron::Schedule::parse("weekly mon 09:00").unwrap()
);
assert_eq!(jobs[0].prompt, "the new prompt");
}
#[tokio::test]
async fn a_rename_through_the_edit_route_is_refused() {
let dir = tempfile::tempdir().unwrap();
seed_job(dir.path(), "brief", "keep me");
let app = router(cron_state(dir.path()));
let r = app
.clone()
.oneshot(cron_req(
"PUT",
"/api/cron/brief",
Some(TEST_CSRF),
Some(json!({"name": "digest", "schedule": "hourly", "prompt": "moved"})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::BAD_REQUEST);
let jobs = eclipse_core::cron::load(dir.path()).unwrap();
assert_eq!(jobs[0].name, "brief");
assert_eq!(jobs[0].prompt, "keep me");
}
#[tokio::test]
async fn a_job_switched_off_stays_in_the_file_and_stops_firing() {
let dir = tempfile::tempdir().unwrap();
seed_job(dir.path(), "brief", "keep me");
let app = router(cron_state(dir.path()));
let r = app
.clone()
.oneshot(cron_req(
"POST",
"/api/cron/brief/enabled",
Some(TEST_CSRF),
Some(json!({"enabled": false})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
let body = body_text(r).await;
let view: serde_json::Value = serde_json::from_str(&body).expect("json");
assert_eq!(view["enabled"], false, "{body}");
assert!(
view["next_ms"].is_null(),
"a disabled job has no next fire: {body}"
);
let jobs = eclipse_core::cron::load(dir.path()).unwrap();
assert_eq!(jobs.len(), 1, "switching off is not deleting");
assert_eq!(jobs[0].prompt, "keep me");
}
#[tokio::test]
async fn removing_a_job_keeps_its_run_logs() {
let dir = tempfile::tempdir().unwrap();
seed_job(dir.path(), "brief", "x");
eclipse_core::cron::write_run(
dir.path(),
"brief",
1_700_000_000_000,
"# brief\n\n---\n\nit ran\n",
)
.unwrap();
let app = router(cron_state(dir.path()));
let r = app
.clone()
.oneshot(cron_req("DELETE", "/api/cron/brief", Some(TEST_CSRF), None))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
assert!(eclipse_core::cron::load(dir.path()).unwrap().is_empty());
assert_eq!(
eclipse_core::cron::recent_runs(dir.path(), "brief", 5).len(),
1,
"the record of what ran outlives the job"
);
let r = app
.clone()
.oneshot(cron_req("DELETE", "/api/cron/brief", Some(TEST_CSRF), None))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn the_logs_route_answers_with_the_text_after_the_header() {
let dir = tempfile::tempdir().unwrap();
seed_job(dir.path(), "brief", "x");
eclipse_core::cron::write_run(
dir.path(),
"brief",
1_700_000_000_000,
"# brief — 2026-11-13 23:13\n\nschedule every 30m\n\n---\n\nthe answer\n",
)
.unwrap();
let app = router(cron_state(dir.path()));
let body = body_text(
app.oneshot(cron_req("GET", "/api/cron/brief/logs?limit=3", None, None))
.await
.unwrap(),
)
.await;
let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
let runs = parsed["runs"].as_array().expect("runs");
assert_eq!(runs.len(), 1, "{body}");
assert_eq!(runs[0]["answer"], "the answer");
assert_eq!(runs[0]["truncated"], false);
assert!(runs[0]["text"].as_str().unwrap().contains("the answer"));
}
#[tokio::test]
async fn run_now_answers_before_the_tick_finishes() {
let _env = cron_env().lock().await;
let dir = tempfile::tempdir().unwrap();
let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../target/fixtures")
.join(std::process::id().to_string())
.join("cron-run");
std::fs::create_dir_all(&fixture).unwrap();
let stub = fixture.join("eclipse");
let seen = fixture.join("seen.txt");
let _ = std::fs::remove_file(&seen);
std::fs::write(
&stub,
format!(
"#!/bin/sh\nprintf '%s\\n' \"$*\" >> {}\nsleep 2\n",
seen.display()
),
)
.unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
}
seed_job(dir.path(), "brief", "x");
std::env::set_var("ECLIPSE_BIN", &stub);
let app = router(cron_state(dir.path()));
let started = std::time::Instant::now();
let r = app
.clone()
.oneshot(cron_req(
"POST",
"/api/cron/brief/run",
Some(TEST_CSRF),
None,
))
.await
.unwrap();
let took = started.elapsed();
std::env::remove_var("ECLIPSE_BIN");
let status = r.status();
let answer = body_text(r).await;
assert_eq!(status, StatusCode::ACCEPTED);
assert!(
took < std::time::Duration::from_millis(1500),
"the handler waited for the tick ({took:?})"
);
let mut seen_text = String::new();
for _ in 0..50 {
if let Ok(t) = std::fs::read_to_string(&seen) {
if t.contains("cron run brief") {
seen_text = t;
break;
}
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
assert!(
seen_text.contains("cron run brief"),
"the stub saw: {seen_text:?}"
);
let parsed: serde_json::Value = serde_json::from_str(&answer).expect("the answer is json");
let pid = parsed["pid"].as_u64().expect("the answer names the pid");
let mut reaped = false;
for _ in 0..40 {
if !std::path::Path::new(&format!("/proc/{pid}")).exists() {
reaped = true;
break;
}
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
}
assert!(
reaped,
"/proc/{pid} is still there: the spawned tick was never reaped"
);
}
#[tokio::test]
async fn the_started_tick_is_told_the_profile_and_config_this_dashboard_uses() {
let _env = cron_env().lock().await;
let dir = tempfile::tempdir().unwrap();
let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../target/fixtures")
.join(std::process::id().to_string())
.join("cron-profile");
std::fs::create_dir_all(&fixture).unwrap();
let stub = fixture.join("eclipse");
let seen = fixture.join("seen.txt");
let _ = std::fs::remove_file(&seen);
std::fs::write(
&stub,
format!("#!/bin/sh\nprintf '%s\\n' \"$*\" >> {}\n", seen.display()),
)
.unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
}
seed_job(dir.path(), "brief", "x");
let config = dir.path().join("config.toml");
let st = Arc::try_unwrap(state(dir.path(), true))
.unwrap_or_else(|_| panic!("a state built here is not shared yet"))
.with_cron_root(dir.path().to_path_buf())
.with_config_path(Some(config.clone()), Some("work".into()));
std::env::set_var("ECLIPSE_BIN", &stub);
let r = router(Arc::new(st))
.oneshot(cron_req(
"POST",
"/api/cron/brief/run",
Some(TEST_CSRF),
None,
))
.await
.unwrap();
std::env::remove_var("ECLIPSE_BIN");
assert_eq!(r.status(), StatusCode::ACCEPTED);
let mut said = String::new();
for _ in 0..50 {
if let Ok(t) = std::fs::read_to_string(&seen) {
if t.contains("cron run brief") {
said = t;
break;
}
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
assert!(said.contains("cron run brief"), "the stub saw: {said:?}");
assert!(
said.contains("--profile work"),
"the tick was started without this dashboard's profile: {said:?}"
);
assert!(
said.contains(&format!("--config {}", config.display())),
"the tick was started without this dashboard's config: {said:?}"
);
}
#[test]
fn an_unnamed_picture_does_not_put_its_data_url_in_the_text() {
let (said, pictures) = compose_attachments(
"what is this?",
&[Attachment {
kind: "image".into(),
name: String::new(),
value: "data:image/png;base64,iVBORw0KGgo=".into(),
}],
)
.unwrap();
assert_eq!(pictures.len(), 1);
assert_eq!(pictures[0].name, "picture");
assert!(
said.contains("--- attached picture: picture (image/png) ---"),
"{said}"
);
assert!(!said.contains("base64"), "the data URL is not text: {said}");
}
#[test]
fn the_body_cap_fits_the_pictures_the_rules_allow() {
let picture_in_base64 = eclipse_core::message::MAX_PICTURE_BYTES / 3 * 4;
assert!(
CHAT_BODY_LIMIT > 2 * picture_in_base64,
"two 2 MiB pictures are {pictures} of data URL and the cap is {CHAT_BODY_LIMIT}",
pictures = 2 * picture_in_base64
);
assert!(
CHAT_BODY_LIMIT > MAX_ATTACHMENTS / 2 * picture_in_base64,
"half a turn of pictures must fit: {CHAT_BODY_LIMIT}"
);
}
fn mcp_state(dir: &std::path::Path, text: &str) -> Shared {
std::fs::write(dir.join("config.toml"), text).unwrap();
state_with(dir, true, Some(dir.join("config.toml")))
}
const FAKE_MCP: &str = r#"#!/usr/bin/env python3
import json, sys
def send(obj):
sys.stdout.write(json.dumps(obj) + "\n"); sys.stdout.flush()
for line in sys.stdin:
line = line.strip()
if not line:
continue
msg = json.loads(line)
mid, method = msg.get("id"), msg.get("method")
if method == "initialize":
send({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": "2024-11-05",
"capabilities": {"tools": {}}, "serverInfo": {"name": "fake", "version": "0"}}})
elif method == "tools/list":
send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
{"name": "echo_text", "description": "Echo", "inputSchema": {"type": "object"}},
{"name": "read_note", "description": "Read", "inputSchema": {"type": "object"}}]}})
"#;
fn fake_mcp(dir: &std::path::Path) -> String {
let path = dir.join("fake_mcp.py");
std::fs::write(&path, FAKE_MCP).unwrap();
path.to_string_lossy().into_owned()
}
fn servers_of(body: &str) -> Vec<serde_json::Value> {
let parsed: serde_json::Value = serde_json::from_str(body).expect("json");
parsed["servers"]
.as_array()
.expect("a servers array")
.clone()
}
#[tokio::test]
async fn the_problems_endpoint_answers_the_shape_the_pane_renders() {
let dir = tempfile::tempdir().unwrap();
let app = router(mcp_state(dir.path(), "[provider]\nmodel = \"m\"\n"));
let body = body_text(
app.oneshot(cron_req("GET", "/api/problems", None, None))
.await
.unwrap(),
)
.await;
let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
assert!(parsed["summary"].is_string(), "{body}");
assert!(parsed["problems"].is_array(), "{body}");
let checked = parsed["checked"].as_array().expect("checked is an array");
assert!(
checked
.iter()
.any(|c| c.as_str().is_some_and(|s| s.starts_with("skill root:"))),
"the readout says what was searched: {body}"
);
for problem in parsed["problems"].as_array().expect("an array") {
assert!(problem["kind"].is_string(), "{problem}");
assert!(problem["text"].is_string(), "{problem}");
}
}
#[tokio::test]
async fn a_config_that_did_not_load_is_reported_beside_the_loader_problems() {
let dir = tempfile::tempdir().unwrap();
let store = SessionStore::new(dir.path().join("sessions"));
let app = router(Arc::new(authed(
None,
store,
"test-<model>",
Some("provider.base_url is not set".into()),
)));
let body = body_text(
app.oneshot(cron_req("GET", "/api/problems", None, None))
.await
.unwrap(),
)
.await;
assert!(
body.contains("provider.base_url is not set"),
"the loader line is carried: {body}"
);
}
#[tokio::test]
async fn an_mcp_entry_in_the_file_is_listed_with_its_source_and_tools() {
let dir = tempfile::tempdir().unwrap();
let script = fake_mcp(dir.path());
let app = router(mcp_state(
dir.path(),
&format!(
"[[mcp]]\nname = \"docs\"\ncommand = \"python3\"\nargs = [\"{script}\"]\n\
timeout_secs = 20\n"
),
));
let body = body_text(
app.oneshot(cron_req("GET", "/api/mcp", None, None))
.await
.unwrap(),
)
.await;
let row = servers_of(&body)
.into_iter()
.find(|r| r["name"] == "docs")
.unwrap_or_else(|| panic!("the entry is not in the list: {body}"));
assert_eq!(row["source"], "config:mcp:docs", "{body}");
assert_eq!(row["tools"], 2, "{body}");
assert_eq!(row["started"], true, "{body}");
assert_eq!(row["protocol"], "2024-11-05", "{body}");
assert_eq!(row["server_name"], "fake", "{body}");
}
#[tokio::test]
async fn switching_an_mcp_server_off_reaches_the_file_and_the_list_agrees() {
let dir = tempfile::tempdir().unwrap();
let app = router(mcp_state(
dir.path(),
"[[mcp]]\nname = \"ghost\"\ncommand = \"/nonexistent/eclipse-test-mcp\"\n",
));
let r = app
.clone()
.oneshot(cron_req(
"POST",
"/api/mcp/ghost/enabled",
Some(TEST_CSRF),
Some(json!({"enabled": false})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
let body = body_text(r).await;
let row: serde_json::Value = serde_json::from_str(&body).expect("json");
assert_eq!(row["disabled"], true, "{body}");
assert_eq!(row["started"], false, "{body}");
assert_eq!(row["tools"], 0, "{body}");
let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
assert!(text.contains("disabled = true"), "{text}");
let listed = body_text(
app.clone()
.oneshot(cron_req("GET", "/api/mcp", None, None))
.await
.unwrap(),
)
.await;
let row = servers_of(&listed)
.into_iter()
.find(|r| r["name"] == "ghost")
.expect("switching off is not deleting");
assert_eq!(row["disabled"], true, "{listed}");
let r = app
.clone()
.oneshot(cron_req(
"POST",
"/api/mcp/ghost/enabled",
Some(TEST_CSRF),
Some(json!({"enabled": true})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
assert!(text.contains("disabled = false"), "{text}");
}
#[tokio::test]
async fn adding_a_server_writes_the_entry_a_duplicate_refuses_and_a_removal_takes() {
let dir = tempfile::tempdir().unwrap();
let script = fake_mcp(dir.path());
let app = router(mcp_state(
dir.path(),
"# mcp servers live below this note\n",
));
let add = json!({"name": "docs", "command": "python3", "args": [script], "policy": "ask"});
let r = app
.clone()
.oneshot(cron_req(
"POST",
"/api/mcp",
Some(TEST_CSRF),
Some(add.clone()),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::CREATED);
let body = body_text(r).await;
let row: serde_json::Value = serde_json::from_str(&body).expect("json");
assert_eq!(row["source"], "config:mcp:docs", "{body}");
assert_eq!(row["tools"], 2, "{body}");
let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
assert!(
text.contains("# mcp servers live below this note"),
"{text}"
);
let r = app
.clone()
.oneshot(cron_req("POST", "/api/mcp", Some(TEST_CSRF), Some(add)))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::CONFLICT);
let body = body_text(r).await;
assert!(body.contains("is already declared at line"), "{body}");
let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
assert_eq!(text.matches("[[mcp]]").count(), 1, "{text}");
let r = app
.clone()
.oneshot(cron_req(
"POST",
"/api/mcp",
Some(TEST_CSRF),
Some(json!({"name": "mixed", "transport": "http", "command": "python3"})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::BAD_REQUEST);
let body = body_text(r).await;
assert!(body.contains("that entry is not usable"), "{body}");
let r = app
.clone()
.oneshot(cron_req("DELETE", "/api/mcp/docs", Some(TEST_CSRF), None))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
assert!(!text.contains("[[mcp]]"), "{text}");
let listed = body_text(
app.clone()
.oneshot(cron_req("GET", "/api/mcp", None, None))
.await
.unwrap(),
)
.await;
assert!(servers_of(&listed).is_empty(), "{listed}");
let r = app
.oneshot(cron_req("DELETE", "/api/mcp/docs", Some(TEST_CSRF), None))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn editing_an_entry_changes_one_field_and_leaves_the_neighbours_byte_identical() {
let dir = tempfile::tempdir().unwrap();
let before = "# the ghost\n[[mcp]]\nname = \"ghost\"\ncommand = \"/nonexistent/one\"\n\n\
# the other one\n[[mcp]]\nname = \"other\"\n\
command = \"/nonexistent/two\"\npolicy = \"allow\"\n";
let app = router(mcp_state(dir.path(), before));
let r = app
.clone()
.oneshot(cron_req(
"PUT",
"/api/mcp/other",
Some(TEST_CSRF),
Some(json!({
"name": "other",
"command": "/nonexistent/three",
"policy": "allow",
})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
let after = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
assert_eq!(
after,
before.replace("/nonexistent/two", "/nonexistent/three"),
"an edit is not a remove and an add:\n{after}"
);
let listed = body_text(
app.clone()
.oneshot(cron_req("GET", "/api/mcp", None, None))
.await
.unwrap(),
)
.await;
let row = servers_of(&listed)
.into_iter()
.find(|r| r["name"] == "other")
.expect("the edited entry is still listed");
assert_eq!(row["program"], "/nonexistent/three", "{listed}");
assert_eq!(row["args"], json!([]), "{listed}");
}
#[tokio::test]
async fn a_token_env_typed_in_the_form_is_written_and_the_listing_says_whether_it_resolves() {
let dir = tempfile::tempdir().unwrap();
let key = format!("ECLIPSE_TEST_WEB_MCP_TOKEN{}", "_SET");
std::env::set_var(&key, "kept-here");
let before = "[[mcp]]\nname = \"ha\"\ntransport = \"http\"\n\
url = \"http://127.0.0.1:9/api/mcp\"\n";
let app = router(mcp_state(dir.path(), before));
let put = |token: String| {
json!({
"name": "ha",
"transport": "http",
"url": "http://127.0.0.1:9/api/mcp",
"token_env": token,
})
};
let r = app
.clone()
.oneshot(cron_req(
"PUT",
"/api/mcp/ha",
Some(TEST_CSRF),
Some(put(key.clone())),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
let body = body_text(r).await;
let row: serde_json::Value = serde_json::from_str(&body).expect("json");
assert_eq!(row["token_env"], key.as_str(), "{body}");
assert_eq!(row["token"], "env", "it resolves: {body}");
assert!(
!body.contains("kept-here"),
"the row carries the word, never the value: {body}"
);
let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
assert!(
text.contains(&format!("token_env = \"{key}\"")),
"the variable name is what the file carries: {text}"
);
let absent = format!("{key}_UNSET");
let r = app
.clone()
.oneshot(cron_req(
"PUT",
"/api/mcp/ha",
Some(TEST_CSRF),
Some(put(absent.clone())),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK);
let body = body_text(r).await;
let row: serde_json::Value = serde_json::from_str(&body).expect("json");
assert_eq!(row["token"], "unset", "{body}");
assert_eq!(row["token_env"], absent.as_str(), "{body}");
std::env::remove_var(&key);
}
#[tokio::test]
async fn an_unknown_entry_is_a_404_a_bad_body_and_a_rename_change_nothing() {
let dir = tempfile::tempdir().unwrap();
let before = "[[mcp]]\nname = \"ghost\"\ncommand = \"/nonexistent/one\"\n";
let app = router(mcp_state(dir.path(), before));
let config = dir.path().join("config.toml");
let r = app
.clone()
.oneshot(cron_req(
"PUT",
"/api/mcp/nope",
Some(TEST_CSRF),
Some(json!({"command": "/nonexistent/any"})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::NOT_FOUND);
let body = body_text(r).await;
assert!(body.contains("no `[[mcp]]` entry for `nope`"), "{body}");
let r = app
.clone()
.oneshot(
HttpRequest::builder()
.method("PUT")
.uri("/api/mcp/ghost")
.header("host", "127.0.0.1:8787")
.header("origin", "null")
.header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
.header(CSRF_HEADER, TEST_CSRF)
.header("content-type", "application/json")
.body(Body::from("{\"command\": "))
.unwrap(),
)
.await
.unwrap();
assert!(
!r.status().is_success(),
"a malformed body is not a saved entry: {}",
body_text(r).await
);
let r = app
.clone()
.oneshot(cron_req(
"PUT",
"/api/mcp/ghost",
Some(TEST_CSRF),
Some(json!({"name": "renamed", "command": "/nonexistent/one"})),
))
.await
.unwrap();
assert_eq!(r.status(), StatusCode::BAD_REQUEST);
let body = body_text(r).await;
assert!(body.contains("an edit does not rename"), "{body}");
assert_eq!(
std::fs::read_to_string(&config).unwrap(),
before,
"three refusals, and the file is exactly what it was"
);
}
fn bot_state(dir: &std::path::Path) -> (Shared, std::path::PathBuf) {
let ws = dir.join("ws");
std::fs::create_dir_all(ws.join(".eclipse/skills/one")).unwrap();
std::fs::write(
ws.join(".eclipse/skills/one/SKILL.md"),
"---\nname: one\ndescription: the skill this bot declared\n---\nbody one\n",
)
.unwrap();
let instructions = dir.join("nox.md");
std::fs::write(&instructions, "you are nox, and this is your own prompt\n").unwrap();
let config = dir.join("config.toml");
std::fs::write(
&config,
format!(
r#"
[provider]
base_url = "http://127.0.0.1:1/v1"
model = "test"
api_key = "k"
[sessions]
dir = {sessions:?}
[tools]
workspace_root = {workspace:?}
[bots.nox]
instructions = {instructions:?}
skills = ["one"]
adapter = "telegram"
"#,
sessions = dir.join("sessions").display().to_string(),
workspace = ws.display().to_string(),
instructions = instructions.display().to_string(),
),
)
.unwrap();
let cfg = eclipse_core::config::Config::from_file(&config).unwrap();
let home = dir.join("home");
std::fs::create_dir_all(&home).unwrap();
let env = |key: &str| (key == "HOME").then(|| home.display().to_string());
let store = SessionStore::new(cfg.sessions_dir(&env).unwrap());
let agent = Arc::new(Agent::new(
Arc::new(Canned),
Arc::new(ToolRegistry::default()),
store.clone(),
"sys".into(),
3,
));
let mut st =
authed(Some(agent), store, "test-<model>", None).with_config_path(Some(config), None);
st.bots = crate::bots::Bots::build(&cfg, &env);
(Arc::new(st), instructions)
}
#[tokio::test]
async fn a_page_with_no_bots_carries_no_bots_tab() {
let dir = tempfile::tempdir().unwrap();
let app = router(state(dir.path(), true));
let page = body_text(app.oneshot(get_req("/", "127.0.0.1:8787")).await.unwrap()).await;
assert!(
!page.contains("id=\"bots\""),
"a config with no bots grew a Bots button: the Sessions tab is not unchanged"
);
assert!(
!page.contains("<section id=\"botspane\""),
"the pane is in the page with no bots"
);
assert!(
page.contains("<ul id=\"sessions\">"),
"the session list is still there"
);
}
#[tokio::test]
async fn a_declared_bot_lists_and_opens_one_session_with_its_own_origin() {
let dir = tempfile::tempdir().unwrap();
let (st, _) = bot_state(dir.path());
let app = router(st.clone());
let listed = body_text(
app.clone()
.oneshot(get_req("/api/bots", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
let rows: Vec<serde_json::Value> = serde_json::from_str(&listed).unwrap();
assert_eq!(rows.len(), 1, "{listed}");
assert_eq!(rows[0]["name"], "nox");
assert_eq!(
rows[0]["lane"], "telegram",
"the declaration's lane is what the row says"
);
assert!(rows[0]["last_session"].is_null(), "it has not spoken yet");
assert!(rows[0]["problem"].is_null(), "{listed}");
let open = |app: axum::Router| async move {
body_text(
app.oneshot(
HttpRequest::post("/api/bots/nox/open")
.header("host", "127.0.0.1:8787")
.header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
.header("content-type", "application/json")
.body(Body::from("{}"))
.unwrap(),
)
.await
.unwrap(),
)
.await
};
let first = open(app.clone()).await;
let second = open(app.clone()).await;
let first: serde_json::Value = serde_json::from_str(&first).unwrap();
let second: serde_json::Value = serde_json::from_str(&second).unwrap();
let id = first["session_id"].as_str().unwrap().to_string();
assert_eq!(
second["session_id"], first["session_id"],
"opening a bot twice made two conversations"
);
assert_eq!(
st.store.origin(&id).unwrap().as_deref(),
Some("bot:nox"),
"the row the send path reads its identity from"
);
let mine = body_text(
app.clone()
.oneshot(get_req("/api/sessions", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
assert!(
!mine.contains(&id),
"a bot's conversation reached the sidebar: {mine}"
);
let agent = st.bots.agent("nox").unwrap().as_ref().unwrap();
assert!(agent.system_prompt().contains("you are nox"));
}
#[tokio::test]
async fn a_bot_conversation_is_cleared_not_deleted() {
let dir = tempfile::tempdir().unwrap();
let (st, _) = bot_state(dir.path());
let app = router(st.clone());
let open = |app: axum::Router, uri: &'static str| async move {
let r = app
.oneshot(
HttpRequest::post(uri)
.header("host", "127.0.0.1:8787")
.header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
.header("content-type", "application/json")
.body(Body::from("{}"))
.unwrap(),
)
.await
.unwrap();
(r.status(), body_text(r).await)
};
let (_, body) = open(app.clone(), "/api/bots/nox/open").await;
let first: serde_json::Value = serde_json::from_str(&body).unwrap();
let first = first["session_id"].as_str().unwrap().to_string();
let (status, body) = open(app.clone(), "/api/bots/nox/clear").await;
assert_eq!(status, StatusCode::OK, "{body}");
let cleared: serde_json::Value = serde_json::from_str(&body).unwrap();
assert_eq!(cleared["archived"], 1);
let fresh = cleared["session_id"].as_str().unwrap();
assert_ne!(
fresh, first,
"a cleared bot kept the conversation it was told to file away"
);
assert!(st.store.exists(&first), "clearing deleted the transcript");
let bots = st.store.list_bots().unwrap();
assert_eq!(bots[0].sessions, 2, "both conversations are counted");
assert_eq!(bots[0].last_session, fresh);
}
#[tokio::test]
async fn the_prompt_view_reads_the_instructions_file_from_disk() {
let dir = tempfile::tempdir().unwrap();
let (st, instructions) = bot_state(dir.path());
std::fs::write(
&instructions,
"you are nox, rewritten after the process started\n",
)
.unwrap();
let app = router(st);
let body = body_text(
app.oneshot(get_req("/api/bots/nox/prompt", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
let data: serde_json::Value = serde_json::from_str(&body).unwrap();
assert_eq!(data["name"], "nox");
assert!(
data["instructions"]["body"]
.as_str()
.unwrap_or_default()
.contains("rewritten after the process started"),
"{body}"
);
assert_eq!(data["skills"], serde_json::json!(["one"]));
assert_eq!(data["adapter"], "telegram");
}
#[tokio::test]
async fn a_page_with_no_flare_runs_carries_no_flares_tab() {
let dir = tempfile::tempdir().unwrap();
let app = router(state(dir.path(), true));
let page = body_text(app.oneshot(get_req("/", "127.0.0.1:8787")).await.unwrap()).await;
assert!(
!page.contains("id=\"flares\""),
"a person with no flare runs grew a Flares button"
);
assert!(
!page.contains("<section id=\"flarespane\""),
"the pane is in the page with no runs to show"
);
assert!(
page.contains("main.flares #flarespane"),
"the tab's styles are part of the page, not spliced with it"
);
assert!(
page.contains("<ul id=\"sessions\">"),
"the session list is still there"
);
}
#[tokio::test]
async fn a_flare_run_lists_its_children_and_a_cancel_reaches_the_store() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path(), true);
let store = st.store.clone();
store
.begin_flare_run(
"run-1",
"audit the retry paths",
&["local".to_string(), "cloud".to_string()],
2,
"web",
)
.unwrap();
store.begin_flare("flare-child-1", "run-1", 1).unwrap();
store
.flare_job_running("run-1", 1, "local", "flare-child-1")
.unwrap();
store
.flare_job_done(&FlareJobRow {
run_id: "run-1".into(),
n: 1,
route: "local".into(),
session_id: Some("flare-child-1".into()),
state: "done".into(),
prompt_tokens: Some(1200),
completion_tokens: Some(340),
iterations: 2,
why: None,
})
.unwrap();
store
.flare_job_done(&FlareJobRow {
run_id: "run-1".into(),
n: 2,
route: "cloud".into(),
session_id: None,
state: "dropped".into(),
prompt_tokens: None,
completion_tokens: None,
iterations: 0,
why: Some("the run was cancelled before it started".into()),
})
.unwrap();
store
.finish_flare_run("run-1", "cancelled", Some(1200), Some(340), 2)
.unwrap();
let app = router(st);
let page = body_text(
app.clone()
.oneshot(get_req("/", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
assert!(
page.contains("id=\"flares\""),
"the sidebar has no Flares button"
);
assert!(
page.contains("<section id=\"flarespane\""),
"the pane is missing"
);
assert!(
page.contains("main.flares #flarespane"),
"the pane's styles came with the page"
);
let listed = body_text(
app.clone()
.oneshot(get_req("/api/flares", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
let rows: Vec<serde_json::Value> = serde_json::from_str(&listed).unwrap();
assert_eq!(rows.len(), 1, "{listed}");
assert_eq!(rows[0]["id"], "run-1");
assert_eq!(
rows[0]["jobs"], 2,
"the count the run planned, not the children that started"
);
assert_eq!(
rows[0]["routes"],
serde_json::json!(["local", "cloud"]),
"the routes the run named"
);
assert_eq!(rows[0]["state"], "cancelled");
assert_eq!(rows[0]["running"], false);
assert_eq!(rows[0]["prompt_tokens"], 1200);
let one = body_text(
app.clone()
.oneshot(get_req("/api/flares/run-1", "127.0.0.1:8787"))
.await
.unwrap(),
)
.await;
let one: serde_json::Value = serde_json::from_str(&one).unwrap();
assert_eq!(
one["jobs"][0]["session_id"], "flare-child-1",
"the session a click opens in the transcript view"
);
assert_eq!(one["jobs"][0]["completion_tokens"], 340);
assert!(
one["jobs"][1]["session_id"].is_null(),
"a dropped child has no transcript"
);
assert!(
one["jobs"][1]["prompt_tokens"].is_null(),
"a dropped child costs nothing, and `null` is what the page turns into `?`"
);
assert_eq!(
one["jobs"][1]["why"],
"the run was cancelled before it started"
);
let cancelled = app
.clone()
.oneshot(
HttpRequest::post("/api/flares/run-1/cancel")
.header("host", "127.0.0.1:8787")
.header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
.header("content-type", "application/json")
.body(Body::from("{}"))
.unwrap(),
)
.await
.unwrap();
let status = cancelled.status();
let body = body_text(cancelled).await;
assert_eq!(status, StatusCode::OK, "{body}");
assert!(
body.contains("next boundary"),
"the answer says what a cancel does, not that it is done: {body}"
);
assert!(
store.flare_cancel_requested("run-1").unwrap(),
"the flag the run checks between children"
);
let missing = app
.oneshot(get_req("/api/flares/nope", "127.0.0.1:8787"))
.await
.unwrap();
assert_eq!(missing.status(), StatusCode::NOT_FOUND);
}
}