1use crate::calls;
4use crate::verb::{self, Answer};
5use async_trait::async_trait;
6use axum::extract::{DefaultBodyLimit, Path, Query, Request, State};
7use axum::http::{header, HeaderMap, HeaderValue, Method, StatusCode};
8use axum::middleware::{self, Next};
9use axum::response::sse::{Event, KeepAlive, Sse};
10use axum::response::{Html, IntoResponse, Response};
11use axum::routing::{get, post, put};
12use axum::{Form, Json, Router};
13use eclipse_core::cancel::Cancel;
14use eclipse_core::commands::{Front, Parsed};
15use eclipse_core::contextbar::Reading;
16use eclipse_core::runtime::{Agent, AgentEvent, RunOptions};
17use eclipse_core::session::{FlareJobRow, FlareRunRow};
18use eclipse_core::tools::Approver;
19use futures_util::stream::{self, Stream};
20use futures_util::StreamExt;
21use serde::Deserialize;
22use serde_json::json;
23use std::collections::HashMap;
24use std::convert::Infallible;
25use std::sync::atomic::{AtomicU64, Ordering};
26use std::sync::{Arc, Mutex};
27use std::time::{Duration, Instant};
28use tokio::sync::{mpsc, oneshot, Semaphore};
29
30const INDEX_HTML: &str = include_str!("index.html");
31
32const BOTS_PANE: &str = r#" <section id="botspane" hidden aria-label="bots">
39 <header>
40 <h2>bots</h2>
41 <small id="botsfile"></small>
42 <span class="grow"></span>
43 <button id="botsrefresh" type="button">refresh</button>
44 </header>
45 <div id="botsmsg"></div>
46 <table id="botstable">
47 <thead><tr><th>bot</th><th>lane</th><th>last</th><th>said</th><th></th></tr></thead>
48 <tbody id="botsrows"></tbody>
49 </table>
50 <div id="botsprompt" hidden></div>
51 </section>
52"#;
53
54const FLARES_PANE: &str = r#" <section id="flarespane" hidden aria-label="flare runs">
61 <header>
62 <h2>flare runs</h2>
63 <small id="flaresfile"></small>
64 <span class="grow"></span>
65 <button id="flaresrefresh" type="button">refresh</button>
66 </header>
67 <div id="flaresmsg"></div>
68 <table id="flaretable">
69 <thead><tr><th>run</th><th>state</th><th>age</th><th>routes</th><th>jobs</th><th>cost</th><th></th></tr></thead>
70 <tbody id="flarerows"></tbody>
71 </table>
72 </section>
73"#;
74
75pub const CHAT_BODY_LIMIT: usize = MAX_ATTACHMENTS
84 * (eclipse_core::message::MAX_PICTURE_BYTES / 3 * 4 + 1024)
85 + MAX_ATTACHED_CHARS;
86
87const MARK_SVG: &str = include_str!("../static/eclipse-mark.svg");
98
99const FAVICON_ICO: &[u8] = include_bytes!("../static/eclipse.ico");
101
102fn mark_svg() -> String {
110 use eclipse_core::palette as p;
111 let hex = |c: (u8, u8, u8)| format!("#{:02X}{:02X}{:02X}", c.0, c.1, c.2);
112 MARK_SVG
113 .replace("#FF8A2B", &hex(p::ACCENT))
115 .replace("#FFB45E", &hex(p::ACCENT))
116 .replace("#FFF7E8", &hex(p::WORDMARK_TOP))
118 .replace("#05060D", &hex(p::BG))
119}
120const LOGIN_HTML: &str = include_str!("login.html");
121
122const SESSION_COOKIE: &str = "eclipse_session";
123
124const MAX_LOGINS: usize = 32;
127
128pub const MAX_CONCURRENT_CHATS: usize = 4;
132
133const APPROVAL_TIMEOUT: Duration = Duration::from_secs(120);
135
136struct Pending {
137 run: u64,
138 decide: oneshot::Sender<bool>,
139}
140
141#[derive(Default)]
144struct Approvals {
145 pending: Mutex<HashMap<String, Pending>>,
146 next_run: AtomicU64,
147}
148
149impl Approvals {
150 fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, Pending>> {
151 self.pending.lock().unwrap_or_else(|e| e.into_inner())
152 }
153
154 fn resolve(&self, id: &str, approved: bool) -> bool {
156 match self.lock().remove(id) {
157 Some(p) => {
158 let _ = p.decide.send(approved);
159 true
160 }
161 None => false,
162 }
163 }
164
165 #[cfg(test)]
166 fn len(&self) -> usize {
167 self.lock().len()
168 }
169}
170
171struct RunScope {
174 state: Shared,
175 run: u64,
176 token: String,
177}
178
179impl Drop for RunScope {
180 fn drop(&mut self) {
181 self.state.approvals.lock().retain(|_, p| p.run != self.run);
182 self.state
183 .cancels
184 .lock()
185 .unwrap_or_else(|e| e.into_inner())
186 .remove(&self.token);
187 }
188}
189
190struct DisconnectGuard {
193 cancel: Cancel,
194}
195
196impl Drop for DisconnectGuard {
197 fn drop(&mut self) {
198 self.cancel.cancel();
199 }
200}
201
202#[derive(Clone, Copy, PartialEq, Eq)]
203enum Verdict {
204 Approved,
205 Denied,
206 TimedOut,
207 Cancelled,
208}
209
210impl Verdict {
211 fn as_str(self) -> &'static str {
212 match self {
213 Verdict::Approved => "approved",
214 Verdict::Denied => "denied",
215 Verdict::TimedOut => "timeout",
216 Verdict::Cancelled => "cancelled",
217 }
218 }
219}
220
221struct WebApprover {
224 state: Shared,
225 run: u64,
226 events: mpsc::UnboundedSender<Out>,
227}
228
229#[async_trait]
230impl Approver for WebApprover {
231 async fn decide(
232 &self,
233 call: &eclipse_core::approvals::Pending,
234 ) -> eclipse_core::approvals::Decision {
235 use eclipse_core::approvals::Decision;
236 let (tool, summary) = (call.tool.as_str(), call.summary.as_str());
237 let Ok(id) = eclipse_core::token::random_hex(16) else {
238 return Decision::Defer;
239 };
240 if self.state.yolo.on() {
243 self.state
244 .unasked
245 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
246 return Decision::Allow;
247 }
248 let (decide, answer) = oneshot::channel();
249 self.state.approvals.lock().insert(
251 id.clone(),
252 Pending {
253 run: self.run,
254 decide,
255 },
256 );
257 let request = Out::ApprovalRequest {
258 id: id.clone(),
259 tool: tool.to_string(),
260 summary: summary.to_string(),
261 timeout_secs: self.state.approval_timeout.as_secs(),
262 };
263 let verdict = if self.events.send(request).is_err() {
264 Verdict::Cancelled
265 } else {
266 tokio::select! {
267 r = answer => match r {
268 Ok(true) => Verdict::Approved,
269 Ok(false) => Verdict::Denied,
270 Err(_) => Verdict::Cancelled,
271 },
272 _ = tokio::time::sleep(self.state.approval_timeout) => Verdict::TimedOut,
273 _ = self.events.closed() => Verdict::Cancelled,
275 }
276 };
277 self.state.approvals.lock().remove(&id);
278 let _ = self.events.send(Out::ApprovalResolved { id, verdict });
279 match verdict {
280 Verdict::Approved => Decision::Allow,
281 Verdict::TimedOut => Decision::Deny("the approval request timed out".to_string()),
285 Verdict::Cancelled => Decision::Defer,
286 Verdict::Denied => Decision::Deny("declined in the panel".to_string()),
287 }
288 }
289}
290
291struct Session {
294 expires: Instant,
295 csrf: String,
302}
303
304struct Logins {
305 sessions: Mutex<HashMap<String, Session>>,
306 ttl: Duration,
309}
310
311impl Logins {
312 fn new(ttl: Duration) -> Self {
313 Self {
314 sessions: Mutex::default(),
315 ttl,
316 }
317 }
318
319 fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, Session>> {
320 self.sessions.lock().unwrap_or_else(|e| e.into_inner())
321 }
322
323 fn create(&self) -> Option<(String, String)> {
325 let id = eclipse_core::token::random_hex(32).ok()?;
326 let csrf = eclipse_core::token::random_hex(32).ok()?;
327 let now = Instant::now();
328 let mut map = self.lock();
329 map.retain(|_, s| s.expires > now);
330 while map.len() >= MAX_LOGINS {
331 let oldest = map
332 .iter()
333 .min_by_key(|(_, s)| s.expires)
334 .map(|(k, _)| k.clone())?;
335 map.remove(&oldest);
336 }
337 map.insert(
338 id.clone(),
339 Session {
340 expires: now + self.ttl,
341 csrf: csrf.clone(),
342 },
343 );
344 Some((id, csrf))
345 }
346
347 fn is_valid(&self, id: &str) -> bool {
348 let mut map = self.lock();
349 match map.get(id) {
350 Some(s) if s.expires > Instant::now() => true,
351 Some(_) => {
352 map.remove(id);
353 false
354 }
355 None => false,
356 }
357 }
358
359 fn csrf_for(&self, id: &str) -> Option<String> {
361 let now = Instant::now();
362 self.lock()
363 .get(id)
364 .filter(|s| s.expires > now)
365 .map(|s| s.csrf.clone())
366 }
367
368 fn csrf_ok(&self, id: &str, presented: &str) -> bool {
371 self.csrf_for(id)
372 .is_some_and(|want| eclipse_core::token::constant_time_eq(presented, &want))
373 }
374
375 fn remove(&self, id: &str) {
376 self.lock().remove(id);
377 }
378}
379
380pub struct AppState {
381 pub agent: Option<Arc<Agent>>,
383 pub store: eclipse_core::session::SessionStore,
384 pub model: String,
385 pub config_error: Option<String>,
386 chat_slots: Arc<Semaphore>,
387 approvals: Approvals,
388 cancels: Mutex<HashMap<String, Cancel>>,
391 approval_timeout: Duration,
392 pub yolo: eclipse_core::yolo::Yolo,
399 pub unasked: std::sync::atomic::AtomicUsize,
402 auth_token: String,
403 auth: eclipse_core::auth::Credentials,
408 login_ttl: Duration,
411 logins: Logins,
412 throttle: LoginThrottle,
414 pub config_path: Option<std::path::PathBuf>,
418 pub profile: Option<String>,
419 pub config_explicit: bool,
424 pub profiles_root: Option<std::path::PathBuf>,
429 pub cron_root: Option<std::path::PathBuf>,
431 pub config_writes: Arc<std::sync::Mutex<()>>,
436 pub model_probe: Arc<std::sync::Mutex<Option<(std::time::Instant, bool)>>>,
439 ticking: Mutex<std::collections::HashSet<String>>,
443 pub update: Option<eclipse_core::update::Watch>,
447 pub bots: crate::bots::Bots,
451}
452
453impl AppState {
454 pub fn new(
455 agent: Option<Arc<Agent>>,
456 store: eclipse_core::session::SessionStore,
457 model: String,
458 config_error: Option<String>,
459 auth_token: String,
460 login_ttl: Duration,
461 ) -> Self {
462 Self {
463 agent,
464 store,
465 model,
466 config_error,
467 chat_slots: Arc::new(Semaphore::new(MAX_CONCURRENT_CHATS)),
468 approvals: Approvals::default(),
469 cancels: Mutex::default(),
470 approval_timeout: APPROVAL_TIMEOUT,
471 yolo: eclipse_core::yolo::Yolo::new(false),
474 unasked: std::sync::atomic::AtomicUsize::new(0),
475 auth_token,
476 auth: eclipse_core::auth::Credentials::Token,
479 login_ttl,
480 logins: Logins::new(login_ttl),
481 throttle: LoginThrottle::default(),
482 config_path: None,
483 profile: None,
484 config_explicit: false,
485 profiles_root: None,
486 cron_root: None,
487 config_writes: Arc::new(std::sync::Mutex::new(())),
488 model_probe: Arc::new(std::sync::Mutex::default()),
489 ticking: Mutex::default(),
490 update: None,
491 bots: crate::bots::Bots::empty(),
492 }
493 }
494
495 pub fn with_bots(
500 mut self,
501 cfg: &eclipse_core::config::Config,
502 env: eclipse_core::config::EnvFn,
503 ) -> Self {
504 self.bots = crate::bots::Bots::build(cfg, env);
505 self
506 }
507
508 fn agent_for(&self, session: &str) -> std::result::Result<Option<Arc<Agent>>, String> {
515 let origin = self.store.origin(session).ok().flatten();
516 let Some(name) = origin.as_deref().and_then(|o| o.strip_prefix("bot:")) else {
517 return Ok(self.agent.clone());
518 };
519 match self.bots.agent(name) {
520 Some(Ok(agent)) => Ok(Some(Arc::clone(agent))),
521 Some(Err(why)) => Err(format!("bot `{name}` cannot run: {why}")),
522 None => Err(format!(
523 "this session belongs to bot `{name}`, which is no longer declared in `[bots]`"
524 )),
525 }
526 }
527
528 pub fn claim_tick(&self, session: &str) -> bool {
530 self.ticking
531 .lock()
532 .unwrap_or_else(|e| e.into_inner())
533 .insert(session.to_string())
534 }
535
536 pub fn release_tick(&self, session: &str) {
538 self.ticking
539 .lock()
540 .unwrap_or_else(|e| e.into_inner())
541 .remove(session);
542 }
543
544 pub fn try_chat_slot(&self) -> Option<tokio::sync::OwnedSemaphorePermit> {
550 self.chat_slots.clone().try_acquire_owned().ok()
551 }
552
553 pub fn token(&self) -> &str {
556 &self.auth_token
557 }
558
559 pub fn with_credentials(mut self, auth: eclipse_core::auth::Credentials) -> Self {
561 self.auth = auth;
562 self
563 }
564
565 pub fn auth_mode(&self) -> &'static str {
567 self.auth.mode()
568 }
569
570 pub fn with_cron_root(mut self, root: std::path::PathBuf) -> Self {
572 self.cron_root = Some(root);
573 self
574 }
575
576 pub fn with_config_path(
578 mut self,
579 path: Option<std::path::PathBuf>,
580 profile: Option<String>,
581 ) -> Self {
582 self.config_path = path;
583 self.profile = profile;
584 self
585 }
586
587 pub fn with_config_targets(
590 mut self,
591 explicit: bool,
592 profiles_root: Option<std::path::PathBuf>,
593 ) -> Self {
594 self.config_explicit = explicit;
595 self.profiles_root = profiles_root;
596 self
597 }
598
599 pub(crate) fn write_path(&self) -> Option<std::path::PathBuf> {
606 let explicit = if self.config_explicit {
607 self.config_path.as_deref()
608 } else {
609 None
610 };
611 eclipse_core::config::write_target(
612 self.profiles_root.as_deref(),
613 explicit,
614 self.config_path.as_deref(),
615 self.profile.as_deref(),
616 )
617 .or_else(|| self.config_path.clone())
618 }
619
620 pub(crate) fn reload_config(&self) -> Result<eclipse_core::config::Config, String> {
622 let path = self
623 .config_path
624 .as_ref()
625 .ok_or_else(|| "this dashboard was started without a config file".to_string())?;
626 eclipse_core::config::Config::load_with_profile(
627 Some(path),
628 self.profile.as_deref(),
629 &eclipse_core::config::process_env,
630 )
631 .map_err(|e| e.to_string())
632 }
633
634 pub fn current_model(&self) -> Option<String> {
640 self.agent
641 .as_ref()
642 .and_then(|a| a.model())
643 .or_else(|| (!self.model.is_empty()).then(|| self.model.clone()))
644 }
645
646 pub(crate) fn configured_model(&self) -> Option<String> {
649 (!self.model.is_empty()).then(|| self.model.clone())
650 }
651
652 #[cfg(test)]
654 fn with_login(self, id: &str) -> Self {
655 self.logins.lock().insert(
656 id.to_string(),
657 Session {
658 expires: Instant::now() + self.login_ttl,
659 csrf: TEST_CSRF.to_string(),
660 },
661 );
662 self
663 }
664
665 #[cfg(test)]
666 fn with_approval_timeout(mut self, timeout: Duration) -> Self {
667 self.approval_timeout = timeout;
668 self
669 }
670}
671
672pub type Shared = Arc<AppState>;
673
674pub fn routes(state: Shared) -> Router<Shared> {
677 Router::new()
678 .route("/", get(index))
679 .route("/login", get(login_page).post(login))
680 .route("/logout", post(logout))
681 .route("/healthz", get(health))
682 .route("/api/update", get(update_state))
683 .route("/api/sessions", get(list_sessions))
684 .route("/api/bots", get(list_bots))
687 .route("/api/bots/:name/open", post(open_bot))
688 .route("/api/bots/:name/rename", post(rename_bot))
689 .route("/api/bots/:name/clear", post(clear_bot))
690 .route("/api/bots/:name/prompt", get(bot_prompt))
691 .route("/api/flares", get(list_flares))
696 .route("/api/flares/:run", get(read_flare))
697 .route("/api/flares/:run/cancel", post(cancel_flare))
698 .route("/api/sessions/:id", get(get_session))
699 .route("/api/sessions/:id/rename", post(rename_session))
700 .route("/api/sessions/:id/pin", post(pin_session))
701 .route("/api/sessions/:id/archive", post(archive_session))
702 .route("/api/sessions/:id/delete", post(delete_session))
703 .route("/api/search", get(search_sessions))
704 .route("/api/settings", get(list_settings).post(write_setting))
705 .route("/api/context", get(list_context).post(write_context))
709 .route("/api/models", get(list_models))
710 .route("/api/commands", get(list_commands))
711 .route("/api/model", post(choose_model))
712 .route("/api/reasoning", get(read_reasoning).post(choose_reasoning))
713 .route("/api/chat", post(chat))
714 .route("/api/approvals/:id", post(decide_approval))
715 .route("/api/runs/:id/cancel", post(cancel_run))
716 .route("/logo.svg", get(logo))
719 .route("/favicon.ico", get(favicon))
720 .route("/api/cron", get(list_cron).post(create_cron))
724 .route("/api/cron/:name", put(update_cron).delete(delete_cron))
725 .route("/api/cron/:name/enabled", post(set_cron_enabled))
726 .route("/api/cron/:name/run", post(run_cron_now))
727 .route("/api/cron/:name/logs", get(cron_logs))
728 .route("/api/problems", get(list_problems))
734 .route("/api/mcp", get(list_mcp).post(add_mcp))
735 .route("/api/mcp/:name", put(update_mcp).delete(remove_mcp))
738 .route("/api/mcp/:name/enabled", post(set_mcp_enabled))
739 .route("/api/mcp/:name/test", post(test_mcp))
740 .layer(middleware::from_fn(refuse_oversized))
745 .layer(DefaultBodyLimit::max(CHAT_BODY_LIMIT))
746 .layer(middleware::from_fn_with_state(state.clone(), require_login))
747 .layer(middleware::from_fn_with_state(
748 state.clone(),
749 guard_local_origin,
750 ))
751}
752
753async fn refuse_oversized(req: Request, next: Next) -> Response {
761 if req.method() == Method::POST && req.uri().path() == "/api/chat" {
762 let declared = req
763 .headers()
764 .get(header::CONTENT_LENGTH)
765 .and_then(|v| v.to_str().ok())
766 .and_then(|v| v.parse::<usize>().ok());
767 if let Some(len) = declared {
768 if len > CHAT_BODY_LIMIT {
769 let mb = |n: usize| format!("{:.1} MB", n as f64 / (1024.0 * 1024.0));
770 let sentence = format!(
771 "that message is {} ({} over the {} limit for one turn) — attach fewer or \
772 smaller pictures, or write the text to a file and send its path",
773 mb(len),
774 mb(len - CHAT_BODY_LIMIT),
775 mb(CHAT_BODY_LIMIT),
776 );
777 return error(StatusCode::PAYLOAD_TOO_LARGE, &sentence).into_response();
778 }
779 }
780 }
781 next.run(req).await
782}
783
784pub fn router(state: Shared) -> Router {
786 routes(state.clone()).with_state(state)
787}
788
789fn cookie_value<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
796 headers
797 .get_all(header::COOKIE)
798 .iter()
799 .filter_map(|v| v.to_str().ok())
800 .flat_map(|v| v.split(';'))
801 .find_map(|pair| {
802 let (k, v) = pair.trim().split_once('=')?;
803 (k == name).then_some(v)
804 })
805}
806
807fn is_logged_in(st: &AppState, headers: &HeaderMap) -> bool {
808 cookie_value(headers, SESSION_COOKIE).is_some_and(|id| st.logins.is_valid(id))
809}
810
811fn session_cookie(value: &str, max_age_secs: u64) -> HeaderValue {
812 HeaderValue::from_str(&format!(
815 "{SESSION_COOKIE}={value}; HttpOnly; SameSite=Strict; Path=/; Max-Age={max_age_secs}"
816 ))
817 .expect("cookie is ascii")
818}
819
820fn login_html(mode: &str, error: &str, hint: &str) -> Html<String> {
829 let intro = match mode {
834 "password" => {
835 "Sign in with the user from <code>ECLIPSE_WEB_USER</code> in <code>.env</code>, and \
836 the password <code>eclipse web passwd</code> set for it."
837 }
838 _ => "Enter the dashboard token from <code>auth_token</code> in your config file.",
839 };
840 Html(
841 LOGIN_HTML
842 .replace("{{PALETTE}}", &palette_css())
843 .replace("{{VERSION}}", env!("CARGO_PKG_VERSION"))
844 .replace("{{AUTH_MODE}}", mode)
845 .replace("{{AUTH_INTRO}}", intro)
846 .replace("{{ERROR}}", &escape_html(error))
847 .replace("{{HINT}}", &escape_html(hint)),
848 )
849}
850
851async fn require_login(State(st): State<Shared>, req: Request, next: Next) -> Response {
857 let path = req.uri().path();
858 if matches!(
859 path,
860 "/healthz" | "/login" | "/logout" | "/logo.svg" | "/favicon.ico"
861 ) || is_logged_in(&st, req.headers())
862 {
863 return next.run(req).await;
864 }
865 if path == "/" {
866 return (StatusCode::UNAUTHORIZED, login_html(st.auth_mode(), "", "")).into_response();
867 }
868 error(StatusCode::UNAUTHORIZED, "login required").into_response()
869}
870
871async fn login_page(State(st): State<Shared>, headers: HeaderMap) -> Response {
872 if is_logged_in(&st, &headers) {
873 return redirect_home(None);
874 }
875 login_html(st.auth_mode(), "", frame_hint(&headers)).into_response()
876}
877
878fn frame_hint(headers: &HeaderMap) -> &'static str {
882 let dest = headers
883 .get("sec-fetch-dest")
884 .and_then(|v| v.to_str().ok())
885 .unwrap_or("");
886 if dest == "iframe" || dest == "frame" || dest == "embed" || dest == "object" {
887 "This page is inside a frame. A frame that cannot name its origin cannot keep the session \
888 cookie either, so signing in will return you here — open the dashboard in its own browser \
889 tab instead."
890 } else {
891 ""
892 }
893}
894
895pub struct LoginThrottle {
904 inner: Mutex<Attempts>,
905 free: u32,
907 base: Duration,
908 cap: Duration,
909}
910
911#[derive(Default)]
912struct Attempts {
913 wrong: u32,
914 until: Option<Instant>,
916}
917
918impl Default for LoginThrottle {
919 fn default() -> Self {
920 Self::new(2, Duration::from_secs(1), Duration::from_secs(60))
921 }
922}
923
924impl LoginThrottle {
925 fn new(free: u32, base: Duration, cap: Duration) -> Self {
926 Self {
927 inner: Mutex::new(Attempts::default()),
928 free,
929 base,
930 cap,
931 }
932 }
933
934 fn wait_for(&self) -> Option<u64> {
937 let g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
938 let until = g.until?;
939 let now = Instant::now();
940 if now >= until {
941 return None;
942 }
943 Some((until - now).as_secs().max(1))
944 }
945
946 fn fail(&self) {
949 let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
950 g.wrong = g.wrong.saturating_add(1);
951 if g.wrong <= self.free {
952 return;
953 }
954 let step = g.wrong - self.free - 1;
955 let delay = self
956 .base
957 .saturating_mul(1u32.checked_shl(step.min(16)).unwrap_or(u32::MAX))
958 .min(self.cap);
959 g.until = Some(Instant::now() + delay);
960 }
961
962 fn reset(&self) {
964 let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
965 *g = Attempts::default();
966 }
967}
968
969fn redirect_home(cookie: Option<HeaderValue>) -> Response {
970 let mut resp = (StatusCode::SEE_OTHER, [(header::LOCATION, "/")]).into_response();
971 if let Some(c) = cookie {
972 resp.headers_mut().insert(header::SET_COOKIE, c);
973 }
974 resp
975}
976
977#[derive(Deserialize)]
982struct LoginForm {
983 #[serde(default)]
984 username: String,
985 #[serde(default)]
986 password: String,
987 #[serde(default)]
988 token: String,
989}
990
991#[derive(Deserialize)]
994struct Find {
995 q: Option<String>,
996 limit: Option<usize>,
997}
998
999async fn login(
1002 State(st): State<Shared>,
1003 headers: HeaderMap,
1004 Form(form): Form<LoginForm>,
1005) -> Response {
1006 if let Some(secs) = st.throttle.wait_for() {
1008 let mut resp = (
1009 StatusCode::TOO_MANY_REQUESTS,
1010 login_html(
1011 st.auth_mode(),
1012 &format!("Too many wrong sign-ins. Try again in {secs} s."),
1013 "Each wrong sign-in makes the next attempt wait longer. Nothing is locked for good: \
1014 wait it out, or restart the dashboard to clear the counter.",
1015 ),
1016 )
1017 .into_response();
1018 resp.headers_mut().insert(
1019 header::RETRY_AFTER,
1020 HeaderValue::from_str(&secs.to_string()).unwrap_or(HeaderValue::from_static("1")),
1021 );
1022 return resp;
1023 }
1024 let secret = if form.password.is_empty() {
1030 form.token.as_str()
1031 } else {
1032 form.password.as_str()
1033 };
1034 let auth = st.auth.clone();
1040 let (user, token, secret) = (
1041 form.username.clone(),
1042 st.auth_token.clone(),
1043 secret.to_string(),
1044 );
1045 let passed = blocking(move || auth.check(&user, &secret, &token))
1046 .await
1047 .unwrap_or(false);
1048 if !passed {
1049 st.throttle.fail();
1050 let hint = match frame_hint(&headers) {
1053 "" if headers.contains_key(header::ORIGIN) => {
1054 "Your browser sent Origin: null, so it will not say which page submitted this \
1055 form (a sandboxed frame, an embedded pane, a file:// page, or an extension that \
1056 rewrites headers). If the credential is right and you land back here, open the \
1057 dashboard in its own tab."
1058 }
1059 other => other,
1060 };
1061 let wrong = match st.auth_mode() {
1062 "password" => "Wrong user or password.",
1065 _ => "Wrong token.",
1066 };
1067 return (
1068 StatusCode::UNAUTHORIZED,
1069 login_html(st.auth_mode(), wrong, hint),
1070 )
1071 .into_response();
1072 }
1073 st.throttle.reset();
1074 match st.logins.create() {
1075 Some((id, _csrf)) => redirect_home(Some(session_cookie(&id, st.login_ttl.as_secs()))),
1076 None => error(StatusCode::INTERNAL_SERVER_ERROR, "cannot create a session").into_response(),
1077 }
1078}
1079
1080async fn logout(State(st): State<Shared>, headers: HeaderMap) -> Response {
1081 if let Some(id) = cookie_value(&headers, SESSION_COOKIE) {
1082 st.logins.remove(id);
1083 }
1084 let mut resp = (StatusCode::SEE_OTHER, [(header::LOCATION, "/")]).into_response();
1085 resp.headers_mut()
1086 .insert(header::SET_COOKIE, session_cookie("", 0));
1087 resp
1088}
1089
1090fn is_loopback_host(authority: &str) -> bool {
1091 let host = if let Some(rest) = authority.strip_prefix('[') {
1092 rest.split(']').next().unwrap_or("")
1093 } else {
1094 authority.split(':').next().unwrap_or("")
1095 };
1096 let host = host.trim_end_matches('.');
1099 host == "127.0.0.1" || host == "::1" || host.eq_ignore_ascii_case("localhost")
1100}
1101
1102const CSRF_HEADER: &str = "x-eclipse-csrf";
1104
1105#[cfg(test)]
1107const TEST_CSRF: &str = "test-csrf-token";
1108
1109fn header_text(req: &Request, name: &str) -> Option<String> {
1111 req.headers()
1112 .get(name)
1113 .and_then(|v| v.to_str().ok())
1114 .map(str::to_string)
1115}
1116
1117fn authority_of(origin: &str) -> &str {
1121 origin.split_once("://").map_or(origin, |(_, rest)| rest)
1122}
1123
1124fn arrival_refusal(
1140 logins: &Logins,
1141 method: &Method,
1142 path: &str,
1143 host: Option<&str>,
1144 origin: Option<&str>,
1145 csrf: Option<&str>,
1146 session: Option<&str>,
1147) -> Option<String> {
1148 let Some(host) = host else {
1149 return Some("the request carried no Host header".to_string());
1150 };
1151 if !is_loopback_host(host) {
1152 return Some(format!(
1153 "Host {host:?} is not 127.0.0.1, ::1 or localhost. Open the dashboard on this \
1154 machine's own address, http://127.0.0.1:<port>; from another machine use an SSH \
1155 tunnel, which keeps the header local. A reverse proxy or a LAN name in front of the \
1156 dashboard is refused by design, because the token is the only thing guarding it"
1157 ));
1158 }
1159
1160 if matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS) {
1163 return None;
1164 }
1165
1166 let stated = origin.map(authority_of);
1167 let same_origin = match stated {
1168 None => true, Some(authority) => authority.eq_ignore_ascii_case(host),
1170 };
1171 if same_origin {
1172 return None;
1173 }
1174
1175 let anonymous_but_harmless = path == "/login" && stated == Some("null");
1178 if anonymous_but_harmless {
1179 return None;
1180 }
1181
1182 if let (Some(id), Some(presented)) = (session, csrf) {
1184 if logins.csrf_ok(id, presented) {
1185 return None;
1186 }
1187 }
1188
1189 let what = match stated {
1190 Some("null") => {
1191 "Origin \"null\" means the browser would not name the page that sent this request: a \
1192 sandboxed frame, an embedded preview pane, a file:// page, or an extension that \
1193 rewrites headers all look like this"
1194 .to_string()
1195 }
1196 Some(authority) => format!(
1197 "Origin {authority:?} is not this dashboard ({host:?}); that mismatch is what a \
1198 cross-site request looks like, or a proxy that rewrote the Host header"
1199 ),
1200 None => "the request says nothing about where it came from".to_string(),
1201 };
1202 Some(format!(
1203 "{what}. This request also carried no valid {CSRF_HEADER} token for its session, and a page \
1204 served from here always does. Open the dashboard in a normal browser tab at \
1205 http://127.0.0.1:<port>: a frame that cannot name its origin cannot keep the session \
1206 cookie either, so signing in from one would bounce straight back to the form"
1207 ))
1208}
1209
1210pub async fn guard_local_origin(State(st): State<Shared>, req: Request, next: Next) -> Response {
1215 let method = req.method().clone();
1218 let path = req.uri().path().to_string();
1219 let host = header_text(&req, "host");
1220 let origin = header_text(&req, "origin");
1221 let csrf = header_text(&req, CSRF_HEADER);
1222 let session = cookie_value(req.headers(), SESSION_COOKIE).map(str::to_string);
1223 let refusal = arrival_refusal(
1224 &st.logins,
1225 &method,
1226 &path,
1227 host.as_deref(),
1228 origin.as_deref(),
1229 csrf.as_deref(),
1230 session.as_deref(),
1231 );
1232 let mut resp = match refusal {
1233 None => next.run(req).await,
1234 Some(why) => (StatusCode::FORBIDDEN, format!("forbidden: {why}")).into_response(),
1235 };
1236 let h = resp.headers_mut();
1237 h.insert(
1238 header::CONTENT_SECURITY_POLICY,
1239 HeaderValue::from_static(
1240 "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; \
1247 img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'self'; \
1248 frame-ancestors 'none'",
1249 ),
1250 );
1251 h.insert(
1252 header::X_CONTENT_TYPE_OPTIONS,
1253 HeaderValue::from_static("nosniff"),
1254 );
1255 h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
1256 h.insert(
1257 header::REFERRER_POLICY,
1258 HeaderValue::from_static("no-referrer"),
1259 );
1260 resp
1261}
1262
1263async fn blocking<T, F>(work: F) -> Option<T>
1271where
1272 F: FnOnce() -> T + Send + 'static,
1273 T: Send + 'static,
1274{
1275 tokio::task::spawn_blocking(work).await.ok()
1276}
1277
1278fn escape_html(s: &str) -> String {
1279 s.replace('&', "&")
1280 .replace('<', "<")
1281 .replace('>', ">")
1282 .replace('"', """)
1283 .replace('\'', "'")
1284}
1285
1286fn palette_css() -> String {
1291 use eclipse_core::palette as p;
1292 let rgb = |c: (u8, u8, u8)| format!("rgb({}, {}, {})", c.0, c.1, c.2);
1293 format!(
1294 ":root {{ color-scheme: dark; \
1295 --bg:{}; --panel:{}; --line:{}; --hover:{}; \
1296 --fg:{}; --dim:{}; --faint:{}; --rule:{}; \
1297 --accent:{}; --user:{}; --ok:{}; --warn:{}; --bad:{}; --ink:{}; }}",
1298 rgb(p::BG),
1299 rgb(p::PANEL),
1300 rgb(p::LINE),
1301 rgb(p::HOVER),
1302 rgb(p::FG),
1303 rgb(p::MUTED),
1304 rgb(p::FAINT),
1308 rgb(p::RULE),
1309 rgb(p::ACCENT),
1310 rgb(p::USER),
1311 rgb(p::OK),
1312 rgb(p::WARN),
1313 rgb(p::BAD),
1314 rgb(p::INK),
1315 )
1316}
1317
1318async fn index(State(st): State<Shared>, headers: HeaderMap) -> Html<String> {
1319 let csrf = cookie_value(&headers, SESSION_COOKIE)
1322 .and_then(|id| st.logins.csrf_for(id))
1323 .unwrap_or_default();
1324 let store = st.store.clone();
1325 let sessions = blocking(move || store.list().unwrap_or_default())
1328 .await
1329 .unwrap_or_default()
1330 .into_iter()
1331 .map(|s| {
1332 let cost = s
1338 .cost
1339 .as_ref()
1340 .and_then(|c| serde_json::to_string(c).ok())
1341 .map(|json| escape_html(&json))
1342 .unwrap_or_default();
1343 format!(
1344 "<li class=\"session\" data-id=\"{}\" data-updated=\"{}\" data-pinned=\"{}\" data-archived=\"{}\" data-cost=\"{}\"><div class=\"name\">{}{}</div></li>",
1345 escape_html(&s.id),
1346 s.updated_ms,
1347 if s.pinned { "1" } else { "0" },
1348 if s.archived { "1" } else { "0" },
1349 cost,
1350 if s.pinned { "\u{2605} " } else { "" },
1351 escape_html(&s.tagged_label())
1352 )
1353 })
1354 .collect::<String>();
1355 let status = st.config_error.as_deref().unwrap_or("");
1356 let judged = st
1359 .reload_config()
1360 .map(|c| c.cli.approval == eclipse_core::config::Approval::Smart)
1361 .unwrap_or(false);
1362 let model = st.current_model();
1363 let model = model.as_deref().unwrap_or("(not configured)");
1364 let (effort, effort_detail, effort_session) = match st.agent.as_deref() {
1374 Some(agent) => {
1375 let report = agent.reasoning_report();
1376 let sentence = report.sentence();
1377 (report.label, sentence, report.session)
1378 }
1379 None => (
1380 eclipse_core::reasoning::NOT_SENT.to_string(),
1381 "no provider is configured: there is no effort to be in force".to_string(),
1382 false,
1383 ),
1384 };
1385 let probe = st.store.clone();
1390 let has_flares = matches!(
1391 blocking(move || probe.flare_runs(1)).await,
1392 Some(Ok(runs)) if !runs.is_empty()
1393 );
1394 Html(
1395 INDEX_HTML
1396 .replace("{{PALETTE}}", &palette_css())
1397 .replace("{{CSRF}}", &escape_html(&csrf))
1398 .replace("{{MODEL}}", &escape_html(model))
1399 .replace("{{EFFORT}}", &escape_html(&effort))
1404 .replace("{{EFFORT_DETAIL}}", &escape_html(&effort_detail))
1405 .replace(
1406 "{{EFFORT_CLASS}}",
1407 if effort_session { "session" } else { "" },
1408 )
1409 .replace("{{YOLO_ATTR}}", if st.yolo.on() { "" } else { "hidden" })
1412 .replace(
1413 "{{YOLO_DETAIL}}",
1414 &escape_html(&eclipse_core::yolo::announce(st.yolo.on())),
1415 )
1416 .replace("{{JUDGE_ATTR}}", if judged { "" } else { "hidden" })
1420 .replace("{{VERSION}}", env!("CARGO_PKG_VERSION"))
1421 .replace(
1424 "{{PASTE_LIMIT}}",
1425 &eclipse_core::paste::PASTE_INLINE_LIMIT.to_string(),
1426 )
1427 .replace("{{STATUS}}", &escape_html(status))
1428 .replace("{{SESSIONS}}", &sessions)
1429 .replace(
1433 "{{BOTS_BUTTON}}",
1434 &if st.bots.is_empty() {
1435 String::new()
1436 } else {
1437 format!(
1438 " <button id=\"bots\" type=\"button\" aria-expanded=\"false\" \
1439title=\"the bots this config declared — open one and talk to it in its own conversation\">bots ({})</button>",
1440 st.bots.declared().count()
1441 )
1442 },
1443 )
1444 .replace(
1445 "{{BOTS_PANE}}",
1446 if st.bots.is_empty() { "" } else { BOTS_PANE },
1447 )
1448 .replace(
1451 "{{FLARES_BUTTON}}",
1452 &if has_flares {
1453 " <button id=\"flares\" type=\"button\" aria-expanded=\"false\" \
1454title=\"the flare runs this install has started — one task split across N read-only agents\">flares</button>"
1455 .to_string()
1456 } else {
1457 String::new()
1458 },
1459 )
1460 .replace(
1461 "{{FLARES_PANE}}",
1462 if has_flares { FLARES_PANE } else { "" },
1463 ),
1464 )
1465}
1466
1467async fn logo() -> impl IntoResponse {
1469 (
1470 [
1471 ("content-type", "image/svg+xml; charset=utf-8"),
1472 ("cache-control", "public, max-age=3600"),
1473 ],
1474 mark_svg(),
1475 )
1476}
1477
1478async fn favicon() -> impl IntoResponse {
1480 (
1481 [
1482 ("content-type", "image/x-icon"),
1483 ("cache-control", "public, max-age=3600"),
1484 ],
1485 FAVICON_ICO,
1486 )
1487}
1488
1489async fn health(
1498 State(st): State<Shared>,
1499 headers: axum::http::HeaderMap,
1500) -> Json<serde_json::Value> {
1501 if !is_logged_in(&st, &headers) {
1502 return Json(json!({"status": "ok"}));
1503 }
1504 let model_probe = (*st.model_probe.lock().unwrap_or_else(|e| e.into_inner()))
1505 .map(|(when, ok)| json!({"reachable": ok, "at_secs_ago": when.elapsed().as_secs()}));
1506 let cron_root = st.cron_root.clone();
1507 let cron = match blocking(move || {
1508 cron_root.and_then(|root| eclipse_core::cron::load_state(&root).ok())
1509 })
1510 .await
1511 .flatten()
1512 {
1513 Some(state) => {
1514 let failed: Vec<&str> = state
1515 .jobs
1516 .iter()
1517 .filter(|(_, j)| j.last_outcome.as_deref() == Some("failed"))
1518 .map(|(name, _)| name.as_str())
1519 .collect();
1520 let last_tick = state.jobs.values().filter_map(|j| j.last_started_ms).max();
1521 Some(json!({
1522 "failed_jobs": failed,
1523 "last_tick_ms": last_tick,
1524 }))
1525 }
1526 None => None,
1527 };
1528 Json(json!({
1529 "status": "ok",
1530 "version": env!("CARGO_PKG_VERSION"),
1531 "configured": st.agent.is_some(),
1532 "model_reachable": model_probe,
1533 "cron": cron,
1534 }))
1535}
1536
1537async fn update_state(State(st): State<Shared>) -> Json<eclipse_core::update::Snapshot> {
1542 let Some(watch) = st.update.clone() else {
1543 return Json(eclipse_core::update::Snapshot::default());
1544 };
1545 let now = eclipse_core::session::now_ms() / 1000;
1546 match blocking(move || watch.snapshot(now)).await {
1547 Some(snapshot) => Json(snapshot),
1548 None => Json(eclipse_core::update::Snapshot::default()),
1549 }
1550}
1551
1552async fn list_sessions(State(st): State<Shared>, Query(list): Query<ListQuery>) -> Response {
1557 let store = st.store.clone();
1558 let all = list.archived.unwrap_or(0) != 0;
1559 let Some(listed) = blocking(move || {
1560 if all {
1561 store.list_with_archived()
1562 } else {
1563 store.list()
1564 }
1565 })
1566 .await
1567 else {
1568 return error(
1569 StatusCode::INTERNAL_SERVER_ERROR,
1570 "the store did not answer",
1571 )
1572 .into_response();
1573 };
1574 match listed {
1575 Ok(list) => Json(
1576 list.into_iter()
1577 .map(|s| {
1578 json!({
1579 "id": s.id, "messages": s.messages, "updated_ms": s.updated_ms,
1580 "preview": s.preview, "title": s.title, "pinned": s.pinned,
1581 "archived": s.archived,
1582 "cost": s.cost,
1586 "subagent": s.subagent().map(|o| json!({"parent": o.parent, "route": o.route})),
1587 })
1588 })
1589 .collect::<Vec<_>>(),
1590 )
1591 .into_response(),
1592 Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
1593 }
1594}
1595
1596#[derive(Deserialize)]
1598struct ListQuery {
1599 archived: Option<u8>,
1600}
1601
1602async fn list_bots(State(st): State<Shared>) -> Response {
1609 let store = st.store.clone();
1610 let conversations = match blocking(move || store.list_bots()).await {
1611 Some(Ok(list)) => list,
1612 Some(Err(e)) => {
1613 return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
1614 }
1615 None => {
1616 return error(
1617 StatusCode::INTERNAL_SERVER_ERROR,
1618 "the store did not answer",
1619 )
1620 .into_response()
1621 }
1622 };
1623 let rows: Vec<serde_json::Value> = st
1624 .bots
1625 .declared()
1626 .map(|(name, bot)| {
1627 let live = conversations.iter().find(|c| c.name == name);
1628 let problem = match st.bots.agent(name) {
1632 Some(Err(why)) => serde_json::Value::String(why.clone()),
1633 _ => serde_json::Value::Null,
1634 };
1635 json!({
1636 "name": name,
1637 "lane": bot.adapter.clone().unwrap_or_else(|| "web".to_string()),
1638 "sessions": live.map(|c| c.sessions).unwrap_or(0),
1639 "messages": live.map(|c| c.messages).unwrap_or(0),
1640 "last_session": live.map(|c| c.last_session.clone()),
1641 "last_activity_ms": live.map(|c| c.last_activity_ms).unwrap_or(0),
1642 "archived": live.map(|c| c.archived).unwrap_or(false),
1643 "problem": problem,
1644 })
1645 })
1646 .collect();
1647 Json(rows).into_response()
1648}
1649
1650async fn open_bot(State(st): State<Shared>, Path(name): Path<String>) -> Response {
1655 if !st.bots.declares(&name) {
1656 return error(
1657 StatusCode::NOT_FOUND,
1658 format!("no bot `{name}` is declared"),
1659 )
1660 .into_response();
1661 }
1662 if let Some(Err(why)) = st.bots.agent(&name) {
1663 return error(
1664 StatusCode::SERVICE_UNAVAILABLE,
1665 format!("bot `{name}` cannot run: {why}"),
1666 )
1667 .into_response();
1668 }
1669 let store = st.store.clone();
1670 let wanted = name.clone();
1671 let opened = blocking(move || store.bot_session(&wanted)).await;
1672 match opened {
1673 Some(Ok(session_id)) => {
1674 Json(json!({ "name": name, "session_id": session_id })).into_response()
1675 }
1676 Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
1677 None => error(
1678 StatusCode::INTERNAL_SERVER_ERROR,
1679 "the store did not answer",
1680 )
1681 .into_response(),
1682 }
1683}
1684
1685async fn rename_bot(
1691 State(st): State<Shared>,
1692 Path(name): Path<String>,
1693 Json(body): Json<RenameBody>,
1694) -> Response {
1695 if !st.bots.declares(&name) {
1696 return error(
1697 StatusCode::NOT_FOUND,
1698 format!("no bot `{name}` is declared"),
1699 )
1700 .into_response();
1701 }
1702 let title = body.title.trim().to_string();
1703 if title.is_empty() {
1704 return error(StatusCode::BAD_REQUEST, "title is empty").into_response();
1705 }
1706 let store = st.store.clone();
1707 let wanted = name.clone();
1708 let named = title.clone();
1709 let renamed = blocking(move || {
1710 let id = store.bot_session(&wanted)?;
1711 store.set_title(&id, &named, eclipse_core::session::TitleSource::User)
1712 })
1713 .await;
1714 match renamed {
1715 Some(Ok(_)) => Json(json!({ "name": name, "title": title })).into_response(),
1716 Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
1717 None => error(
1718 StatusCode::INTERNAL_SERVER_ERROR,
1719 "the store did not answer",
1720 )
1721 .into_response(),
1722 }
1723}
1724
1725async fn clear_bot(State(st): State<Shared>, Path(name): Path<String>) -> Response {
1731 if !st.bots.declares(&name) {
1732 return error(
1733 StatusCode::NOT_FOUND,
1734 format!("no bot `{name}` is declared"),
1735 )
1736 .into_response();
1737 }
1738 let store = st.store.clone();
1739 let wanted = name.clone();
1740 let cleared = blocking(move || {
1741 let mut filed = 0usize;
1742 for id in store.bot_sessions(&wanted)? {
1743 store.set_archived(&id, true)?;
1744 filed += 1;
1745 }
1746 let fresh = store.bot_session(&wanted)?;
1747 Ok::<_, eclipse_core::Error>((filed, fresh))
1748 })
1749 .await;
1750 match cleared {
1751 Some(Ok((filed, session_id))) => {
1752 Json(json!({ "name": name, "archived": filed, "session_id": session_id }))
1753 .into_response()
1754 }
1755 Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
1756 None => error(
1757 StatusCode::INTERNAL_SERVER_ERROR,
1758 "the store did not answer",
1759 )
1760 .into_response(),
1761 }
1762}
1763
1764async fn bot_prompt(State(st): State<Shared>, Path(name): Path<String>) -> Response {
1770 let Some((bot, ..)) = st
1771 .bots
1772 .declared()
1773 .find(|(declared, _)| *declared == name)
1774 .map(|(n, b)| (b.clone(), n))
1775 else {
1776 return error(
1777 StatusCode::NOT_FOUND,
1778 format!("no bot `{name}` is declared"),
1779 )
1780 .into_response();
1781 };
1782 let env: eclipse_core::config::EnvFn = &eclipse_core::config::process_env;
1783 let read = bot
1784 .instructions
1785 .as_deref()
1786 .filter(|p| !p.trim().is_empty())
1787 .map(|declared| {
1788 let Some(path) = st
1789 .reload_config()
1790 .ok()
1791 .and_then(|cfg| cfg.bot_file(env, declared))
1792 else {
1793 return (
1794 None,
1795 format!("cannot resolve `instructions = {declared:?}`"),
1796 );
1797 };
1798 match std::fs::read_to_string(&path) {
1799 Ok(text) => (Some((path, text)), String::new()),
1800 Err(e) => (None, format!("cannot read {}: {e}", path.display())),
1801 }
1802 });
1803 let (instructions, why) = match read {
1804 Some((Some((path, text)), _)) => (
1805 json!({ "path": path.display().to_string(), "body": text }),
1806 String::new(),
1807 ),
1808 Some((None, why)) => (serde_json::Value::Null, why),
1809 None => (serde_json::Value::Null, String::new()),
1810 };
1811 let memory = st
1812 .reload_config()
1813 .ok()
1814 .and_then(|cfg| cfg.bot_memory(env, &name, &bot))
1815 .map(|p| p.display().to_string());
1816 Json(json!({
1817 "name": name,
1818 "instructions": instructions,
1819 "skills": bot.skills,
1820 "memory": memory,
1821 "adapter": bot.adapter,
1822 "problem": match st.bots.agent(&name) { Some(Err(why)) => json!(why), _ => serde_json::Value::Null },
1823 "why": why,
1824 }))
1825 .into_response()
1826}
1827
1828fn flare_json(run: &FlareRunRow) -> serde_json::Value {
1839 json!({
1840 "id": run.id,
1841 "task": run.task,
1842 "state": run.state,
1843 "routes": run.routes,
1844 "jobs": run.jobs,
1845 "parent": run.parent,
1846 "started_ms": run.started_ms,
1847 "finished_ms": run.finished_ms,
1848 "prompt_tokens": run.prompt_tokens,
1849 "completion_tokens": run.completion_tokens,
1850 "iterations": run.iterations,
1851 "running": !run.finished(),
1852 })
1853}
1854
1855fn flare_job_json(job: &FlareJobRow) -> serde_json::Value {
1862 json!({
1863 "n": job.n,
1864 "route": job.route,
1865 "session_id": job.session_id,
1866 "state": job.state,
1867 "prompt_tokens": job.prompt_tokens,
1868 "completion_tokens": job.completion_tokens,
1869 "iterations": job.iterations,
1870 "why": job.why,
1871 })
1872}
1873
1874#[derive(Deserialize)]
1877struct FlaresQuery {
1878 limit: Option<usize>,
1879}
1880
1881async fn list_flares(State(st): State<Shared>, Query(q): Query<FlaresQuery>) -> Response {
1888 let limit = q.limit.unwrap_or(50);
1889 let store = st.store.clone();
1890 match blocking(move || store.flare_runs(limit)).await {
1891 Some(Ok(runs)) => Json(
1892 runs.iter()
1893 .map(flare_json)
1894 .collect::<Vec<serde_json::Value>>(),
1895 )
1896 .into_response(),
1897 Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
1898 None => error(
1899 StatusCode::INTERNAL_SERVER_ERROR,
1900 "the store did not answer",
1901 )
1902 .into_response(),
1903 }
1904}
1905
1906async fn read_flare(State(st): State<Shared>, Path(run): Path<String>) -> Response {
1913 let store = st.store.clone();
1914 let wanted = run.clone();
1915 match blocking(move || store.flare_run(&wanted)).await {
1916 Some(Ok(Some((row, jobs)))) => {
1917 let jobs: Vec<serde_json::Value> = jobs.iter().map(flare_job_json).collect();
1918 Json(json!({ "run": flare_json(&row), "jobs": jobs })).into_response()
1919 }
1920 Some(Ok(None)) => {
1921 error(StatusCode::NOT_FOUND, format!("no flare run `{run}`")).into_response()
1922 }
1923 Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
1924 None => error(
1925 StatusCode::INTERNAL_SERVER_ERROR,
1926 "the store did not answer",
1927 )
1928 .into_response(),
1929 }
1930}
1931
1932async fn cancel_flare(State(st): State<Shared>, Path(run): Path<String>) -> Response {
1939 let store = st.store.clone();
1940 let wanted = run.clone();
1941 match blocking(move || store.cancel_flare_run(&wanted)).await {
1942 Some(Ok(true)) => Json(json!({
1943 "run": run,
1944 "cancel_requested": true,
1945 "note": "cancel requested: queued flares are dropped, running ones stop at their next boundary",
1946 }))
1947 .into_response(),
1948 Some(Ok(false)) => {
1949 error(StatusCode::NOT_FOUND, format!("no flare run `{run}`")).into_response()
1950 }
1951 Some(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
1952 None => error(
1953 StatusCode::INTERNAL_SERVER_ERROR,
1954 "the store did not answer",
1955 )
1956 .into_response(),
1957 }
1958}
1959
1960async fn search_sessions(State(st): State<Shared>, Query(find): Query<Find>) -> Response {
1967 let term = find.q.unwrap_or_default();
1968 let term = term.trim();
1969 if term.is_empty() {
1970 return Json(Vec::<serde_json::Value>::new()).into_response();
1971 }
1972 let limit = find.limit.unwrap_or(20).clamp(1, 100);
1973 let store = st.store.clone();
1974 let term = term.to_string();
1975 let Some(found) = blocking(move || {
1976 let hits = store.search(&term, limit);
1977 let named: HashMap<String, (Option<String>, u64)> = store
1980 .list()
1981 .map(|list| {
1982 list.into_iter()
1983 .map(|s| (s.id, (s.title, s.updated_ms)))
1984 .collect()
1985 })
1986 .unwrap_or_default();
1987 (hits, named)
1988 })
1989 .await
1990 else {
1991 return error(
1992 StatusCode::INTERNAL_SERVER_ERROR,
1993 "the store did not answer",
1994 )
1995 .into_response();
1996 };
1997 let (hits, named) = found;
1998 let hits = match hits {
1999 Ok(hits) => hits,
2000 Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2001 };
2002 Json(
2003 hits.into_iter()
2004 .map(|h| {
2005 let (title, updated_ms) = named.get(&h.session_id).cloned().unwrap_or((None, 0));
2006 json!({
2007 "session_id": h.session_id,
2008 "seq": h.seq,
2009 "at_ms": h.at_ms,
2010 "role": h.role,
2011 "snippet": h.snippet,
2012 "title": title,
2013 "updated_ms": updated_ms,
2014 })
2015 })
2016 .collect::<Vec<_>>(),
2017 )
2018 .into_response()
2019}
2020
2021async fn list_commands() -> Json<serde_json::Value> {
2038 use eclipse_core::commands::{Args, Command, Front, COMMANDS};
2039 let row = |c: &Command| {
2040 json!({
2041 "name": c.name,
2042 "aliases": c.aliases,
2043 "label": c.label(),
2044 "args": match c.args {
2045 Args::Shown(args) => json!(args),
2046 Args::None | Args::Unshown => serde_json::Value::Null,
2047 },
2048 "takes_arg": c.args.takes(),
2049 "help": c.help,
2050 })
2051 };
2052 Json(json!({
2053 "commands": COMMANDS
2054 .iter()
2055 .filter(|c| c.serves(Front::Web))
2056 .map(row)
2057 .collect::<Vec<_>>(),
2058 }))
2059}
2060
2061async fn list_models(State(st): State<Shared>) -> Response {
2062 let Some(agent) = st.agent.clone() else {
2063 return error(StatusCode::SERVICE_UNAVAILABLE, unconfigured(&st)).into_response();
2064 };
2065 match agent.list_models().await {
2066 Ok(models) => Json(json!({
2067 "model": st.current_model(),
2068 "configured": st.configured_model(),
2069 "models": models,
2070 }))
2071 .into_response(),
2072 Err(e) => error(StatusCode::BAD_GATEWAY, e.to_string()).into_response(),
2073 }
2074}
2075
2076#[derive(Deserialize)]
2077struct ModelChoice {
2078 #[serde(default, deserialize_with = "some_option")]
2084 model: Option<Option<String>>,
2085}
2086
2087fn some_option<'de, D>(d: D) -> Result<Option<Option<String>>, D::Error>
2090where
2091 D: serde::Deserializer<'de>,
2092{
2093 Option::<String>::deserialize(d).map(Some)
2094}
2095
2096async fn list_settings(State(st): State<Shared>) -> Response {
2101 match st.reload_config() {
2102 Ok(cfg) => Json(json!({
2103 "profile": cfg.profile_name(),
2104 "settings": cfg.settings().iter().map(setting_json).collect::<Vec<_>>(),
2105 }))
2106 .into_response(),
2107 Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
2108 }
2109}
2110
2111fn setting_json(s: &eclipse_core::config::Setting) -> serde_json::Value {
2117 json!({
2118 "key": s.path(),
2119 "section": s.section,
2120 "value": if s.secret { serde_json::Value::Null } else { json!(s.rendered()) },
2121 "default": s.default.as_ref().map(std::string::ToString::to_string),
2122 "is_default": s.is_default(),
2123 "secret": s.secret,
2124 "set": s.value.is_some(),
2125 "applies": s.applies.as_str(),
2126 "kind": s.kind.as_str(),
2129 "about": s.about,
2131 "choices": s.choices,
2133 })
2134}
2135
2136#[derive(Deserialize)]
2137struct SettingWrite {
2138 key: String,
2139 #[serde(default, deserialize_with = "some_option")]
2145 value: Option<Option<String>>,
2146}
2147
2148async fn write_setting(State(st): State<Shared>, Json(body): Json<SettingWrite>) -> Response {
2151 let Some(value) = body.value else {
2152 return error(
2153 StatusCode::BAD_REQUEST,
2154 "name a value: {\"value\": \"text\"} to set it, or {\"value\": null} to go back to the \
2155 default",
2156 )
2157 .into_response();
2158 };
2159 match apply_setting(&st, &body.key, value.as_deref()).await {
2160 Ok(setting) => Json(setting).into_response(),
2161 Err((code, why)) => error(code, why).into_response(),
2162 }
2163}
2164
2165pub(crate) async fn apply_setting(
2171 st: &AppState,
2172 key: &str,
2173 value: Option<&str>,
2174) -> Result<serde_json::Value, (StatusCode, String)> {
2175 let Some(path) = st.write_path() else {
2176 return Err((
2177 StatusCode::SERVICE_UNAVAILABLE,
2178 "this dashboard was started without a config file".to_string(),
2179 ));
2180 };
2181 let base = st.config_path.clone();
2184 let (key, value) = (key.to_string(), value.map(str::to_string));
2185 let edited_key = key.clone();
2186 let profile = st.profile.clone();
2189 let writes = st.config_writes.clone();
2193 let written = blocking(
2196 move || -> Result<eclipse_core::config::Config, (StatusCode, String)> {
2197 let _one_writer = writes
2198 .lock()
2199 .unwrap_or_else(|poisoned| poisoned.into_inner());
2200 let text = match std::fs::read_to_string(&path) {
2204 Ok(text) => text,
2205 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
2206 Err(e) => {
2207 return Err((
2208 StatusCode::INTERNAL_SERVER_ERROR,
2209 format!("{}: {e}", path.display()),
2210 ))
2211 }
2212 };
2213 let edited = match &value {
2217 Some(raw) => {
2218 let typed = eclipse_core::config::parse_value(raw);
2219 eclipse_core::config::set_in_text(&text, &edited_key, &typed)
2220 }
2221 None => eclipse_core::config::unset_in_text(&text, &edited_key),
2222 }
2223 .map_err(|why| (StatusCode::BAD_REQUEST, why))?;
2224 if let Some(dir) = path.parent() {
2225 std::fs::create_dir_all(dir).map_err(|e| {
2226 (
2227 StatusCode::INTERNAL_SERVER_ERROR,
2228 format!("{}: {e}", dir.display()),
2229 )
2230 })?;
2231 }
2232 eclipse_core::config::save_config_text(&path, &edited)
2233 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
2234 eclipse_core::config::Config::load_with_profile(
2235 base.as_deref(),
2236 profile.as_deref(),
2237 &eclipse_core::config::process_env,
2238 )
2239 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
2240 },
2241 )
2242 .await;
2243 let Some(written) = written else {
2244 return Err((
2245 StatusCode::INTERNAL_SERVER_ERROR,
2246 "the write did not finish".to_string(),
2247 ));
2248 };
2249 match written {
2250 Ok(cfg) => match cfg.setting(&key) {
2251 Some(setting) => Ok(setting_json(&setting)),
2252 None => Err((
2253 StatusCode::INTERNAL_SERVER_ERROR,
2254 format!("`{key}` is not in the file it was just written to"),
2255 )),
2256 },
2257 Err((code, why)) => Err((code, why)),
2258 }
2259}
2260
2261fn context_json(
2264 e: &eclipse_core::context_files::Editable,
2265 home: Option<&std::path::Path>,
2266) -> serde_json::Value {
2267 json!({
2268 "name": e.which.id(),
2269 "file": e.file,
2270 "path": short_path(&e.path, home),
2271 "exists": e.exists,
2272 "chars": e.chars,
2273 "kept": e.kept,
2274 "truncated": e.truncated(),
2275 "max_chars": e.max_chars,
2276 "own_budget": e.own_budget,
2277 "total": e.total,
2278 "total_budget": e.total_budget,
2279 "position": e.position,
2280 "others": e.others,
2281 "kind": match e.which {
2282 eclipse_core::context_files::Which::Memory => "memory",
2283 _ => "prose",
2284 },
2285 "text": e.text,
2286 })
2287}
2288
2289fn short_path(path: &std::path::Path, home: Option<&std::path::Path>) -> String {
2292 let shown = path.to_string_lossy().into_owned();
2293 match home {
2294 Some(home) => {
2295 let home = home.to_string_lossy();
2296 match shown.strip_prefix(home.as_ref()) {
2297 Some(rest) => format!("~{rest}"),
2298 None => shown,
2299 }
2300 }
2301 None => shown,
2302 }
2303}
2304
2305async fn list_context(State(st): State<Shared>) -> Response {
2307 let cfg = match st.reload_config() {
2308 Ok(cfg) => cfg,
2309 Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
2310 };
2311 let home = cfg.home(&eclipse_core::config::process_env);
2312 let files = blocking(move || {
2313 eclipse_core::context_files::editable(&cfg, &eclipse_core::config::process_env)
2314 })
2315 .await;
2316 match files {
2317 Some(files) => Json(json!({
2318 "profile": st.profile.clone(),
2319 "files": files.iter().map(|e| context_json(e, home.as_deref())).collect::<Vec<_>>(),
2320 }))
2321 .into_response(),
2322 None => error(
2323 StatusCode::INTERNAL_SERVER_ERROR,
2324 "the context files took too long to read",
2325 )
2326 .into_response(),
2327 }
2328}
2329
2330#[derive(Deserialize)]
2331struct ContextWrite {
2332 name: String,
2334 text: String,
2335}
2336
2337async fn write_context(State(st): State<Shared>, Json(body): Json<ContextWrite>) -> Response {
2345 let Some(which) = eclipse_core::context_files::Which::from_id(&body.name) else {
2346 return error(
2347 StatusCode::BAD_REQUEST,
2348 format!(
2349 "name one of the three context files: \"agent\", \"user\" or \"memory\" — not {:?}",
2350 body.name
2351 ),
2352 )
2353 .into_response();
2354 };
2355 let cfg = match st.reload_config() {
2356 Ok(cfg) => cfg,
2357 Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
2358 };
2359 let home = cfg.home(&eclipse_core::config::process_env);
2360 let text = body.text;
2361 let written = blocking(move || {
2362 eclipse_core::context_files::write_file(
2363 &cfg,
2364 &eclipse_core::config::process_env,
2365 which,
2366 &text,
2367 )
2368 })
2369 .await;
2370 match written {
2371 Some(Ok(row)) => Json(json!({
2372 "file": context_json(&row, home.as_deref()),
2373 "applies": "the next run uses it",
2376 }))
2377 .into_response(),
2378 Some(Err(e)) => error(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
2379 None => error(
2381 StatusCode::INTERNAL_SERVER_ERROR,
2382 "the write did not finish",
2383 )
2384 .into_response(),
2385 }
2386}
2387
2388async fn choose_model(State(st): State<Shared>, Json(choice): Json<ModelChoice>) -> Response {
2392 let Some(choice) = choice.model else {
2393 return error(
2394 StatusCode::BAD_REQUEST,
2395 "name a model: {\"model\": \"name\"}, or {\"model\": null} to go back to the configured one",
2396 )
2397 .into_response();
2398 };
2399 match apply_model(&st, choice).await {
2400 Ok(answer) => Json(answer).into_response(),
2401 Err((code, why)) => error(code, why).into_response(),
2402 }
2403}
2404
2405pub(crate) async fn apply_model(
2411 st: &AppState,
2412 picked: Option<String>,
2413) -> Result<serde_json::Value, (StatusCode, String)> {
2414 let Some(agent) = st.agent.clone() else {
2415 return Err((StatusCode::SERVICE_UNAVAILABLE, unconfigured(st)));
2416 };
2417 let picked = match picked {
2418 Some(name) => {
2419 let name = name.trim().to_string();
2420 if name.is_empty() {
2421 return Err((StatusCode::BAD_REQUEST, "model is empty".to_string()));
2422 }
2423 Some(name)
2424 }
2425 None => None,
2426 };
2427 match agent.set_model(picked) {
2428 Ok(()) => {
2429 let probe = agent.clone();
2434 tokio::spawn(async move {
2435 if let Some(window) = probe
2436 .advertised_context_window(Duration::from_secs(2))
2437 .await
2438 {
2439 probe.set_advertised_window(window);
2440 }
2441 });
2442 Ok(json!({
2443 "model": st.current_model(),
2444 "configured": st.configured_model(),
2445 }))
2446 }
2447 Err(e) => Err((StatusCode::BAD_REQUEST, e.to_string())),
2448 }
2449}
2450
2451pub(crate) fn unconfigured(st: &AppState) -> String {
2453 st.config_error
2454 .clone()
2455 .unwrap_or_else(|| "agent is not configured".into())
2456}
2457
2458fn reasoning_json(agent: &Agent) -> serde_json::Value {
2466 use eclipse_core::provider::Reasoning;
2467 let report = agent.reasoning_report();
2468 let control = agent.reasoning_control();
2469 let (levels, described, note): (Vec<String>, serde_json::Value, String) = match &control {
2470 Some(Reasoning::Policy(policy)) => {
2471 let levels = policy.vocabulary();
2472 let said: serde_json::Map<String, serde_json::Value> = levels
2473 .iter()
2474 .map(|level| (level.clone(), json!(policy.describe(Some(level)))))
2475 .collect();
2476 (levels, serde_json::Value::Object(said), String::new())
2477 }
2478 Some(Reasoning::Off) => (
2481 Vec::new(),
2482 json!({}),
2483 "no reasoning control on this model".to_string(),
2484 ),
2485 Some(Reasoning::Undeclared) => (
2486 Vec::new(),
2487 json!({}),
2488 "this backend declares no reasoning control, so a level goes out verbatim and only \
2489 `/reasoning` in the terminal can set one"
2490 .to_string(),
2491 ),
2492 None => (
2493 Vec::new(),
2494 json!({}),
2495 "this dashboard has no provider configuration to describe".to_string(),
2496 ),
2497 };
2498 let (off_word, off_why) = match &control {
2503 Some(Reasoning::Policy(policy)) if policy.has_off() => (json!("none"), String::new()),
2504 Some(Reasoning::Policy(policy)) => (
2505 json!(null),
2506 format!(
2507 "this route has no off switch: nothing at {} turns thinking off on it",
2508 policy.field
2509 ),
2510 ),
2511 Some(Reasoning::Off) => (
2512 json!(null),
2513 "this model has no reasoning field, so there is nothing to switch off".to_string(),
2514 ),
2515 Some(Reasoning::Undeclared) => (
2516 json!(null),
2517 "this backend declares no reasoning control, so a level goes out verbatim: \
2518 `/reasoning none` in the terminal is the only off"
2519 .to_string(),
2520 ),
2521 None => (
2522 json!(null),
2523 "this dashboard has no provider configuration, so there is nothing to switch"
2524 .to_string(),
2525 ),
2526 };
2527 json!({
2528 "off_word": off_word,
2529 "off_why": off_why,
2530 "effort": report.label,
2531 "effort_detail": report.sentence(),
2532 "effort_session": report.session,
2533 "effort_default": report.by_default,
2534 "in_force": report.in_force,
2535 "resolved": report.resolved,
2536 "configured": agent.reasoning().configured(),
2539 "levels": levels,
2540 "described": described,
2541 "note": note,
2542 })
2543}
2544
2545async fn read_reasoning(State(st): State<Shared>) -> Response {
2547 let Some(agent) = st.agent.clone() else {
2548 return error(StatusCode::SERVICE_UNAVAILABLE, unconfigured(&st)).into_response();
2549 };
2550 Json(reasoning_json(&agent)).into_response()
2551}
2552
2553#[derive(Deserialize)]
2554struct ReasoningChoice {
2555 #[serde(default, deserialize_with = "some_option")]
2559 level: Option<Option<String>>,
2560}
2561
2562async fn choose_reasoning(
2571 State(st): State<Shared>,
2572 Json(choice): Json<ReasoningChoice>,
2573) -> Response {
2574 let Some(level) = choice.level else {
2575 return error(
2576 StatusCode::BAD_REQUEST,
2577 "name a level: {\"level\": \"high\"}, or {\"level\": null} to go back to the file",
2578 )
2579 .into_response();
2580 };
2581 match apply_reasoning(&st, level).await {
2582 Ok(answer) => Json(answer).into_response(),
2583 Err((code, why)) => error(code, why).into_response(),
2584 }
2585}
2586
2587pub(crate) async fn apply_reasoning(
2593 st: &AppState,
2594 level: Option<String>,
2595) -> Result<serde_json::Value, (StatusCode, String)> {
2596 use eclipse_core::provider::Reasoning;
2597 use eclipse_core::reasoning::Wire;
2598 let Some(agent) = st.agent.clone() else {
2599 return Err((StatusCode::SERVICE_UNAVAILABLE, unconfigured(st)));
2600 };
2601 match level {
2602 Some(level) => {
2603 let level = level.trim().to_lowercase();
2604 if level.is_empty() {
2605 return Err((StatusCode::BAD_REQUEST, "level is empty".to_string()));
2606 }
2607 let omit = eclipse_core::reasoning::is_omit(&level);
2612 match agent.reasoning_control() {
2613 Some(Reasoning::Policy(policy)) => {
2614 if !omit && matches!(policy.resolve(Some(&level)), Wire::Omit(_)) {
2615 return Err((
2616 StatusCode::BAD_REQUEST,
2617 format!(
2618 "{} — this route takes: {}",
2619 policy.describe(Some(&level)),
2620 policy.vocabulary().join(" · ")
2621 ),
2622 ));
2623 }
2624 }
2625 Some(Reasoning::Off) => {
2626 if !omit {
2627 return Err((
2628 StatusCode::BAD_REQUEST,
2629 "no reasoning control on this model: it has no field to carry a level"
2630 .to_string(),
2631 ));
2632 }
2633 }
2634 Some(Reasoning::Undeclared) => {
2637 if !omit && !eclipse_core::reasoning::is_level(&level) {
2638 return Err((
2639 StatusCode::BAD_REQUEST,
2640 format!(
2641 "{level:?} is not a level; the ladder is {}",
2642 eclipse_core::reasoning::LADDER.join(" · ")
2643 ),
2644 ));
2645 }
2646 }
2647 None => {
2648 return Err((
2649 StatusCode::SERVICE_UNAVAILABLE,
2650 "this dashboard has no provider configuration, so there is no dial to turn"
2651 .to_string(),
2652 ));
2653 }
2654 }
2655 agent.reasoning().set_session(Some(level));
2656 }
2657 None => agent.reasoning().clear_session(),
2658 }
2659 Ok(reasoning_json(&agent))
2660}
2661
2662async fn get_session(State(st): State<Shared>, Path(id): Path<String>) -> Response {
2663 if eclipse_core::session::validate_id(&id).is_err() {
2664 return error(StatusCode::BAD_REQUEST, "invalid session id").into_response();
2665 }
2666 let store = st.store.clone();
2667 let Some(loaded) = blocking(move || {
2668 if !store.exists(&id) {
2669 return Err(None::<eclipse_core::Error>);
2670 }
2671 let msgs = store.load(&id).map_err(Some)?;
2672 let marks = store.tool_outcomes(&id).map_err(Some)?;
2676 Ok((msgs, marks))
2677 })
2678 .await
2679 else {
2680 return error(
2681 StatusCode::INTERNAL_SERVER_ERROR,
2682 "the store did not answer",
2683 )
2684 .into_response();
2685 };
2686 match loaded {
2687 Ok((msgs, marks)) => {
2688 let mut results: std::collections::HashMap<&str, (&str, Option<bool>)> =
2698 std::collections::HashMap::new();
2699 for m in &msgs {
2700 if let (Some(id), Some(text)) = (m.tool_call_id.as_deref(), m.content.as_deref()) {
2701 let mark = marks.get(id).copied();
2705 results.entry(id).or_insert((text, mark));
2706 }
2707 }
2708 let shown: Vec<serde_json::Value> = msgs
2709 .iter()
2710 .filter_map(|m| {
2711 let mut v = serde_json::to_value(m).ok()?;
2712 let calls: Vec<serde_json::Value> = m
2713 .tool_calls
2714 .iter()
2715 .map(|c| {
2716 let state = results
2717 .get(c.id.as_str())
2718 .map(|(text, mark)| calls::outcome(text, *mark))
2719 .unwrap_or(calls::Outcome::Running);
2720 serde_json::json!({
2721 "summary": calls::statement(&c.function.name, &c.function.arguments),
2722 "state": state.as_str(),
2723 })
2724 })
2725 .collect();
2726 if !calls.is_empty() {
2727 v["calls"] = serde_json::Value::Array(calls);
2728 }
2729 Some(v)
2730 })
2731 .collect();
2732 Json(shown).into_response()
2733 }
2734 Err(None) => error(StatusCode::NOT_FOUND, "no such session").into_response(),
2735 Err(Some(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2736 }
2737}
2738
2739type ApiError = (StatusCode, Json<serde_json::Value>);
2740
2741fn session_id_ok(id: &str, st: &AppState) -> Option<ApiError> {
2749 if eclipse_core::session::validate_id(id).is_err() {
2750 return Some(error(StatusCode::BAD_REQUEST, "invalid session id"));
2751 }
2752 if !st.store.exists(id) {
2753 return Some(error(StatusCode::NOT_FOUND, "no such session"));
2754 }
2755 None
2756}
2757
2758#[derive(Deserialize)]
2759struct RenameBody {
2760 title: String,
2761}
2762
2763async fn rename_session(
2764 State(st): State<Shared>,
2765 Path(id): Path<String>,
2766 Json(body): Json<RenameBody>,
2767) -> Response {
2768 if let Some(refusal) = session_id_ok(&id, &st) {
2769 return refusal.into_response();
2770 }
2771 match st.store.rename(&id, &body.title) {
2772 Ok(()) => Json(json!({ "id": id, "title": body.title.trim() })).into_response(),
2773 Err(e) => error(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
2776 }
2777}
2778
2779#[derive(Deserialize)]
2780struct PinBody {
2781 pinned: bool,
2782}
2783
2784async fn pin_session(
2785 State(st): State<Shared>,
2786 Path(id): Path<String>,
2787 Json(body): Json<PinBody>,
2788) -> Response {
2789 if let Some(refusal) = session_id_ok(&id, &st) {
2790 return refusal.into_response();
2791 }
2792 match st.store.set_pinned(&id, body.pinned) {
2793 Ok(()) => Json(json!({ "id": id, "pinned": body.pinned })).into_response(),
2794 Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2795 }
2796}
2797
2798#[derive(Deserialize)]
2799struct ArchiveBody {
2800 archived: bool,
2801}
2802
2803async fn archive_session(
2804 State(st): State<Shared>,
2805 Path(id): Path<String>,
2806 Json(body): Json<ArchiveBody>,
2807) -> Response {
2808 if let Some(refusal) = session_id_ok(&id, &st) {
2809 return refusal.into_response();
2810 }
2811 match st.store.set_archived(&id, body.archived) {
2812 Ok(()) => Json(json!({ "id": id, "archived": body.archived })).into_response(),
2813 Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2814 }
2815}
2816
2817async fn delete_session(State(st): State<Shared>, Path(id): Path<String>) -> Response {
2818 if let Some(refusal) = session_id_ok(&id, &st) {
2819 return refusal.into_response();
2820 }
2821 match st.store.delete(&id) {
2822 Ok(()) => Json(json!({ "id": id, "deleted": true })).into_response(),
2823 Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2824 }
2825}
2826
2827const MAX_ITERATIONS_BOUND: usize = 200;
2831
2832fn error(status: StatusCode, msg: impl Into<String>) -> ApiError {
2833 (status, Json(json!({"error": msg.into()})))
2834}
2835
2836type Refusal = (StatusCode, String);
2847
2848fn cron_root(st: &AppState) -> Result<std::path::PathBuf, Refusal> {
2849 st.cron_root.clone().ok_or((
2850 StatusCode::SERVICE_UNAVAILABLE,
2851 "this dashboard was started without an install root, so it has no cron files to show"
2852 .to_string(),
2853 ))
2854}
2855
2856fn cron_job(root: &std::path::Path, name: &str) -> Result<eclipse_core::cron::Job, Refusal> {
2858 let jobs = eclipse_core::cron::load(root)
2859 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
2860 jobs.into_iter().find(|j| j.name == name).ok_or((
2861 StatusCode::NOT_FOUND,
2862 format!("no job named `{name}`; the list shows the names"),
2863 ))
2864}
2865
2866async fn list_cron(State(st): State<Shared>) -> Response {
2869 let root = match cron_root(&st) {
2870 Ok(root) => root,
2871 Err((status, why)) => return error(status, why).into_response(),
2872 };
2873 let now = eclipse_core::session::now_ms() as i64;
2874 let reader = {
2877 let root = root.clone();
2878 move || eclipse_core::cron::views(&root, now)
2879 };
2880 let Some(listing) = blocking(reader).await else {
2881 return error(
2882 StatusCode::SERVICE_UNAVAILABLE,
2883 "the blocking pool did not take the read; try again",
2884 )
2885 .into_response();
2886 };
2887 match listing {
2888 Ok(jobs) => Json(json!({
2889 "now_ms": now,
2890 "jobs_file": eclipse_core::cron::jobs_path(&root).display().to_string(),
2891 "runs_dir": eclipse_core::cron::runs_root(&root).display().to_string(),
2892 "jobs": jobs,
2893 }))
2894 .into_response(),
2895 Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2898 }
2899}
2900
2901async fn create_cron(
2903 State(st): State<Shared>,
2904 Json(draft): Json<eclipse_core::cron::Draft>,
2905) -> Response {
2906 let root = match cron_root(&st) {
2907 Ok(root) => root,
2908 Err((status, why)) => return error(status, why).into_response(),
2909 };
2910 let job = match draft.to_job() {
2911 Ok(job) => job,
2912 Err(e) => return error(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
2914 };
2915 let existing = match eclipse_core::cron::load(&root) {
2916 Ok(jobs) => jobs,
2917 Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2918 };
2919 if existing.iter().any(|j| j.name == job.name) {
2920 return error(
2921 StatusCode::CONFLICT,
2922 format!("a job named `{}` already exists", job.name),
2923 )
2924 .into_response();
2925 }
2926 if let Err(e) = eclipse_core::cron::append_job(&root, &job) {
2927 return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
2928 }
2929 let now = eclipse_core::session::now_ms() as i64;
2931 match eclipse_core::cron::views(&root, now)
2932 .map(|all| all.into_iter().find(|v| v.name == job.name))
2933 {
2934 Ok(Some(view)) => (StatusCode::CREATED, Json(view)).into_response(),
2935 Ok(None) => error(
2936 StatusCode::INTERNAL_SERVER_ERROR,
2937 "the job was written but does not read back",
2938 )
2939 .into_response(),
2940 Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2941 }
2942}
2943
2944async fn update_cron(
2950 State(st): State<Shared>,
2951 Path(name): Path<String>,
2952 Json(draft): Json<eclipse_core::cron::Draft>,
2953) -> Response {
2954 let root = match cron_root(&st) {
2955 Ok(root) => root,
2956 Err((status, why)) => return error(status, why).into_response(),
2957 };
2958 if draft.name != name {
2959 return error(
2960 StatusCode::BAD_REQUEST,
2961 "a job's name is its identity: remove this one and add the new name",
2962 )
2963 .into_response();
2964 }
2965 if let Err((status, why)) = cron_job(&root, &name) {
2966 return error(status, why).into_response();
2967 }
2968 let job = match draft.to_job() {
2969 Ok(job) => job,
2970 Err(e) => return error(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
2971 };
2972 if let Err(e) = eclipse_core::cron::replace_job(&root, &job) {
2973 return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
2974 }
2975 let now = eclipse_core::session::now_ms() as i64;
2976 match eclipse_core::cron::views(&root, now).map(|all| all.into_iter().find(|v| v.name == name))
2977 {
2978 Ok(Some(view)) => Json(view).into_response(),
2979 Ok(None) => error(
2980 StatusCode::INTERNAL_SERVER_ERROR,
2981 "the job was written but does not read back",
2982 )
2983 .into_response(),
2984 Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
2985 }
2986}
2987
2988#[derive(Deserialize)]
2989struct EnabledBody {
2990 enabled: bool,
2991}
2992
2993async fn set_cron_enabled(
2998 State(st): State<Shared>,
2999 Path(name): Path<String>,
3000 Json(body): Json<EnabledBody>,
3001) -> Response {
3002 let root = match cron_root(&st) {
3003 Ok(root) => root,
3004 Err((status, why)) => return error(status, why).into_response(),
3005 };
3006 let job = match eclipse_core::cron::set_enabled(&root, &name, body.enabled) {
3007 Ok(Some(job)) => job,
3008 Ok(None) => {
3009 return error(StatusCode::NOT_FOUND, format!("no job named `{name}`")).into_response()
3010 }
3011 Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
3012 };
3013 let now = eclipse_core::session::now_ms() as i64;
3014 let state = eclipse_core::cron::load_state(&root).unwrap_or_default();
3015 Json(eclipse_core::cron::view(&job, &state, now)).into_response()
3016}
3017
3018async fn delete_cron(State(st): State<Shared>, Path(name): Path<String>) -> Response {
3020 let root = match cron_root(&st) {
3021 Ok(root) => root,
3022 Err((status, why)) => return error(status, why).into_response(),
3023 };
3024 match eclipse_core::cron::remove_job(&root, &name) {
3025 Ok(true) => Json(json!({ "name": name, "removed": true })).into_response(),
3026 Ok(false) => error(StatusCode::NOT_FOUND, format!("no job named `{name}`")).into_response(),
3027 Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
3028 }
3029}
3030
3031fn eclipse_bin() -> std::path::PathBuf {
3037 if let Some(path) = std::env::var_os("ECLIPSE_BIN") {
3038 return std::path::PathBuf::from(path);
3039 }
3040 if let Ok(exe) = std::env::current_exe() {
3041 if let Some(dir) = exe.parent() {
3042 let beside = dir.join("eclipse");
3043 if beside.is_file() {
3044 return beside;
3045 }
3046 }
3047 }
3048 std::path::PathBuf::from("eclipse")
3049}
3050
3051async fn run_cron_now(State(st): State<Shared>, Path(name): Path<String>) -> Response {
3057 let root = match cron_root(&st) {
3058 Ok(root) => root,
3059 Err((status, why)) => return error(status, why).into_response(),
3060 };
3061 let job = match cron_job(&root, &name) {
3062 Ok(job) => job,
3063 Err((status, why)) => return error(status, why).into_response(),
3064 };
3065 let mut command = std::process::Command::new(eclipse_bin());
3071 if let Some(profile) = st.profile.as_deref() {
3072 command.arg("--profile").arg(profile);
3073 }
3074 if let Some(config) = st.config_path.as_deref() {
3075 command.arg("--config").arg(config);
3076 }
3077 let spawned = command
3078 .arg("cron")
3079 .arg("run")
3080 .arg(&name)
3081 .stdin(std::process::Stdio::null())
3082 .stdout(std::process::Stdio::null())
3083 .stderr(std::process::Stdio::null())
3084 .spawn();
3085 match spawned {
3086 Ok(mut child) => {
3089 let pid = child.id();
3090 tokio::task::spawn_blocking(move || {
3095 let _ = child.wait();
3096 });
3097 (
3098 StatusCode::ACCEPTED,
3099 Json(json!({
3100 "name": name,
3101 "started": true,
3102 "pid": pid,
3103 "enabled": job.enabled,
3104 })),
3105 )
3106 .into_response()
3107 }
3108 Err(e) => error(
3109 StatusCode::INTERNAL_SERVER_ERROR,
3110 format!(
3111 "could not start `{} cron run {name}`: {e}",
3112 eclipse_bin().display()
3113 ),
3114 )
3115 .into_response(),
3116 }
3117}
3118
3119async fn cron_logs(
3121 State(st): State<Shared>,
3122 Path(name): Path<String>,
3123 Query(q): Query<LogsQuery>,
3124) -> Response {
3125 let root = match cron_root(&st) {
3126 Ok(root) => root,
3127 Err((status, why)) => return error(status, why).into_response(),
3128 };
3129 if let Err((status, why)) = cron_job(&root, &name) {
3130 return error(status, why).into_response();
3131 }
3132 let limit = q.limit.unwrap_or(3).clamp(1, 20);
3134 Json(json!({
3135 "job": name,
3136 "runs_dir": eclipse_core::cron::runs_dir(&root, &name).display().to_string(),
3137 "runs": eclipse_core::cron::runs(&root, &name, limit),
3138 }))
3139 .into_response()
3140}
3141
3142#[derive(Deserialize)]
3143struct LogsQuery {
3144 limit: Option<usize>,
3145}
3146
3147fn mcp_config_path(st: &AppState) -> Result<std::path::PathBuf, Refusal> {
3154 st.write_path().ok_or((
3158 StatusCode::SERVICE_UNAVAILABLE,
3159 "this dashboard was started without a config file, so it has no `[[mcp]]` entries to \
3160 show or edit"
3161 .to_string(),
3162 ))
3163}
3164
3165fn mcp_row(s: &eclipse_core::plugins::McpServerState) -> serde_json::Value {
3169 json!({
3170 "name": s.name,
3171 "source": s.source.label(),
3172 "owner": s.owner,
3173 "command": s.command,
3174 "policy": format!("{:?}", s.policy).to_lowercase(),
3175 "prefix": s.prefix,
3176 "timeout_secs": s.timeout_secs,
3177 "disabled": s.disabled,
3178 "transport": s.transport.as_str(),
3181 "program": s.program,
3182 "args": s.args,
3183 "url": s.url,
3184 "token_env": s.token_env,
3185 "token": s.token.as_str(),
3186 "tools": s.tools,
3187 "started": s.error.is_none() && !s.disabled,
3191 "error": s.error,
3192 "protocol": s.protocol,
3193 "server_name": s.server_name,
3194 "server_version": s.server_version,
3195 })
3196}
3197
3198fn mcp_listing(cfg: &eclipse_core::config::Config) -> (Vec<serde_json::Value>, Vec<String>) {
3202 let loaded = eclipse_core::plugins::load(
3203 &cfg.plugins_dirs(&eclipse_core::config::process_env),
3204 &cfg.plugins.enabled,
3205 )
3206 .with_mcp(eclipse_core::plugins::McpSettings::from_config(cfg))
3207 .with_config_mcp(cfg);
3208 let workspace = cfg.workspace_root(&eclipse_core::config::process_env);
3209 let (servers, problems) = loaded.mcp_report(&workspace);
3210 (servers.iter().map(mcp_row).collect(), problems)
3211}
3212
3213fn mcp_writer_error(why: String) -> (StatusCode, String) {
3219 let status = if why.starts_with("no `[[mcp]]` entry") {
3220 StatusCode::NOT_FOUND
3221 } else if why.contains("is already declared at line") {
3222 StatusCode::CONFLICT
3223 } else if why.starts_with("that entry is not usable") {
3224 StatusCode::BAD_REQUEST
3225 } else {
3226 StatusCode::INTERNAL_SERVER_ERROR
3227 };
3228 (status, why)
3229}
3230
3231async fn mcp_edit(
3235 st: &AppState,
3236 edit: impl FnOnce(&str) -> Result<String, (StatusCode, String)> + Send + 'static,
3237) -> Result<eclipse_core::config::Config, (StatusCode, String)> {
3238 let path = mcp_config_path(st)?;
3239 let base = st.config_path.clone();
3240 let profile = st.profile.clone();
3241 let writes = st.config_writes.clone();
3242 let written = blocking(move || -> Result<_, (StatusCode, String)> {
3243 let _one_writer = writes
3244 .lock()
3245 .unwrap_or_else(|poisoned| poisoned.into_inner());
3246 let text = match std::fs::read_to_string(&path) {
3249 Ok(text) => text,
3250 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
3251 Err(e) => {
3252 return Err((
3253 StatusCode::INTERNAL_SERVER_ERROR,
3254 format!("{}: {e}", path.display()),
3255 ))
3256 }
3257 };
3258 let edited = edit(&text)?;
3259 if let Some(dir) = path.parent() {
3260 std::fs::create_dir_all(dir).map_err(|e| {
3261 (
3262 StatusCode::INTERNAL_SERVER_ERROR,
3263 format!("{}: {e}", dir.display()),
3264 )
3265 })?;
3266 }
3267 eclipse_core::config::save_config_text(&path, &edited)
3268 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
3269 eclipse_core::config::Config::load_with_profile(
3272 base.as_deref(),
3273 profile.as_deref(),
3274 &eclipse_core::config::process_env,
3275 )
3276 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
3277 })
3278 .await;
3279 let Some(written) = written else {
3280 return Err((
3281 StatusCode::INTERNAL_SERVER_ERROR,
3282 "the write did not finish".to_string(),
3283 ));
3284 };
3285 written
3286}
3287
3288async fn mcp_row_after(
3291 cfg: eclipse_core::config::Config,
3292 name: &str,
3293) -> Result<serde_json::Value, (StatusCode, String)> {
3294 let Some(rows) = blocking(move || mcp_listing(&cfg)).await else {
3295 return Err((
3296 StatusCode::SERVICE_UNAVAILABLE,
3297 "the blocking pool did not take the read; try again".to_string(),
3298 ));
3299 };
3300 rows.0
3301 .into_iter()
3302 .find(|r| r["name"] == name)
3303 .ok_or_else(|| {
3304 (
3305 StatusCode::INTERNAL_SERVER_ERROR,
3306 format!("the entry was written but `{name}` does not read back"),
3307 )
3308 })
3309}
3310
3311async fn list_problems(State(st): State<Shared>) -> Response {
3317 let cfg = match st.reload_config() {
3321 Ok(cfg) => cfg,
3322 Err(e) => {
3323 return Json(json!({
3324 "summary": format!("the config could not be loaded: {e}"),
3325 "config_error": st.config_error.clone().unwrap_or_else(|| e.clone()),
3326 "problems": [],
3327 "checked": [],
3328 }))
3329 .into_response()
3330 }
3331 };
3332 let report =
3333 blocking(move || eclipse_core::problems::collect(&cfg, &eclipse_core::config::process_env))
3334 .await;
3335 let Some(report) = report else {
3336 return error(
3337 StatusCode::SERVICE_UNAVAILABLE,
3338 "the blocking pool did not take the read; try again",
3339 )
3340 .into_response();
3341 };
3342 let problems: Vec<serde_json::Value> = report
3343 .problems
3344 .iter()
3345 .map(|p| {
3346 json!({
3347 "kind": p.kind.as_str(),
3348 "text": p.text,
3349 "path": p.path.as_ref().map(|p| p.display().to_string()),
3350 })
3351 })
3352 .collect();
3353 Json(json!({
3354 "summary": report.summary(),
3355 "config_error": st.config_error.clone(),
3359 "problems": problems,
3360 "checked": report.checked,
3361 }))
3362 .into_response()
3363}
3364
3365async fn list_mcp(State(st): State<Shared>) -> Response {
3368 let path = match mcp_config_path(&st) {
3369 Ok(path) => path,
3370 Err((status, why)) => return error(status, why).into_response(),
3371 };
3372 let cfg = match st.reload_config() {
3373 Ok(cfg) => cfg,
3374 Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
3375 };
3376 let Some(listing) = blocking(move || mcp_listing(&cfg)).await else {
3377 return error(
3378 StatusCode::SERVICE_UNAVAILABLE,
3379 "the blocking pool did not take the read; try again",
3380 )
3381 .into_response();
3382 };
3383 Json(json!({
3384 "config_path": path.display().to_string(),
3385 "servers": listing.0,
3386 "problems": listing.1,
3387 }))
3388 .into_response()
3389}
3390
3391type TokenEnv = Option<String>;
3394
3395#[derive(Deserialize)]
3400struct McpEntry {
3401 #[serde(default)]
3402 name: Option<String>,
3403 #[serde(default)]
3406 transport: Option<String>,
3407 #[serde(default)]
3408 command: Option<String>,
3409 #[serde(default)]
3410 args: Option<Vec<String>>,
3411 #[serde(default)]
3412 url: Option<String>,
3413 #[serde(default)]
3414 prefix: Option<String>,
3415 #[serde(default)]
3416 policy: Option<String>,
3417 #[serde(default)]
3418 token_env: TokenEnv,
3419 #[serde(default)]
3420 timeout_secs: Option<u64>,
3421}
3422
3423fn filled(v: Option<&String>) -> bool {
3424 v.is_some_and(|s| !s.trim().is_empty())
3425}
3426
3427async fn add_mcp(State(st): State<Shared>, Json(body): Json<McpEntry>) -> Response {
3431 let name = body.name.clone().unwrap_or_default().trim().to_string();
3432 if name.is_empty() {
3433 return error(
3434 StatusCode::BAD_REQUEST,
3435 "a server needs a name — it is what `eclipse mcp test` and the tool names use",
3436 )
3437 .into_response();
3438 }
3439 let transport = match mcp_transport(&body) {
3440 Ok(transport) => transport,
3441 Err((status, why)) => return error(status, why).into_response(),
3442 };
3443 let policy = match mcp_policy(&body) {
3444 Ok(policy) => policy,
3445 Err((status, why)) => return error(status, why).into_response(),
3446 };
3447 let spec = eclipse_core::mcp::Spec {
3448 name: name.clone(),
3449 transport,
3450 command: body.command.unwrap_or_default(),
3451 args: body.args.unwrap_or_default(),
3452 env: Vec::new(),
3453 cwd: Default::default(),
3454 url: body.url.filter(|u| !u.trim().is_empty()),
3455 token_env: body.token_env.filter(|t| !t.trim().is_empty()),
3456 timeout_secs: body.timeout_secs,
3457 policy,
3458 policies: Default::default(),
3459 prefix: body.prefix.unwrap_or_default(),
3460 override_builtin: false,
3461 disabled: false,
3462 };
3463 let wrote = mcp_edit(&st, move |text| {
3464 eclipse_core::config::mcp_add(text, &spec).map_err(mcp_writer_error)
3465 })
3466 .await;
3467 let cfg = match wrote {
3468 Ok(cfg) => cfg,
3469 Err((status, why)) => return error(status, why).into_response(),
3470 };
3471 match mcp_row_after(cfg, &name).await {
3472 Ok(row) => (StatusCode::CREATED, Json(row)).into_response(),
3473 Err((status, why)) => error(status, why).into_response(),
3474 }
3475}
3476
3477fn mcp_transport(body: &McpEntry) -> Result<eclipse_core::mcp::Transport, (StatusCode, String)> {
3481 match body.transport.as_deref() {
3482 None | Some("") => {
3483 if filled(body.url.as_ref()) && !filled(body.command.as_ref()) {
3484 Ok(eclipse_core::mcp::Transport::Http)
3485 } else {
3486 Ok(eclipse_core::mcp::Transport::Stdio)
3487 }
3488 }
3489 Some("stdio") => Ok(eclipse_core::mcp::Transport::Stdio),
3490 Some("http") => Ok(eclipse_core::mcp::Transport::Http),
3491 Some(other) => Err((
3492 StatusCode::BAD_REQUEST,
3493 format!("`{other}` is not a transport: this build speaks `stdio` and `http`"),
3494 )),
3495 }
3496}
3497
3498fn mcp_policy(body: &McpEntry) -> Result<eclipse_core::config::Policy, (StatusCode, String)> {
3501 match body.policy.as_deref() {
3502 None | Some("") => Ok(eclipse_core::config::Policy::Ask),
3503 Some(raw) => {
3504 serde_json::from_value::<eclipse_core::config::Policy>(json!(raw)).map_err(|_| {
3505 (
3506 StatusCode::BAD_REQUEST,
3507 format!("`{raw}` is not a policy: `ask`, `allow` or `deny`"),
3508 )
3509 })
3510 }
3511 }
3512}
3513
3514struct McpFields {
3518 transport: eclipse_core::mcp::Transport,
3519 command: String,
3520 args: Vec<String>,
3521 url: Option<String>,
3522 prefix: String,
3523 policy: eclipse_core::config::Policy,
3524 token_env: Option<String>,
3525 timeout_secs: Option<u64>,
3527}
3528
3529async fn update_mcp(
3535 State(st): State<Shared>,
3536 Path(name): Path<String>,
3537 Json(body): Json<McpEntry>,
3538) -> Response {
3539 if let Some(named) = body
3540 .name
3541 .as_deref()
3542 .map(str::trim)
3543 .filter(|n| !n.is_empty())
3544 {
3545 if named != name {
3546 return error(
3547 StatusCode::BAD_REQUEST,
3548 format!(
3549 "this is the entry for `{name}`, and an edit does not rename it — remove it and add `{named}` instead"
3550 ),
3551 )
3552 .into_response();
3553 }
3554 }
3555 let transport = match mcp_transport(&body) {
3556 Ok(transport) => transport,
3557 Err((status, why)) => return error(status, why).into_response(),
3558 };
3559 let policy = match mcp_policy(&body) {
3560 Ok(policy) => policy,
3561 Err((status, why)) => return error(status, why).into_response(),
3562 };
3563 let edit = McpFields {
3564 transport,
3565 command: body.command.unwrap_or_default(),
3566 args: body.args.unwrap_or_default(),
3567 url: body.url.filter(|u| !u.trim().is_empty()),
3568 prefix: body.prefix.unwrap_or_default(),
3569 policy,
3570 token_env: body.token_env.filter(|t| !t.trim().is_empty()),
3571 timeout_secs: body.timeout_secs,
3572 };
3573 let for_writer = name.clone();
3574 let wrote = mcp_edit(&st, move |text| {
3575 eclipse_core::config::mcp_update(text, &for_writer, move |spec| {
3576 spec.transport = edit.transport;
3577 spec.command = edit.command;
3578 spec.args = edit.args;
3579 spec.url = edit.url;
3580 spec.prefix = edit.prefix;
3581 spec.policy = edit.policy;
3582 spec.token_env = edit.token_env;
3583 if edit.timeout_secs.is_some() {
3584 spec.timeout_secs = edit.timeout_secs;
3585 }
3586 })
3587 .map_err(mcp_writer_error)
3588 })
3589 .await;
3590 let cfg = match wrote {
3591 Ok(cfg) => cfg,
3592 Err((status, why)) => return error(status, why).into_response(),
3593 };
3594 match mcp_row_after(cfg, &name).await {
3595 Ok(row) => Json(row).into_response(),
3596 Err((status, why)) => error(status, why).into_response(),
3597 }
3598}
3599
3600async fn set_mcp_enabled(
3604 State(st): State<Shared>,
3605 Path(name): Path<String>,
3606 Json(body): Json<EnabledBody>,
3607) -> Response {
3608 let for_writer = name.clone();
3609 let wrote = mcp_edit(&st, move |text| {
3610 eclipse_core::config::mcp_set_disabled(text, &for_writer, !body.enabled)
3611 .map_err(mcp_writer_error)
3612 })
3613 .await;
3614 let cfg = match wrote {
3615 Ok(cfg) => cfg,
3616 Err((status, why)) => return error(status, why).into_response(),
3617 };
3618 match mcp_row_after(cfg, &name).await {
3619 Ok(row) => Json(row).into_response(),
3620 Err((status, why)) => error(status, why).into_response(),
3621 }
3622}
3623
3624async fn test_mcp(State(st): State<Shared>, Path(name): Path<String>) -> Response {
3630 if let Err((status, why)) = mcp_config_path(&st) {
3631 return error(status, why).into_response();
3632 }
3633 let cfg = match st.reload_config() {
3634 Ok(cfg) => cfg,
3635 Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
3636 };
3637 let wanted = name.clone();
3638 let Some(rows) = blocking(move || mcp_listing(&cfg)).await else {
3639 return error(
3640 StatusCode::SERVICE_UNAVAILABLE,
3641 "the blocking pool did not take the run; try again",
3642 )
3643 .into_response();
3644 };
3645 match rows.0.into_iter().find(|r| r["name"] == wanted) {
3646 Some(row) => Json(row).into_response(),
3647 None => error(
3648 StatusCode::NOT_FOUND,
3649 format!("no MCP server is called `{name}` — the list shows the names this build sees"),
3650 )
3651 .into_response(),
3652 }
3653}
3654
3655async fn remove_mcp(State(st): State<Shared>, Path(name): Path<String>) -> Response {
3658 let for_writer = name.clone();
3659 let wrote = mcp_edit(&st, move |text| {
3660 eclipse_core::config::mcp_remove(text, &for_writer).map_err(mcp_writer_error)
3661 })
3662 .await;
3663 match wrote {
3664 Ok(_) => Json(json!({ "name": name, "removed": true })).into_response(),
3665 Err((status, why)) => error(status, why).into_response(),
3666 }
3667}
3668
3669#[derive(Deserialize)]
3670struct ChatRequest {
3671 #[serde(default)]
3672 message: String,
3673 session_id: Option<String>,
3674 max_iterations: Option<usize>,
3677 #[serde(default)]
3681 attachments: Vec<Attachment>,
3682}
3683
3684#[derive(Debug, Deserialize)]
3697struct Attachment {
3698 kind: String,
3701 #[serde(default)]
3704 name: String,
3705 #[serde(default)]
3706 value: String,
3707}
3708
3709const MAX_ATTACHMENTS: usize = 8;
3713const MAX_ATTACHMENT_CHARS: usize = 64 * 1024;
3714const MAX_ATTACHED_CHARS: usize = 192 * 1024;
3715
3716fn compose_attachments(
3725 message: &str,
3726 items: &[Attachment],
3727) -> Result<(String, Vec<eclipse_core::message::ImagePart>), String> {
3728 if items.is_empty() {
3729 return Ok((message.to_string(), Vec::new()));
3730 }
3731 if items.len() > MAX_ATTACHMENTS {
3732 return Err(format!(
3733 "at most {MAX_ATTACHMENTS} attachments per turn; this one has {}",
3734 items.len()
3735 ));
3736 }
3737 let mut blocks: Vec<String> = Vec::new();
3738 let mut pictures: Vec<eclipse_core::message::ImagePart> = Vec::new();
3739 let mut added = 0usize;
3740 for item in items {
3741 let name = if item.name.trim().is_empty() {
3742 item.value.trim().to_string()
3743 } else {
3744 item.name.trim().to_string()
3745 };
3746 let block = match item.kind.as_str() {
3747 "text" => {
3748 let body = item.value.trim_end_matches('\n');
3750 let chars = body.chars().count();
3751 if chars > MAX_ATTACHMENT_CHARS {
3752 return Err(format!(
3753 "{name} is {chars} characters and the limit is {MAX_ATTACHMENT_CHARS}: \
3754 attach it as a path and let the agent read the part it needs"
3755 ));
3756 }
3757 added = added.saturating_add(chars);
3758 format!("--- attached file: {name} ({chars} chars) ---\n{body}\n--- end of {name} ---")
3759 }
3760 "path" => {
3761 let path = item.value.trim();
3762 if path.is_empty() || path.chars().count() > 512 || path.chars().any(char::is_control) {
3763 return Err(format!(
3764 "cannot attach {path:?} as a path: a path is one line, at most 512 characters"
3765 ));
3766 }
3767 format!(
3768 "--- attached path: {path} (not inlined; read it with read_file if you need it) ---"
3769 )
3770 }
3771 "url" => {
3772 let url = item.value.trim();
3773 let ok = (url.starts_with("http://") || url.starts_with("https://"))
3774 && url.chars().count() <= 2048
3775 && !url.chars().any(|c| c.is_whitespace() || c.is_control());
3776 if !ok {
3777 return Err(format!(
3778 "cannot attach {url:?} as a link: it has to start with http:// or https:// and hold no spaces"
3779 ));
3780 }
3781 format!("--- attached link: {url} (fetch it if you need it) ---")
3782 }
3783 "image" => {
3788 let parts = image_parts(std::slice::from_ref(item))?;
3789 let part = parts.into_iter().next().expect("one item, one part");
3790 let label = part.name.clone();
3794 pictures.push(part.clone());
3795 format!("--- attached picture: {label} ({}) ---", part.mime)
3796 }
3797 other => {
3798 return Err(format!(
3799 "this page cannot attach {other} yet: the request has no part for one, so it would \
3800 be dropped rather than read. Attach a file, a picture, a path or a link."
3801 ))
3802 }
3803 };
3804 blocks.push(block);
3805 }
3806 if added > MAX_ATTACHED_CHARS {
3807 return Err(format!(
3808 "the attachments add {added} characters and the limit is {MAX_ATTACHED_CHARS}: \
3809 send fewer, or attach the paths instead"
3810 ));
3811 }
3812 let blocks = blocks.join("\n\n");
3815 let head = message.trim_end();
3816 let text = if head.is_empty() {
3817 blocks
3818 } else {
3819 format!("{head}\n\n{blocks}")
3820 };
3821 Ok((text, pictures))
3822}
3823
3824fn image_parts(items: &[Attachment]) -> Result<Vec<eclipse_core::message::ImagePart>, String> {
3832 items
3833 .iter()
3834 .map(|item| {
3835 eclipse_core::message::ImagePart::from_data_url(item.name.trim(), item.value.trim())
3836 })
3837 .collect()
3838}
3839
3840enum Out {
3841 Event(AgentEvent),
3842 ApprovalRequest {
3843 id: String,
3844 tool: String,
3845 summary: String,
3846 timeout_secs: u64,
3847 },
3848 ApprovalResolved {
3849 id: String,
3850 verdict: Verdict,
3851 },
3852 Cancelled,
3855 Failed(String),
3856 Done,
3857}
3858
3859#[derive(Deserialize)]
3860struct Decision {
3861 approved: bool,
3862}
3863
3864async fn cancel_run(State(st): State<Shared>, Path(id): Path<String>) -> Response {
3867 if id.is_empty() || id.len() > 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
3868 return error(StatusCode::BAD_REQUEST, "invalid run id").into_response();
3869 }
3870 let cancel = st
3871 .cancels
3872 .lock()
3873 .unwrap_or_else(|e| e.into_inner())
3874 .get(&id)
3875 .cloned();
3876 match cancel {
3877 Some(cancel) => {
3878 cancel.cancel();
3879 Json(json!({"cancelled": true})).into_response()
3880 }
3881 None => error(StatusCode::NOT_FOUND, "no such run").into_response(),
3882 }
3883}
3884
3885async fn decide_approval(
3887 State(st): State<Shared>,
3888 Path(id): Path<String>,
3889 Json(decision): Json<Decision>,
3890) -> Response {
3891 if id.is_empty() || id.len() > 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
3892 return error(StatusCode::BAD_REQUEST, "invalid approval id").into_response();
3893 }
3894 if st.approvals.resolve(&id, decision.approved) {
3895 Json(json!({"ok": true})).into_response()
3896 } else {
3897 error(
3898 StatusCode::NOT_FOUND,
3899 "no such pending approval (already answered or expired)",
3900 )
3901 .into_response()
3902 }
3903}
3904
3905fn sse(name: &str, data: serde_json::Value) -> Event {
3906 Event::default().event(name).data(data.to_string())
3907}
3908
3909type EventStream = Sse<std::pin::Pin<Box<dyn Stream<Item = Result<Event, Infallible>> + Send>>>;
3913
3914fn notice_stream(answer: Answer) -> EventStream {
3919 let events = vec![
3920 Ok(sse(
3921 "notice",
3922 json!({
3923 "text": answer.text,
3924 "kind": if answer.refused { "refusal" } else { "command" },
3925 "clear_session": answer.clear_session,
3926 "yolo": answer.yolo,
3929 }),
3930 )),
3931 Ok(sse("done", json!({}))),
3932 ];
3933 Sse::new(stream::iter(events).boxed())
3934}
3935
3936async fn chat(
3943 State(st): State<Shared>,
3944 Json(req): Json<ChatRequest>,
3945) -> Result<EventStream, ApiError> {
3946 if req.message.trim().is_empty() && req.attachments.is_empty() {
3949 return Err(error(StatusCode::BAD_REQUEST, "message is empty"));
3950 }
3951 if let Some(answer) = verb::bang_refusal(&req.message) {
3969 return Ok(notice_stream(answer));
3970 }
3971 let parsed = eclipse_core::commands::parse(&req.message, Front::Web);
3972 let command_line = matches!(parsed, Parsed::Run(..) | Parsed::Elsewhere(..))
3976 || matches!(&parsed, Parsed::Unknown(line) if line.starts_with('/'));
3977 if command_line && !req.attachments.is_empty() {
3978 return Ok(notice_stream(Answer::refused(
3979 "a command runs on its own: remove the attachment, or send it with a message",
3980 )));
3981 }
3982 match parsed {
3983 Parsed::Run(command, arg) => {
3984 let answer = verb::serve(&st, command, arg, req.session_id.as_deref()).await;
3985 return Ok(notice_stream(answer));
3986 }
3987 Parsed::Elsewhere(command) => {
3988 return Ok(notice_stream(Answer::refused(
3989 command.unavailable_in(Front::Web),
3990 )))
3991 }
3992 Parsed::Unknown(line) if line.starts_with('/') => {
3993 return Ok(notice_stream(Answer::refused("unknown command; try /help")))
3994 }
3995 Parsed::Unknown(_) => {}
3996 }
3997 let (message, pictures) = compose_attachments(&req.message, &req.attachments)
4002 .map_err(|e| error(StatusCode::BAD_REQUEST, e))?;
4003 let Some(_) = st.agent.clone() else {
4004 return Err(error(StatusCode::SERVICE_UNAVAILABLE, unconfigured(&st)));
4005 };
4006 if req.max_iterations == Some(0) {
4007 return Err(error(
4008 StatusCode::BAD_REQUEST,
4009 "max_iterations must be at least 1: a run allowed no request is not a run",
4010 ));
4011 }
4012 if let Some(n) = req.max_iterations.filter(|n| *n > MAX_ITERATIONS_BOUND) {
4017 return Err(error(
4018 StatusCode::BAD_REQUEST,
4019 format!(
4020 "max_iterations is at most {MAX_ITERATIONS_BOUND} (asked for {n}): a bound that \
4021 large is a request for the model, not a turn"
4022 ),
4023 ));
4024 }
4025 let session_id = match req.session_id.filter(|s| !s.is_empty()) {
4026 Some(id) => {
4027 eclipse_core::session::validate_id(&id)
4028 .map_err(|e| error(StatusCode::BAD_REQUEST, e.to_string()))?;
4029 id
4030 }
4031 None => st.store.new_id(),
4032 };
4033 let agent = match st.agent_for(&session_id) {
4038 Ok(Some(agent)) => agent,
4039 Ok(None) => return Err(error(StatusCode::SERVICE_UNAVAILABLE, unconfigured(&st))),
4040 Err(why) => return Err(error(StatusCode::SERVICE_UNAVAILABLE, why)),
4041 };
4042
4043 let Some(permit) = st.try_chat_slot() else {
4044 return Err(error(
4045 StatusCode::TOO_MANY_REQUESTS,
4046 "too many chats in progress; try again shortly",
4047 ));
4048 };
4049
4050 let (tx, rx) = mpsc::unbounded_channel::<Out>();
4051 let sid = session_id.clone();
4052 let run = st.approvals.next_run.fetch_add(1, Ordering::Relaxed);
4053 let run_id = eclipse_core::token::random_hex(16)
4056 .map_err(|e| error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
4057 let cancel = Cancel::new();
4058 st.cancels
4059 .lock()
4060 .unwrap_or_else(|e| e.into_inner())
4061 .insert(run_id.clone(), cancel.clone());
4062 let run_token = run_id.clone();
4063 let guard_cancel = cancel.clone();
4064 let budget = req.max_iterations.unwrap_or_else(|| agent.max_iterations());
4067 let opts = RunOptions {
4068 max_iterations: req.max_iterations,
4069 resume: false,
4072 output_schema: None,
4076 title: true,
4079 images: pictures,
4082 };
4083 let rail = agent.context_reading(None);
4088 let report = agent.reasoning_report();
4089 tokio::spawn(async move {
4090 let _permit = permit;
4091 let _scope = RunScope {
4092 state: st.clone(),
4093 run,
4094 token: run_token,
4095 };
4096 let events = tx.clone();
4097 let sink = move |e: AgentEvent| {
4098 let _ = events.send(Out::Event(e));
4099 };
4100 let approver = WebApprover {
4101 state: st.clone(),
4102 run,
4103 events: tx.clone(),
4104 };
4105 match agent
4106 .run_cancellable_with(Some(&sid), &message, &approver, &sink, &cancel, &opts)
4107 .await
4108 {
4109 Ok(_) => {}
4110 Err(eclipse_core::Error::Cancelled) => {
4111 let _ = tx.send(Out::Cancelled);
4112 }
4113 Err(e) => {
4114 let _ = tx.send(Out::Failed(e.to_string()));
4115 }
4116 }
4117 let _ = tx.send(Out::Done);
4118 });
4119
4120 let first = stream::once(async move {
4121 Ok::<_, Infallible>(sse(
4122 "session",
4123 json!({"session_id": session_id, "run_id": run_id, "max_iterations": budget}),
4124 ))
4125 });
4126 let guard = DisconnectGuard {
4130 cancel: guard_cancel,
4131 };
4132 let state = (rx, guard, rail, report);
4136 let rest = stream::unfold(state, |(mut rx, guard, rail, report)| async move {
4137 let item = rx.recv().await?;
4138 let ev = match item {
4139 Out::Event(AgentEvent::ToolCall {
4140 call_id,
4141 name,
4142 arguments,
4143 }) => {
4144 let summary = calls::statement(&name, &arguments);
4147 sse(
4148 "tool_call",
4149 json!({
4150 "call_id": call_id,
4151 "name": name,
4152 "arguments": arguments,
4153 "summary": summary,
4154 }),
4155 )
4156 }
4157 Out::Event(AgentEvent::ToolResult {
4158 call_id,
4159 name,
4160 output,
4161 is_error,
4162 }) => sse(
4163 "tool_result",
4164 json!({
4165 "call_id": call_id,
4166 "name": name,
4167 "state": calls::outcome(&output, Some(is_error)).as_str(),
4171 "output": output,
4172 "is_error": is_error,
4173 }),
4174 ),
4175 Out::Event(AgentEvent::Delta(text)) => sse("delta", json!({"text": text})),
4176 Out::Event(AgentEvent::ReasoningDelta(text)) => sse("reasoning", json!({"text": text})),
4177 Out::Event(AgentEvent::ToolCallDelta { index, json }) => {
4178 sse("tool_call_delta", json!({"index": index, "json": json}))
4179 }
4180 Out::Event(AgentEvent::Message(text)) => sse("message", json!({"text": text})),
4181 Out::Event(AgentEvent::TurnStats {
4182 usage,
4183 context_tokens,
4184 budget_tokens,
4185 }) => sse(
4186 "stats",
4187 json!({
4188 "prompt_tokens": usage.prompt_tokens,
4189 "completion_tokens": usage.completion_tokens,
4190 "total_tokens": usage.total_tokens,
4191 "cached_tokens": usage.cached_tokens,
4192 "prompt_ms": usage.prompt_ms,
4193 "completion_ms": usage.completion_ms,
4194 "latency_ms": usage.latency_ms,
4195 "ttft_ms": usage.ttft_ms,
4196 "tokens_per_sec": usage.tokens_per_sec(),
4197 "context_tokens": context_tokens,
4198 "budget_tokens": budget_tokens,
4199 "window_tokens": rail.denominator,
4200 "ctx": Reading::new(
4203 usage
4204 .prompt_tokens
4205 .or((context_tokens > 0).then_some(context_tokens as u64)),
4206 rail.denominator,
4207 rail.marker,
4208 )
4209 .text(12),
4210 "effort": report.label.clone(),
4211 "effort_detail": report.sentence(),
4212 "effort_session": report.session,
4213 }),
4214 ),
4215 Out::Event(AgentEvent::SchemaRejected { error, retrying }) => sse(
4218 "schema_rejected",
4219 json!({ "error": error, "retrying": retrying }),
4220 ),
4221 Out::Event(AgentEvent::ContextTrimmed {
4222 turns,
4223 messages,
4224 memory,
4225 judgement,
4226 }) => {
4227 let (memory, memory_error) = match memory {
4228 eclipse_core::MemoryStatus::NotUsed => ("not_used", None),
4229 eclipse_core::MemoryStatus::Reused => ("reused", None),
4230 eclipse_core::MemoryStatus::Saved => ("saved", None),
4231 eclipse_core::MemoryStatus::SaveFailed(e) => ("save_failed", Some(e)),
4232 };
4233 let (judgement, judgement_bullets, judgement_error) = match judgement {
4236 eclipse_core::JudgementStatus::Off => ("off", 0, None),
4237 eclipse_core::JudgementStatus::Used { bullets } => ("used", bullets, None),
4238 eclipse_core::JudgementStatus::Rejected(e) => ("rejected", 0, Some(e)),
4239 eclipse_core::JudgementStatus::Failed(e) => ("failed", 0, Some(e)),
4240 };
4241 sse(
4242 "context_trimmed",
4243 json!({
4244 "turns": turns,
4245 "messages": messages,
4246 "memory": memory,
4247 "memory_error": memory_error,
4248 "judgement": judgement,
4249 "judgement_bullets": judgement_bullets,
4250 "judgement_error": judgement_error,
4251 }),
4252 )
4253 }
4254 Out::ApprovalRequest {
4255 id,
4256 tool,
4257 summary,
4258 timeout_secs,
4259 } => sse(
4260 "approval_request",
4261 json!({"id": id, "tool": tool, "summary": summary, "timeout_secs": timeout_secs}),
4262 ),
4263 Out::ApprovalResolved { id, verdict } => sse(
4264 "approval_resolved",
4265 json!({"id": id, "outcome": verdict.as_str()}),
4266 ),
4267 Out::Cancelled => sse("cancelled", json!({})),
4268 Out::Failed(message) => sse("error", json!({"message": message})),
4269 Out::Done => sse("done", json!({})),
4270 };
4271 Some((Ok::<_, Infallible>(ev), (rx, guard, rail, report)))
4272 });
4273 Ok(Sse::new(first.chain(rest).boxed()).keep_alive(KeepAlive::default()))
4274}
4275
4276#[cfg(test)]
4277mod tests {
4278 use super::*;
4279 use async_trait::async_trait;
4280 use axum::body::Body;
4281 use axum::http::Request as HttpRequest;
4282 use eclipse_core::error::Result as CoreResult;
4283 use eclipse_core::message::Message;
4284 use eclipse_core::provider::ChatProvider;
4285 use eclipse_core::session::SessionStore;
4286 use eclipse_core::tools::{ToolRegistry, ToolSpec};
4287 use eclipse_core::usage::TurnUsage;
4288 use tower::ServiceExt;
4289
4290 struct Canned;
4291
4292 #[async_trait]
4293 impl ChatProvider for Canned {
4294 async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
4295 Ok(Message::assistant("canned reply"))
4296 }
4297 }
4298
4299 struct Measured;
4303
4304 #[async_trait]
4305 impl ChatProvider for Measured {
4306 async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
4307 unreachable!()
4308 }
4309 async fn chat_stream(
4310 &self,
4311 _: &[Message],
4312 _: &[ToolSpec],
4313 on_delta: eclipse_core::stream::DeltaFn<'_>,
4314 ) -> CoreResult<Message> {
4315 tokio::time::sleep(std::time::Duration::from_millis(25)).await;
4318 on_delta(eclipse_core::stream::Delta::Text("measured ".into()));
4319 on_delta(eclipse_core::stream::Delta::Text("reply".into()));
4320 Ok(Message::assistant("measured reply"))
4321 }
4322
4323 fn take_usage(&self) -> Option<TurnUsage> {
4324 let prompt = 30_000_u64;
4328 let total = 30_120_u64;
4329 let cached = 19_000_u64;
4330 Some(TurnUsage {
4331 prompt_tokens: Some(prompt),
4332 completion_tokens: Some(120),
4333 total_tokens: Some(total),
4334 cached_tokens: Some(cached),
4335 prompt_ms: Some(300),
4336 completion_ms: Some(2_500),
4337 latency_ms: 2_900,
4338 ttft_ms: Some(1_500),
4339 })
4340 }
4341 }
4342
4343 struct Scripted(Mutex<Vec<Message>>);
4345
4346 impl Scripted {
4347 fn new(mut replies: Vec<Message>) -> Arc<Self> {
4348 replies.reverse();
4349 Arc::new(Self(Mutex::new(replies)))
4350 }
4351 }
4352
4353 #[async_trait]
4354 impl ChatProvider for Scripted {
4355 async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
4356 Ok(self.0.lock().unwrap().pop().expect("script exhausted"))
4357 }
4358 }
4359
4360 struct Streaming;
4361
4362 #[async_trait]
4363 impl ChatProvider for Streaming {
4364 async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
4365 unreachable!()
4366 }
4367 async fn chat_stream(
4368 &self,
4369 _: &[Message],
4370 _: &[ToolSpec],
4371 on_delta: eclipse_core::stream::DeltaFn<'_>,
4372 ) -> CoreResult<Message> {
4373 on_delta(eclipse_core::stream::Delta::Text("tok".into()));
4374 on_delta(eclipse_core::stream::Delta::Text("ens".into()));
4375 Ok(Message::assistant("tokens"))
4376 }
4377 }
4378
4379 struct Hangs {
4383 entered: Arc<std::sync::atomic::AtomicBool>,
4384 dropped: Arc<std::sync::atomic::AtomicBool>,
4385 }
4386
4387 struct MarkDropped(Arc<std::sync::atomic::AtomicBool>);
4388
4389 impl Drop for MarkDropped {
4390 fn drop(&mut self) {
4391 self.0.store(true, Ordering::SeqCst);
4392 }
4393 }
4394
4395 #[async_trait]
4396 impl ChatProvider for Hangs {
4397 async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
4398 unreachable!()
4399 }
4400 async fn chat_stream(
4401 &self,
4402 _: &[Message],
4403 _: &[ToolSpec],
4404 _: eclipse_core::stream::DeltaFn<'_>,
4405 ) -> CoreResult<Message> {
4406 self.entered.store(true, Ordering::SeqCst);
4407 let _dropped = MarkDropped(self.dropped.clone());
4408 tokio::time::sleep(Duration::from_secs(600)).await;
4409 Ok(Message::assistant("too late"))
4410 }
4411 }
4412
4413 fn hanging_state(
4415 dir: &std::path::Path,
4416 ) -> (
4417 Shared,
4418 Arc<std::sync::atomic::AtomicBool>,
4419 Arc<std::sync::atomic::AtomicBool>,
4420 ) {
4421 let store = SessionStore::new(dir.join("sessions"));
4422 let entered = Arc::new(std::sync::atomic::AtomicBool::new(false));
4423 let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false));
4424 let agent = Agent::new(
4425 Arc::new(Hangs {
4426 entered: entered.clone(),
4427 dropped: dropped.clone(),
4428 }),
4429 Arc::new(ToolRegistry::default()),
4430 store.clone(),
4431 "sys".into(),
4432 3,
4433 );
4434 let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
4435 (st, entered, dropped)
4436 }
4437
4438 async fn wait_for(flag: &Arc<std::sync::atomic::AtomicBool>, ms: u64) -> bool {
4440 for _ in 0..(ms / 20) {
4441 if flag.load(Ordering::SeqCst) {
4442 return true;
4443 }
4444 tokio::time::sleep(Duration::from_millis(20)).await;
4445 }
4446 flag.load(Ordering::SeqCst)
4447 }
4448
4449 fn cancel_req(run_id: &str) -> HttpRequest<Body> {
4450 HttpRequest::post(format!("/api/runs/{run_id}/cancel"))
4451 .header("host", "127.0.0.1:8787")
4452 .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
4453 .body(Body::empty())
4454 .unwrap()
4455 }
4456
4457 const TOKEN: &str = "0123456789abcdef0123456789abcdef";
4458 const LOGIN_ID: &str = "test-login-id";
4459
4460 fn authed(
4461 agent: Option<Arc<Agent>>,
4462 store: SessionStore,
4463 model: &str,
4464 config_error: Option<String>,
4465 ) -> AppState {
4466 AppState::new(
4467 agent,
4468 store,
4469 model.into(),
4470 config_error,
4471 TOKEN.into(),
4472 std::time::Duration::from_secs(
4473 eclipse_core::config::DEFAULT_SESSION_TTL_HOURS * 60 * 60,
4474 ),
4475 )
4476 .with_login(LOGIN_ID)
4477 }
4478
4479 fn state(dir: &std::path::Path, configured: bool) -> Shared {
4480 state_with(dir, configured, None)
4481 }
4482
4483 fn state_throttled(dir: &std::path::Path, throttle: LoginThrottle) -> Shared {
4485 match Arc::try_unwrap(state(dir, true)) {
4486 Ok(mut st) => {
4487 st.throttle = throttle;
4488 Arc::new(st)
4489 }
4490 Err(_) => panic!("a state built here is not shared yet"),
4491 }
4492 }
4493
4494 fn state_with(
4496 dir: &std::path::Path,
4497 configured: bool,
4498 config: Option<std::path::PathBuf>,
4499 ) -> Shared {
4500 let store = SessionStore::new(dir.join("sessions"));
4501 let agent = configured.then(|| {
4502 Arc::new(Agent::new(
4503 Arc::new(Canned),
4504 Arc::new(ToolRegistry::default()),
4505 store.clone(),
4506 "sys".into(),
4507 3,
4508 ))
4509 });
4510 Arc::new(
4511 authed(
4512 agent,
4513 store,
4514 "test-<model>",
4515 (!configured).then(|| "provider.base_url is not set".into()),
4516 )
4517 .with_config_path(config, None),
4518 )
4519 }
4520
4521 async fn body_text(r: Response) -> String {
4528 let bytes = axum::body::to_bytes(r.into_body(), 512 * 1024)
4529 .await
4530 .unwrap_or_default();
4531 String::from_utf8_lossy(&bytes).into_owned()
4532 }
4533
4534 fn state_watching(dir: &std::path::Path, check: eclipse_core::config::UpdateCheck) -> Shared {
4536 let store = SessionStore::new(dir.join("sessions"));
4537 let mut st = authed(None, store, "test-<model>", None);
4538 st.update = Some(eclipse_core::update::Watch::at(
4539 dir.join("state"),
4540 &eclipse_core::config::UpdateConfig {
4541 check,
4542 track: eclipse_core::config::Track::Release,
4543 remote: None,
4544 releases: Some("http://127.0.0.1:1/latest".into()),
4545 },
4546 ));
4547 Arc::new(st)
4548 }
4549
4550 #[tokio::test]
4553 async fn api_update_reports_the_cache_the_cli_would_show() {
4554 let dir = tempfile::tempdir().unwrap();
4555 let state = dir.path().join("state");
4556 std::fs::create_dir_all(&state).unwrap();
4557 std::fs::write(
4558 state.join("install.json"),
4559 r#"{"channel":"release","prefix":"/x","installed_at":"t","version":"0.2.0"}"#,
4560 )
4561 .unwrap();
4562 let now = eclipse_core::session::now_ms() / 1000;
4563 std::fs::write(
4564 state.join("update.json"),
4565 format!(r#"{{"checked_at":{now},"latest":"v0.3.0"}}"#),
4566 )
4567 .unwrap();
4568
4569 let app = router(state_watching(
4570 dir.path(),
4571 eclipse_core::config::UpdateCheck::Daily,
4572 ));
4573 let resp = app
4574 .clone()
4575 .oneshot(get_req("/api/update", "127.0.0.1:8787"))
4576 .await
4577 .unwrap();
4578 assert_eq!(resp.status(), StatusCode::OK);
4579 let body: serde_json::Value = serde_json::from_str(&text(resp).await).unwrap();
4580 assert_eq!(body["installed"], "0.2.0");
4581 assert_eq!(body["latest"], "v0.3.0");
4582 assert_eq!(body["behind"], true, "the same answer the CLI badges");
4583 assert_eq!(body["channel"], "release");
4584 assert_eq!(body["checked_at"], now);
4585
4586 let post = HttpRequest::post("/api/update")
4588 .header("host", "127.0.0.1:8787")
4589 .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
4590 .header("origin", "http://127.0.0.1:8787")
4591 .body(Body::empty())
4592 .unwrap();
4593 let resp = app.oneshot(post).await.unwrap();
4594 assert_eq!(
4595 resp.status(),
4596 StatusCode::METHOD_NOT_ALLOWED,
4597 "nothing writes this endpoint"
4598 );
4599 }
4600
4601 #[tokio::test]
4604 async fn api_update_shows_nothing_when_the_check_is_off() {
4605 let dir = tempfile::tempdir().unwrap();
4606 let state = dir.path().join("state");
4607 std::fs::create_dir_all(&state).unwrap();
4608 std::fs::write(
4609 state.join("install.json"),
4610 r#"{"channel":"release","prefix":"/x","installed_at":"t","version":"0.2.0"}"#,
4611 )
4612 .unwrap();
4613 let now = eclipse_core::session::now_ms() / 1000;
4614 std::fs::write(
4615 state.join("update.json"),
4616 format!(r#"{{"checked_at":{now},"latest":"v0.3.0"}}"#),
4617 )
4618 .unwrap();
4619
4620 let app = router(state_watching(
4621 dir.path(),
4622 eclipse_core::config::UpdateCheck::Off,
4623 ));
4624 let resp = app
4625 .oneshot(get_req("/api/update", "127.0.0.1:8787"))
4626 .await
4627 .unwrap();
4628 assert_eq!(resp.status(), StatusCode::OK);
4629 let body: serde_json::Value = serde_json::from_str(&text(resp).await).unwrap();
4630 assert_eq!(body["behind"], false, "the user said not to be told");
4631 assert_eq!(body["latest"], serde_json::Value::Null);
4632 }
4633
4634 #[tokio::test]
4639 async fn a_stored_session_carries_a_statement_beside_each_call() {
4640 let dir = tempfile::tempdir().unwrap();
4641 let st = state(dir.path(), true);
4642 let store = st.agent.as_ref().unwrap().store().clone();
4643 let id = store.new_id();
4644 let arguments = r#"{"path":"crates/x/src/session.rs","content":"abc"}"#;
4645 store.append(&id, &Message::user("write it")).unwrap();
4646 store
4647 .append(
4648 &id,
4649 &Message::assistant_tool_calls(
4650 None,
4651 vec![eclipse_core::message::ToolCall {
4652 id: "c1".into(),
4653 kind: "function".into(),
4654 function: eclipse_core::message::FunctionCall {
4655 name: "write_file".into(),
4656 arguments: arguments.into(),
4657 },
4658 }],
4659 ),
4660 )
4661 .unwrap();
4662 store
4663 .append(&id, &Message::tool_result("c1", "wrote it"))
4664 .unwrap();
4665 let app = router(st);
4666
4667 let r = app
4668 .clone()
4669 .oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
4670 .await
4671 .unwrap();
4672 assert_eq!(r.status(), StatusCode::OK);
4673 let body: Vec<serde_json::Value> = serde_json::from_str(&text(r).await).unwrap();
4674 assert_eq!(body.len(), 3, "the whole transcript, oldest first");
4675 assert!(
4676 body[0].get("calls").is_none(),
4677 "a message with no calls grows no array"
4678 );
4679 assert_eq!(
4680 body[1]["calls"][0]["summary"], "write_file crates/x/src/session.rs · 3 B",
4681 "the statement the page puts on the row"
4682 );
4683 assert_eq!(
4684 body[1]["calls"][0]["state"], "ok",
4685 "and the verdict, so the row's mark is right on replay and not only live"
4686 );
4687 assert_eq!(
4688 body[1]["tool_calls"][0]["function"]["arguments"], arguments,
4689 "and the arguments are exactly what the store holds, for the toggle"
4690 );
4691 assert_eq!(body[2]["content"], "wrote it", "a result is unaffected");
4692 }
4693
4694 #[tokio::test]
4698 async fn a_replayed_session_marks_each_call_the_way_it_ended() {
4699 let dir = tempfile::tempdir().unwrap();
4700 let st = state(dir.path(), true);
4701 let store = st.agent.as_ref().unwrap().store().clone();
4702 let id = store.new_id();
4703 let call = |id: &str| eclipse_core::message::ToolCall {
4704 id: id.into(),
4705 kind: "function".into(),
4706 function: eclipse_core::message::FunctionCall {
4707 name: "shell".into(),
4708 arguments: r#"{"command":"date"}"#.into(),
4709 },
4710 };
4711 store.append(&id, &Message::user("three of them")).unwrap();
4712 store
4713 .append(
4714 &id,
4715 &Message::assistant_tool_calls(None, vec![call("a"), call("b"), call("c")]),
4716 )
4717 .unwrap();
4718 store
4719 .append(
4720 &id,
4721 &Message::tool_result("a", "exit code: 0\nstdout:\nMon Nov 30\n"),
4722 )
4723 .unwrap();
4724 store
4725 .append(
4726 &id,
4727 &Message::tool_result("b", "exit code: 2\nstdout:\n\nstderr:\nno\n"),
4728 )
4729 .unwrap();
4730 store
4731 .append(
4732 &id,
4733 &Message::tool_result("c", "the user declined to run `shell`: that is a delete"),
4734 )
4735 .unwrap();
4736 let app = router(st);
4737
4738 let r = app
4739 .clone()
4740 .oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
4741 .await
4742 .unwrap();
4743 let body: Vec<serde_json::Value> = serde_json::from_str(&text(r).await).unwrap();
4744 let states: Vec<&str> = body[1]["calls"]
4745 .as_array()
4746 .unwrap()
4747 .iter()
4748 .map(|c| c["state"].as_str().unwrap())
4749 .collect();
4750 assert_eq!(
4751 states,
4752 ["ok", "failed", "refused"],
4753 "the exit code and the refusal are read off the text, one mark each"
4754 );
4755 assert_eq!(
4756 body[1]["calls"][2]["summary"], "shell date",
4757 "and every row still has its statement"
4758 );
4759 }
4760
4761 #[tokio::test]
4766 async fn a_replayed_failure_with_no_exit_code_is_marked_failed() {
4767 let dir = tempfile::tempdir().unwrap();
4768 let st = state(dir.path(), true);
4769 let store = st.agent.as_ref().unwrap().store().clone();
4770 let id = store.new_id();
4771 let call = |call_id: &str| eclipse_core::message::ToolCall {
4772 id: call_id.into(),
4773 kind: "function".into(),
4774 function: eclipse_core::message::FunctionCall {
4775 name: "read_file".into(),
4776 arguments: r#"{"path":"gone.txt"}"#.into(),
4777 },
4778 };
4779 store.append(&id, &Message::user("read two files")).unwrap();
4780 store
4781 .append(
4782 &id,
4783 &Message::assistant_tool_calls(None, vec![call("a"), call("b")]),
4784 )
4785 .unwrap();
4786 store
4788 .append(&id, &Message::tool_result("a", "no such file: gone.txt"))
4789 .unwrap();
4790 store.set_tool_outcome(&id, "a", true).unwrap();
4791 store
4792 .append(&id, &Message::tool_result("b", "no such file: gone.txt"))
4793 .unwrap();
4794 let app = router(st);
4795
4796 let r = app
4797 .oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
4798 .await
4799 .unwrap();
4800 let body: Vec<serde_json::Value> = serde_json::from_str(&text(r).await).unwrap();
4801 let states: Vec<&str> = body[1]["calls"]
4802 .as_array()
4803 .unwrap()
4804 .iter()
4805 .map(|c| c["state"].as_str().unwrap())
4806 .collect();
4807 assert_eq!(
4808 states,
4809 ["failed", "ok"],
4810 "the record decides when there is one; without it the text still guesses"
4811 );
4812 }
4813
4814 #[tokio::test]
4817 async fn a_call_with_no_result_is_still_running() {
4818 let dir = tempfile::tempdir().unwrap();
4819 let st = state(dir.path(), true);
4820 let store = st.agent.as_ref().unwrap().store().clone();
4821 let id = store.new_id();
4822 store
4823 .append(
4824 &id,
4825 &Message::assistant_tool_calls(
4826 None,
4827 vec![eclipse_core::message::ToolCall {
4828 id: "c1".into(),
4829 kind: "function".into(),
4830 function: eclipse_core::message::FunctionCall {
4831 name: "shell".into(),
4832 arguments: r#"{"command":"sleep 900"}"#.into(),
4833 },
4834 }],
4835 ),
4836 )
4837 .unwrap();
4838 let app = router(st);
4839
4840 let r = app
4841 .clone()
4842 .oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
4843 .await
4844 .unwrap();
4845 let body: Vec<serde_json::Value> = serde_json::from_str(&text(r).await).unwrap();
4846 assert_eq!(body[0]["calls"][0]["state"], "running");
4847 }
4848
4849 #[test]
4850 fn the_refusal_names_which_check_failed_and_what_arrived() {
4851 let logins = Logins::new(Duration::from_secs(60));
4852 let post = Method::POST;
4853 let at = |h: Option<&str>, o: Option<&str>| {
4854 arrival_refusal(&logins, &post, "/api/chat", h, o, None, None)
4855 };
4856
4857 let no_host = at(None, None).expect("refused");
4858 assert!(no_host.contains("no Host header"), "{no_host}");
4859 let foreign = at(Some("dash.example.com"), None).expect("refused");
4860 assert!(foreign.contains("dash.example.com"), "{foreign}");
4861 let cross_site =
4862 at(Some("127.0.0.1:8787"), Some("http://127.0.0.1:9999")).expect("refused");
4863 assert!(
4864 cross_site.contains("Origin") && cross_site.contains("9999"),
4865 "{cross_site}"
4866 );
4867
4868 let anonymous = at(Some("127.0.0.1:8787"), Some("null")).expect("refused");
4871 assert!(anonymous.contains("Origin \"null\""), "{anonymous}");
4872 assert!(
4873 anonymous.contains(CSRF_HEADER),
4874 "and names the token that would have let it through: {anonymous}"
4875 );
4876
4877 assert!(at(Some("localhost:8787"), None).is_none());
4880 assert!(at(Some("127.0.0.1:8787"), Some("http://127.0.0.1:8787")).is_none());
4881 assert!(at(Some("127.0.0.1:8787"), Some("https://127.0.0.1:8787")).is_none());
4882 assert!(at(Some("localhost.:8787"), Some("http://localhost.:8787")).is_none());
4883 }
4884
4885 #[test]
4886 fn reading_is_never_refused_and_signing_in_survives_a_null_origin() {
4887 let logins = Logins::new(Duration::from_secs(60));
4888 let at = |m: Method, path: &str, o: Option<&str>| {
4889 arrival_refusal(&logins, &m, path, Some("127.0.0.1:8787"), o, None, None)
4890 };
4891 assert!(at(Method::GET, "/api/sessions", Some("https://evil.example")).is_none());
4894 assert!(at(Method::POST, "/login", Some("null")).is_none());
4897 assert!(at(Method::POST, "/login", Some("https://evil.example")).is_some());
4899 }
4900
4901 #[test]
4902 fn the_csrf_token_is_what_lets_an_anonymous_origin_change_something() {
4903 let logins = Logins::new(Duration::from_secs(60));
4904 let (id, csrf) = logins.create().expect("session");
4905 let at = |o: &str, presented: Option<&str>, session: &str| {
4906 arrival_refusal(
4907 &logins,
4908 &Method::POST,
4909 "/api/chat",
4910 Some("127.0.0.1:8787"),
4911 Some(o),
4912 presented,
4913 Some(session),
4914 )
4915 };
4916 assert!(
4917 at("null", Some(&csrf), &id).is_none(),
4918 "the session token is the second lock"
4919 );
4920 assert!(at("https://evil.example", Some(&csrf), &id).is_none());
4921 assert!(at("null", None, &id).is_some(), "no token, no entry");
4922 assert!(at("null", Some("not-the-token"), &id).is_some());
4923 assert!(at("null", Some(&csrf), "some-other-session").is_some());
4924
4925 let (other, other_csrf) = logins.create().expect("session");
4927 assert_ne!(other, id);
4928 assert!(at("null", Some(&other_csrf), &id).is_some());
4929 }
4930
4931 async fn sign_in(app: &axum::Router) -> (String, String) {
4933 let r = app
4934 .clone()
4935 .oneshot(
4936 HttpRequest::post("/login")
4937 .header("host", "127.0.0.1:8787")
4938 .header("content-type", "application/x-www-form-urlencoded")
4939 .body(Body::from(format!("token={TOKEN}")))
4940 .unwrap(),
4941 )
4942 .await
4943 .unwrap();
4944 assert_eq!(r.status(), StatusCode::SEE_OTHER, "signed in");
4945 let cookie = r
4946 .headers()
4947 .get(header::SET_COOKIE)
4948 .and_then(|v| v.to_str().ok())
4949 .expect("a session cookie")
4950 .to_string();
4951 let jar = cookie.split(';').next().unwrap().to_string();
4952 let page = body_text(
4953 app.clone()
4954 .oneshot(
4955 HttpRequest::get("/")
4956 .header("host", "127.0.0.1:8787")
4957 .header("cookie", &jar)
4958 .body(Body::empty())
4959 .unwrap(),
4960 )
4961 .await
4962 .unwrap(),
4963 )
4964 .await;
4965 let csrf = csrf_of(&page);
4966 (jar, csrf)
4967 }
4968
4969 #[tokio::test]
4970 async fn the_settings_endpoints_read_the_file_write_it_and_never_show_a_secret() {
4971 let dir = tempfile::tempdir().unwrap();
4972 let config_path = dir.path().join("config.toml");
4973 std::fs::write(
4974 &config_path,
4975 "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"seed\"\n",
4976 )
4977 .unwrap();
4978 let app = router(state_with(dir.path(), true, Some(config_path.clone())));
4979 let (jar, csrf) = sign_in(&app).await;
4980
4981 let body = body_text(
4983 app.clone()
4984 .oneshot(
4985 HttpRequest::get("/api/settings")
4986 .header("host", "127.0.0.1:8787")
4987 .header("cookie", &jar)
4988 .body(Body::empty())
4989 .unwrap(),
4990 )
4991 .await
4992 .unwrap(),
4993 )
4994 .await;
4995 let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
4996 let keys: Vec<&str> = parsed["settings"]
4997 .as_array()
4998 .expect("a settings array")
4999 .iter()
5000 .filter_map(|s| s["key"].as_str())
5001 .collect();
5002 assert!(keys.contains(&"provider.model"), "{keys:?}");
5003
5004 let written = body_text(
5006 app.clone()
5007 .oneshot(
5008 HttpRequest::post("/api/settings")
5009 .header("host", "127.0.0.1:8787")
5010 .header("cookie", &jar)
5011 .header("x-eclipse-csrf", &csrf)
5012 .header("content-type", "application/json")
5013 .body(Body::from(
5014 r#"{"key":"provider.model","value":"qwen3-coder"}"#,
5015 ))
5016 .unwrap(),
5017 )
5018 .await
5019 .unwrap(),
5020 )
5021 .await;
5022 let parsed: serde_json::Value = serde_json::from_str(&written).expect("json");
5023 assert_eq!(parsed["key"], "provider.model");
5024 assert_eq!(parsed["value"], "\"qwen3-coder\"");
5025 assert_eq!(parsed["is_default"], false);
5026 let on_disk = std::fs::read_to_string(&config_path).unwrap();
5028 assert!(on_disk.contains("qwen3-coder"), "{on_disk}");
5029 }
5030
5031 #[tokio::test]
5038 async fn a_settings_write_under_a_profile_lands_in_that_profiles_overlay() {
5039 let dir = tempfile::tempdir().unwrap();
5040 let root = dir.path().join("home/.eclipse");
5041 std::fs::create_dir_all(&root).unwrap();
5042 let base = root.join("config.toml");
5043 let before = "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"seed\"\n";
5044 std::fs::write(&base, before).unwrap();
5045 let overlay = root.join("profiles/work/config.toml");
5046
5047 let st = match Arc::try_unwrap(state(dir.path(), true)) {
5048 Ok(st) => st,
5049 Err(_) => panic!("a state built here is not shared yet"),
5050 }
5051 .with_config_path(Some(base.clone()), Some("work".into()))
5052 .with_config_targets(false, Some(root.clone()));
5053 let app = router(Arc::new(st));
5054 let (jar, csrf) = sign_in(&app).await;
5055
5056 let written = body_text(
5057 app.clone()
5058 .oneshot(
5059 HttpRequest::post("/api/settings")
5060 .header("host", "127.0.0.1:8787")
5061 .header("cookie", &jar)
5062 .header("x-eclipse-csrf", &csrf)
5063 .header("content-type", "application/json")
5064 .body(Body::from(
5065 r#"{"key":"provider.model","value":"work-model"}"#,
5066 ))
5067 .unwrap(),
5068 )
5069 .await
5070 .unwrap(),
5071 )
5072 .await;
5073 assert_eq!(
5074 serde_json::from_str::<serde_json::Value>(&written).expect("json")["key"],
5075 "provider.model",
5076 "the write answered for the key it was given: {written}"
5077 );
5078
5079 let overlay_text = std::fs::read_to_string(&overlay).expect("the overlay was written");
5081 assert!(overlay_text.contains("work-model"), "{overlay_text}");
5082 assert_eq!(
5083 std::fs::read_to_string(&base).unwrap(),
5084 before,
5085 "the shared base file was not touched"
5086 );
5087 let home = root.parent().unwrap().display().to_string();
5091 let env = |key: &str| match key {
5092 "HOME" => Some(home.clone()),
5093 _ => None,
5094 };
5095 let loaded =
5096 eclipse_core::config::Config::load_with_profile(Some(&base), Some("work"), &env)
5097 .expect("the profile loads");
5098 assert_eq!(loaded.provider.model, "work-model");
5099
5100 let listing = body_text(
5102 app.clone()
5103 .oneshot(
5104 HttpRequest::get("/api/mcp")
5105 .header("host", "127.0.0.1:8787")
5106 .header("cookie", &jar)
5107 .body(Body::empty())
5108 .unwrap(),
5109 )
5110 .await
5111 .unwrap(),
5112 )
5113 .await;
5114 let parsed: serde_json::Value = serde_json::from_str(&listing).expect("json");
5115 assert_eq!(parsed["config_path"], overlay.display().to_string());
5116 }
5117
5118 #[tokio::test]
5121 async fn a_settings_write_with_no_profile_still_lands_in_the_file_it_was_started_with() {
5122 let dir = tempfile::tempdir().unwrap();
5123 let root = dir.path().join("home/.eclipse");
5124 std::fs::create_dir_all(&root).unwrap();
5125 let base = root.join("config.toml");
5126 std::fs::write(
5127 &base,
5128 "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"seed\"\n",
5129 )
5130 .unwrap();
5131
5132 let st = match Arc::try_unwrap(state(dir.path(), true)) {
5133 Ok(st) => st,
5134 Err(_) => panic!("a state built here is not shared yet"),
5135 }
5136 .with_config_path(Some(base.clone()), None)
5137 .with_config_targets(false, Some(root.clone()));
5138 let st = Arc::new(st);
5139 let _app = router(st.clone());
5140
5141 let written = apply_setting(&st, "provider.model", Some("base-model")).await;
5142 assert!(written.is_ok(), "{written:?}");
5143 let on_disk = std::fs::read_to_string(&base).unwrap();
5144 assert!(on_disk.contains("base-model"), "{on_disk}");
5145 assert!(
5146 !root.join("profiles").exists(),
5147 "nothing was created for a profile nobody serves"
5148 );
5149 }
5150
5151 #[tokio::test]
5156 async fn a_settings_write_waits_for_the_one_already_in_flight() {
5157 let dir = tempfile::tempdir().unwrap();
5158 let config_path = dir.path().join("config.toml");
5159 std::fs::write(
5160 &config_path,
5161 "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"seed\"\n",
5162 )
5163 .unwrap();
5164 let st = state_with(dir.path(), true, Some(config_path.clone()));
5165
5166 let writes = st.config_writes.clone();
5167 let holder = tokio::task::spawn_blocking(move || {
5168 let guard = writes
5169 .lock()
5170 .unwrap_or_else(|poisoned| poisoned.into_inner());
5171 std::thread::sleep(std::time::Duration::from_millis(1000));
5172 drop(guard);
5173 });
5174 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
5176
5177 let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
5178 let finished = done.clone();
5179 let writer = tokio::spawn(async move {
5180 let written = apply_setting(&st, "provider.model", Some("waited")).await;
5181 finished.store(true, std::sync::atomic::Ordering::SeqCst);
5182 written
5183 });
5184 tokio::time::sleep(std::time::Duration::from_millis(300)).await;
5187 assert!(
5188 !done.load(std::sync::atomic::Ordering::SeqCst),
5189 "the second write finished while the first one held the file"
5190 );
5191 holder.await.unwrap();
5192 let written = writer.await.unwrap();
5193 assert!(written.is_ok(), "the write failed: {written:?}");
5194 let on_disk = std::fs::read_to_string(&config_path).unwrap();
5195 assert!(on_disk.contains("waited"), "{on_disk}");
5196 }
5197
5198 #[tokio::test]
5199 async fn a_key_nothing_reads_is_refused_rather_than_written() {
5200 let dir = tempfile::tempdir().unwrap();
5201 let path = dir.path().join("config.toml");
5202 std::fs::write(&path, "[provider]\nmodel = \"seed\"\n").unwrap();
5203 let app = router(state_with(dir.path(), true, Some(path.clone())));
5204 let (jar, csrf) = sign_in(&app).await;
5205 let r = app
5206 .clone()
5207 .oneshot(
5208 HttpRequest::post("/api/settings")
5209 .header("host", "127.0.0.1:8787")
5210 .header("cookie", &jar)
5211 .header("x-eclipse-csrf", &csrf)
5212 .header("content-type", "application/json")
5213 .body(Body::from(r#"{"key":"nope.nope","value":"1"}"#))
5214 .unwrap(),
5215 )
5216 .await
5217 .unwrap();
5218 assert_eq!(r.status(), StatusCode::BAD_REQUEST);
5219 let on_disk = std::fs::read_to_string(&path).unwrap();
5220 assert!(!on_disk.contains("nope"), "{on_disk}");
5221 }
5222
5223 #[tokio::test]
5224 async fn a_secret_setting_is_listed_without_its_value() {
5225 let dir = tempfile::tempdir().unwrap();
5226 let path = dir.path().join("config.toml");
5227 std::fs::write(
5228 &path,
5229 "[provider]\napi_key = \"sk-live-0123456789abcdef\"\n",
5230 )
5231 .unwrap();
5232 let app = router(state_with(dir.path(), true, Some(path)));
5233 let (jar, _csrf) = sign_in(&app).await;
5234 let page = body_text(
5235 app.clone()
5236 .oneshot(
5237 HttpRequest::get("/api/settings")
5238 .header("host", "127.0.0.1:8787")
5239 .header("cookie", &jar)
5240 .body(Body::empty())
5241 .unwrap(),
5242 )
5243 .await
5244 .unwrap(),
5245 )
5246 .await;
5247 assert!(!page.contains("sk-live"), "the key leaked: {page}");
5248 assert!(page.contains("\"secret\":true"), "{page}");
5249 assert!(page.contains("\"set\":true"), "{page}");
5250 }
5251 #[tokio::test]
5255 async fn a_setting_row_carries_its_type_its_words_and_its_choices() {
5256 let dir = tempfile::tempdir().unwrap();
5257 let path = dir.path().join("config.toml");
5258 std::fs::write(&path, "[provider]\nmodel = \"seed\"\n").unwrap();
5259 let app = router(state_with(dir.path(), true, Some(path)));
5260 let (jar, _csrf) = sign_in(&app).await;
5261 let body = body_text(
5262 app.oneshot(
5263 HttpRequest::get("/api/settings")
5264 .header("host", "127.0.0.1:8787")
5265 .header("cookie", &jar)
5266 .body(Body::empty())
5267 .unwrap(),
5268 )
5269 .await
5270 .unwrap(),
5271 )
5272 .await;
5273 let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
5274 let rows = parsed["settings"].as_array().expect("an array");
5275 let row = |key: &str| {
5276 rows.iter()
5277 .find(|r| r["key"] == json!(key))
5278 .unwrap_or_else(|| panic!("{key} is in the catalogue"))
5279 };
5280
5281 assert_eq!(row("agent.trace_content")["kind"], json!("bool"));
5283 assert_eq!(row("provider.temperature")["kind"], json!("float"));
5284 assert_eq!(row("provider.model")["kind"], json!("str"));
5285 assert_eq!(row("tools.deferred")["kind"], json!("list"));
5286
5287 assert_eq!(
5289 row("cli.approval")["choices"],
5290 json!(["ask", "auto", "smart"])
5291 );
5292 assert_eq!(
5293 row("tools.shell")["choices"],
5294 json!(["deny", "ask", "allow"])
5295 );
5296 assert_eq!(
5297 row("update.check")["choices"],
5298 json!(["daily", "weekly", "off"])
5299 );
5300 assert_eq!(row("provider.model")["choices"], json!([]));
5301
5302 for r in rows {
5304 let about = r["about"].as_str().unwrap_or("");
5305 assert!(
5306 !about.trim().is_empty(),
5307 "{} has no description: {}",
5308 r["key"],
5309 r
5310 );
5311 }
5312 }
5313
5314 #[tokio::test]
5318 async fn a_null_value_puts_a_key_back_to_its_default_and_a_missing_one_is_refused() {
5319 let dir = tempfile::tempdir().unwrap();
5320 let path = dir.path().join("config.toml");
5321 std::fs::write(&path, "[agent]\nmax_iterations = 3\n").unwrap();
5322 let app = router(state_with(dir.path(), true, Some(path.clone())));
5323 let (jar, csrf) = sign_in(&app).await;
5324
5325 let write = |body: &'static str| {
5326 let app = app.clone();
5327 let jar = jar.clone();
5328 let csrf = csrf.clone();
5329 async move {
5330 app.oneshot(
5331 HttpRequest::post("/api/settings")
5332 .header("host", "127.0.0.1:8787")
5333 .header("cookie", &jar)
5334 .header("x-eclipse-csrf", &csrf)
5335 .header("content-type", "application/json")
5336 .body(Body::from(body))
5337 .unwrap(),
5338 )
5339 .await
5340 .unwrap()
5341 }
5342 };
5343
5344 let r = write(r#"{"key":"agent.max_iterations","value":"42"}"#).await;
5346 assert_eq!(r.status(), StatusCode::OK);
5347 assert!(std::fs::read_to_string(&path).unwrap().contains("42"));
5348
5349 let r = write(r#"{"key":"agent.max_iterations","value":null}"#).await;
5351 assert_eq!(r.status(), StatusCode::OK);
5352 let said = body_text(r).await;
5353 let row: serde_json::Value = serde_json::from_str(&said).expect("json");
5354 assert_eq!(row["is_default"], json!(true), "{row}");
5358 assert_eq!(row["value"], json!("\"unlimited\""), "{row}");
5359 let on_disk = std::fs::read_to_string(&path).unwrap();
5360 assert!(
5361 !on_disk
5362 .lines()
5363 .any(|l| l.trim_start().starts_with("max_iterations")),
5364 "the line is gone or commented: {on_disk}"
5365 );
5366
5367 let r = write(r#"{"key":"agent.max_iterations"}"#).await;
5369 assert_eq!(r.status(), StatusCode::BAD_REQUEST);
5370 }
5371
5372 #[tokio::test]
5376 async fn a_boolean_is_written_as_a_boolean() {
5377 let dir = tempfile::tempdir().unwrap();
5378 let path = dir.path().join("config.toml");
5379 std::fs::write(&path, "[agent]\nmax_iterations = 3\n").unwrap();
5380 let app = router(state_with(dir.path(), true, Some(path.clone())));
5381 let (jar, csrf) = sign_in(&app).await;
5382 let r = app
5383 .clone()
5384 .oneshot(
5385 HttpRequest::post("/api/settings")
5386 .header("host", "127.0.0.1:8787")
5387 .header("cookie", &jar)
5388 .header("x-eclipse-csrf", &csrf)
5389 .header("content-type", "application/json")
5390 .body(Body::from(
5391 r#"{"key":"agent.trace_content","value":"true"}"#,
5392 ))
5393 .unwrap(),
5394 )
5395 .await
5396 .unwrap();
5397 assert_eq!(r.status(), StatusCode::OK);
5398 let on_disk = std::fs::read_to_string(&path).unwrap();
5399 assert!(
5400 on_disk.contains("trace_content = true"),
5401 "a boolean, not a string: {on_disk}"
5402 );
5403 }
5404
5405 fn context_fixture(dir: &std::path::Path) -> std::path::PathBuf {
5415 let workspace = dir.join("work");
5416 std::fs::create_dir_all(&workspace).unwrap();
5417 std::fs::write(workspace.join("AGENT.md"), "RULE: in the tree\n").unwrap();
5418 let memory = dir.join("memory");
5419 std::fs::create_dir_all(&memory).unwrap();
5420 std::fs::write(memory.join("USER.md"), "USER FACT: one line").unwrap();
5421 let path = dir.join(".eclipse/config.toml");
5422 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
5423 std::fs::write(
5424 &path,
5425 format!(
5426 "[provider]\nmodel = \"m\"\n[tools]\nworkspace_root = \"{ws}\"\n\
5427 [user]\nfile = \"{user}\"\nmemory_file = \"{mem}\"\n",
5428 ws = workspace.display(),
5429 user = memory.join("USER.md").display(),
5430 mem = memory.join("MEMORY.md").display(),
5431 ),
5432 )
5433 .unwrap();
5434 path
5435 }
5436
5437 #[tokio::test]
5438 async fn the_context_list_resolves_three_files_from_the_config_not_the_request() {
5439 let dir = tempfile::tempdir().unwrap();
5440 let workspace = dir.path().join("work");
5441 let memory = dir.path().join("memory");
5442 let path = context_fixture(dir.path());
5443
5444 let app = router(state_with(dir.path(), true, Some(path)));
5445 let (jar, _csrf) = sign_in(&app).await;
5446 let body = body_text(
5447 app.oneshot(
5448 HttpRequest::get("/api/context")
5449 .header("host", "127.0.0.1:8787")
5450 .header("cookie", &jar)
5451 .body(Body::empty())
5452 .unwrap(),
5453 )
5454 .await
5455 .unwrap(),
5456 )
5457 .await;
5458 let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
5459 let files = parsed["files"].as_array().expect("an array");
5460 assert_eq!(
5461 files
5462 .iter()
5463 .map(|f| f["name"].as_str().unwrap())
5464 .collect::<Vec<_>>(),
5465 vec!["agent", "user", "memory"]
5466 );
5467 let user = &files[1];
5468 assert_eq!(user["file"], json!("USER.md"));
5469 assert_eq!(user["exists"], json!(true));
5470 assert_eq!(user["chars"], json!(19));
5471 assert_eq!(user["text"], json!("USER FACT: one line"));
5472 assert_eq!(user["kind"], json!("prose"));
5473 assert!(
5474 user["path"].as_str().unwrap().ends_with("memory/USER.md"),
5475 "{user}"
5476 );
5477 assert_eq!(files[0]["exists"], json!(true));
5479 assert!(
5480 files[0]["path"]
5481 .as_str()
5482 .unwrap()
5483 .ends_with("work/AGENT.md"),
5484 "{}",
5485 files[0]["path"]
5486 );
5487 assert!(files[0]["others"].as_u64().is_some(), "{}", files[0]);
5490 assert_eq!(files[2]["own_budget"], json!(3000));
5492 assert_eq!(user["own_budget"], serde_json::Value::Null);
5493 assert_eq!(files[2]["exists"], json!(false));
5495 assert!(
5496 files[2]["path"]
5497 .as_str()
5498 .unwrap()
5499 .ends_with("memory/MEMORY.md"),
5500 "{}",
5501 files[2]["path"]
5502 );
5503 for f in files {
5505 let shown = f["path"].as_str().unwrap();
5506 assert!(!shown.contains("/home/mmhorda/.eclipse"), "{shown}");
5507 }
5508 let _ = (&workspace, &memory);
5509 }
5510
5511 #[tokio::test]
5514 async fn a_context_write_may_not_name_a_path_and_lands_where_the_file_belongs() {
5515 let dir = tempfile::tempdir().unwrap();
5516 let memory = dir.path().join("memory");
5517 let path = context_fixture(dir.path());
5518
5519 let app = router(state_with(dir.path(), true, Some(path)));
5520 let (jar, csrf) = sign_in(&app).await;
5521 let write = |body: &'static str| {
5522 let app = app.clone();
5523 let jar = jar.clone();
5524 let csrf = csrf.clone();
5525 async move {
5526 app.oneshot(
5527 HttpRequest::post("/api/context")
5528 .header("host", "127.0.0.1:8787")
5529 .header("cookie", &jar)
5530 .header("x-eclipse-csrf", &csrf)
5531 .header("content-type", "application/json")
5532 .body(Body::from(body))
5533 .unwrap(),
5534 )
5535 .await
5536 .unwrap()
5537 }
5538 };
5539
5540 for bad in [
5541 r#"{"name":"../../../etc/passwd","text":"x"}"#,
5542 r#"{"name":"/etc/passwd","text":"x"}"#,
5543 r#"{"name":"AGENT.md","text":"x"}"#,
5544 r#"{"name":"skill","text":"x"}"#,
5545 ] {
5546 let r = write(Box::leak(bad.to_string().into_boxed_str())).await;
5547 assert_eq!(r.status(), StatusCode::BAD_REQUEST, "{bad}");
5548 let said = body_text(r).await;
5549 assert!(
5550 said.contains("agent"),
5551 "the refusal names the legal ones: {said}"
5552 );
5553 }
5554 assert!(!dir.path().join("etc/passwd").exists());
5555
5556 let r = write(r#"{"name":"user","text":"USER FACT: written from the page"}"#).await;
5558 assert_eq!(r.status(), StatusCode::OK);
5559 let said: serde_json::Value = serde_json::from_str(&body_text(r).await).expect("json");
5560 assert_eq!(said["file"]["name"], json!("user"));
5561 assert_eq!(
5562 said["file"]["text"],
5563 json!("USER FACT: written from the page")
5564 );
5565 assert_eq!(said["applies"], json!("the next run uses it"));
5566 assert_eq!(
5567 std::fs::read_to_string(memory.join("USER.md")).unwrap(),
5568 "USER FACT: written from the page"
5569 );
5570
5571 let r = write(r#"{"name":"memory","text":"one\n§\ntwo"}"#).await;
5573 assert_eq!(r.status(), StatusCode::OK);
5574 let mem = eclipse_core::memory::Memory::new(memory.join("MEMORY.md"), 3000);
5575 assert_eq!(mem.read().unwrap(), vec!["one", "two"]);
5576 }
5577
5578 #[tokio::test]
5582 async fn two_cookie_headers_are_read_the_same_way_by_the_guard_and_the_login_check() {
5583 let dir = tempfile::tempdir().unwrap();
5584 let app = router(state(dir.path(), true));
5585
5586 let r = app.clone().oneshot(login_req(TOKEN)).await.unwrap();
5587 assert_eq!(r.status(), StatusCode::SEE_OTHER);
5588 let jar = r
5589 .headers()
5590 .get(header::SET_COOKIE)
5591 .and_then(|v| v.to_str().ok())
5592 .expect("a session cookie")
5593 .split(';')
5594 .next()
5595 .unwrap()
5596 .to_string();
5597 let page = body_text(
5598 app.clone()
5599 .oneshot(
5600 HttpRequest::get("/")
5601 .header("host", "127.0.0.1:8787")
5602 .header("cookie", &jar)
5603 .body(Body::empty())
5604 .unwrap(),
5605 )
5606 .await
5607 .unwrap(),
5608 )
5609 .await;
5610 let csrf = csrf_of(&page);
5611
5612 let r = app
5615 .clone()
5616 .oneshot(
5617 HttpRequest::post("/api/chat")
5618 .header("host", "127.0.0.1:8787")
5619 .header("origin", "null")
5620 .header("cookie", "theme=dark")
5621 .header("cookie", &jar)
5622 .header(CSRF_HEADER, &csrf)
5623 .header("content-type", "application/json")
5624 .body(Body::from(json!({ "message": "hi" }).to_string()))
5625 .unwrap(),
5626 )
5627 .await
5628 .unwrap();
5629 assert_ne!(
5630 r.status(),
5631 StatusCode::FORBIDDEN,
5632 "the second Cookie header carries the session; the guard must see it"
5633 );
5634 }
5635
5636 #[tokio::test]
5637 async fn a_browser_that_reports_no_origin_can_sign_in_and_then_act() {
5638 let dir = tempfile::tempdir().unwrap();
5639 let app = router(state(dir.path(), true));
5640
5641 let r = app
5643 .clone()
5644 .oneshot(
5645 HttpRequest::post("/login")
5646 .header("host", "127.0.0.1:8787")
5647 .header("origin", "null")
5648 .header("content-type", "application/x-www-form-urlencoded")
5649 .body(Body::from(format!("token={TOKEN}")))
5650 .unwrap(),
5651 )
5652 .await
5653 .unwrap();
5654 assert_eq!(
5655 r.status(),
5656 StatusCode::SEE_OTHER,
5657 "not refused at the guard"
5658 );
5659 let cookie = r
5660 .headers()
5661 .get(header::SET_COOKIE)
5662 .and_then(|v| v.to_str().ok())
5663 .expect("a session cookie")
5664 .to_string();
5665
5666 let jar = cookie.split(';').next().unwrap().to_string();
5669 let page = body_text(
5670 app.clone()
5671 .oneshot(
5672 HttpRequest::get("/")
5673 .header("host", "127.0.0.1:8787")
5674 .header("cookie", &jar)
5675 .body(Body::empty())
5676 .unwrap(),
5677 )
5678 .await
5679 .unwrap(),
5680 )
5681 .await;
5682 let csrf = csrf_of(&page);
5683 assert_eq!(csrf.len(), 64, "a real token, not an empty meta tag");
5684
5685 let r = app
5686 .clone()
5687 .oneshot(
5688 HttpRequest::post("/api/chat")
5689 .header("host", "127.0.0.1:8787")
5690 .header("origin", "null")
5691 .header("cookie", &jar)
5692 .header(CSRF_HEADER, &csrf)
5693 .header("content-type", "application/json")
5694 .body(Body::from(json!({ "message": "hi" }).to_string()))
5695 .unwrap(),
5696 )
5697 .await
5698 .unwrap();
5699 assert_ne!(r.status(), StatusCode::FORBIDDEN, "the token opened it");
5700
5701 let r = app
5704 .clone()
5705 .oneshot(
5706 HttpRequest::post("/api/chat")
5707 .header("host", "127.0.0.1:8787")
5708 .header("origin", "null")
5709 .header("cookie", &jar)
5710 .header(CSRF_HEADER, TEST_CSRF)
5711 .header("content-type", "application/json")
5712 .body(Body::from(json!({ "message": "hi" }).to_string()))
5713 .unwrap(),
5714 )
5715 .await
5716 .unwrap();
5717 assert_eq!(
5718 r.status(),
5719 StatusCode::FORBIDDEN,
5720 "a foreign token is no token"
5721 );
5722
5723 let r = app
5725 .clone()
5726 .oneshot(
5727 HttpRequest::post("/api/model")
5728 .header("host", "127.0.0.1:8787")
5729 .header("origin", "null")
5730 .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
5731 .header("content-type", "application/json")
5732 .body(Body::from(json!({ "model": "picked" }).to_string()))
5733 .unwrap(),
5734 )
5735 .await
5736 .unwrap();
5737 assert_eq!(r.status(), StatusCode::FORBIDDEN);
5738 let said = body_text(r).await;
5739 assert!(said.contains(CSRF_HEADER), "{said}");
5740 }
5741
5742 #[tokio::test]
5743 async fn the_page_hands_the_token_to_every_request_it_makes() {
5744 let dir = tempfile::tempdir().unwrap();
5745 let app = router(state(dir.path(), true));
5746 let page = body_text(
5747 app.clone()
5748 .oneshot(get_req("/", "127.0.0.1:8787"))
5749 .await
5750 .unwrap(),
5751 )
5752 .await;
5753 assert!(
5754 page.contains(&format!("<meta name=\"csrf\" content=\"{TEST_CSRF}\">")),
5755 "the meta tag the script reads"
5756 );
5757 assert_eq!(
5764 page.matches("await post(").count(),
5765 11,
5766 "model, reasoning, settings, context, approval, chat, cancel, logout, the session \
5767 writes, the bot writes and the flare cancel"
5768 );
5769 assert!(page.contains("'X-Eclipse-CSRF': CSRF"), "{page:.0}");
5770 assert!(page.contains("id=\"logout\""), "sign-out is a fetch too");
5771 }
5772
5773 #[test]
5777 fn the_context_pane_edits_the_files_by_id_and_shows_their_budget() {
5778 assert!(
5779 INDEX_HTML.contains("area.id = 'filetext'")
5780 && INDEX_HTML.contains("const area = document.createElement('textarea')"),
5781 "a textarea, because these are prose"
5782 );
5783 assert!(
5784 INDEX_HTML.contains("fetch('/api/context')"),
5785 "the list is the server's, not the page's"
5786 );
5787 assert!(
5788 INDEX_HTML.contains("post('/api/context', { name: row.name, text: area.value })"),
5789 "a save names an id and the text"
5790 );
5791 assert!(
5792 INDEX_HTML.contains("row.own_budget === null"),
5793 "MEMORY.md is measured against its own budget, not the per-file ceiling"
5794 );
5795 assert!(
5796 INDEX_HTML.contains("a save applies to the next run"),
5797 "what a save applies to is said once, in the same words the settings rows use"
5798 );
5799 assert!(
5800 INDEX_HTML.contains("entries are separated by a line holding"),
5801 "the `§` storage format is explained where it is edited"
5802 );
5803 for literal in [
5806 "'USER.md'",
5807 "'MEMORY.md'",
5808 "\"USER.md\"",
5809 ".eclipse/memory",
5810 "\"agent\"",
5811 "\"memory\"",
5812 ] {
5813 assert!(
5814 !INDEX_HTML.contains(literal),
5815 "the page spells {literal}: the names come from `GET /api/context`"
5816 );
5817 }
5818 assert!(
5819 INDEX_HTML.contains("for (const f of ctxFiles)"),
5820 "the rail's file entries are built from the server's list"
5821 );
5822 }
5823
5824 #[tokio::test]
5825 async fn the_sign_in_page_says_when_it_is_inside_a_frame() {
5826 let dir = tempfile::tempdir().unwrap();
5827 let app = router(state(dir.path(), false));
5828 let framed = body_text(
5829 app.clone()
5830 .oneshot(
5831 HttpRequest::get("/login")
5832 .header("host", "127.0.0.1:8787")
5833 .header("sec-fetch-dest", "iframe")
5834 .body(Body::empty())
5835 .unwrap(),
5836 )
5837 .await
5838 .unwrap(),
5839 )
5840 .await;
5841 assert!(framed.contains("inside a frame"), "{framed}");
5842 let plain = body_text(
5843 app.oneshot(
5844 HttpRequest::get("/login")
5845 .header("host", "127.0.0.1:8787")
5846 .body(Body::empty())
5847 .unwrap(),
5848 )
5849 .await
5850 .unwrap(),
5851 )
5852 .await;
5853 assert!(!plain.contains("inside a frame"), "{plain}");
5854 }
5855
5856 fn csrf_of(page: &str) -> String {
5858 const AT: &str = "name=\"csrf\" content=\"";
5859 let start = page.find(AT).expect("the page carries a csrf token") + AT.len();
5860 page[start..].split('"').next().unwrap_or("").to_string()
5861 }
5862
5863 fn get_req(uri: &str, host: &str) -> HttpRequest<Body> {
5864 HttpRequest::get(uri)
5865 .header("host", host)
5866 .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
5867 .body(Body::empty())
5868 .unwrap()
5869 }
5870
5871 fn model_req(body: serde_json::Value) -> HttpRequest<Body> {
5872 HttpRequest::post("/api/model")
5873 .header("host", "127.0.0.1:8787")
5874 .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
5875 .header("content-type", "application/json")
5876 .body(Body::from(body.to_string()))
5877 .unwrap()
5878 }
5879
5880 async fn serve_models(names: &[(&str, Option<u64>)]) -> String {
5885 let rows: Vec<serde_json::Value> = names
5886 .iter()
5887 .map(|(n, window)| match window {
5888 Some(w) => json!({ "id": n, "context_length": w }),
5889 None => json!({ "id": n }),
5890 })
5891 .collect();
5892 let app = Router::new().route(
5893 "/v1/models",
5894 get(move || {
5895 let body = json!({ "data": rows });
5896 async move { Json(body) }
5897 }),
5898 );
5899 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
5900 let addr = listener.local_addr().unwrap();
5901 tokio::spawn(async move {
5902 let _ = axum::serve(listener, app).await;
5903 });
5904 format!("http://{addr}/v1")
5905 }
5906
5907 fn provider_state(dir: &std::path::Path, base_url: &str, model: &str) -> (Shared, Arc<Agent>) {
5911 let store = SessionStore::new(dir.join("sessions"));
5912 let cfg = eclipse_core::config::ProviderConfig {
5913 base_url: base_url.into(),
5914 model: model.into(),
5915 ..Default::default()
5916 };
5917 let agent = Arc::new(
5918 Agent::new(
5919 Arc::new(Canned),
5920 Arc::new(ToolRegistry::default()),
5921 store.clone(),
5922 "sys".into(),
5923 3,
5924 )
5925 .with_provider_config(cfg),
5926 );
5927 (
5928 Arc::new(authed(Some(agent.clone()), store, model, None)),
5929 agent,
5930 )
5931 }
5932
5933 fn chat_req(body: serde_json::Value) -> HttpRequest<Body> {
5934 HttpRequest::post("/api/chat")
5935 .header("host", "127.0.0.1:8787")
5936 .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
5937 .header("content-type", "application/json")
5938 .body(Body::from(body.to_string()))
5939 .unwrap()
5940 }
5941
5942 async fn text(resp: Response) -> String {
5943 let bytes = axum::body::to_bytes(resp.into_body(), 1 << 20)
5944 .await
5945 .unwrap();
5946 String::from_utf8(bytes.to_vec()).unwrap()
5947 }
5948
5949 fn anon(method: &str, uri: &str) -> axum::http::request::Builder {
5950 HttpRequest::builder()
5951 .method(method)
5952 .uri(uri)
5953 .header("host", "127.0.0.1:8787")
5954 }
5955
5956 fn login_req(token: &str) -> HttpRequest<Body> {
5957 anon("POST", "/login")
5958 .header("content-type", "application/x-www-form-urlencoded")
5959 .header("origin", "http://127.0.0.1:8787")
5960 .body(Body::from(format!("token={token}")))
5961 .unwrap()
5962 }
5963
5964 fn pair_req(user: &str, password: &str) -> HttpRequest<Body> {
5966 anon("POST", "/login")
5967 .header("content-type", "application/x-www-form-urlencoded")
5968 .header("origin", "http://127.0.0.1:8787")
5969 .body(Body::from(format!("username={user}&password={password}")))
5970 .unwrap()
5971 }
5972
5973 fn state_with_password(dir: &std::path::Path, user: &str, password: &str) -> Arc<AppState> {
5977 state_with_password_throttled(
5978 dir,
5979 user,
5980 password,
5981 LoginThrottle::new(100, Duration::from_millis(1), Duration::from_millis(1)),
5982 )
5983 }
5984
5985 fn state_with_password_throttled(
5986 dir: &std::path::Path,
5987 user: &str,
5988 password: &str,
5989 throttle: LoginThrottle,
5990 ) -> Arc<AppState> {
5991 let mut st = match Arc::try_unwrap(state_with_password_inner(dir, user, password)) {
5992 Ok(st) => st,
5993 Err(_) => panic!("a state built here is not shared yet"),
5994 };
5995 st.throttle = throttle;
5996 Arc::new(st)
5997 }
5998
5999 fn state_with_password_inner(
6000 dir: &std::path::Path,
6001 user: &str,
6002 password: &str,
6003 ) -> Arc<AppState> {
6004 let hash = eclipse_core::auth::hash_password(password).unwrap();
6005 Arc::new(
6006 authed(None, SessionStore::new(dir.join("sessions")), "m", None).with_credentials(
6007 eclipse_core::auth::Credentials::Password {
6008 user: user.into(),
6009 hash: eclipse_core::auth::Stored::parse(&hash).unwrap(),
6010 },
6011 ),
6012 )
6013 }
6014
6015 #[tokio::test]
6019 async fn a_username_and_password_sign_in_and_every_wrong_answer_is_the_same() {
6020 let dir = tempfile::tempdir().unwrap();
6021 let app = router(state_with_password(dir.path(), "max", "open sesame"));
6022
6023 let r = app
6024 .clone()
6025 .oneshot(pair_req("max", "open sesame"))
6026 .await
6027 .unwrap();
6028 assert_eq!(r.status(), StatusCode::SEE_OTHER, "the right pair");
6029 assert!(
6030 r.headers().get("set-cookie").is_some(),
6031 "and it hands out the session cookie"
6032 );
6033
6034 for (user, password) in [
6035 ("max", "open sesam"),
6036 ("mor", "open sesame"),
6037 ("", "open sesame"),
6038 ("max", ""),
6039 ] {
6040 let r = app.clone().oneshot(pair_req(user, password)).await.unwrap();
6041 assert_eq!(r.status(), StatusCode::UNAUTHORIZED, "{user}/{password}");
6042 let body = text(r).await;
6043 assert!(body.contains("Wrong user or password."), "{body}");
6044 assert!(
6045 !body.contains("Wrong token."),
6046 "the page does not offer the old wording in this mode: {body}"
6047 );
6048 }
6049 }
6050
6051 #[tokio::test]
6056 async fn the_right_pair_gets_in_after_the_failed_attempt_wait() {
6057 let dir = tempfile::tempdir().unwrap();
6058 let app = router(state_with_password_throttled(
6059 dir.path(),
6060 "max",
6061 "open sesame",
6062 LoginThrottle::new(0, Duration::from_secs(2), Duration::from_secs(2)),
6066 ));
6067
6068 let wrong = app.clone().oneshot(pair_req("max", "nope")).await.unwrap();
6069 assert_eq!(wrong.status(), StatusCode::UNAUTHORIZED);
6070
6071 let held = app
6073 .clone()
6074 .oneshot(pair_req("max", "open sesame"))
6075 .await
6076 .unwrap();
6077 assert_eq!(held.status(), StatusCode::TOO_MANY_REQUESTS);
6078 let wait: u64 = held
6079 .headers()
6080 .get("retry-after")
6081 .expect("the wait says how long")
6082 .to_str()
6083 .unwrap()
6084 .parse()
6085 .unwrap();
6086 assert!(wait >= 1, "at least a second: {wait}");
6087
6088 tokio::time::sleep(Duration::from_millis(2_100)).await;
6090 let r = app.oneshot(pair_req("max", "open sesame")).await.unwrap();
6091 assert_eq!(r.status(), StatusCode::SEE_OTHER);
6092 }
6093
6094 #[tokio::test]
6097 async fn a_token_only_install_still_signs_in_through_the_new_form() {
6098 let dir = tempfile::tempdir().unwrap();
6099 let app = router(state(dir.path(), true));
6100 let r = app.clone().oneshot(pair_req("", TOKEN)).await.unwrap();
6101 assert_eq!(r.status(), StatusCode::SEE_OTHER, "the token still works");
6102 let r = router(state(dir.path(), true))
6104 .oneshot(anon("GET", "/login").body(Body::empty()).unwrap())
6105 .await
6106 .unwrap();
6107 let html = text(r).await;
6108 assert!(html.contains("class=\"token\""), "token mode: {html:.0}");
6109 assert!(html.contains("Enter the dashboard token from"), "{html:.0}");
6110 assert!(!html.contains("ECLIPSE_WEB_USER"), "no password advice yet");
6111 }
6112
6113 #[tokio::test]
6115 async fn the_password_page_asks_for_a_user_and_a_password() {
6116 let dir = tempfile::tempdir().unwrap();
6117 let r = router(state_with_password(dir.path(), "max", "open sesame"))
6118 .oneshot(anon("GET", "/login").body(Body::empty()).unwrap())
6119 .await
6120 .unwrap();
6121 let html = text(r).await;
6122 assert!(
6123 html.contains("class=\"password\""),
6124 "password mode: {html:.0}"
6125 );
6126 assert!(html.contains("autocomplete=\"username\""), "{html:.0}");
6127 assert!(
6128 html.contains("autocomplete=\"current-password\""),
6129 "{html:.0}"
6130 );
6131 assert!(
6132 html.contains("ECLIPSE_WEB_USER"),
6133 "it names where the user comes from"
6134 );
6135 assert!(
6136 !html.contains("auth_token"),
6137 "the token is the machine credential; the page does not offer it as a human one"
6138 );
6139 }
6140
6141 #[tokio::test]
6144 async fn blocking_runs_the_work_off_the_async_worker() {
6145 let here = std::thread::current().id();
6146 let there = blocking(move || std::thread::current().id()).await;
6147 assert!(there.is_some(), "the work finished");
6148 assert_ne!(
6149 there.unwrap(),
6150 here,
6151 "a blocking call must not run on the async worker"
6152 );
6153 }
6154
6155 #[tokio::test]
6157 async fn blocking_turns_a_panic_into_nothing() {
6158 let died = blocking(|| -> usize { panic!("the disk went away") }).await;
6159 assert!(
6160 died.is_none(),
6161 "a panic comes back as None, not a dropped request"
6162 );
6163 }
6164
6165 #[tokio::test]
6167 async fn a_couple_of_wrong_tokens_is_not_an_attack() {
6168 let dir = tempfile::tempdir().unwrap();
6169 let app = router(state(dir.path(), true));
6170 for attempt in 1..=2 {
6171 let r = app
6172 .clone()
6173 .oneshot(login_req("not-the-token"))
6174 .await
6175 .unwrap();
6176 assert_eq!(r.status(), StatusCode::UNAUTHORIZED, "attempt {attempt}");
6177 }
6178 }
6179
6180 #[tokio::test]
6183 async fn a_run_of_wrong_tokens_is_answered_429_and_even_the_right_one_waits() {
6184 let dir = tempfile::tempdir().unwrap();
6185 let app = router(state_throttled(
6186 dir.path(),
6187 LoginThrottle::new(2, Duration::from_secs(1), Duration::from_secs(30)),
6188 ));
6189 for _ in 1..=2 {
6190 let r = app
6191 .clone()
6192 .oneshot(login_req("not-the-token"))
6193 .await
6194 .unwrap();
6195 assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
6196 }
6197 let r = app
6198 .clone()
6199 .oneshot(login_req("not-the-token"))
6200 .await
6201 .unwrap();
6202 assert_eq!(
6203 r.status(),
6204 StatusCode::UNAUTHORIZED,
6205 "the 2 free ones, then the wait"
6206 );
6207
6208 let r = app.clone().oneshot(login_req(TOKEN)).await.unwrap();
6209 assert_eq!(r.status(), StatusCode::TOO_MANY_REQUESTS);
6210 assert!(
6211 r.headers().contains_key("retry-after"),
6212 "a 429 without Retry-After is a riddle"
6213 );
6214 }
6215
6216 #[tokio::test]
6218 async fn the_wait_ends_and_a_right_token_clears_it() {
6219 let dir = tempfile::tempdir().unwrap();
6220 let app = router(state_throttled(
6221 dir.path(),
6222 LoginThrottle::new(1, Duration::from_millis(30), Duration::from_millis(60)),
6223 ));
6224 for _ in 1..=2 {
6225 let _ = app
6226 .clone()
6227 .oneshot(login_req("not-the-token"))
6228 .await
6229 .unwrap();
6230 }
6231 let r = app.clone().oneshot(login_req(TOKEN)).await.unwrap();
6232 assert_eq!(r.status(), StatusCode::TOO_MANY_REQUESTS, "still waiting");
6233
6234 tokio::time::sleep(Duration::from_millis(70)).await;
6235 let r = app.clone().oneshot(login_req(TOKEN)).await.unwrap();
6236 assert_eq!(r.status(), StatusCode::SEE_OTHER, "the wait is over");
6237 let r = app
6239 .clone()
6240 .oneshot(login_req("not-the-token"))
6241 .await
6242 .unwrap();
6243 assert_eq!(r.status(), StatusCode::UNAUTHORIZED, "free attempts again");
6244 }
6245
6246 #[tokio::test]
6247 async fn everything_but_healthz_and_login_needs_the_cookie() {
6248 let dir = tempfile::tempdir().unwrap();
6249 let app = router(state(dir.path(), true));
6250 for (method, uri) in [
6251 ("GET", "/"),
6252 ("GET", "/api/sessions"),
6253 ("GET", "/api/sessions/s1"),
6254 ("GET", "/api/models"),
6255 ("GET", "/api/update"),
6256 ("POST", "/api/model"),
6257 ("POST", "/api/chat"),
6258 ("POST", "/api/approvals/deadbeef"),
6259 ("POST", "/api/runs/deadbeef/cancel"),
6260 ("GET", "/nonexistent"),
6261 ] {
6262 let r = app
6263 .clone()
6264 .oneshot(anon(method, uri).body(Body::empty()).unwrap())
6265 .await
6266 .unwrap();
6267 assert_eq!(r.status(), StatusCode::UNAUTHORIZED, "{method} {uri}");
6268 }
6269 let r = app
6271 .clone()
6272 .oneshot(
6273 anon("GET", "/api/sessions")
6274 .header("cookie", format!("{SESSION_COOKIE}=forged"))
6275 .body(Body::empty())
6276 .unwrap(),
6277 )
6278 .await
6279 .unwrap();
6280 assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
6281 let r = app
6283 .clone()
6284 .oneshot(
6285 anon("GET", "/api/sessions")
6286 .header("cookie", format!("{SESSION_COOKIE}={TOKEN}"))
6287 .body(Body::empty())
6288 .unwrap(),
6289 )
6290 .await
6291 .unwrap();
6292 assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
6293
6294 for uri in ["/", "/api/sessions"] {
6295 let r = app
6296 .clone()
6297 .oneshot(get_req(uri, "127.0.0.1:8787"))
6298 .await
6299 .unwrap();
6300 assert_eq!(r.status(), StatusCode::OK, "{uri} with cookie");
6301 }
6302 let r = app
6303 .clone()
6304 .oneshot(anon("GET", "/healthz").body(Body::empty()).unwrap())
6305 .await
6306 .unwrap();
6307 assert_eq!(r.status(), StatusCode::OK);
6308 }
6309
6310 #[tokio::test]
6315 async fn healthz_tells_an_anonymous_caller_only_that_it_is_up() {
6316 let dir = tempfile::tempdir().unwrap();
6317 let root = dir.path().join("state");
6318 std::fs::create_dir_all(&root).unwrap();
6319 std::fs::write(
6320 root.join("cron.json"),
6321 r#"{"jobs": {"backup-everything": {"runs": 1, "last_outcome": "failed"}}}"#,
6322 )
6323 .unwrap();
6324 let store = SessionStore::new(dir.path().join("sessions"));
6325 let agent = Some(Arc::new(Agent::new(
6326 Arc::new(Canned),
6327 Arc::new(ToolRegistry::default()),
6328 store.clone(),
6329 "sys".into(),
6330 3,
6331 )));
6332 let st = Arc::new(
6333 authed(agent, store, "test-<model>", None).with_cron_root(dir.path().to_path_buf()),
6334 );
6335 let app = router(st);
6336
6337 let public: serde_json::Value = serde_json::from_str(
6338 &text(
6339 app.clone()
6340 .oneshot(anon("GET", "/healthz").body(Body::empty()).unwrap())
6341 .await
6342 .unwrap(),
6343 )
6344 .await,
6345 )
6346 .unwrap();
6347 assert_eq!(public, json!({"status": "ok"}), "one word and nothing else");
6348
6349 let signed_in: serde_json::Value = serde_json::from_str(
6350 &text(
6351 app.oneshot(get_req("/healthz", "127.0.0.1:8787"))
6352 .await
6353 .unwrap(),
6354 )
6355 .await,
6356 )
6357 .unwrap();
6358 assert_eq!(signed_in["status"], "ok");
6359 assert!(signed_in.get("version").is_some(), "{signed_in}");
6360 assert_eq!(
6361 signed_in["cron"]["failed_jobs"][0], "backup-everything",
6362 "the detail is still there for the person who is signed in"
6363 );
6364 }
6365
6366 #[tokio::test]
6367 async fn unauthenticated_index_is_the_login_form_without_the_app() {
6368 let dir = tempfile::tempdir().unwrap();
6369 let st = state(dir.path(), true);
6370 st.store
6371 .append("s1", &Message::user("secret preview"))
6372 .unwrap();
6373 let r = router(st)
6374 .oneshot(anon("GET", "/").body(Body::empty()).unwrap())
6375 .await
6376 .unwrap();
6377 assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
6378 let html = text(r).await;
6379 assert!(html.contains("name=\"username\"") && html.contains("name=\"password\""));
6383 assert!(html.contains("method=\"post\"") && html.contains("class=\"token\""));
6384 assert!(!html.contains("secret preview") && !html.contains("test-<model"));
6385 let r = router(state(dir.path(), true))
6386 .oneshot(anon("GET", "/login").body(Body::empty()).unwrap())
6387 .await
6388 .unwrap();
6389 assert_eq!(r.status(), StatusCode::OK);
6390 assert!(text(r).await.contains("name=\"password\""));
6391 }
6392
6393 #[tokio::test]
6394 async fn login_with_the_token_sets_a_strict_httponly_cookie_that_works() {
6395 let dir = tempfile::tempdir().unwrap();
6396 let app = router(state(dir.path(), true));
6397 let r = app.clone().oneshot(login_req(TOKEN)).await.unwrap();
6398 assert_eq!(r.status(), StatusCode::SEE_OTHER);
6399 assert_eq!(r.headers()[header::LOCATION], "/");
6400 let set = r.headers()[header::SET_COOKIE]
6401 .to_str()
6402 .unwrap()
6403 .to_string();
6404 assert!(set.starts_with(&format!("{SESSION_COOKIE}=")));
6405 assert!(set.contains("HttpOnly") && set.contains("SameSite=Strict"));
6406 assert!(set.contains("Path=/") && set.contains("Max-Age="));
6407 assert!(!set.contains(TOKEN), "the cookie must not carry the token");
6408
6409 let cookie = set.split(';').next().unwrap();
6410 let r = app
6411 .clone()
6412 .oneshot(
6413 anon("GET", "/api/sessions")
6414 .header("cookie", cookie)
6415 .body(Body::empty())
6416 .unwrap(),
6417 )
6418 .await
6419 .unwrap();
6420 assert_eq!(r.status(), StatusCode::OK);
6421
6422 let r = app
6424 .clone()
6425 .oneshot(
6426 anon("POST", "/logout")
6427 .header("cookie", cookie)
6428 .body(Body::empty())
6429 .unwrap(),
6430 )
6431 .await
6432 .unwrap();
6433 assert!(r.headers()[header::SET_COOKIE]
6434 .to_str()
6435 .unwrap()
6436 .contains("Max-Age=0"));
6437 let r = app
6438 .clone()
6439 .oneshot(
6440 anon("GET", "/api/sessions")
6441 .header("cookie", cookie)
6442 .body(Body::empty())
6443 .unwrap(),
6444 )
6445 .await
6446 .unwrap();
6447 assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
6448 }
6449
6450 #[tokio::test]
6451 async fn wrong_or_empty_token_is_rejected_without_a_cookie() {
6452 let dir = tempfile::tempdir().unwrap();
6453 let app = router(state_throttled(
6456 dir.path(),
6457 LoginThrottle::new(8, Duration::from_secs(1), Duration::from_secs(1)),
6458 ));
6459 for req in [
6460 login_req("nope"),
6461 login_req(""),
6462 login_req(&TOKEN[..TOKEN.len() - 1]),
6463 login_req(&format!("{TOKEN}x")),
6464 ] {
6465 let r = app.clone().oneshot(req).await.unwrap();
6466 assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
6467 assert!(r.headers().get(header::SET_COOKIE).is_none());
6468 }
6469 let malformed = anon("POST", "/login")
6470 .header("content-type", "application/x-www-form-urlencoded")
6471 .body(Body::from("other=1"))
6472 .unwrap();
6473 let r = app.oneshot(malformed).await.unwrap();
6474 assert!(r.status().is_client_error());
6475 assert!(r.headers().get(header::SET_COOKIE).is_none());
6476 }
6477
6478 #[tokio::test]
6479 async fn login_from_a_foreign_origin_is_forbidden() {
6480 let dir = tempfile::tempdir().unwrap();
6481 let req = anon("POST", "/login")
6482 .header("content-type", "application/x-www-form-urlencoded")
6483 .header("origin", "https://evil.example.com")
6484 .body(Body::from(format!("token={TOKEN}")))
6485 .unwrap();
6486 let r = router(state(dir.path(), true)).oneshot(req).await.unwrap();
6487 assert_eq!(r.status(), StatusCode::FORBIDDEN);
6488 assert!(r.headers().get(header::SET_COOKIE).is_none());
6489 }
6490
6491 #[tokio::test]
6494 async fn the_login_cookie_lives_as_long_as_the_configured_ttl() {
6495 let dir = tempfile::tempdir().unwrap();
6496 let store = SessionStore::new(dir.path().join("sessions"));
6497 let st = AppState::new(
6498 None,
6499 store,
6500 "m".into(),
6501 None,
6502 TOKEN.into(),
6503 Duration::from_secs(3600),
6504 );
6505 let req = login_req(TOKEN);
6506 let r = router(Arc::new(st)).oneshot(req).await.unwrap();
6507 assert_eq!(r.status(), StatusCode::SEE_OTHER);
6508 let cookie = r
6509 .headers()
6510 .get(header::SET_COOKIE)
6511 .expect("a login sets a cookie")
6512 .to_str()
6513 .unwrap()
6514 .to_string();
6515 assert!(cookie.contains("Max-Age=3600"), "{cookie}");
6516 assert!(cookie.contains("HttpOnly"), "{cookie}");
6517 }
6518
6519 #[test]
6520 fn login_ids_expire_and_are_capped() {
6521 let logins = Logins::new(Duration::from_secs(
6522 eclipse_core::config::DEFAULT_SESSION_TTL_HOURS * 60 * 60,
6523 ));
6524 let first = logins.create().unwrap().0;
6525 assert!(logins.is_valid(&first));
6526 for _ in 0..MAX_LOGINS + 5 {
6527 logins.create().unwrap();
6528 }
6529 assert!(logins.lock().len() <= MAX_LOGINS);
6530 logins.lock().insert(
6531 "old".into(),
6532 Session {
6533 expires: Instant::now() - Duration::from_secs(1),
6534 csrf: String::new(),
6535 },
6536 );
6537 assert!(!logins.is_valid("old"));
6538 assert!(!logins.is_valid(""));
6539 }
6540
6541 #[tokio::test]
6542 async fn health_reports_configuration() {
6543 let dir = tempfile::tempdir().unwrap();
6544 let resp = router(state(dir.path(), true))
6545 .oneshot(get_req("/healthz", "127.0.0.1:8787"))
6546 .await
6547 .unwrap();
6548 assert_eq!(resp.status(), StatusCode::OK);
6549 let v: serde_json::Value = serde_json::from_str(&text(resp).await).unwrap();
6550 assert_eq!(v["status"], "ok");
6551 assert_eq!(v["configured"], true);
6552 }
6553
6554 #[tokio::test]
6555 async fn health_reports_the_cron_state_when_a_root_is_set() {
6556 let dir = tempfile::tempdir().unwrap();
6557 let root = dir.path().join("state");
6558 std::fs::create_dir_all(&root).unwrap();
6559 let jobs = root.join("cron.json");
6560 std::fs::write(
6561 &jobs,
6562 r#"{"jobs": {"brief": {"runs": 1, "last_started_ms": 1000, "last_finished_ms": 1100, "last_outcome": "failed"}}}"#,
6563 ).unwrap();
6564 let store = SessionStore::new(dir.path().join("sessions"));
6565 let agent = Some(Arc::new(Agent::new(
6566 Arc::new(Canned),
6567 Arc::new(ToolRegistry::default()),
6568 store.clone(),
6569 "sys".into(),
6570 3,
6571 )));
6572 let st = Arc::new(
6573 authed(agent, store, "test-<model>", None).with_cron_root(dir.path().to_path_buf()),
6574 );
6575 let resp = router(st)
6576 .oneshot(get_req("/healthz", "127.0.0.1:8787"))
6577 .await
6578 .unwrap();
6579 let v: serde_json::Value = serde_json::from_str(&text(resp).await).unwrap();
6580 assert_eq!(v["cron"]["failed_jobs"][0], "brief");
6581 assert_eq!(v["cron"]["last_tick_ms"], 1000);
6582 }
6583
6584 #[tokio::test]
6585 async fn index_is_server_rendered_and_escaped() {
6586 let dir = tempfile::tempdir().unwrap();
6587 let st = state(dir.path(), true);
6588 st.store.append("s1", &Message::user("<b>hi</b>")).unwrap();
6589 let html = text(
6590 router(st)
6591 .oneshot(get_req("/", "localhost:8787"))
6592 .await
6593 .unwrap(),
6594 )
6595 .await;
6596 assert!(html.contains("test-<model>"));
6597 assert!(html.contains("data-id=\"s1\""));
6598 assert!(
6599 html.contains("class=\"name\"><b>hi</b>"),
6600 "the label is escaped text, not markup"
6601 );
6602 assert!(
6603 html.contains("data-updated=") && html.contains("class=\"session\""),
6604 "a row says when it last moved, which is what the page sections by"
6605 );
6606 assert!(!html.contains("{{"));
6607 }
6608
6609 #[tokio::test]
6613 async fn the_page_cannot_spell_a_colour_of_its_own() {
6614 let dir = tempfile::tempdir().unwrap();
6615 let html = text(
6616 router(state(dir.path(), true))
6617 .oneshot(get_req("/", "localhost:8787"))
6618 .await
6619 .unwrap(),
6620 )
6621 .await;
6622 let accent = eclipse_core::palette::ACCENT;
6623 assert!(
6624 html.contains(&format!(
6625 "--accent:rgb({}, {}, {})",
6626 accent.0, accent.1, accent.2
6627 )),
6628 "the accent arrives as a custom property from the table"
6629 );
6630 assert!(
6631 !html.to_lowercase().contains("#5aa9ff"),
6632 "the blue the dashboard used to be is gone, not merely overridden"
6633 );
6634 let styles = html.split("</style>").next().unwrap_or_default();
6635 assert!(
6636 !styles.contains(":#") && !styles.contains(": #"),
6637 "no colour literal in the stylesheet: {:?}",
6638 styles
6639 .match_indices(":#")
6640 .map(|(i, _)| &styles[i..(i + 8).min(styles.len())])
6641 .collect::<Vec<_>>()
6642 );
6643 }
6644
6645 #[test]
6652 fn only_the_pane_decides_where_the_pane_is() {
6653 let assignments: Vec<&str> = INDEX_HTML
6654 .lines()
6655 .filter(|l| !l.trim_start().starts_with("//"))
6656 .filter(|l| l.contains("log.scrollTop ="))
6657 .collect();
6658 assert_eq!(
6659 assignments.len(),
6660 1,
6661 "the pane is scrolled from `pin()` and nowhere else, found: {assignments:?}"
6662 );
6663 let pin = INDEX_HTML
6665 .split("function pin()")
6666 .nth(1)
6667 .expect("the page has a `pin()`");
6668 let body = pin.split("\n }").next().unwrap_or_default();
6669 assert!(
6670 body.contains("log.scrollTop = log.scrollHeight"),
6671 "the single assignment lives in `pin()`: {body:?}"
6672 );
6673 assert!(
6675 INDEX_HTML.contains("log.addEventListener('scroll'"),
6676 "the page learns where the reader is by listening to the pane"
6677 );
6678 }
6679
6680 #[test]
6683 fn the_way_back_down_is_a_button_on_the_stats_row() {
6684 assert!(
6685 INDEX_HTML.contains(r#"<button id="jump" type="button" hidden"#),
6686 "the control starts hidden and says what it is"
6687 );
6688 let css = INDEX_HTML
6689 .split("#statsrow #yolo[hidden] { display:none; }")
6690 .nth(1)
6691 .expect("the stats row's rules come before the button's");
6692 assert!(
6693 css.contains("#jump { position:absolute") && css.contains("bottom:calc(100% + 8px)"),
6694 "it floats over the transcript's corner, the way the model menu does"
6695 );
6696 assert!(
6697 INDEX_HTML.contains("jump.addEventListener('click'"),
6698 "and clicking it is wired"
6699 );
6700 }
6701
6702 #[test]
6712 fn every_token_a_page_asks_for_is_one_the_palette_emits() {
6713 let css = palette_css();
6714 let emitted: Vec<&str> = css
6717 .match_indices("--")
6718 .filter_map(|(i, _)| {
6719 let rest = &css[i + 2..];
6720 let end = rest.find(':')?;
6721 let name = &rest[..end];
6722 if name.chars().next()?.is_ascii_alphanumeric() {
6723 Some(name)
6724 } else {
6725 None
6726 }
6727 })
6728 .collect();
6729 assert!(
6730 emitted.len() >= 14,
6731 "the palette block reads back as {emitted:?}"
6732 );
6733
6734 for (name, page) in [("index.html", INDEX_HTML), ("login.html", LOGIN_HTML)] {
6735 let mut asked = std::collections::BTreeSet::new();
6736 for (i, _) in page.match_indices("var(--") {
6737 let rest = &page[i + "var(--".len()..];
6740 let end = rest
6741 .find(|c: char| !(c.is_ascii_alphanumeric() || c == '-'))
6742 .unwrap_or(rest.len());
6743 asked.insert(&rest[..end]);
6744 }
6745 assert!(
6746 asked.len() >= 6,
6747 "{name} asks for {asked:?} — the scan found almost nothing to check"
6748 );
6749 for token in asked {
6750 assert!(
6751 emitted.contains(&token),
6752 "{name} uses var(--{token}) and the palette emits no --{token}: \
6753 the declaration would be dropped and the property would inherit"
6754 );
6755 }
6756 }
6757 }
6758
6759 #[test]
6765 fn the_sign_in_page_is_the_same_brand() {
6766 use eclipse_core::palette as p;
6767 let page = login_html("token", "", "").0;
6768
6769 assert!(
6770 page.contains(&format!(
6771 "--accent:rgb({}, {}, {})",
6772 p::ACCENT.0,
6773 p::ACCENT.1,
6774 p::ACCENT.2
6775 )),
6776 "the accent arrives from the table, on this page too"
6777 );
6778 assert!(page.contains(&format!(
6781 "--bad:rgb({}, {}, {})",
6782 p::BAD.0,
6783 p::BAD.1,
6784 p::BAD.2
6785 )));
6786 assert!(page.contains(&format!(
6787 "--ink:rgb({}, {}, {})",
6788 p::INK.0,
6789 p::INK.1,
6790 p::INK.2
6791 )));
6792
6793 assert!(page.contains("src=\"/logo.svg\""), "the mark is on it");
6795 assert!(page.contains("class=\"version\""), "and the version");
6796 assert!(
6797 page.contains(&format!("v{}", env!("CARGO_PKG_VERSION"))),
6798 "the version is this build's"
6799 );
6800
6801 let styles = page.split("</style>").next().unwrap_or_default();
6803 assert!(
6804 !styles.contains(":#") && !styles.contains(": #"),
6805 "no colour literal in the sign-in sheet: {:?}",
6806 styles
6807 .match_indices(":#")
6808 .map(|(i, _)| &styles[i..(i + 8).min(styles.len())])
6809 .collect::<Vec<_>>()
6810 );
6811 for gone in ["#5aa2ff", "#5aa9ff"] {
6812 assert!(
6813 !page.to_lowercase().contains(gone),
6814 "{gone} is the blue this page used to be, and is not this brand"
6815 );
6816 }
6817 assert!(
6818 !page.contains("{{"),
6819 "a placeholder was left unfilled, and would render literally"
6820 );
6821 }
6822
6823 #[tokio::test]
6829 async fn the_mark_is_served_in_the_palettes_colours() {
6830 use eclipse_core::palette as p;
6831 let dir = tempfile::tempdir().unwrap();
6832 let app = router(state(dir.path(), true));
6833
6834 let r = app
6835 .clone()
6836 .oneshot(get_req("/logo.svg", "localhost:8787"))
6837 .await
6838 .unwrap();
6839 assert_eq!(r.status(), StatusCode::OK);
6841 assert!(
6842 r.headers()["content-type"]
6843 .to_str()
6844 .unwrap_or_default()
6845 .starts_with("image/svg+xml"),
6846 "{:?}",
6847 r.headers()["content-type"]
6848 );
6849 let svg = text(r).await;
6850 let hex = |c: (u8, u8, u8)| format!("#{:02X}{:02X}{:02X}", c.0, c.1, c.2);
6851 for (label, colour) in [
6852 ("the accent", p::ACCENT),
6853 ("the wordmark's hot end", p::WORDMARK_TOP),
6854 ("the page background", p::BG),
6855 ] {
6856 assert!(
6857 svg.contains(&hex(colour)),
6858 "{label} is {} in the served mark",
6859 hex(colour)
6860 );
6861 }
6862 for literal in ["#FF8A2B", "#FFB45E", "#FFF7E8", "#05060D"] {
6864 assert!(
6865 !svg.contains(literal),
6866 "{literal} is the file's, not the brand's"
6867 );
6868 }
6869 assert!(
6871 svg.contains("feGaussianBlur"),
6872 "the corona's blur is the file's"
6873 );
6874
6875 let ico = app
6876 .clone()
6877 .oneshot(get_req("/favicon.ico", "localhost:8787"))
6878 .await
6879 .unwrap();
6880 assert_eq!(ico.status(), StatusCode::OK);
6881 assert_eq!(ico.headers()["content-type"], "image/x-icon");
6882 let bytes = axum::body::to_bytes(ico.into_body(), 1 << 20)
6883 .await
6884 .unwrap();
6885 assert_eq!(
6886 bytes.len(),
6887 FAVICON_ICO.len(),
6888 "the committed icon, byte for byte"
6889 );
6890 assert!(bytes.starts_with(&[0, 0, 1, 0]), "an ICO header");
6891
6892 let page = text(
6894 app.clone()
6895 .oneshot(get_req("/", "localhost:8787"))
6896 .await
6897 .unwrap(),
6898 )
6899 .await;
6900 assert_eq!(page.matches("rel=\"icon\"").count(), 1, "one icon link");
6901 assert!(page.contains("href=\"/favicon.ico\""), "{page:.0}");
6902 let login = text(
6905 app.oneshot(anon("GET", "/login").body(Body::empty()).unwrap())
6906 .await
6907 .unwrap(),
6908 )
6909 .await;
6910 assert!(
6911 login.contains("rel=\"icon\""),
6912 "the sign-in page too: {:?}",
6913 &login[..login.len().min(400)]
6914 );
6915 }
6916
6917 #[tokio::test]
6920 async fn the_header_carries_the_mark_and_a_readable_name() {
6921 let dir = tempfile::tempdir().unwrap();
6922 let html = text(
6923 router(state(dir.path(), true))
6924 .oneshot(get_req("/", "localhost:8787"))
6925 .await
6926 .unwrap(),
6927 )
6928 .await;
6929 let h1 = html
6930 .split("<h1>")
6931 .nth(1)
6932 .and_then(|rest| rest.split("</h1>").next())
6933 .expect("the header");
6934 assert!(h1.contains("id=\"mark\""), "{h1}");
6935 assert!(h1.contains("src=\"/logo.svg\""), "{h1}");
6936 assert!(
6937 h1.contains("aria-hidden=\"true\""),
6938 "the picture is not the name: {h1}"
6939 );
6940 assert!(h1.contains("alt=\"\""), "{h1}");
6941 assert!(h1.contains(">eclipse"), "the word is still there: {h1}");
6942 assert!(
6943 h1.contains(env!("CARGO_PKG_VERSION")),
6944 "the version is the binary's: {h1}"
6945 );
6946 }
6947
6948 #[tokio::test]
6952 async fn a_turn_that_never_started_gives_the_composer_back() {
6953 let dir = tempfile::tempdir().unwrap();
6954 let html = text(
6955 router(state(dir.path(), true))
6956 .oneshot(get_req("/", "localhost:8787"))
6957 .await
6958 .unwrap(),
6959 )
6960 .await;
6961
6962 let refused = html
6966 .split("if (!resp.ok) {")
6967 .nth(1)
6968 .and_then(|rest| rest.split("let finished = false;").next())
6969 .expect("the refusal branch");
6970 assert!(
6971 refused.contains("restoreComposer();"),
6972 "what the press took goes back: {refused}"
6973 );
6974 assert!(
6975 refused.contains("if (echo) echo.remove();"),
6976 "and the bubble the press drew goes with it"
6977 );
6978 assert!(
6979 html.contains("const restoreComposer = () => {"),
6980 "the snapshot is taken before anything is cleared"
6981 );
6982
6983 let end = html
6986 .split("} finally {")
6987 .nth(1)
6988 .and_then(|rest| rest.split("busy = false;").next())
6989 .expect("the finally block");
6990 assert!(
6991 end.contains("deferredLine = null;"),
6992 "an unlanded command line is not echoed into the next turn: {end}"
6993 );
6994
6995 assert!(
6998 html.contains("try { handle(event, JSON.parse(data)); }"),
6999 "one bad event is contained where it happens"
7000 );
7001 assert!(
7002 html.contains("await reader.cancel()"),
7003 "the connection is closed on the way out"
7004 );
7005 assert!(
7006 html.contains("let reader = null;"),
7007 "and `finally` can reach the reader to do it"
7008 );
7009 }
7010
7011 #[tokio::test]
7013 async fn the_model_picker_lives_in_the_stats_row() {
7014 let dir = tempfile::tempdir().unwrap();
7015 let html = text(
7016 router(state(dir.path(), true))
7017 .oneshot(get_req("/", "localhost:8787"))
7018 .await
7019 .unwrap(),
7020 )
7021 .await;
7022 let aside = html
7023 .split("<aside>")
7024 .nth(1)
7025 .and_then(|rest| rest.split("</aside>").next())
7026 .expect("the sidebar");
7027 assert!(
7028 !aside.contains("id=\"model\""),
7029 "the sidebar no longer carries a model control: {aside:.0}"
7030 );
7031 let row = html
7032 .split("id=\"statsrow\"")
7033 .nth(1)
7034 .and_then(|rest| rest.split("<form id=\"form\"").next())
7035 .expect("the stats row");
7036 assert!(
7037 row.contains("id=\"model\""),
7038 "the button is in the row: {row}"
7039 );
7040 assert!(
7041 row.contains("id=\"models\""),
7042 "and its panel is anchored to it"
7043 );
7044 assert!(row.contains("role=\"menu\""), "a menu, not a panel");
7045
7046 assert!(html.contains("showReasoning"), "the reasoning submenu");
7050 assert!(
7051 html.contains("fetch('/api/reasoning')"),
7052 "the words on offer are served, not spelled here"
7053 );
7054 assert!(
7055 !html.contains("const EFFORTS"),
7056 "the page owns no level list of its own"
7057 );
7058 assert!(
7059 !html.contains("the effort is fixed when eclipse-web starts"),
7060 "the page is no longer ignorant of the level"
7061 );
7062 assert!(
7063 html.contains("eclipse-web restarts. config.toml is not touched"),
7064 "the note says what a pick lasts for and what it does not write"
7065 );
7066 assert!(
7067 html.contains("modelRow('effort · '"),
7068 "a head row that names the level and cannot be picked"
7069 );
7070 assert!(
7074 html.contains("id=\"effort\""),
7075 "the row carries the effort the next turn will ask for"
7076 );
7077 assert!(html.contains(">effort not sent</span>"), "{html:.0}");
7078 assert!(
7079 !html.contains("{{EFFORT}}"),
7080 "every placeholder is filled on the way out"
7081 );
7082 assert!(
7087 html.contains("const EFFORT0 = effortEl.dataset.label;")
7088 && html.contains("const EFFORT_DETAIL0 = effortEl.title;"),
7089 "the level and its sentence are read from the element, not written into the script"
7090 );
7091 assert!(
7092 !html.contains("const EFFORT0 = \""),
7093 "an interpolated literal is escaped for HTML and then parsed as JavaScript"
7094 );
7095 assert!(
7096 html.contains("data-label=\"not sent\""),
7097 "the label the script reads rides on the element"
7098 );
7099 assert!(
7104 !html.contains("{{CTX}}") && !html.contains("CTX0"),
7105 "the page-load window is gone, not merely unfilled"
7106 );
7107 assert!(
7108 html.contains("ctx -- · first --"),
7109 "an unmeasured row states no denominator"
7110 );
7111 assert!(
7112 html.contains("li.dataset.cost = s.cost"),
7113 "the sidebar's rows carry what the session last cost, so a click needs no request"
7114 );
7115 assert!(html.contains("focusRow"), "arrows walk the rows");
7117 assert!(
7118 html.contains("if (!modelSub.hidden) showModelList();"),
7119 "esc is one level"
7120 );
7121 assert!(html.contains("modelLabel.focus()"), "and focus returns");
7122
7123 assert!(
7125 !html.contains("· current' : level"),
7126 "no guessed current effort"
7127 );
7128 }
7129
7130 #[tokio::test]
7137 async fn the_transcript_column_is_the_pane() {
7138 let dir = tempfile::tempdir().unwrap();
7139 let html = text(
7140 router(state(dir.path(), true))
7141 .oneshot(get_req("/", "localhost:8787"))
7142 .await
7143 .unwrap(),
7144 )
7145 .await;
7146 let styles = html.split("</style>").next().unwrap_or_default();
7147
7148 let rule = |selector: &str| -> String {
7149 styles
7150 .split(selector)
7151 .nth(1)
7152 .and_then(|rest| rest.split('}').next())
7153 .map(|body| body.to_string())
7154 .unwrap_or_default()
7155 };
7156
7157 for (selector, what) in [(".msg {", "the transcript"), ("#form {", "the composer")] {
7158 let body = rule(selector);
7159 assert!(!body.is_empty(), "{selector} is styled");
7160 assert!(
7161 !body.contains("max-width"),
7162 "{what} reaches the pane's edges: {selector} {body}"
7163 );
7164 assert!(
7165 !body.contains("margin:0 auto"),
7166 "{what} is not centred in a wider row: {selector} {body}"
7167 );
7168 }
7169 assert!(
7171 rule("#log {").contains("padding:20px"),
7172 "one gutter, on the box that scrolls"
7173 );
7174
7175 let assistant = rule(".msg.assistant {");
7177 assert!(!assistant.contains("background"), "{assistant}");
7178 assert!(!assistant.contains("border"), "{assistant}");
7179 let user = rule(".msg.user {");
7180 assert!(user.contains("background:var(--panel)"), "{user}");
7181 assert!(user.contains("border-left:3px solid var(--user)"), "{user}");
7182 assert!(user.contains("padding"), "{user}");
7184 assert!(
7185 rule(".msg.approval {").contains("padding"),
7186 "the approval card"
7187 );
7188 assert!(
7189 rule(".msg.error {").contains("padding"),
7190 "the error verdict"
7191 );
7192 }
7193
7194 #[tokio::test]
7196 async fn the_composer_has_one_control_with_two_states() {
7197 let dir = tempfile::tempdir().unwrap();
7198 let html = text(
7199 router(state(dir.path(), true))
7200 .oneshot(get_req("/", "localhost:8787"))
7201 .await
7202 .unwrap(),
7203 )
7204 .await;
7205 let form = html
7206 .split("<form id=\"form\"")
7207 .nth(1)
7208 .and_then(|rest| rest.split("</form>").next())
7209 .expect("the composer form");
7210
7211 assert_eq!(form.matches("class=\"go\"").count(), 1, "{form}");
7215 assert!(form.contains("id=\"go\""), "{form}");
7216 assert!(!html.contains("id=\"send\""), "the second button is gone");
7217 assert!(!html.contains("id=\"stop\""), "not hidden, removed");
7218
7219 let styles = html.split("</style>").next().unwrap_or_default();
7221 let go = styles
7222 .split("button.go {")
7223 .nth(1)
7224 .and_then(|rest| rest.split('}').next())
7225 .unwrap_or_default();
7226 assert!(go.contains("align-self:center"), "{go}");
7227 assert!(go.contains("height:34px"), "{go}");
7228
7229 assert!(
7231 html.contains("setGo('starting')"),
7232 "the press is acknowledged"
7233 );
7234 assert!(
7235 html.contains("setGo('stop')"),
7236 "a run with an id can be stopped"
7237 );
7238 assert!(html.contains("setGo('idle')"), "and the control comes back");
7239 assert!(
7240 html.contains("'Stop the run in flight'"),
7241 "the accessible name changes with the state"
7242 );
7243 assert!(
7244 html.contains("/cancel"),
7245 "the Stop state posts the route the server has"
7246 );
7247 assert!(
7248 html.contains("nothing to cancel yet"),
7249 "a press in the gap says so instead of doing nothing"
7250 );
7251 }
7252
7253 #[tokio::test]
7262 async fn every_view_switch_closes_the_cron_pane() {
7263 let dir = tempfile::tempdir().unwrap();
7264 let html = text(
7265 router(state(dir.path(), true))
7266 .oneshot(get_req("/", "localhost:8787"))
7267 .await
7268 .unwrap(),
7269 )
7270 .await;
7271
7272 let helper = function_body(&html, "setView").expect("setView is the one switch");
7274 for bit in [
7275 "main').classList.toggle('cron'",
7276 "cronBtn.classList.toggle('on'",
7277 "aria-expanded",
7278 "cronPane.hidden",
7279 ] {
7280 assert!(helper.contains(bit), "`setView` sets {bit}: {helper}");
7281 }
7282 let writers = html.matches("classList.toggle('cron'").count();
7284 assert_eq!(writers, 1, "the class is written in one place, not two");
7285
7286 let wrapper = function_body(&html, "showCron").expect("showCron still exists");
7288 assert!(
7289 wrapper.contains("setView(open ? 'cron' : 'session')"),
7290 "{wrapper}"
7291 );
7292
7293 let loads = function_body(&html, "loadSession").expect("loadSession");
7295 assert!(
7296 loads.contains("setView('session')"),
7297 "opening a session closes the pane: {loads}"
7298 );
7299 let new_session = html
7300 .split("getElementById('new').addEventListener")
7301 .nth(1)
7302 .and_then(|rest| rest.split("\n });").next())
7303 .expect("the + New session handler");
7304 assert!(new_session.contains("setView('session')"), "{new_session}");
7305 let stream = html
7306 .split("case 'session':")
7307 .nth(1)
7308 .and_then(|rest| rest.split("break;").next())
7309 .expect("the SSE session case");
7310 assert!(
7311 stream.contains("setView('session')"),
7312 "a run that starts a session takes the column: {stream}"
7313 );
7314 }
7315
7316 #[tokio::test]
7319 async fn a_closed_section_reads_its_state_from_outside_the_rebuild() {
7320 let dir = tempfile::tempdir().unwrap();
7321 let html = text(
7322 router(state(dir.path(), true))
7323 .oneshot(get_req("/", "localhost:8787"))
7324 .await
7325 .unwrap(),
7326 )
7327 .await;
7328
7329 let groups = function_body(&html, "groupList").expect("groupList is the one partition");
7333 assert!(
7334 groups.contains("collapsed.has"),
7335 "the rebuild consults the closed set: {groups}"
7336 );
7337 assert!(
7338 !groups.contains("saveCollapsed"),
7339 "the rebuild never writes the set back: {groups}"
7340 );
7341 assert!(
7342 !groups.contains("list.children"),
7343 "rows come from `master`, not from what is currently on screen: {groups}"
7344 );
7345 assert!(
7347 html.contains("closest('.grouptoggle')"),
7348 "one delegated listener toggles any heading"
7349 );
7350
7351 let head = function_body(&html, "header").expect("header builds every heading");
7354 for bit in [
7355 "createElement('button')",
7356 "aria-expanded",
7357 "grouptoggle",
7358 "\\u00b7",
7359 ] {
7360 assert!(head.contains(bit), "a heading carries {bit}: {head}");
7361 }
7362
7363 assert!(
7366 html.contains("localStorage.setItem(COLLAPSED_KEY"),
7367 "the set persists"
7368 );
7369 assert!(
7370 html.contains("localStorage.getItem(COLLAPSED_KEY"),
7371 "and is read back"
7372 );
7373
7374 let mark = function_body(&html, "markActive").expect("markActive");
7376 assert!(
7377 mark.contains("isConnected"),
7378 "a row that is not in the DOM marks its heading instead: {mark}"
7379 );
7380 }
7381
7382 fn function_body<'a>(html: &'a str, name: &str) -> Option<&'a str> {
7384 let start = html.find(&format!("function {name}("))?;
7385 let rest = &html[start..];
7386 if let Some(line) = rest.split('\n').next() {
7387 if line.contains('}') {
7388 return Some(line);
7389 }
7390 }
7391 let end = rest.find("\n }")? + 3;
7392 Some(&rest[..end])
7393 }
7394
7395 #[tokio::test]
7396 async fn rejects_foreign_host_and_origin() {
7397 let dir = tempfile::tempdir().unwrap();
7398 let app = router(state(dir.path(), true));
7399 let r = app
7400 .clone()
7401 .oneshot(get_req("/healthz", "evil.example.com"))
7402 .await
7403 .unwrap();
7404 assert_eq!(r.status(), StatusCode::FORBIDDEN);
7405 let said = body_text(r).await;
7408 assert!(
7409 said.contains("evil.example.com") && said.contains("127.0.0.1"),
7410 "{said}"
7411 );
7412 assert!(said.contains("SSH tunnel"), "{said}");
7413 let req = HttpRequest::get("/healthz")
7417 .header("host", "127.0.0.1:8787")
7418 .header("origin", "https://evil.example.com")
7419 .body(Body::empty())
7420 .unwrap();
7421 assert_eq!(
7422 app.clone().oneshot(req).await.unwrap().status(),
7423 StatusCode::OK
7424 );
7425
7426 let req = HttpRequest::post("/api/model")
7429 .header("host", "127.0.0.1:8787")
7430 .header("origin", "http://127.0.0.1:9999")
7431 .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
7432 .header("content-type", "application/json")
7433 .body(Body::from(json!({ "model": "picked" }).to_string()))
7434 .unwrap();
7435 let r = app.clone().oneshot(req).await.unwrap();
7436 assert_eq!(r.status(), StatusCode::FORBIDDEN);
7437 let said = body_text(r).await;
7438 assert!(
7439 said.contains("Origin") && said.contains("9999") && said.contains("8787"),
7440 "the message names both sides: {said}"
7441 );
7442 assert!(
7443 !said.contains("is not 127.0.0.1"),
7444 "not the Host refusal: {said}"
7445 );
7446 let req = HttpRequest::get("/healthz")
7447 .header("host", "localhost:8787")
7448 .header("origin", "http://localhost:8787")
7449 .body(Body::empty())
7450 .unwrap();
7451 assert_eq!(app.oneshot(req).await.unwrap().status(), StatusCode::OK);
7452 }
7453
7454 #[tokio::test]
7455 async fn responses_carry_hardening_headers() {
7456 let dir = tempfile::tempdir().unwrap();
7457 let r = router(state(dir.path(), true))
7458 .oneshot(get_req("/", "127.0.0.1:8787"))
7459 .await
7460 .unwrap();
7461 let csp = r.headers()[header::CONTENT_SECURITY_POLICY]
7462 .to_str()
7463 .unwrap();
7464 assert!(csp.contains("frame-ancestors 'none'") && csp.contains("default-src 'none'"));
7465 assert!(
7470 csp.contains("img-src 'self' data:;"),
7471 "the mark, the icon and a message's picture are loadable: {csp}"
7472 );
7473 assert!(!csp.contains("img-src 'self' https:"), "{csp}");
7474 assert!(csp.contains("script-src 'unsafe-inline';"), "{csp}");
7475 assert_eq!(r.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
7476 }
7477
7478 #[tokio::test]
7479 async fn chat_is_rejected_when_all_slots_are_busy() {
7480 let dir = tempfile::tempdir().unwrap();
7481 let st = state(dir.path(), true);
7482 let _held = st
7483 .chat_slots
7484 .clone()
7485 .acquire_many_owned(MAX_CONCURRENT_CHATS as u32)
7486 .await
7487 .unwrap();
7488 let r = router(st)
7489 .oneshot(chat_req(json!({"message": "x"})))
7490 .await
7491 .unwrap();
7492 assert_eq!(r.status(), StatusCode::TOO_MANY_REQUESTS);
7493 }
7494
7495 #[tokio::test]
7496 async fn chat_streams_events_and_persists_session() {
7497 let dir = tempfile::tempdir().unwrap();
7498 let st = state(dir.path(), true);
7499 let resp = router(st.clone())
7500 .oneshot(chat_req(json!({"message": "hello"})))
7501 .await
7502 .unwrap();
7503 assert_eq!(resp.status(), StatusCode::OK);
7504 let body = text(resp).await;
7505 let order: Vec<_> = ["event: session", "event: message", "event: done"]
7506 .iter()
7507 .map(|m| {
7508 body.find(m)
7509 .unwrap_or_else(|| panic!("missing {m} in {body}"))
7510 })
7511 .collect();
7512 assert!(order.windows(2).all(|w| w[0] < w[1]));
7513 assert!(body.contains("canned reply"));
7514
7515 let list = st.store.list().unwrap();
7516 assert_eq!(list.len(), 1);
7517 assert_eq!(list[0].messages, 2);
7518 }
7519
7520 #[tokio::test]
7524 async fn a_large_paste_is_one_chip_and_the_model_still_gets_the_text() {
7525 use eclipse_core::paste::{chip_for, expand, fits_inline, Paste, PASTE_INLINE_LIMIT};
7526
7527 let dir = tempfile::tempdir().unwrap();
7528 let st = state(dir.path(), true);
7529 let page = text(
7530 router(st.clone())
7531 .oneshot(get_req("/", "localhost:8787"))
7532 .await
7533 .unwrap(),
7534 )
7535 .await;
7536
7537 assert!(
7539 page.contains(&format!("data-paste-limit=\"{PASTE_INLINE_LIMIT}\"")),
7540 "the composer reads its limit from `eclipse_core::paste`"
7541 );
7542 assert!(
7543 !page.contains("{{PASTE_LIMIT}}"),
7544 "the placeholder was filled"
7545 );
7546 for needle in [
7549 "function fitsInline",
7550 "function chipFor",
7551 "function expandPastes",
7552 "addEventListener('paste'",
7553 "function userMessage",
7554 "PASTE_FOLD_LINES",
7555 ] {
7556 assert!(page.contains(needle), "the composer's paste rule: {needle}");
7557 }
7558
7559 let log: String = (1..=200).map(|i| format!("line {i}\n")).collect();
7562 assert!(!fits_inline(&log));
7563 let chip = chip_for(&log, 1);
7564 assert_eq!(
7566 chip,
7567 format!("[Pasted #1: 200 line(s), {} chars]", log.chars().count())
7568 );
7569 assert_eq!(
7570 expand(
7571 &format!("why is this failing? {chip}"),
7572 &[Paste {
7573 chip: chip.clone(),
7574 text: log.clone(),
7575 }]
7576 ),
7577 format!("why is this failing? {log}")
7578 );
7579
7580 let message = format!("here is the log:\n{log}");
7583 let resp = router(st.clone())
7584 .oneshot(chat_req(json!({ "message": message })))
7585 .await
7586 .unwrap();
7587 assert_eq!(resp.status(), StatusCode::OK);
7588 assert!(text(resp).await.contains("event: done"));
7589
7590 let list = st.store.list().unwrap();
7591 assert_eq!(list.len(), 1);
7592 let stored = st.store.load(&list[0].id).unwrap();
7593 let first = &stored[0];
7594 assert_eq!(first.role, eclipse_core::message::Role::User);
7595 let content = first.content.as_deref().unwrap_or_default();
7596 assert_eq!(content, message, "every character, and no chip");
7597 assert!(
7598 !content.contains("[Pasted"),
7599 "a chip is a display, not a message"
7600 );
7601 }
7602
7603 #[tokio::test]
7607 async fn a_body_over_the_limit_is_refused_by_name() {
7608 let dir = tempfile::tempdir().unwrap();
7609 let st = state(dir.path(), true);
7610 let too_big = CHAT_BODY_LIMIT * 2;
7611 let r = router(st)
7612 .oneshot(
7613 HttpRequest::post("/api/chat")
7614 .header("host", "127.0.0.1:8787")
7615 .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
7616 .header("content-type", "application/json")
7617 .header("content-length", too_big.to_string())
7618 .body(Body::empty())
7619 .unwrap(),
7620 )
7621 .await
7622 .unwrap();
7623 assert_eq!(r.status(), StatusCode::PAYLOAD_TOO_LARGE);
7624 let body = text(r).await;
7625 assert!(body.contains("that message is"), "{body}");
7626 let named = format!("{:.1} MB limit", CHAT_BODY_LIMIT as f64 / (1024.0 * 1024.0));
7629 assert!(
7630 body.contains(&named),
7631 "the limit is named in the sentence: {body}"
7632 );
7633 assert!(
7634 body.contains("smaller pictures") && body.contains("send its path"),
7635 "and so is what to do instead: {body}"
7636 );
7637
7638 let r = router(state(dir.path(), true))
7640 .oneshot(chat_req(json!({ "message": "small" })))
7641 .await
7642 .unwrap();
7643 assert_eq!(r.status(), StatusCode::OK);
7644 }
7645
7646 #[tokio::test]
7647 async fn chat_emits_a_delta_event_per_chunk_before_the_final_message() {
7648 let dir = tempfile::tempdir().unwrap();
7649 let store = SessionStore::new(dir.path().join("sessions"));
7650 let agent = Agent::new(
7651 Arc::new(Streaming),
7652 Arc::new(ToolRegistry::default()),
7653 store.clone(),
7654 "sys".into(),
7655 3,
7656 );
7657 let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
7658 let body = text(
7659 router(st)
7660 .oneshot(chat_req(json!({"message": "hi"})))
7661 .await
7662 .unwrap(),
7663 )
7664 .await;
7665 let at = |needle: &str| {
7666 body.find(needle)
7667 .unwrap_or_else(|| panic!("missing {needle} in {body}"))
7668 };
7669 assert_eq!(body.matches("event: delta").count(), 2);
7670 assert!(at("data: {\"text\":\"tok\"}") < at("data: {\"text\":\"ens\"}"));
7671 assert!(at("event: delta") < at("event: message"));
7672 assert!(body.contains("data: {\"text\":\"tokens\"}"));
7673 }
7674
7675 #[tokio::test]
7679 async fn the_stats_event_carries_the_numbers_the_footer_prints() {
7680 let dir = tempfile::tempdir().unwrap();
7681 let store = SessionStore::new(dir.path().join("sessions"));
7682 let agent = Agent::new(
7683 Arc::new(Measured),
7684 Arc::new(ToolRegistry::default()),
7685 store.clone(),
7686 "sys".into(),
7687 3,
7688 );
7689 let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
7690 let body = text(
7691 router(st)
7692 .oneshot(chat_req(json!({"message": "hi"})))
7693 .await
7694 .unwrap(),
7695 )
7696 .await;
7697 assert!(body.contains("event: stats"), "{body}");
7698 let stats = stats_payload(&body);
7699 assert_eq!(stats["prompt_tokens"], json!(30000));
7700 assert_eq!(stats["completion_tokens"], json!(120));
7701 assert_eq!(stats["cached_tokens"], json!(19000));
7702 assert_eq!(stats["latency_ms"], json!(2900));
7703 assert_eq!(
7704 stats["tokens_per_sec"],
7705 json!(48.0),
7706 "120 tokens over the 2.5 s the server timed"
7707 );
7708 assert!(
7709 stats["ttft_ms"].as_u64().unwrap_or(0) >= 20,
7710 "the client's own first-token time: {}",
7711 stats["ttft_ms"]
7712 );
7713 assert!(
7714 stats["context_tokens"].as_u64().unwrap() > 0,
7715 "the assembled prompt is a size, not a placeholder"
7716 );
7717 assert_eq!(
7718 stats["budget_tokens"],
7719 json!(0),
7720 "no budget set is 0, and the footer draws that as `ctx <used>` with no denominator"
7721 );
7722 assert_eq!(
7726 stats["ctx"],
7727 json!("ctx 30.0K tokens · no budget"),
7728 "the page's context field is the shared reading: {}",
7729 stats["ctx"]
7730 );
7731 assert_eq!(stats["window_tokens"], json!(0), "nobody stated a window");
7732 assert_eq!(
7733 stats["effort"],
7734 json!("not sent"),
7735 "this agent has no provider configuration, so nothing is sent — and the label says \
7736 that rather than naming a level"
7737 );
7738 assert_eq!(stats["effort_session"], json!(false), "nothing overrode it");
7739 assert!(
7740 !stats["effort_detail"].as_str().unwrap_or("").is_empty(),
7741 "the long sentence travels for the row's title: {}",
7742 stats["effort_detail"]
7743 );
7744 assert!(
7745 INDEX_HTML.contains(
7746 "case 'stats':\n // A turn in flight is the one row that is current"
7747 ) && INDEX_HTML.contains("paintLive(data);")
7748 && INDEX_HTML.contains("if (data.effort) setEffort("),
7749 "the page has to put the event in the bar, or the numbers go nowhere"
7750 );
7751 }
7752
7753 #[tokio::test]
7758 async fn the_context_bar_ends_at_the_window_and_marks_the_threshold_inside_it() {
7759 let dir = tempfile::tempdir().unwrap();
7760 let store = SessionStore::new(dir.path().join("sessions"));
7761 let agent = Agent::new(
7762 Arc::new(Measured),
7763 Arc::new(ToolRegistry::default()),
7764 store.clone(),
7765 "sys".into(),
7766 3,
7767 )
7768 .with_context_policy(0.85, 20, 328_000, 120_000);
7770 let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
7771 let body = text(
7772 router(st)
7773 .oneshot(chat_req(json!({"message": "hi"})))
7774 .await
7775 .unwrap(),
7776 )
7777 .await;
7778 let stats = stats_payload(&body);
7779 assert_eq!(
7780 stats["window_tokens"],
7781 json!(328_000),
7782 "the window is the end"
7783 );
7784 let ctx = stats["ctx"].as_str().unwrap_or_default();
7785 assert!(
7786 ctx.starts_with("ctx 30.0K/328K "),
7787 "the prompt out of the window, not out of the rail: {ctx}"
7788 );
7789 assert!(
7790 ctx.contains('│'),
7791 "the compaction threshold is a mark inside the bar, not its end: {ctx}"
7792 );
7793 assert!(
7794 ctx.ends_with(" 9%"),
7795 "the same percentage the CLI prints: {ctx}"
7796 );
7797 assert!(!ctx.contains("compacts at"));
7800 }
7801
7802 fn stats_payload(body: &str) -> serde_json::Value {
7804 let data = body
7805 .lines()
7806 .skip_while(|l| *l != "event: stats")
7807 .nth(1)
7808 .and_then(|l| l.strip_prefix("data: "))
7809 .unwrap_or_else(|| panic!("no stats event in {body}"));
7810 serde_json::from_str(data).unwrap()
7811 }
7812
7813 #[tokio::test]
7816 async fn a_silent_server_sends_nulls_and_the_footer_draws_dashes_for_them() {
7817 let dir = tempfile::tempdir().unwrap();
7818 let st = state(dir.path(), true);
7819 let body = text(
7820 router(st)
7821 .oneshot(chat_req(json!({"message": "hi"})))
7822 .await
7823 .unwrap(),
7824 )
7825 .await;
7826 for needle in [
7827 "\"cached_tokens\":null",
7828 "\"ttft_ms\":null",
7829 "\"tokens_per_sec\":null",
7830 "\"prompt_tokens\":null",
7831 ] {
7832 assert!(
7833 body.contains(needle),
7834 "an unreported field is null, never a made-up number: {needle} in {body}"
7835 );
7836 }
7837 for needle in [
7838 "id=\"stats\"",
7839 "const UNKNOWN = '--'",
7840 "const ctx = d.ctx || 'ctx --';",
7843 "'first ' + duration(d.ttft_ms)",
7844 ] {
7845 assert!(INDEX_HTML.contains(needle), "the page draws {needle}");
7846 }
7847 }
7848
7849 #[tokio::test]
7853 async fn reasoning_and_argument_fragments_are_their_own_events_before_the_reply() {
7854 let dir = tempfile::tempdir().unwrap();
7855 let store = SessionStore::new(dir.path().join("sessions"));
7856 let agent = Agent::new(
7857 Arc::new(ThinksAloud),
7858 Arc::new(ToolRegistry::default()),
7859 store.clone(),
7860 "sys".into(),
7861 3,
7862 );
7863 let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
7864 let body = text(
7865 router(st)
7866 .oneshot(chat_req(json!({"message": "hi"})))
7867 .await
7868 .unwrap(),
7869 )
7870 .await;
7871 let at = |needle: &str| {
7872 body.find(needle)
7873 .unwrap_or_else(|| panic!("missing {needle} in {body}"))
7874 };
7875 assert!(body.contains("event: reasoning"), "{body}");
7876 assert!(
7877 body.contains("data: {\"text\":\"weighing \"}")
7878 && body.contains("data: {\"text\":\"it\"}"),
7879 "each reasoning fragment is its own event: {body}"
7880 );
7881 assert!(
7882 body.contains("event: tool_call_delta")
7883 && body.contains("data: {\"index\":0,\"json\":\"{\\\"path\\\"\"}"),
7884 "the argument fragment keeps its call index: {body}"
7885 );
7886 assert!(
7887 at("event: reasoning") < at("event: tool_call_delta"),
7888 "reasoning comes before the call it explains"
7889 );
7890 assert!(at("event: tool_call_delta") < at("event: message"));
7891 for handler in [
7894 "case 'reasoning'",
7895 "case 'tool_call_delta'",
7896 "addThinking(",
7897 "addCall(",
7898 ] {
7899 assert!(INDEX_HTML.contains(handler), "the page handles {handler}");
7900 }
7901 for rule in ["details.reasoning", "details.tool", "#thinkall"] {
7903 assert!(INDEX_HTML.contains(rule), "the page styles {rule}");
7904 }
7905 assert!(
7906 INDEX_HTML.contains("function addThinking") && INDEX_HTML.contains("function addCall"),
7907 "a reload rebuilds the same folds the stream built"
7908 );
7909 assert!(
7910 INDEX_HTML.contains("m.reasoning_content"),
7911 "a reloaded session shows the reasoning it stored"
7912 );
7913 }
7914
7915 struct ThinksAloud;
7918
7919 #[async_trait]
7920 impl ChatProvider for ThinksAloud {
7921 async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
7922 unreachable!()
7923 }
7924 async fn chat_stream(
7925 &self,
7926 _: &[Message],
7927 _: &[ToolSpec],
7928 on_delta: eclipse_core::stream::DeltaFn<'_>,
7929 ) -> CoreResult<Message> {
7930 on_delta(eclipse_core::stream::Delta::Reasoning("weighing ".into()));
7931 on_delta(eclipse_core::stream::Delta::Reasoning("it".into()));
7932 on_delta(eclipse_core::stream::Delta::ToolCallArgs {
7933 index: 0,
7934 json: "{\"path\"".into(),
7935 });
7936 on_delta(eclipse_core::stream::Delta::Text("done".into()));
7937 Ok(Message::assistant("done"))
7938 }
7939 }
7940
7941 #[tokio::test]
7942 async fn context_trimmed_event_reports_the_judgement_pass_and_the_handoff() {
7943 let dir = tempfile::tempdir().unwrap();
7944 let store = SessionStore::new(dir.path().join("sessions"));
7945 for i in 0..3 {
7946 store
7947 .append("s", &Message::user(format!("old{i} {}", "y".repeat(400))))
7948 .unwrap();
7949 store.append("s", &Message::assistant("ok")).unwrap();
7950 }
7951 let agent = Agent::new(
7952 Arc::new(Canned),
7953 Arc::new(ToolRegistry::default()),
7954 store.clone(),
7955 "sys".into(),
7956 3,
7957 )
7958 .with_context_budget(150)
7959 .with_judgement(false, std::time::Duration::from_secs(1));
7960 let st = Arc::new(authed(Some(Arc::new(agent)), store, "m", None));
7961 let body = text(
7962 router(st)
7963 .oneshot(chat_req(json!({"message": "hi", "session_id": "s"})))
7964 .await
7965 .unwrap(),
7966 )
7967 .await;
7968 assert!(body.contains("event: context_trimmed"), "{body}");
7969 assert!(
7972 body.contains("\"judgement\":\"off\"")
7973 && body.contains("\"judgement_bullets\":0")
7974 && body.contains("\"judgement_error\":null"),
7975 "{body}"
7976 );
7977 assert!(
7978 body.contains("\"memory\":\"saved\"") && body.contains("\"memory_error\":null"),
7979 "{body}"
7980 );
7981 assert!(
7982 !body.contains("summarized") && !body.contains("summary_error"),
7983 "the summary path is gone from the wire too: {body}"
7984 );
7985 assert!(body.contains("event: message"));
7986 }
7987
7988 fn approval_app(dir: &std::path::Path, timeout: Duration) -> (Router, Shared) {
7990 use eclipse_core::config::ToolsConfig;
7991 std::fs::create_dir_all(dir.join("ws")).unwrap();
7992 let store = SessionStore::new(dir.join("sessions"));
7993 let call = Message::assistant_tool_calls(
7994 None,
7995 vec![eclipse_core::message::ToolCall {
7996 id: "c1".into(),
7997 kind: "function".into(),
7998 function: eclipse_core::message::FunctionCall {
7999 name: "write_file".into(),
8000 arguments: r#"{"path":"o.txt","content":"x"}"#.into(),
8001 },
8002 }],
8003 );
8004 let cfg = ToolsConfig {
8007 write_file: eclipse_core::config::Policy::Ask,
8008 ..ToolsConfig::default()
8009 };
8010 let agent = Agent::new(
8011 Scripted::new(vec![call, Message::assistant("finished")]),
8012 Arc::new(ToolRegistry::from_config(&cfg, dir.join("ws"))),
8013 store.clone(),
8014 "sys".into(),
8015 4,
8016 );
8017 let st = Arc::new(
8018 authed(Some(Arc::new(agent)), store, "m", None).with_approval_timeout(timeout),
8019 );
8020 (router(st.clone()), st)
8021 }
8022
8023 async fn read_until(
8024 body: &mut (impl Stream<Item = Result<axum::body::Bytes, axum::Error>> + Unpin),
8025 seen: &mut String,
8026 needle: &str,
8027 ) {
8028 while !seen.contains(needle) {
8029 let chunk = tokio::time::timeout(Duration::from_secs(5), body.next())
8030 .await
8031 .unwrap_or_else(|_| panic!("timed out waiting for {needle} in {seen}"))
8032 .unwrap_or_else(|| panic!("stream ended before {needle}: {seen}"))
8033 .unwrap();
8034 seen.push_str(&String::from_utf8_lossy(&chunk));
8035 }
8036 }
8037
8038 fn request_id(seen: &str) -> String {
8040 let at = seen.find("event: approval_request").unwrap();
8041 let data = seen[at..]
8042 .lines()
8043 .nth(1)
8044 .unwrap()
8045 .trim_start_matches("data: ");
8046 serde_json::from_str::<serde_json::Value>(data).unwrap()["id"]
8047 .as_str()
8048 .unwrap()
8049 .to_string()
8050 }
8051
8052 fn decision_req(id: &str, body: serde_json::Value) -> HttpRequest<Body> {
8053 HttpRequest::post(format!("/api/approvals/{id}"))
8054 .header("host", "127.0.0.1:8787")
8055 .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
8056 .header("content-type", "application/json")
8057 .body(Body::from(body.to_string()))
8058 .unwrap()
8059 }
8060
8061 async fn run_with_decision(approved: bool) -> (String, bool, usize) {
8062 let dir = tempfile::tempdir().unwrap();
8063 let (app, st) = approval_app(dir.path(), Duration::from_secs(30));
8064 let resp = app
8065 .clone()
8066 .oneshot(chat_req(json!({"message": "write it"})))
8067 .await
8068 .unwrap();
8069 let mut body = resp.into_body().into_data_stream();
8070 let mut seen = String::new();
8071 read_until(&mut body, &mut seen, "event: approval_request").await;
8072 read_until(&mut body, &mut seen, "\"tool\":\"write_file\"}").await;
8073 let id = request_id(&seen);
8074 assert!(!dir.path().join("ws/o.txt").exists());
8076 let r = app
8077 .clone()
8078 .oneshot(decision_req(&id, json!({"approved": approved})))
8079 .await
8080 .unwrap();
8081 assert_eq!(r.status(), StatusCode::OK);
8082 while let Some(chunk) = body.next().await {
8083 seen.push_str(&String::from_utf8_lossy(&chunk.unwrap()));
8084 }
8085 let again = app
8087 .oneshot(decision_req(&id, json!({"approved": true})))
8088 .await
8089 .unwrap();
8090 assert_eq!(again.status(), StatusCode::NOT_FOUND);
8091 let written = dir.path().join("ws/o.txt").exists();
8092 (seen, written, st.approvals.len())
8093 }
8094
8095 #[tokio::test]
8096 async fn approving_an_ask_tool_in_the_ui_runs_it() {
8097 let (events, written, pending) = run_with_decision(true).await;
8098 assert!(written, "{events}");
8099 assert!(events.contains(r#""outcome":"approved""#), "{events}");
8100 assert!(events.contains("event: done") && events.contains("finished"));
8101 assert_eq!(pending, 0);
8102 assert!(
8105 events.contains(r#""summary":"write_file o.txt · 1 B""#),
8106 "the call's statement travels with it: {events}"
8107 );
8108 }
8109
8110 #[tokio::test]
8111 async fn denying_an_ask_tool_in_the_ui_declines_it_and_the_run_continues() {
8112 let (events, written, pending) = run_with_decision(false).await;
8113 assert!(!written, "{events}");
8114 assert!(events.contains(r#""outcome":"denied""#), "{events}");
8115 assert!(events.contains("declined"), "{events}");
8116 assert!(events.contains("finished"));
8117 assert_eq!(pending, 0);
8118 }
8119
8120 #[tokio::test]
8121 async fn unanswered_approval_times_out_declined_and_is_cleaned_up() {
8122 let dir = tempfile::tempdir().unwrap();
8123 let (app, st) = approval_app(dir.path(), Duration::from_millis(100));
8124 let resp = app
8125 .clone()
8126 .oneshot(chat_req(json!({"message": "write it"})))
8127 .await
8128 .unwrap();
8129 let events = text(resp).await;
8130 assert!(events.contains(r#""outcome":"timeout""#), "{events}");
8131 assert!(events.contains("declined") && events.contains("event: done"));
8132 assert!(!dir.path().join("ws/o.txt").exists());
8133 assert_eq!(st.approvals.len(), 0);
8134 let id = request_id(&events);
8135 let late = app
8136 .oneshot(decision_req(&id, json!({"approved": true})))
8137 .await
8138 .unwrap();
8139 assert_eq!(late.status(), StatusCode::NOT_FOUND);
8140 assert!(!dir.path().join("ws/o.txt").exists());
8141 }
8142
8143 #[tokio::test]
8144 async fn disconnecting_while_an_approval_is_pending_frees_the_run() {
8145 let dir = tempfile::tempdir().unwrap();
8146 let (app, st) = approval_app(dir.path(), Duration::from_secs(60));
8147 let resp = app
8148 .oneshot(chat_req(json!({"message": "write it"})))
8149 .await
8150 .unwrap();
8151 let mut body = resp.into_body().into_data_stream();
8152 let mut seen = String::new();
8153 read_until(&mut body, &mut seen, "event: approval_request").await;
8154 assert_eq!(st.approvals.len(), 1);
8155 drop(body);
8156 for _ in 0..100 {
8157 if st.approvals.len() == 0 && st.chat_slots.available_permits() == MAX_CONCURRENT_CHATS
8158 {
8159 break;
8160 }
8161 tokio::time::sleep(Duration::from_millis(20)).await;
8162 }
8163 assert_eq!(st.approvals.len(), 0);
8164 assert_eq!(st.chat_slots.available_permits(), MAX_CONCURRENT_CHATS);
8165 assert!(!dir.path().join("ws/o.txt").exists());
8166 }
8167
8168 #[tokio::test]
8169 async fn approval_endpoint_rejects_bad_ids_and_bodies() {
8170 let dir = tempfile::tempdir().unwrap();
8171 let (app, _) = approval_app(dir.path(), Duration::from_secs(1));
8172 let r = app
8173 .clone()
8174 .oneshot(decision_req("deadbeef", json!({"approved": true})))
8175 .await
8176 .unwrap();
8177 assert_eq!(r.status(), StatusCode::NOT_FOUND);
8178 let r = app
8179 .clone()
8180 .oneshot(decision_req("not-hex!", json!({"approved": true})))
8181 .await
8182 .unwrap();
8183 assert_eq!(r.status(), StatusCode::BAD_REQUEST);
8184 let r = app
8185 .clone()
8186 .oneshot(decision_req("deadbeef", json!({"approve": true})))
8187 .await
8188 .unwrap();
8189 assert!(r.status().is_client_error());
8190 }
8191
8192 #[tokio::test]
8193 async fn chat_validates_input_and_configuration() {
8194 let dir = tempfile::tempdir().unwrap();
8195 let app = router(state(dir.path(), true));
8196 let r = app
8197 .clone()
8198 .oneshot(chat_req(json!({"message": " "})))
8199 .await
8200 .unwrap();
8201 assert_eq!(r.status(), StatusCode::BAD_REQUEST);
8202 let r = app
8203 .clone()
8204 .oneshot(chat_req(json!({"message": "x", "session_id": "../x"})))
8205 .await
8206 .unwrap();
8207 assert_eq!(r.status(), StatusCode::BAD_REQUEST);
8208 let r = app
8212 .clone()
8213 .oneshot(chat_req(json!({"message": "/bg count the files"})))
8214 .await
8215 .unwrap();
8216 assert_eq!(r.status(), StatusCode::OK);
8217 let said = text(r).await;
8218 assert!(
8219 said.contains("only in the full-screen interface and the plain REPL"),
8220 "{said}"
8221 );
8222
8223 let r = router(state(dir.path(), false))
8224 .oneshot(chat_req(json!({"message": "x"})))
8225 .await
8226 .unwrap();
8227 assert_eq!(r.status(), StatusCode::SERVICE_UNAVAILABLE);
8228 assert!(text(r).await.contains("base_url"));
8229 }
8230
8231 #[tokio::test]
8232 async fn renamed_sessions_show_their_title() {
8233 let dir = tempfile::tempdir().unwrap();
8234 let st = state(dir.path(), true);
8235 st.store
8236 .append("s1", &Message::user("first words"))
8237 .unwrap();
8238 st.store.rename("s1", "Trip <plan>").unwrap();
8239 let app = router(st);
8240 let html = text(
8241 app.clone()
8242 .oneshot(get_req("/", "127.0.0.1:1"))
8243 .await
8244 .unwrap(),
8245 )
8246 .await;
8247 assert!(
8248 html.contains("data-id=\"s1\"") && html.contains("class=\"name\">Trip <plan>"),
8249 "{html}"
8250 );
8251 let r = app
8252 .clone()
8253 .oneshot(get_req("/api/sessions", "127.0.0.1:1"))
8254 .await
8255 .unwrap();
8256 let v: serde_json::Value = serde_json::from_str(&text(r).await).unwrap();
8257 assert_eq!(v[0]["title"], "Trip <plan>");
8258 assert_eq!(v[0]["preview"], "first words");
8259 }
8260
8261 #[tokio::test]
8262 async fn search_finds_the_message_and_names_its_session() {
8263 let dir = tempfile::tempdir().unwrap();
8264 let st = state(dir.path(), true);
8265 st.store
8266 .append("s1", &Message::user("the quick brown fox"))
8267 .unwrap();
8268 st.store
8269 .append("s2", &Message::user("nothing here"))
8270 .unwrap();
8271 let app = router(st);
8272
8273 for path in ["/api/search", "/api/search?q=", "/api/search?q=%20%20"] {
8275 let r = app
8276 .clone()
8277 .oneshot(get_req(path, "127.0.0.1:1"))
8278 .await
8279 .unwrap();
8280 assert_eq!(r.status(), StatusCode::OK, "{path}");
8281 assert_eq!(text(r).await.trim(), "[]", "{path}");
8282 }
8283
8284 let r = app
8285 .clone()
8286 .oneshot(get_req("/api/search?q=brown", "127.0.0.1:1"))
8287 .await
8288 .unwrap();
8289 assert_eq!(r.status(), StatusCode::OK);
8290 let body = text(r).await;
8291 assert!(body.contains("\"s1\""), "{body}");
8292 assert!(
8293 !body.contains("\"s2\""),
8294 "only the matching session: {body}"
8295 );
8296 assert!(
8297 body.contains("brown"),
8298 "the snippet carries the match: {body}"
8299 );
8300 assert!(
8301 body.contains("\"seq\":0"),
8302 "the hit says where it is: {body}"
8303 );
8304
8305 let r = app
8307 .clone()
8308 .oneshot(get_req("/api/search?q=zebra", "127.0.0.1:1"))
8309 .await
8310 .unwrap();
8311 assert_eq!(text(r).await.trim(), "[]");
8312 }
8313
8314 #[tokio::test]
8315 async fn search_demands_a_login_like_everything_else() {
8316 let dir = tempfile::tempdir().unwrap();
8317 let st = state(dir.path(), false);
8318 let app = router(st);
8319 let req = HttpRequest::get("/api/search?q=anything")
8321 .header("host", "127.0.0.1:1")
8322 .body(Body::empty())
8323 .unwrap();
8324 let r = app.oneshot(req).await.unwrap();
8325 assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
8326 }
8327
8328 #[test]
8329 fn the_page_has_a_cron_pane_that_talks_to_the_cron_routes() {
8330 for needle in [
8331 "id=\"cron\"",
8332 "id=\"cronpane\"",
8333 "id=\"cronrows\"",
8334 "id=\"cronform\"",
8335 "id=\"cr-schedule\"",
8336 ] {
8337 assert!(INDEX_HTML.contains(needle), "the pane has {needle}");
8338 }
8339 for route in [
8341 "'/api/cron'",
8342 "'/api/cron/' + encodeURIComponent(name) + '/run'",
8343 "'/api/cron/' + encodeURIComponent(name) + '/enabled'",
8344 "'/api/cron/' + encodeURIComponent(name) + '/logs?limit=3'",
8345 ] {
8346 assert!(INDEX_HTML.contains(route), "the pane calls {route}");
8347 }
8348 assert!(!INDEX_HTML.contains("cronRows.innerHTML"));
8351 assert!(INDEX_HTML.contains("pre.textContent = body.trim()"));
8352 }
8353
8354 #[test]
8355 fn the_page_has_a_find_box_that_draws_hits_as_text() {
8356 assert!(INDEX_HTML.contains("id=\"find\""), "a box to type in");
8357 assert!(INDEX_HTML.contains("/api/search?q="), "wired to the route");
8358 assert!(INDEX_HTML.contains("snip.textContent ="));
8360 assert!(
8361 !INDEX_HTML.contains("list.innerHTML"),
8362 "no markup is rebuilt from data"
8363 );
8364 }
8365
8366 #[tokio::test]
8367 async fn search_is_bounded_and_says_so() {
8368 let dir = tempfile::tempdir().unwrap();
8369 let st = state(dir.path(), true);
8370 for i in 0..5 {
8371 st.store
8372 .append(&format!("s{i}"), &Message::user("repeated needle"))
8373 .unwrap();
8374 }
8375 let app = router(st);
8376 let r = app
8377 .clone()
8378 .oneshot(get_req("/api/search?q=needle&limit=2", "127.0.0.1:1"))
8379 .await
8380 .unwrap();
8381 let body = text(r).await;
8382 let hits: serde_json::Value = serde_json::from_str(&body).unwrap();
8383 assert_eq!(hits.as_array().unwrap().len(), 2, "{body}");
8384
8385 let r = app
8387 .clone()
8388 .oneshot(get_req("/api/search?q=needle&limit=99999", "127.0.0.1:1"))
8389 .await
8390 .unwrap();
8391 let body = text(r).await;
8392 let hits: serde_json::Value = serde_json::from_str(&body).unwrap();
8393 assert!(hits.as_array().unwrap().len() <= 100, "{body}");
8394 }
8395
8396 #[tokio::test]
8397 async fn the_picker_lists_what_the_endpoint_serves_and_names_the_one_in_use() {
8398 let dir = tempfile::tempdir().unwrap();
8399 let base = serve_models(&[("small", None), ("big", None)]).await;
8400 let (st, _agent) = provider_state(dir.path(), &base, "small");
8401 let app = router(st);
8402 let r = app
8403 .clone()
8404 .oneshot(get_req("/api/models", "127.0.0.1:8787"))
8405 .await
8406 .unwrap();
8407 assert_eq!(r.status(), StatusCode::OK);
8408 let body = text(r).await;
8409 let v: serde_json::Value = serde_json::from_str(&body).unwrap();
8410 assert_eq!(v["models"], json!(["small", "big"]), "{body}");
8411 assert_eq!(v["model"], "small", "the one the next turn uses: {body}");
8412 assert_eq!(v["configured"], "small", "{body}");
8413 }
8414
8415 #[tokio::test]
8416 async fn choosing_a_model_changes_the_next_turn_and_leaves_the_file_alone() {
8417 let dir = tempfile::tempdir().unwrap();
8418 let (st, agent) = provider_state(dir.path(), "http://127.0.0.1:9/v1", "configured");
8421 let app = router(st);
8422 let r = app
8423 .clone()
8424 .oneshot(model_req(json!({ "model": "picked" })))
8425 .await
8426 .unwrap();
8427 assert_eq!(r.status(), StatusCode::OK);
8428 let body = text(r).await;
8429 assert!(body.contains("\"model\":\"picked\""), "{body}");
8430 assert_eq!(agent.model().as_deref(), Some("picked"));
8431
8432 let page = text(
8434 app.clone()
8435 .oneshot(get_req("/", "127.0.0.1:8787"))
8436 .await
8437 .unwrap(),
8438 )
8439 .await;
8440 assert!(
8442 page.contains(">picked</button>") || page.contains(">picked\n"),
8443 "the model button follows the choice: {page:.0}"
8444 );
8445
8446 let r = app
8449 .clone()
8450 .oneshot(model_req(json!({ "model": null })))
8451 .await
8452 .unwrap();
8453 assert_eq!(r.status(), StatusCode::OK);
8454 assert_eq!(agent.model().as_deref(), Some("configured"));
8455 assert!(dir.path().join("sessions").exists(), "state untouched");
8456
8457 assert!(!dir.path().join("config.toml").exists());
8459 }
8460
8461 #[tokio::test]
8462 async fn a_body_that_names_no_model_is_refused_rather_than_read_as_a_reset() {
8463 let dir = tempfile::tempdir().unwrap();
8464 let (st, agent) = provider_state(dir.path(), "http://127.0.0.1:9/v1", "configured");
8465 let app = router(st);
8466 for body in [json!({}), json!({ "model": " " }), json!({ "model": "" })] {
8467 let r = app.clone().oneshot(model_req(body.clone())).await.unwrap();
8468 assert_eq!(r.status(), StatusCode::BAD_REQUEST, "{body}");
8469 }
8470 assert_eq!(agent.model().as_deref(), Some("configured"));
8471 }
8472
8473 #[tokio::test]
8474 async fn a_model_cannot_be_picked_on_an_agent_with_no_provider_configuration() {
8475 let dir = tempfile::tempdir().unwrap();
8476 let app = router(state(dir.path(), true));
8479 let r = app
8480 .clone()
8481 .oneshot(model_req(json!({ "model": "picked" })))
8482 .await
8483 .unwrap();
8484 assert_eq!(r.status(), StatusCode::BAD_REQUEST);
8485 assert!(
8486 text(r)
8487 .await
8488 .contains("not built from a provider configuration"),
8489 "the reason says what is missing"
8490 );
8491 }
8492
8493 #[tokio::test]
8494 async fn an_endpoint_that_cannot_be_reached_says_so_instead_of_listing_nothing() {
8495 let dir = tempfile::tempdir().unwrap();
8496 let (st, _agent) = provider_state(dir.path(), "http://127.0.0.1:9/v1", "m");
8497 let app = router(st);
8498 let r = app
8499 .clone()
8500 .oneshot(get_req("/api/models", "127.0.0.1:8787"))
8501 .await
8502 .unwrap();
8503 assert_eq!(r.status(), StatusCode::BAD_GATEWAY);
8504 let body = text(r).await;
8505 assert!(body.contains("\"error\""), "{body}");
8506 }
8507
8508 #[tokio::test]
8513 async fn a_command_needs_no_provider() {
8514 let dir = tempfile::tempdir().unwrap();
8515 let app = router(state(dir.path(), false));
8517
8518 let events = notices(
8519 app.clone()
8520 .oneshot(chat_req(json!({"message": "/help"})))
8521 .await
8522 .unwrap(),
8523 )
8524 .await;
8525 assert_eq!(events[0].1["kind"], json!("command"), "{events:?}");
8526 assert!(events[0].1["text"].as_str().unwrap().contains("/settings"));
8527
8528 let events = notices(
8530 app.clone()
8531 .oneshot(chat_req(json!({"message": "/model"})))
8532 .await
8533 .unwrap(),
8534 )
8535 .await;
8536 assert_eq!(events[0].1["kind"], json!("refusal"));
8537 assert!(events[0].1["text"]
8538 .as_str()
8539 .unwrap()
8540 .contains("provider.base_url"));
8541
8542 let r = app
8544 .clone()
8545 .oneshot(chat_req(json!({"message": "hello"})))
8546 .await
8547 .unwrap();
8548 assert_eq!(r.status(), StatusCode::SERVICE_UNAVAILABLE);
8549 }
8550
8551 async fn notices(resp: Response) -> Vec<(String, serde_json::Value)> {
8553 let body = text(resp).await;
8554 let mut out = Vec::new();
8555 for block in body.split("\n\n") {
8556 let mut event = "message".to_string();
8557 let mut data = String::new();
8558 for line in block.split('\n') {
8559 if let Some(rest) = line.strip_prefix("event:") {
8560 event = rest.trim().to_string();
8561 } else if let Some(rest) = line.strip_prefix("data:") {
8562 data.push_str(rest.trim());
8563 }
8564 }
8565 if !data.is_empty() {
8566 out.push((event, serde_json::from_str(&data).unwrap_or_default()));
8567 }
8568 }
8569 out
8570 }
8571
8572 #[tokio::test]
8576 async fn a_bang_line_is_refused_and_nothing_runs() {
8577 let dir = tempfile::tempdir().unwrap();
8578 let cfg = eclipse_core::config::ProviderConfig {
8579 base_url: "http://127.0.0.1:9/v1".into(),
8580 model: "m".into(),
8581 ..Default::default()
8582 };
8583 let (st, _agent) = agent_state(dir.path(), cfg, Default::default());
8584 let app = router(st);
8585
8586 for line in ["!ls", " !rm -rf /", "!!echo hi"] {
8587 let events = notices(
8588 app.clone()
8589 .oneshot(chat_req(json!({ "message": line })))
8590 .await
8591 .unwrap(),
8592 )
8593 .await;
8594 assert_eq!(events.len(), 2, "{line}: {events:?}");
8595 assert_eq!(events[0].0, "notice", "{line}");
8596 assert_eq!(events[0].1["kind"], json!("refusal"), "{line}: {events:?}");
8597 let said = events[0].1["text"].as_str().unwrap();
8598 assert!(said.contains("terminal and nowhere else"), "{line}: {said}");
8599 assert_eq!(events[1].0, "done", "{line}: the composer returns to idle");
8601 assert!(
8602 !events
8603 .iter()
8604 .any(|(kind, _)| kind == "session" || kind == "error"),
8605 "{line}: nothing was started"
8606 );
8607 }
8608
8609 let r = app
8613 .clone()
8614 .oneshot(chat_req(json!({ "message": "fix the bug!" })))
8615 .await
8616 .unwrap();
8617 assert_eq!(r.status(), StatusCode::OK, "a message is a message");
8618 let events = notices(r).await;
8619 assert!(
8620 !events
8621 .iter()
8622 .any(|(_, data)| data["kind"] == json!("refusal")),
8623 "prose is not refused by the bang rule: {events:?}"
8624 );
8625 }
8626
8627 #[tokio::test]
8631 async fn the_composer_speaks_the_table_and_a_command_is_a_row() {
8632 let dir = tempfile::tempdir().unwrap();
8633 let cfg = eclipse_core::config::ProviderConfig {
8634 base_url: "http://127.0.0.1:9/v1".into(),
8635 model: "m".into(),
8636 ..Default::default()
8637 };
8638 let (st, agent) = agent_state(dir.path(), cfg, Default::default());
8639 let app = router(st);
8640
8641 let events = notices(
8644 app.clone()
8645 .oneshot(chat_req(json!({"message": "/help"})))
8646 .await
8647 .unwrap(),
8648 )
8649 .await;
8650 assert_eq!(events.len(), 2, "{events:?}");
8651 assert_eq!(events[0].0, "notice");
8652 assert_eq!(events[1].0, "done", "the composer returns to idle");
8653 let help = events[0].1["text"].as_str().unwrap();
8654 assert_eq!(events[0].1["kind"], json!("command"));
8655 assert!(help.contains("/reasoning"), "{help}");
8656 assert!(!help.contains("!command"), "no bang in a browser: {help}");
8657 assert!(
8658 !help.contains("/resume"),
8659 "a terminal-only verb is not in this list: {help}"
8660 );
8661
8662 let events = notices(
8665 app.clone()
8666 .oneshot(chat_req(json!({"message": "/reasoning"})))
8667 .await
8668 .unwrap(),
8669 )
8670 .await;
8671 assert!(events[0].1["text"]
8672 .as_str()
8673 .unwrap()
8674 .contains("effort: medium"));
8675 let events = notices(
8676 app.clone()
8677 .oneshot(chat_req(json!({"message": "/reasoning high"})))
8678 .await
8679 .unwrap(),
8680 )
8681 .await;
8682 assert!(events[0].1["text"]
8683 .as_str()
8684 .unwrap()
8685 .contains("effort: high"));
8686 assert_eq!(agent.reasoning().effort(), Some("high".to_string()));
8687
8688 let events = notices(
8690 app.clone()
8691 .oneshot(chat_req(json!({"message": "/reasoning none"})))
8692 .await
8693 .unwrap(),
8694 )
8695 .await;
8696 assert_eq!(events[0].1["kind"], json!("refusal"));
8697 assert!(events[0].1["text"]
8698 .as_str()
8699 .unwrap()
8700 .contains("this route takes"));
8701
8702 let events = notices(
8704 app.clone()
8705 .oneshot(chat_req(json!({"message": "/resume"})))
8706 .await
8707 .unwrap(),
8708 )
8709 .await;
8710 assert_eq!(events[0].1["kind"], json!("refusal"));
8711 assert!(events[0].1["text"]
8712 .as_str()
8713 .unwrap()
8714 .contains("only in the full-screen interface"));
8715
8716 let events = notices(
8718 app.clone()
8719 .oneshot(chat_req(json!({"message": "/bg write me a poem"})))
8720 .await
8721 .unwrap(),
8722 )
8723 .await;
8724 assert!(events[0].1["text"]
8725 .as_str()
8726 .unwrap()
8727 .contains("only in the full-screen interface and the plain REPL"));
8728
8729 let events = notices(
8731 app.clone()
8732 .oneshot(chat_req(json!({"message": "/nope"})))
8733 .await
8734 .unwrap(),
8735 )
8736 .await;
8737 assert_eq!(events[0].1["kind"], json!("refusal"));
8738 assert_eq!(events[0].1["text"], json!("unknown command; try /help"));
8739
8740 let events = notices(
8742 app.clone()
8743 .oneshot(chat_req(json!({"message": "/new"})))
8744 .await
8745 .unwrap(),
8746 )
8747 .await;
8748 assert_eq!(events[0].1["clear_session"], json!(true));
8749 }
8750
8751 #[tokio::test]
8755 async fn yolo_in_the_dashboard_is_a_switch_the_page_can_show() {
8756 use eclipse_core::approvals::{Decision, Pending};
8757 use eclipse_core::tools::Approver;
8758
8759 let dir = tempfile::tempdir().unwrap();
8760 std::fs::write(
8761 dir.path().join("config.toml"),
8762 "[provider]\nbase_url = \"http://h:1/v1\"\nmodel = \"m\"\n",
8763 )
8764 .unwrap();
8765 let cfg = eclipse_core::config::ProviderConfig {
8766 base_url: "http://h:1/v1".into(),
8767 model: "m".into(),
8768 ..Default::default()
8769 };
8770 let (st, _agent) = agent_state(dir.path(), cfg, Default::default());
8771 let st = match Arc::try_unwrap(st) {
8772 Ok(st) => Arc::new(st.with_config_path(Some(dir.path().join("config.toml")), None)),
8773 Err(_) => panic!("a state built here is not shared yet"),
8774 };
8775 let app = router(st.clone());
8776
8777 assert!(!st.yolo.on());
8779 let Html(html) = index(State(st.clone()), HeaderMap::new()).await;
8782 assert!(
8783 html.contains("id=\"yolo\""),
8784 "the chip exists: {html:.4000}"
8785 );
8786 assert!(
8787 html.contains("id=\"yolo\" hidden"),
8788 "and it is hidden while approvals are on: {html:.4000}"
8789 );
8790
8791 let events = notices(
8793 app.clone()
8794 .oneshot(chat_req(json!({"message": "/yolo"})))
8795 .await
8796 .unwrap(),
8797 )
8798 .await;
8799 assert_eq!(events[0].1["kind"], json!("command"));
8800 let said = events[0].1["text"].as_str().unwrap();
8801 assert!(said.contains("approvals: auto"), "{said}");
8802 assert!(
8803 said.contains("config.toml"),
8804 "the promise is still there: {said}"
8805 );
8806 assert_eq!(
8807 events[0].1["yolo"],
8808 json!(true),
8809 "the page learns the state"
8810 );
8811
8812 let Html(html) = index(State(st.clone()), HeaderMap::new()).await;
8814 assert!(
8815 !html.contains("id=\"yolo\" hidden"),
8816 "a reload shows a mode that is still in force: {html:.4000}"
8817 );
8818
8819 let (tx, mut rx) = mpsc::unbounded_channel();
8821 let approver = WebApprover {
8822 state: st.clone(),
8823 run: 1,
8824 events: tx,
8825 };
8826 let call = Pending {
8827 call_id: "c1".into(),
8828 tool: "shell".into(),
8829 summary: "echo hi".into(),
8830 args: "{}".into(),
8831 };
8832 let decision = approver.decide(&call).await;
8833 assert!(
8834 matches!(decision, Decision::Allow),
8835 "with yolo on the call runs: {decision:?}"
8836 );
8837 assert!(
8838 rx.try_recv().is_err(),
8839 "and nothing was sent to the browser to click"
8840 );
8841 assert_eq!(
8842 st.unasked.load(std::sync::atomic::Ordering::Relaxed),
8843 1,
8844 "the count is the honest part"
8845 );
8846 assert!(st.approvals.lock().is_empty(), "nothing left waiting");
8847
8848 let events = notices(
8850 app.clone()
8851 .oneshot(chat_req(json!({"message": "/yolo off"})))
8852 .await
8853 .unwrap(),
8854 )
8855 .await;
8856 let said = events[0].1["text"].as_str().unwrap();
8857 assert!(said.contains("approvals: ask"), "{said}");
8858 assert!(
8859 said.contains("1 tool call"),
8860 "the count rides along: {said}"
8861 );
8862 assert_eq!(events[0].1["yolo"], json!(false));
8863
8864 let (tx, mut rx) = mpsc::unbounded_channel();
8866 let approver = WebApprover {
8867 state: st.clone(),
8868 run: 2,
8869 events: tx,
8870 };
8871 let call = Pending {
8872 call_id: "c2".into(),
8873 tool: "shell".into(),
8874 summary: "echo hi".into(),
8875 args: "{}".into(),
8876 };
8877 let asked = tokio::spawn(async move { approver.decide(&call).await });
8878 let id = match rx.recv().await.expect("an approval request") {
8880 Out::ApprovalRequest { id, .. } => id,
8881 Out::Event(_) | Out::Done | Out::Cancelled | Out::Failed(_) => {
8883 panic!("the approver did not ask before running the call")
8884 }
8885 Out::ApprovalResolved { .. } => {
8886 panic!("the approval resolved before it was sent")
8887 }
8888 };
8889 assert_eq!(
8890 st.unasked.load(std::sync::atomic::Ordering::Relaxed),
8891 1,
8892 "a parked call is not an unasked one"
8893 );
8894 let sender = st
8896 .approvals
8897 .lock()
8898 .remove(&id)
8899 .expect("the pending call")
8900 .decide;
8901 let _ = sender.send(true);
8902 assert!(
8903 matches!(asked.await.unwrap(), Decision::Allow),
8904 "an explicit yes is still an allow"
8905 );
8906 }
8907
8908 #[tokio::test]
8911 async fn a_verb_and_its_route_are_one_implementation() {
8912 use eclipse_core::config::ProviderConfig;
8913
8914 let dir = tempfile::tempdir().unwrap();
8915 let path = dir.path().join("config.toml");
8916 std::fs::write(
8917 &path,
8918 "[provider]\nbase_url = \"http://h:1/v1\"\nmodel = \"m\"\n",
8919 )
8920 .unwrap();
8921 let cfg = ProviderConfig {
8922 base_url: "http://h:1/v1".into(),
8923 model: "m".into(),
8924 ..Default::default()
8925 };
8926 let (st, agent) = agent_state(dir.path(), cfg, Default::default());
8927 let st = match Arc::try_unwrap(st) {
8928 Ok(st) => Arc::new(st.with_config_path(Some(path.clone()), None)),
8929 Err(_) => panic!("a state built here is not shared yet"),
8930 };
8931 let app = router(st);
8932
8933 let _ = notices(
8935 app.clone()
8936 .oneshot(chat_req(json!({"message": "/reasoning low"})))
8937 .await
8938 .unwrap(),
8939 )
8940 .await;
8941 let body = json_body(
8942 app.clone()
8943 .oneshot(get_req("/api/reasoning", "127.0.0.1:8787"))
8944 .await
8945 .unwrap(),
8946 )
8947 .await;
8948 assert_eq!(
8949 body["effort"],
8950 json!("low"),
8951 "the route sees the command's pick"
8952 );
8953
8954 let _ = notices(
8956 app.clone()
8957 .oneshot(chat_req(json!({"message": "/set provider.model other"})))
8958 .await
8959 .unwrap(),
8960 )
8961 .await;
8962 let text = std::fs::read_to_string(&path).unwrap();
8963 assert!(
8964 text.contains("model = \"other\""),
8965 "the file is the store: {text}"
8966 );
8967 let body = json_body(
8968 app.clone()
8969 .oneshot(get_req("/api/settings", "127.0.0.1:8787"))
8970 .await
8971 .unwrap(),
8972 )
8973 .await;
8974 let row = body["settings"]
8975 .as_array()
8976 .unwrap()
8977 .iter()
8978 .find(|r| r["key"] == json!("provider.model"))
8979 .expect("the key");
8980 assert_eq!(row["value"], json!("\"other\""));
8981
8982 let events = notices(
8984 app.clone()
8985 .oneshot(chat_req(json!({"message": "/model"})))
8986 .await
8987 .unwrap(),
8988 )
8989 .await;
8990 assert!(events[0].1["text"]
8991 .as_str()
8992 .unwrap()
8993 .contains("configured:"));
8994 let _ = agent;
8995 }
8996
8997 fn agent_state(
9000 dir: &std::path::Path,
9001 cfg: eclipse_core::config::ProviderConfig,
9002 plugins: eclipse_core::plugins::Plugins,
9003 ) -> (Shared, Arc<Agent>) {
9004 let store = SessionStore::new(dir.join("sessions"));
9005 let agent = Arc::new(
9006 Agent::new(
9007 Arc::new(Canned),
9008 Arc::new(ToolRegistry::default()),
9009 store.clone(),
9010 "sys".into(),
9011 3,
9012 )
9013 .with_provider_config(cfg)
9014 .with_plugins(plugins),
9015 );
9016 (
9017 Arc::new(authed(Some(agent.clone()), store, "m", None)),
9018 agent,
9019 )
9020 }
9021
9022 fn reasoning_req(body: serde_json::Value) -> HttpRequest<Body> {
9023 HttpRequest::post("/api/reasoning")
9024 .header("host", "127.0.0.1:8787")
9025 .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
9026 .header("content-type", "application/json")
9027 .body(Body::from(body.to_string()))
9028 .unwrap()
9029 }
9030
9031 async fn json_body(resp: Response) -> serde_json::Value {
9034 serde_json::from_str(&text(resp).await).expect("a JSON reply")
9035 }
9036
9037 #[tokio::test]
9042 async fn the_submenu_is_served_the_levels_this_route_takes() {
9043 use eclipse_core::config::ProviderConfig;
9044
9045 let dir = tempfile::tempdir().unwrap();
9046 let openai = ProviderConfig {
9047 base_url: "http://h:1/v1".into(),
9048 model: "m".into(),
9049 ..Default::default()
9050 };
9051 let (st, _agent) = agent_state(dir.path(), openai, Default::default());
9052 let body = json_body(
9053 router(st)
9054 .oneshot(get_req("/api/reasoning", "127.0.0.1:8787"))
9055 .await
9056 .unwrap(),
9057 )
9058 .await;
9059 assert_eq!(
9060 body["levels"],
9061 json!(["minimal", "low", "medium", "high"]),
9062 "four rungs, and no off switch to offer"
9063 );
9064 assert_eq!(
9065 body["effort"],
9066 json!("medium"),
9067 "the shipped default is what an unconfigured install reasons at"
9068 );
9069 assert_eq!(body["effort_default"], json!(true));
9070 assert_eq!(body["effort_session"], json!(false));
9071 assert!(
9072 body["configured"].is_null(),
9073 "the file sets nothing: {}",
9074 body["configured"]
9075 );
9076 assert_eq!(
9077 body["described"]["high"],
9078 json!("sends high"),
9079 "each row quotes the policy, so a clamp is visible before the click"
9080 );
9081 assert_eq!(body["off_word"], json!(null), "no off to offer");
9083 assert!(
9084 body["off_why"]
9085 .as_str()
9086 .unwrap_or_default()
9087 .contains("no off switch"),
9088 "and the switch's title carries the reason: {}",
9089 body["off_why"]
9090 );
9091
9092 let dir = tempfile::tempdir().unwrap();
9095 let llama = ProviderConfig {
9096 base_url: "http://h:1/v1".into(),
9097 model: "mmnuc/inkling-2-mini".into(),
9098 profile: Some("llamacpp".into()),
9099 ..Default::default()
9100 };
9101 let (st, _agent) = agent_state(dir.path(), llama, Default::default());
9102 let body = json_body(
9103 router(st)
9104 .oneshot(get_req("/api/reasoning", "127.0.0.1:8787"))
9105 .await
9106 .unwrap(),
9107 )
9108 .await;
9109 assert_eq!(body["levels"], json!(["low", "medium", "high", "none"]));
9110 assert_eq!(
9111 body["described"]["none"],
9112 json!("sends none"),
9113 "the off switch is named as the wire takes it"
9114 );
9115 assert_eq!(
9118 body["off_word"],
9119 json!("none"),
9120 "this route declares an off, so the switch is live"
9121 );
9122 assert_eq!(body["off_why"], json!(""));
9123
9124 let dir = tempfile::tempdir().unwrap();
9127 let plugins_dir = dir.path().join("plugins").join("provider-profile-bare");
9128 std::fs::create_dir_all(&plugins_dir).unwrap();
9129 std::fs::write(
9130 plugins_dir.join("plugin.toml"),
9131 "name = \"provider-profile-bare\"\nversion = \"0.1.0\"\napi = 1\n\
9132 description = \"a profile that declares no reasoning control\"\n\n\
9133 [[provider_profile]]\nname = \"bare\"\n",
9134 )
9135 .unwrap();
9136 let loaded = eclipse_core::plugins::load(&[dir.path().join("plugins")], &[]);
9137 let bare = ProviderConfig {
9138 base_url: "http://h:1/v1".into(),
9139 model: "m".into(),
9140 profile: Some("bare".into()),
9141 ..Default::default()
9142 };
9143 let (st, _agent) = agent_state(dir.path(), bare, loaded);
9144 let body = json_body(
9145 router(st)
9146 .oneshot(get_req("/api/reasoning", "127.0.0.1:8787"))
9147 .await
9148 .unwrap(),
9149 )
9150 .await;
9151 assert_eq!(
9152 body["levels"],
9153 json!([]),
9154 "nothing to offer is the honest list for this backend"
9155 );
9156 assert!(
9157 body["note"]
9158 .as_str()
9159 .unwrap_or_default()
9160 .contains("declares no reasoning control"),
9161 "and the menu says why: {}",
9162 body["note"]
9163 );
9164 }
9165
9166 #[tokio::test]
9170 async fn a_pick_changes_the_next_request_body_and_nothing_else() {
9171 use eclipse_core::config::ProviderConfig;
9172
9173 let seen: Arc<Mutex<Vec<serde_json::Value>>> = Arc::new(Mutex::new(Vec::new()));
9174 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
9175 let addr = listener.local_addr().unwrap();
9176 let recorder = {
9177 let seen = Arc::clone(&seen);
9178 Router::new().route(
9179 "/v1/chat/completions",
9180 post(move |Json(body): Json<serde_json::Value>| {
9181 let seen = Arc::clone(&seen);
9182 async move {
9183 seen.lock().unwrap().push(body);
9184 Json(json!({
9185 "choices": [{"message": {"role": "assistant", "content": "ok"}}]
9186 }))
9187 }
9188 }),
9189 )
9190 };
9191 tokio::spawn(async move {
9192 let _ = axum::serve(listener, recorder).await;
9193 });
9194
9195 let dir = tempfile::tempdir().unwrap();
9196 let cfg = ProviderConfig {
9197 base_url: format!("http://{addr}/v1"),
9198 model: "m".into(),
9199 stream: false,
9200 retry_base_delay_ms: 20,
9201 ..Default::default()
9202 };
9203 let (st, agent) = agent_state(dir.path(), cfg, Default::default());
9204 let app = router(st);
9205 let r = app
9208 .clone()
9209 .oneshot(model_req(json!({ "model": "m" })))
9210 .await
9211 .unwrap();
9212 assert_eq!(r.status(), StatusCode::OK);
9213
9214 for level in ["low", "high"] {
9215 let r = app
9216 .clone()
9217 .oneshot(reasoning_req(json!({ "level": level })))
9218 .await
9219 .unwrap();
9220 assert_eq!(r.status(), StatusCode::OK, "{level}");
9221 let body = json_body(r).await;
9222 assert_eq!(body["effort"], json!(level));
9223 assert_eq!(body["effort_session"], json!(true), "and it says why");
9224
9225 let r = app
9226 .clone()
9227 .oneshot(chat_req(json!({ "message": "same prompt" })))
9228 .await
9229 .unwrap();
9230 assert_eq!(r.status(), StatusCode::OK);
9231 let _ = text(r).await; }
9233
9234 let seen = seen.lock().unwrap().clone();
9235 assert_eq!(seen.len(), 2, "one request per turn: {seen:?}");
9236 assert_eq!(seen[0]["reasoning_effort"], json!("low"), "{:?}", seen[0]);
9237 assert_eq!(seen[1]["reasoning_effort"], json!("high"), "{:?}", seen[1]);
9238 let strip = |mut body: serde_json::Value| {
9240 body.as_object_mut().unwrap().remove("reasoning_effort");
9241 body
9242 };
9243 assert_eq!(
9244 strip(seen[0].clone()),
9245 strip(seen[1].clone()),
9246 "two identical prompts, and only the level differs"
9247 );
9248 assert!(agent.reasoning().overridden(), "a session dial, not a file");
9249 }
9250
9251 #[tokio::test]
9255 async fn the_off_switch_reaches_the_wire_as_this_route_spells_it() {
9256 use eclipse_core::config::ProviderConfig;
9257
9258 let seen: Arc<Mutex<Vec<serde_json::Value>>> = Arc::new(Mutex::new(Vec::new()));
9259 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
9260 let addr = listener.local_addr().unwrap();
9261 let recorder = {
9262 let seen = Arc::clone(&seen);
9263 Router::new().route(
9264 "/v1/chat/completions",
9265 post(move |Json(body): Json<serde_json::Value>| {
9266 let seen = Arc::clone(&seen);
9267 async move {
9268 seen.lock().unwrap().push(body);
9269 Json(json!({
9270 "choices": [{"message": {"role": "assistant", "content": "ok"}}]
9271 }))
9272 }
9273 }),
9274 )
9275 };
9276 tokio::spawn(async move {
9277 let _ = axum::serve(listener, recorder).await;
9278 });
9279
9280 let dir = tempfile::tempdir().unwrap();
9281 let cfg = ProviderConfig {
9282 base_url: format!("http://{addr}/v1"),
9283 model: "mmnuc/inkling-2-mini".into(),
9284 profile: Some("llamacpp".into()),
9285 stream: false,
9286 retry_base_delay_ms: 20,
9287 ..Default::default()
9288 };
9289 let (st, agent) = agent_state(dir.path(), cfg, Default::default());
9290 let app = router(st);
9291 let r = app
9292 .clone()
9293 .oneshot(model_req(json!({ "model": "mmnuc/inkling-2-mini" })))
9294 .await
9295 .unwrap();
9296 assert_eq!(r.status(), StatusCode::OK);
9297
9298 for level in ["high", "none"] {
9300 let r = app
9301 .clone()
9302 .oneshot(reasoning_req(json!({ "level": level })))
9303 .await
9304 .unwrap();
9305 assert_eq!(r.status(), StatusCode::OK, "{level}");
9306 }
9307 let r = app
9308 .clone()
9309 .oneshot(chat_req(json!({ "message": "same prompt" })))
9310 .await
9311 .unwrap();
9312 assert_eq!(r.status(), StatusCode::OK);
9313 let _ = text(r).await;
9314
9315 let first = seen.lock().unwrap().clone();
9316 assert_eq!(first.len(), 1, "one request for the turn: {first:?}");
9317 assert_eq!(
9318 first[0]["reasoning_effort"],
9319 json!("none"),
9320 "the off is the policy's own word on this wire: {:?}",
9321 first[0]
9322 );
9323 assert!(agent.reasoning().overridden(), "still a session dial");
9324
9325 let r = app
9328 .clone()
9329 .oneshot(reasoning_req(json!({ "level": "omit" })))
9330 .await
9331 .unwrap();
9332 assert_eq!(r.status(), StatusCode::OK, "omit on the route with a dial");
9333 let r = app
9334 .clone()
9335 .oneshot(chat_req(json!({ "message": "now quiet" })))
9336 .await
9337 .unwrap();
9338 assert_eq!(r.status(), StatusCode::OK);
9339 let _ = text(r).await;
9340 let bodies = seen.lock().unwrap().clone();
9341 assert_eq!(bodies.len(), 2, "one request per turn: {bodies:?}");
9342 assert!(
9343 bodies[1].get("reasoning_effort").is_none(),
9344 "asked for no field, and none is sent: {:?}",
9345 bodies[1]
9346 );
9347
9348 let dir = tempfile::tempdir().unwrap();
9351 let openai = ProviderConfig {
9352 base_url: format!("http://{addr}/v1"),
9353 model: "m".into(),
9354 stream: false,
9355 retry_base_delay_ms: 20,
9356 ..Default::default()
9357 };
9358 let (st, _agent) = agent_state(dir.path(), openai, Default::default());
9359 let app = router(st);
9360 let r = app
9361 .clone()
9362 .oneshot(reasoning_req(json!({ "level": "none" })))
9363 .await
9364 .unwrap();
9365 assert_eq!(
9366 r.status(),
9367 StatusCode::BAD_REQUEST,
9368 "there is no off to ask for on this route"
9369 );
9370 let why = text(r).await;
9371 assert!(why.contains("not a level this backend takes"), "{why}");
9372
9373 let r = app
9375 .clone()
9376 .oneshot(reasoning_req(json!({ "level": "omit" })))
9377 .await
9378 .unwrap();
9379 assert_eq!(
9380 r.status(),
9381 StatusCode::OK,
9382 "a route with no off switch can still be told to send nothing"
9383 );
9384 }
9385
9386 #[test]
9390 fn the_reasoning_row_is_a_switch_and_never_a_renamed_verb() {
9391 for verb in ["show reasoning", "hide reasoning"] {
9392 assert!(
9393 !INDEX_HTML.contains(verb),
9394 "the row is not a phrase that changes {verb:?}"
9395 );
9396 }
9397 assert!(
9398 INDEX_HTML.contains("switchRow('Reasoning'"),
9399 "one row, labelled with the setting"
9400 );
9401 assert!(
9402 INDEX_HTML.contains("b.setAttribute('role', 'switch')")
9403 && INDEX_HTML.contains("b.setAttribute('aria-checked'"),
9404 "a switch with a state on the control, so Up/Down still reaches it"
9405 );
9406 assert!(
9408 INDEX_HTML.contains("pickEffort(isOff ? restore : offWord)"),
9409 "the flip posts the route's off word, never a sentinel"
9410 );
9411 assert!(
9412 INDEX_HTML.contains("onClick: offWord ?"),
9413 "a route with no off gets a switch with no handler"
9414 );
9415 assert!(
9416 INDEX_HTML.contains("if (word === offWord) continue;"),
9417 "the off word is not also a level row: one dial, one control"
9418 );
9419 let submenu = INDEX_HTML
9421 .split("function renderReasoning(")
9422 .nth(1)
9423 .and_then(|rest| rest.split("async function showReasoning(").next())
9424 .expect("the submenu's renderer");
9425 assert!(
9426 !submenu.contains("setThinking"),
9427 "the menu row must not fold a single block: {submenu:.0}"
9428 );
9429 assert!(
9430 INDEX_HTML.contains("id=\"thinkall\""),
9431 "the fold control is where it was"
9432 );
9433 }
9434
9435 #[tokio::test]
9439 async fn a_pick_never_writes_the_config_file() {
9440 use eclipse_core::config::ProviderConfig;
9441
9442 let dir = tempfile::tempdir().unwrap();
9443 let path = dir.path().join("config.toml");
9444 std::fs::write(
9445 &path,
9446 "[provider]\nbase_url = \"http://h:1/v1\"\nmodel = \"m\"\nreasoning_effort = \"low\"\n",
9447 )
9448 .unwrap();
9449 let before = std::fs::read(&path).unwrap();
9450 let cfg = ProviderConfig {
9451 base_url: "http://h:1/v1".into(),
9452 model: "m".into(),
9453 reasoning_effort: Some("low".into()),
9454 ..Default::default()
9455 };
9456 let (st, agent) = agent_state(dir.path(), cfg, Default::default());
9457 let st = match Arc::try_unwrap(st) {
9458 Ok(st) => Arc::new(st.with_config_path(Some(path.clone()), None)),
9459 Err(_) => panic!("a state built here is not shared yet"),
9460 };
9461 let app = router(st);
9462
9463 let body = json_body(
9464 app.clone()
9465 .oneshot(reasoning_req(json!({ "level": "high" })))
9466 .await
9467 .unwrap(),
9468 )
9469 .await;
9470 assert_eq!(body["effort"], json!("high"));
9471 assert_eq!(
9472 body["configured"],
9473 json!("low"),
9474 "the row that goes back to the file says what it would go back to"
9475 );
9476 assert_eq!(
9477 std::fs::read(&path).unwrap(),
9478 before,
9479 "a click is not a `config set`"
9480 );
9481 assert_eq!(
9482 agent.reasoning().configured(),
9483 Some("low"),
9484 "the agent still holds the file's level underneath"
9485 );
9486
9487 let body = json_body(
9489 app.clone()
9490 .oneshot(get_req("/api/settings", "127.0.0.1:8787"))
9491 .await
9492 .unwrap(),
9493 )
9494 .await;
9495 let rows = body["settings"]
9496 .as_array()
9497 .unwrap_or_else(|| panic!("the settings page answers rows: {body}"));
9498 let row = rows
9499 .iter()
9500 .find(|r| r["key"] == json!("provider.reasoning_effort"))
9501 .expect("the key is on the settings page");
9502 assert_eq!(
9503 row["value"],
9504 json!("\"low\""),
9505 "the page reports the file, not the dashboard's dial"
9506 );
9507 }
9508
9509 #[tokio::test]
9512 async fn default_goes_back_to_the_file_and_a_level_the_route_lacks_is_refused() {
9513 use eclipse_core::config::ProviderConfig;
9514
9515 let dir = tempfile::tempdir().unwrap();
9516 let cfg = ProviderConfig {
9517 base_url: "http://h:1/v1".into(),
9518 model: "m".into(),
9519 reasoning_effort: Some("low".into()),
9520 ..Default::default()
9521 };
9522 let (st, agent) = agent_state(dir.path(), cfg, Default::default());
9523 let app = router(st);
9524
9525 let body = json_body(
9526 app.clone()
9527 .oneshot(reasoning_req(json!({ "level": "high" })))
9528 .await
9529 .unwrap(),
9530 )
9531 .await;
9532 assert_eq!(body["effort_session"], json!(true));
9533
9534 let body = json_body(
9536 app.clone()
9537 .oneshot(reasoning_req(json!({ "level": null })))
9538 .await
9539 .unwrap(),
9540 )
9541 .await;
9542 assert_eq!(body["effort"], json!("low"));
9543 assert_eq!(body["effort_session"], json!(false));
9544 assert!(!agent.reasoning().overridden());
9545
9546 let r = app
9549 .clone()
9550 .oneshot(reasoning_req(json!({ "level": "none" })))
9551 .await
9552 .unwrap();
9553 assert_eq!(r.status(), StatusCode::BAD_REQUEST);
9554 let said = text(r).await;
9555 assert!(
9556 said.contains("not sent") && said.contains("this route takes"),
9557 "the refusal is the policy's sentence plus the vocabulary: {said}"
9558 );
9559 assert!(!agent.reasoning().overridden(), "a refusal changes nothing");
9560
9561 let r = app.clone().oneshot(reasoning_req(json!({}))).await.unwrap();
9563 assert_eq!(r.status(), StatusCode::BAD_REQUEST);
9564 }
9565
9566 #[tokio::test]
9567 async fn a_pick_moves_the_context_window_to_the_new_model() {
9568 let dir = tempfile::tempdir().unwrap();
9569 let base = serve_models(&[("small", Some(4_096)), ("big", Some(131_072))]).await;
9570 let (st, agent) = provider_state(dir.path(), &base, "small");
9571 assert_eq!(agent.context_window(), 0, "nothing probed yet");
9572 let app = router(st);
9573 let r = app
9574 .clone()
9575 .oneshot(model_req(json!({ "model": "big" })))
9576 .await
9577 .unwrap();
9578 assert_eq!(r.status(), StatusCode::OK);
9579 for _ in 0..100 {
9582 if agent.context_window() == 131_072 {
9583 return;
9584 }
9585 tokio::time::sleep(Duration::from_millis(20)).await;
9586 }
9587 panic!(
9588 "the window still reads {} after a pick",
9589 agent.context_window()
9590 );
9591 }
9592
9593 #[test]
9598 fn the_pane_names_the_session_that_is_open() {
9599 assert!(
9600 INDEX_HTML.contains("id=\"openname\"") && INDEX_HTML.contains("id=\"openid\""),
9601 "a name and its id, above the transcript"
9602 );
9603 let script = INDEX_HTML.split("<script>").nth(1).unwrap_or_default();
9604 assert!(
9605 script.contains("row.querySelector('.name')"),
9606 "the name is read off the row the list already drew, not fetched again"
9607 );
9608 assert!(
9609 script.contains("showOpen(parked)"),
9610 "and it follows every rebuild of the list, naming the row the list may not be showing \
9611 (#345: the section holding the open session can be closed)"
9612 );
9613 assert!(
9614 INDEX_HTML.contains("#open[hidden] { display:none; }"),
9615 "an empty bar takes no height"
9616 );
9617 }
9618
9619 #[test]
9622 fn the_page_has_the_archive_filter_and_the_row_menu_word() {
9623 assert!(
9624 INDEX_HTML.contains("id=\"showarchived\""),
9625 "the filter exists"
9626 );
9627 assert!(
9628 INDEX_HTML.contains("?archived=1"),
9629 "and it is the server's list with the filed rows back in it"
9630 );
9631 assert!(
9632 INDEX_HTML.contains("li.dataset.archived"),
9633 "a row says whether it is filed away"
9634 );
9635 assert!(
9636 INDEX_HTML.contains("data-archived=\""),
9637 "and the first paint says so too"
9638 );
9639 assert!(
9640 INDEX_HTML.contains("'archive'") && INDEX_HTML.contains("'unarchive'"),
9641 "the menu offers the write and its undo"
9642 );
9643 assert!(
9644 INDEX_HTML.contains("add('Archived', archived)"),
9645 "filed rows get their own heading, not a date bucket"
9646 );
9647 assert!(INDEX_HTML.contains("out of the list, still in the find box"));
9649 assert!(
9650 INDEX_HTML.contains("'delete the transcript, its title and its memory', 'danger'"),
9651 "delete is still the only irreversible row"
9652 );
9653 }
9654
9655 #[test]
9656 fn the_page_has_a_model_picker_wired_to_its_routes() {
9657 assert!(INDEX_HTML.contains("id=\"model\""), "the label is a button");
9658 assert!(INDEX_HTML.contains("/api/models"), "asked for the list");
9659 assert!(
9660 INDEX_HTML.contains("'/api/model'"),
9661 "and tells the server a choice"
9662 );
9663 assert!(INDEX_HTML.contains("b.textContent = text"));
9665 assert!(!INDEX_HTML.contains("innerHTML"));
9666 assert!(
9668 INDEX_HTML.contains("/api/settings"),
9669 "the catalogue is asked for"
9670 );
9671 assert!(
9672 INDEX_HTML.contains("name.textContent = row.key"),
9673 "a key is text, not markup"
9674 );
9675 assert!(
9676 INDEX_HTML.contains("about.textContent = row.about"),
9677 "a description is text too — it comes from the catalogue"
9678 );
9679 }
9680
9681 #[tokio::test]
9685 async fn the_commands_route_is_the_table() {
9686 use eclipse_core::commands::{Args, Front, COMMANDS};
9687
9688 let dir = tempfile::tempdir().unwrap();
9689 let app = router(state(dir.path(), true));
9690 let body = json_body(
9691 app.oneshot(get_req("/api/commands", "127.0.0.1:1"))
9692 .await
9693 .unwrap(),
9694 )
9695 .await;
9696 let served: Vec<&str> = body["commands"]
9697 .as_array()
9698 .expect("a list")
9699 .iter()
9700 .map(|r| r["name"].as_str().expect("a name"))
9701 .collect();
9702 let expected: Vec<&str> = COMMANDS
9703 .iter()
9704 .filter(|c| c.serves(Front::Web))
9705 .map(|c| c.name)
9706 .collect();
9707 assert_eq!(served, expected, "the route is the table, in table order");
9708 assert!(
9709 !served.contains(&"/resume"),
9710 "a terminal-only verb is not offered: {served:?}"
9711 );
9712
9713 for row in body["commands"].as_array().unwrap() {
9715 let name = row["name"].as_str().unwrap();
9716 let command = COMMANDS.iter().find(|c| c.name == name).unwrap();
9717 assert_eq!(row["label"], json!(command.label()));
9718 assert_eq!(row["help"], json!(command.help));
9719 assert_eq!(row["aliases"], json!(command.aliases));
9720 assert_eq!(row["takes_arg"], json!(command.args.takes()));
9721 match command.args {
9722 Args::Shown(args) => assert_eq!(row["args"], json!(args)),
9723 Args::None | Args::Unshown => assert_eq!(row["args"], serde_json::Value::Null),
9724 }
9725 }
9726 let set = body["commands"]
9728 .as_array()
9729 .unwrap()
9730 .iter()
9731 .find(|r| r["name"] == json!("/set"))
9732 .expect("/set");
9733 assert_eq!(set["label"], json!("/set <key> <value>"));
9734 }
9735
9736 #[test]
9739 fn the_command_menu_is_the_servers_list_not_the_pages() {
9740 use eclipse_core::commands::{Front, COMMANDS};
9741
9742 assert!(
9743 INDEX_HTML.contains("fetch('/api/commands')"),
9744 "the menu asks the server"
9745 );
9746 for c in COMMANDS.iter().filter(|c| c.serves(Front::Web)) {
9747 for quoted in [format!("'{}'", c.name), format!("\"{}\"", c.name)] {
9748 assert!(
9749 !INDEX_HTML.contains("ed),
9750 "the page spells {} — the menu must come from the table",
9751 c.name
9752 );
9753 }
9754 }
9755 for key in ["ArrowDown", "ArrowUp", "'Tab'", "'Escape'"] {
9757 assert!(
9758 INDEX_HTML.contains(key),
9759 "{key} is handled: the menu owns {key}"
9760 );
9761 }
9762 assert!(INDEX_HTML.contains("role=\"listbox\""));
9763 assert!(INDEX_HTML.contains("aria-activedescendant"));
9764 }
9765
9766 #[test]
9771 fn the_settings_window_draws_its_rows_from_the_catalogue() {
9772 use eclipse_core::commands::COMMANDS;
9773
9774 assert!(
9775 INDEX_HTML.contains("<dialog id=\"settingswindow\""),
9776 "a dialog, not a box in the sidebar"
9777 );
9778 assert!(INDEX_HTML.contains("setWin.showModal()"));
9779 assert!(
9780 INDEX_HTML.contains("for (const choice of row.choices)"),
9781 "a select's options are the server's words"
9782 );
9783 assert!(
9784 INDEX_HTML.contains("row.kind === 'bool'"),
9785 "a boolean is a toggle, chosen by kind"
9786 );
9787 assert!(
9788 INDEX_HTML.contains("send(null)"),
9789 "reset is a null, which the route reads as \"comment the line out\""
9790 );
9791 for key in [
9792 "provider.model",
9793 "agent.max_iterations",
9794 "tools.shell",
9795 "web.port",
9796 "cli.approval",
9797 ] {
9798 assert!(
9799 !INDEX_HTML.contains(key),
9800 "the page spells {key} — the rows must come from the catalogue"
9801 );
9802 }
9803 assert!(COMMANDS.iter().any(|c| c.name == "/settings"));
9806 }
9807
9808 #[test]
9812 fn the_settings_window_keeps_its_frame_whatever_section_is_picked() {
9813 assert!(
9814 INDEX_HTML.contains("height:min(760px, 84vh)"),
9815 "the dialog states a height rather than a maximum, so it cannot be as small as its rows"
9816 );
9817 assert!(
9818 INDEX_HTML.contains("#settingswindow[open] { display:flex; flex-direction:column; }"),
9819 "and the body is a column that fills it — `[open]`, or the dialog would draw closed"
9820 );
9821 assert!(
9822 INDEX_HTML.contains("scrollbar-gutter:stable"),
9823 "the rows pane reserves its scrollbar, so picking a long section does not shift the text"
9824 );
9825 assert!(
9826 !INDEX_HTML.contains("max-height:62vh"),
9827 "the old cap is what let the window collapse: the rows pane scrolls instead"
9828 );
9829 assert!(
9832 INDEX_HTML.contains("ctl.appendChild(where)"),
9833 "`now: …` is on the control's line, not a fourth line under it"
9834 );
9835 assert!(
9838 INDEX_HTML.contains("setAttribute('role', 'switch')"),
9839 "a boolean is a switch, not a button shaped like `set`"
9840 );
9841 assert!(
9842 INDEX_HTML.contains(".srow .switch[aria-checked=\"true\"] .track"),
9843 "and the switch has a drawn on-state"
9844 );
9845 assert!(INDEX_HTML.contains("SET_SECTION_ABOUT"));
9849 for section in ["agent", "provider", "web", "tools"] {
9850 assert!(
9851 INDEX_HTML.contains(&format!(" {section}: '")),
9852 "the {section} section has a sentence"
9853 );
9854 }
9855 }
9856
9857 #[test]
9861 fn an_attachment_becomes_a_block_the_model_can_tell_from_the_sentence() {
9862 let said = compose_attachments(
9863 "here is the trace",
9864 &[Attachment {
9865 kind: "text".into(),
9866 name: "trace.txt".into(),
9867 value: "ERROR: the pool was rebuilt\n".into(),
9868 }],
9869 )
9870 .unwrap()
9871 .0;
9872 assert!(said.starts_with("here is the trace"), "{said}");
9873 assert!(
9874 said.contains("--- attached file: trace.txt (27 chars) ---"),
9875 "the block names the file and its size: {said}"
9876 );
9877 assert!(said.contains("ERROR: the pool was rebuilt"), "{said}");
9878 assert!(
9879 said.contains("--- end of trace.txt ---"),
9880 "and says where the file stopped, so the model does not read on: {said}"
9881 );
9882
9883 let said = compose_attachments(
9886 "",
9887 &[
9888 Attachment {
9889 kind: "path".into(),
9890 name: String::new(),
9891 value: "crates/eclipse-core/src/session.rs".into(),
9892 },
9893 Attachment {
9894 kind: "url".into(),
9895 name: String::new(),
9896 value: "https://example.com/report".into(),
9897 },
9898 ],
9899 )
9900 .unwrap()
9901 .0;
9902 assert!(
9903 said.contains("attached path: crates/eclipse-core/src/session.rs"),
9904 "{said}"
9905 );
9906 assert!(
9907 said.contains("read_file"),
9908 "it says what to do with it: {said}"
9909 );
9910 assert!(
9911 said.contains("attached link: https://example.com/report"),
9912 "{said}"
9913 );
9914 assert!(said.contains("fetch"), "{said}");
9915 assert!(said.starts_with("--- attached path:"), "{said:?}");
9917
9918 let (said, pictures) = compose_attachments(
9921 "look",
9922 &[Attachment {
9923 kind: "image".into(),
9924 name: "shot.png".into(),
9925 value: "data:image/png;base64,iVBORw0KGgo=".into(),
9926 }],
9927 )
9928 .unwrap();
9929 assert_eq!(pictures.len(), 1, "{pictures:?}");
9930 assert_eq!(pictures[0].name, "shot.png");
9931 assert_eq!(pictures[0].mime, "image/png");
9932 assert!(
9933 said.contains("--- attached picture: shot.png (image/png) ---"),
9934 "the words still read sensibly when a model is sent a description: {said}"
9935 );
9936 assert!(compose_attachments(
9938 "x",
9939 &[Attachment {
9940 kind: "image".into(),
9941 name: "shot.svg".into(),
9942 value: "data:image/svg+xml;base64,iVBORw0KGgo=".into(),
9943 }]
9944 )
9945 .unwrap_err()
9946 .contains("not a picture this build can carry"));
9947 assert!(compose_attachments(
9948 "x",
9949 &[Attachment {
9950 kind: "image".into(),
9951 name: "shot.png".into(),
9952 value: "/tmp/shot.png".into(),
9953 }]
9954 )
9955 .unwrap_err()
9956 .contains("data: URL"));
9957
9958 let big = "x".repeat(MAX_ATTACHMENT_CHARS + 1);
9960 let refused = compose_attachments(
9961 "read this",
9962 &[Attachment {
9963 kind: "text".into(),
9964 name: "huge.log".into(),
9965 value: big,
9966 }],
9967 )
9968 .unwrap_err();
9969 assert!(refused.contains("huge.log"), "{refused}");
9970 assert!(
9971 refused.contains(&MAX_ATTACHMENT_CHARS.to_string()),
9972 "{refused}"
9973 );
9974 assert!(refused.contains("attach it as a path"), "{refused}");
9975
9976 assert!(compose_attachments(
9978 "x",
9979 &[Attachment {
9980 kind: "url".into(),
9981 name: String::new(),
9982 value: "javascript:alert(1)".into(),
9983 }]
9984 )
9985 .is_err());
9986 assert!(compose_attachments(
9987 "x",
9988 &[Attachment {
9989 kind: "path".into(),
9990 name: String::new(),
9991 value: "a path\nwith a newline".into(),
9992 }]
9993 )
9994 .is_err());
9995
9996 assert_eq!(
9998 compose_attachments("just words", &[]).unwrap().0,
9999 "just words"
10000 );
10001 let many: Vec<Attachment> = (0..=MAX_ATTACHMENTS)
10002 .map(|i| Attachment {
10003 kind: "url".into(),
10004 name: String::new(),
10005 value: format!("https://example.com/{i}"),
10006 })
10007 .collect();
10008 assert!(compose_attachments("x", &many)
10009 .unwrap_err()
10010 .contains("at most 8"));
10011 }
10012
10013 #[tokio::test]
10017 async fn an_attached_file_is_the_turn_the_model_read_and_the_text_the_store_keeps() {
10018 let dir = tempfile::tempdir().unwrap();
10019 let st = state(dir.path(), true);
10020 let store = st.agent.as_ref().unwrap().store().clone();
10021 let app = router(st);
10022
10023 let r = app
10024 .clone()
10025 .oneshot(chat_req(json!({
10026 "message": "what broke?",
10027 "attachments": [
10028 { "kind": "text", "name": "trace.txt", "value": "ERROR: the pool was rebuilt" },
10029 { "kind": "url", "value": "https://example.com/report" }
10030 ]
10031 })))
10032 .await
10033 .unwrap();
10034 assert_eq!(r.status(), StatusCode::OK, "a run, not a refusal");
10035 let events = notices(r).await;
10038 let session = events
10039 .iter()
10040 .find(|(kind, _)| kind == "session")
10041 .expect("a run opens a session");
10042 let id = session.1["session_id"].as_str().unwrap().to_string();
10043 let kept = store.load(&id).unwrap();
10044 let asked = kept
10045 .iter()
10046 .find(|m| m.role == eclipse_core::message::Role::User)
10047 .and_then(|m| m.content.clone())
10048 .expect("the turn is stored");
10049 assert!(asked.starts_with("what broke?"), "{asked}");
10050 assert!(asked.contains("--- attached file: trace.txt"), "{asked}");
10051 assert!(asked.contains("ERROR: the pool was rebuilt"), "{asked}");
10052 assert!(
10053 asked.contains("--- attached link: https://example.com/report"),
10054 "the link is a reference in the same turn: {asked}"
10055 );
10056
10057 let r = app
10059 .clone()
10060 .oneshot(chat_req(json!({
10061 "message": "/help",
10062 "attachments": [{ "kind": "text", "name": "x.txt", "value": "hello" }]
10063 })))
10064 .await
10065 .unwrap();
10066 let events = notices(r).await;
10067 assert_eq!(events[0].0, "notice", "{events:?}");
10068 assert_eq!(events[0].1["kind"], json!("refusal"), "{events:?}");
10069 assert!(
10070 events[0].1["text"]
10071 .as_str()
10072 .unwrap()
10073 .contains("a command runs on its own"),
10074 "{events:?}"
10075 );
10076
10077 let r = app
10081 .clone()
10082 .oneshot(chat_req(json!({
10083 "message": "look at this",
10084 "attachments": [{ "kind": "image", "name": "shot.png", "value": "AAAA" }]
10085 })))
10086 .await
10087 .unwrap();
10088 assert_eq!(r.status(), StatusCode::BAD_REQUEST);
10089 assert!(
10090 body_text(r).await.contains("data: URL"),
10091 "the refusal says what a picture has to be"
10092 );
10093
10094 let r = app
10096 .clone()
10097 .oneshot(chat_req(json!({
10098 "message": "listen to this",
10099 "attachments": [{ "kind": "audio", "name": "clip.wav", "value": "AAAA" }]
10100 })))
10101 .await
10102 .unwrap();
10103 assert_eq!(r.status(), StatusCode::BAD_REQUEST);
10104 assert!(
10105 body_text(r).await.contains("cannot attach audio"),
10106 "the refusal names the kind"
10107 );
10108 }
10109
10110 #[test]
10113 fn the_composer_has_a_plus_menu_and_sends_what_its_chips_say() {
10114 assert!(INDEX_HTML.contains("id=\"plus\""), "the control exists");
10115 assert!(
10116 INDEX_HTML.contains("aria-haspopup=\"menu\""),
10117 "and it says it opens a menu"
10118 );
10119 for kind in ["file", "path", "url", "image", "audio"] {
10120 assert!(
10121 INDEX_HTML.contains(&format!("data-attach=\"{kind}\"")),
10122 "the {kind} row exists"
10123 );
10124 }
10125 assert!(
10129 INDEX_HTML.contains("accept=\"image/png,image/jpeg,image/webp,image/gif\""),
10130 "the picture picker exists and is limited to what the wire carries"
10131 );
10132 assert!(
10133 INDEX_HTML.contains("readAsDataURL"),
10134 "and it reads the bytes here, because the page is the only thing that has them"
10135 );
10136 assert!(
10137 !INDEX_HTML.contains("data-attach=\"image\" disabled"),
10138 "the picture row is no longer a disabled row"
10139 );
10140 assert!(INDEX_HTML.contains("needs a transcription endpoint"));
10141 assert!(INDEX_HTML.contains("function renderAttached()"));
10144 assert!(INDEX_HTML.contains("attached.splice(i, 1)"));
10145 assert!(
10146 INDEX_HTML.contains("const carrying = attached.map"),
10147 "the body is built from the chips at send time"
10148 );
10149 assert!(
10150 INDEX_HTML.contains("attachments: carrying"),
10151 "and travels in the same JSON body as the message"
10152 );
10153 assert!(INDEX_HTML.contains("const ATTACH_MAX_CHARS = 65536;"));
10156 assert!(
10157 INDEX_HTML.contains("attach it as a path instead"),
10158 "an over-cap file is told what to do instead"
10159 );
10160 assert!(INDEX_HTML.contains("(!text && attached.length === 0)"));
10162 assert!(INDEX_HTML.contains("closeAttach(); plus.focus();"));
10164 }
10165
10166 #[tokio::test]
10167 async fn session_endpoints() {
10168 let dir = tempfile::tempdir().unwrap();
10169 let st = state(dir.path(), true);
10170 st.store.append("s1", &Message::user("q")).unwrap();
10171 let app = router(st);
10172 let r = app
10173 .clone()
10174 .oneshot(get_req("/api/sessions", "127.0.0.1:1"))
10175 .await
10176 .unwrap();
10177 assert!(text(r).await.contains("\"s1\""));
10178 let r = app
10179 .clone()
10180 .oneshot(get_req("/api/sessions/s1", "127.0.0.1:1"))
10181 .await
10182 .unwrap();
10183 assert!(text(r).await.contains("\"q\""));
10184 let r = app
10185 .clone()
10186 .oneshot(get_req("/api/sessions/nope", "127.0.0.1:1"))
10187 .await
10188 .unwrap();
10189 assert_eq!(r.status(), StatusCode::NOT_FOUND);
10190 let r = app
10191 .clone()
10192 .oneshot(get_req("/api/sessions/a.b", "127.0.0.1:1"))
10193 .await
10194 .unwrap();
10195 assert_eq!(r.status(), StatusCode::BAD_REQUEST);
10196 }
10197
10198 #[test]
10199 fn loopback_host_parsing() {
10200 assert!(is_loopback_host("127.0.0.1:80"));
10201 assert!(is_loopback_host("localhost"));
10202 assert!(is_loopback_host("[::1]:8787"));
10203 assert!(!is_loopback_host("127.0.0.1.evil.com"));
10204 assert!(!is_loopback_host("example.com:80"));
10205 assert!(is_loopback_host("localhost.:8787"));
10207 assert!(is_loopback_host("127.0.0.1.:8787"));
10208 assert!(!is_loopback_host("localhost.evil.com:8787"));
10209 }
10210
10211 #[tokio::test]
10212 async fn stop_cancels_a_run_in_flight_and_ends_the_stream() {
10213 use futures_util::StreamExt;
10214 let dir = tempfile::tempdir().unwrap();
10215 let (st, entered, dropped) = hanging_state(dir.path());
10216
10217 let resp = router(st.clone())
10218 .oneshot(chat_req(json!({"message": "hang"})))
10219 .await
10220 .unwrap();
10221 assert_eq!(resp.status(), StatusCode::OK);
10222 let mut body = resp.into_body().into_data_stream();
10223 let first = String::from_utf8(body.next().await.unwrap().unwrap().to_vec()).unwrap();
10224 let run_id = first
10225 .split("run_id\":\"")
10226 .nth(1)
10227 .and_then(|rest| rest.split('"').next())
10228 .unwrap_or_else(|| panic!("no run_id in {first}"))
10229 .to_string();
10230 assert!(
10233 wait_for(&entered, 2000).await,
10234 "the model call never started"
10235 );
10236
10237 let r = router(st.clone())
10238 .oneshot(cancel_req(&run_id))
10239 .await
10240 .unwrap();
10241 assert_eq!(r.status(), StatusCode::OK);
10242 assert!(text(r).await.contains("\"cancelled\":true"));
10243
10244 let mut all = String::new();
10245 while let Ok(Some(Ok(chunk))) =
10246 tokio::time::timeout(Duration::from_secs(5), body.next()).await
10247 {
10248 all.push_str(&String::from_utf8_lossy(&chunk));
10249 }
10250 assert!(all.contains("event: cancelled"), "{all}");
10251 assert!(all.contains("event: done"), "{all}");
10252 assert!(
10253 !all.contains("event: error"),
10254 "cancelling is not a failure: {all}"
10255 );
10256 assert!(
10257 dropped.load(Ordering::SeqCst),
10258 "the provider request must be dropped, not waited out"
10259 );
10260 assert_eq!(st.store.list().unwrap()[0].messages, 1);
10262
10263 assert!(wait_for(&dropped, 1000).await);
10265 tokio::time::sleep(Duration::from_millis(100)).await;
10266 let again = router(st).oneshot(cancel_req(&run_id)).await.unwrap();
10267 assert_eq!(again.status(), StatusCode::NOT_FOUND);
10268 }
10269
10270 #[tokio::test]
10271 async fn closing_the_connection_cancels_the_run() {
10272 use futures_util::StreamExt;
10273 let dir = tempfile::tempdir().unwrap();
10274 let (st, entered, dropped) = hanging_state(dir.path());
10275 let resp = router(st.clone())
10276 .oneshot(chat_req(json!({"message": "hang"})))
10277 .await
10278 .unwrap();
10279 let mut body = resp.into_body().into_data_stream();
10280 body.next().await.unwrap().unwrap();
10281 assert!(
10282 wait_for(&entered, 2000).await,
10283 "the model call never started"
10284 );
10285 assert!(
10286 !dropped.load(Ordering::SeqCst),
10287 "the run must still be in flight"
10288 );
10289 drop(body);
10291 assert!(
10292 wait_for(&dropped, 3000).await,
10293 "a closed connection must cancel the run, not leave it running"
10294 );
10295 tokio::time::sleep(Duration::from_millis(100)).await;
10296 assert_eq!(st.store.list().unwrap()[0].messages, 1);
10297 }
10298
10299 #[tokio::test]
10300 async fn cancel_rejects_malformed_and_unknown_run_ids() {
10301 let dir = tempfile::tempdir().unwrap();
10302 let st = state(dir.path(), true);
10303 for (uri, want) in [
10304 ("/api/runs/not-hex/cancel", StatusCode::BAD_REQUEST),
10305 ("/api/runs/deadbeef/cancel", StatusCode::NOT_FOUND),
10306 ] {
10307 let r = router(st.clone())
10308 .oneshot(
10309 anon("POST", uri)
10310 .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
10311 .body(Body::empty())
10312 .unwrap(),
10313 )
10314 .await
10315 .unwrap();
10316 assert_eq!(r.status(), want, "{uri}");
10317 }
10318 }
10319
10320 #[tokio::test]
10321 async fn a_chat_can_ask_for_its_own_turn_budget_and_hears_what_it_got() {
10322 let dir = tempfile::tempdir().unwrap();
10323 let st = state(dir.path(), true);
10324 let resp = router(st)
10325 .oneshot(chat_req(json!({"message": "hello", "max_iterations": 7})))
10326 .await
10327 .unwrap();
10328 assert_eq!(resp.status(), StatusCode::OK);
10329 let body = text(resp).await;
10330 assert!(
10331 body.contains("\"max_iterations\":7"),
10332 "the session event must report the budget that will apply: {body}"
10333 );
10334 }
10335
10336 #[tokio::test]
10340 async fn a_chat_asking_for_a_turn_budget_past_the_ceiling_is_refused() {
10341 let dir = tempfile::tempdir().unwrap();
10342 let st = state(dir.path(), true);
10343 let resp = router(st)
10344 .oneshot(chat_req(json!({
10345 "message": "hello",
10346 "max_iterations": MAX_ITERATIONS_BOUND + 1
10347 })))
10348 .await
10349 .unwrap();
10350 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
10351 let body = text(resp).await;
10352 assert!(
10353 body.contains(&MAX_ITERATIONS_BOUND.to_string()),
10354 "the refusal names the ceiling: {body}"
10355 );
10356 }
10357
10358 #[tokio::test]
10359 async fn a_chat_asks_for_zero_turns_is_refused_rather_than_silently_corrected() {
10360 let dir = tempfile::tempdir().unwrap();
10361 let st = state(dir.path(), true);
10362 let resp = router(st)
10363 .oneshot(chat_req(json!({"message": "hello", "max_iterations": 0})))
10364 .await
10365 .unwrap();
10366 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
10367 }
10368
10369 fn write_session(
10373 id: &str,
10374 act: &str,
10375 csrf: Option<&str>,
10376 body: Option<serde_json::Value>,
10377 ) -> HttpRequest<Body> {
10378 let mut b = HttpRequest::post(format!("/api/sessions/{id}/{act}"))
10379 .header("host", "127.0.0.1:8787")
10380 .header("origin", "null")
10381 .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"));
10382 if let Some(token) = csrf {
10383 b = b.header(CSRF_HEADER, token);
10384 }
10385 match body {
10386 Some(v) => b
10387 .header("content-type", "application/json")
10388 .body(Body::from(v.to_string()))
10389 .unwrap(),
10390 None => b.body(Body::empty()).unwrap(),
10391 }
10392 }
10393
10394 #[tokio::test]
10395 async fn a_rename_in_the_dashboard_is_the_rename_the_terminal_reads() {
10396 let dir = tempfile::tempdir().unwrap();
10397 let st = state(dir.path(), true);
10398 let store = st.agent.as_ref().unwrap().store().clone();
10399 let id = store.new_id();
10400 store.append(&id, &Message::user("the question")).unwrap();
10401 let app = router(st);
10402
10403 let r = app
10404 .clone()
10405 .oneshot(write_session(
10406 &id,
10407 "rename",
10408 Some(TEST_CSRF),
10409 Some(json!({"title": "named in the browser"})),
10410 ))
10411 .await
10412 .unwrap();
10413 assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
10414
10415 assert_eq!(
10417 store.title(&id).unwrap().as_deref(),
10418 Some("named in the browser")
10419 );
10420 let listed = body_text(
10421 app.oneshot(get_req("/api/sessions", "127.0.0.1:8787"))
10422 .await
10423 .unwrap(),
10424 )
10425 .await;
10426 assert!(listed.contains("named in the browser"), "{listed}");
10427 assert!(listed.contains(&format!("\"id\":\"{id}\"")), "{listed}");
10428 }
10429
10430 #[tokio::test]
10431 async fn a_pin_in_the_dashboard_puts_a_session_first_and_keeps_a_prune_off_it() {
10432 let dir = tempfile::tempdir().unwrap();
10433 let st = state(dir.path(), true);
10434 let store = st.agent.as_ref().unwrap().store().clone();
10435 let older = store.new_id();
10436 store
10437 .append(&older, &Message::user("the older one"))
10438 .unwrap();
10439 std::thread::sleep(std::time::Duration::from_millis(5));
10440 let newer = store.new_id();
10441 store
10442 .append(&newer, &Message::user("the newer one"))
10443 .unwrap();
10444 let app = router(st);
10445
10446 let r = app
10447 .clone()
10448 .oneshot(write_session(
10449 &older,
10450 "pin",
10451 Some(TEST_CSRF),
10452 Some(json!({"pinned": true})),
10453 ))
10454 .await
10455 .unwrap();
10456 assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
10457
10458 let listed = body_text(
10459 app.oneshot(get_req("/api/sessions", "127.0.0.1:8787"))
10460 .await
10461 .unwrap(),
10462 )
10463 .await;
10464 let rows: Vec<serde_json::Value> = serde_json::from_str(&listed).unwrap();
10465 assert_eq!(rows[0]["id"], json!(older), "pinned first: {listed}");
10466 assert_eq!(rows[0]["pinned"], json!(true));
10467 assert_eq!(rows[1]["id"], json!(newer));
10468
10469 let now = eclipse_core::session::now_ms();
10471 let plan = store.prune_candidates(0, 1, now, false).unwrap();
10472 assert!(!plan.candidates.contains(&older), "{:?}", plan.candidates);
10473 assert_eq!(plan.pinned_kept, 1);
10474 }
10475
10476 #[tokio::test]
10480 async fn an_archive_in_the_dashboard_is_the_archive_the_terminal_reads() {
10481 let dir = tempfile::tempdir().unwrap();
10482 let st = state(dir.path(), true);
10483 let store = st.agent.as_ref().unwrap().store().clone();
10484 let id = store.new_id();
10485 store
10486 .append(&id, &Message::user("the zfs pool was rebuilt"))
10487 .unwrap();
10488 store.rename(&id, "the nginx migration").unwrap();
10489 let app = router(st);
10490
10491 let r = app
10492 .clone()
10493 .oneshot(write_session(
10494 &id,
10495 "archive",
10496 Some(TEST_CSRF),
10497 Some(json!({"archived": true})),
10498 ))
10499 .await
10500 .unwrap();
10501 assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
10502
10503 assert!(store.list().unwrap().is_empty());
10505 assert!(store.list_with_archived().unwrap()[0].archived);
10506
10507 let listed = body_text(
10508 app.clone()
10509 .oneshot(get_req("/api/sessions", "127.0.0.1:8787"))
10510 .await
10511 .unwrap(),
10512 )
10513 .await;
10514 assert_eq!(listed.trim(), "[]", "out of the list: {listed}");
10515
10516 let all = body_text(
10518 app.clone()
10519 .oneshot(get_req("/api/sessions?archived=1", "127.0.0.1:8787"))
10520 .await
10521 .unwrap(),
10522 )
10523 .await;
10524 let rows: Vec<serde_json::Value> = serde_json::from_str(&all).unwrap();
10525 assert_eq!(rows.len(), 1, "{all}");
10526 assert_eq!(rows[0]["archived"], json!(true), "{all}");
10527 assert_eq!(rows[0]["title"], json!("the nginx migration"), "{all}");
10528
10529 let hits = body_text(
10532 app.clone()
10533 .oneshot(get_req("/api/search?q=zfs", "127.0.0.1:8787"))
10534 .await
10535 .unwrap(),
10536 )
10537 .await;
10538 assert!(hits.contains(&id), "the find box still answers: {hits}");
10539 let transcript = body_text(
10540 app.clone()
10541 .oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
10542 .await
10543 .unwrap(),
10544 )
10545 .await;
10546 assert!(transcript.contains("zfs pool"), "{transcript}");
10547 let later = eclipse_core::session::now_ms() + 86_400_000;
10548 let plan = store.prune_candidates(1, 0, later, false).unwrap();
10549 assert!(plan.candidates.is_empty(), "{:?}", plan.candidates);
10550 assert_eq!(plan.archived_kept, 1);
10551 let asked = store.prune_candidates(1, 0, later, true).unwrap();
10552 assert_eq!(asked.candidates, vec![id.clone()]);
10553
10554 let r = app
10556 .clone()
10557 .oneshot(write_session(
10558 &id,
10559 "archive",
10560 Some(TEST_CSRF),
10561 Some(json!({"archived": false})),
10562 ))
10563 .await
10564 .unwrap();
10565 assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
10566 let listed = body_text(
10567 app.oneshot(get_req("/api/sessions", "127.0.0.1:8787"))
10568 .await
10569 .unwrap(),
10570 )
10571 .await;
10572 assert!(listed.contains(&id), "{listed}");
10573 }
10574
10575 #[tokio::test]
10578 async fn the_composers_archive_verb_files_the_open_session_away() {
10579 let dir = tempfile::tempdir().unwrap();
10580 let st = state(dir.path(), true);
10581 let store = st.agent.as_ref().unwrap().store().clone();
10582 let id = store.new_id();
10583 store
10584 .append(&id, &Message::user("the nginx migration"))
10585 .unwrap();
10586 store.rename(&id, "the nginx migration").unwrap();
10587 let app = router(st);
10588
10589 let events = notices(
10590 app.clone()
10591 .oneshot(chat_req(json!({"message": "/archive", "session_id": id})))
10592 .await
10593 .unwrap(),
10594 )
10595 .await;
10596 assert_eq!(events[0].0, "notice", "{events:?}");
10597 assert_eq!(events[0].1["kind"], json!("command"));
10598 let said = events[0].1["text"].as_str().unwrap();
10599 assert!(said.contains("still in the find box"), "{said}");
10600 assert!(store.list().unwrap().is_empty(), "the row left the listing");
10601 assert!(store.list_with_archived().unwrap()[0].archived);
10602
10603 let events = notices(
10605 app.clone()
10606 .oneshot(chat_req(json!({"message": "/archive list"})))
10607 .await
10608 .unwrap(),
10609 )
10610 .await;
10611 let said = events[0].1["text"].as_str().unwrap();
10612 assert!(
10613 said.contains(&id) && said.contains("the nginx migration"),
10614 "{said}"
10615 );
10616
10617 let events = notices(
10619 app.clone()
10620 .oneshot(chat_req(
10621 json!({"message": "/archive off", "session_id": id}),
10622 ))
10623 .await
10624 .unwrap(),
10625 )
10626 .await;
10627 let said = events[0].1["text"].as_str().unwrap();
10628 assert!(said.contains("back in the list"), "{said}");
10629 assert_eq!(store.list().unwrap().len(), 1);
10630 assert_eq!(store.load(&id).unwrap().len(), 1, "a verb is not a turn");
10631
10632 let events = notices(
10634 app.oneshot(chat_req(
10635 json!({"message": "/archive everything", "session_id": id}),
10636 ))
10637 .await
10638 .unwrap(),
10639 )
10640 .await;
10641 assert_eq!(events[0].1["kind"], json!("refusal"));
10642 let said = events[0].1["text"].as_str().unwrap();
10643 assert!(said.contains("`list` or `off`"), "{said}");
10644 }
10645
10646 #[tokio::test]
10647 async fn deleting_from_the_dashboard_takes_the_transcript_title_and_memory() {
10648 let dir = tempfile::tempdir().unwrap();
10649 let st = state(dir.path(), true);
10650 let store = st.agent.as_ref().unwrap().store().clone();
10651 let id = store.new_id();
10652 store.append(&id, &Message::user("doomed")).unwrap();
10653 store.rename(&id, "a name").unwrap();
10654 let app = router(st);
10655
10656 let r = app
10657 .clone()
10658 .oneshot(write_session(&id, "delete", Some(TEST_CSRF), None))
10659 .await
10660 .unwrap();
10661 assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
10662 assert!(!store.exists(&id), "the whole session, not just the row");
10663 assert!(store.load(&id).is_err(), "the transcript went with it");
10664
10665 let r = app
10666 .clone()
10667 .oneshot(get_req(&format!("/api/sessions/{id}"), "127.0.0.1:8787"))
10668 .await
10669 .unwrap();
10670 assert_eq!(r.status(), StatusCode::NOT_FOUND);
10671 }
10672
10673 #[tokio::test]
10674 async fn every_session_write_is_refused_without_the_csrf_token() {
10675 let dir = tempfile::tempdir().unwrap();
10676 let st = state(dir.path(), true);
10677 let store = st.agent.as_ref().unwrap().store().clone();
10678 let id = store.new_id();
10679 store.append(&id, &Message::user("untouched")).unwrap();
10680 let app = router(st);
10681
10682 for (act, body) in [
10683 ("rename", Some(json!({"title": "should not land"}))),
10684 ("pin", Some(json!({"pinned": true}))),
10685 ("archive", Some(json!({"archived": true}))),
10686 ("delete", None),
10687 ] {
10688 let r = app
10689 .clone()
10690 .oneshot(write_session(&id, act, None, body))
10691 .await
10692 .unwrap();
10693 assert_eq!(r.status(), StatusCode::FORBIDDEN, "{act}");
10694 let said = body_text(r).await;
10695 assert!(said.contains(CSRF_HEADER), "{act}: {said}");
10696 }
10697 assert_eq!(store.title(&id).unwrap(), None);
10700 assert!(!store.list().unwrap()[0].pinned);
10701 assert!(!store.list().unwrap()[0].archived);
10702 assert!(store.exists(&id));
10703 }
10704
10705 #[tokio::test]
10706 async fn a_session_write_names_an_unknown_session_rather_than_creating_one() {
10707 let dir = tempfile::tempdir().unwrap();
10708 let app = router(state(dir.path(), true));
10709 let r = app
10710 .clone()
10711 .oneshot(write_session(
10712 "no-such-session",
10713 "pin",
10714 Some(TEST_CSRF),
10715 Some(json!({"pinned": true})),
10716 ))
10717 .await
10718 .unwrap();
10719 assert_eq!(r.status(), StatusCode::NOT_FOUND);
10720 }
10721
10722 fn cron_state(dir: &std::path::Path) -> Shared {
10728 match Arc::try_unwrap(state(dir, true)) {
10729 Ok(st) => Arc::new(st.with_cron_root(dir.to_path_buf())),
10730 Err(_) => panic!("a state built here is not shared yet"),
10731 }
10732 }
10733
10734 fn cron_env() -> &'static tokio::sync::Mutex<()> {
10739 static LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
10740 &LOCK
10741 }
10742
10743 fn cron_req(
10744 method: &str,
10745 path: &str,
10746 csrf: Option<&str>,
10747 body: Option<serde_json::Value>,
10748 ) -> HttpRequest<Body> {
10749 let mut b = HttpRequest::builder()
10750 .method(method)
10751 .uri(path)
10752 .header("host", "127.0.0.1:8787")
10753 .header("origin", "null")
10756 .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"));
10757 if let Some(token) = csrf {
10758 b = b.header(CSRF_HEADER, token);
10759 }
10760 match body {
10761 Some(v) => b
10762 .header("content-type", "application/json")
10763 .body(Body::from(v.to_string()))
10764 .unwrap(),
10765 None => b.body(Body::empty()).unwrap(),
10766 }
10767 }
10768
10769 fn seed_job(dir: &std::path::Path, name: &str, prompt: &str) {
10770 let job = eclipse_core::cron::Draft {
10771 name: name.to_string(),
10772 schedule: "every 30m".to_string(),
10773 prompt: prompt.to_string(),
10774 ..Default::default()
10775 }
10776 .to_job()
10777 .unwrap();
10778 eclipse_core::cron::append_job(dir, &job).unwrap();
10779 }
10780
10781 #[tokio::test]
10782 async fn the_cron_list_is_the_same_job_the_cli_prints() {
10783 let dir = tempfile::tempdir().unwrap();
10784 seed_job(dir.path(), "brief", "summarise yesterday");
10785 let app = router(cron_state(dir.path()));
10786 let body = body_text(
10787 app.oneshot(cron_req("GET", "/api/cron", None, None))
10788 .await
10789 .unwrap(),
10790 )
10791 .await;
10792 let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
10793 assert!(parsed["now_ms"].as_i64().unwrap_or(0) > 0, "{body}");
10794 let jobs = parsed["jobs"].as_array().expect("a jobs array");
10795 assert_eq!(jobs.len(), 1, "{body}");
10796 assert_eq!(jobs[0]["name"], "brief");
10797 assert_eq!(jobs[0]["schedule"], "every 30m");
10800 assert_eq!(jobs[0]["prompt"], "summarise yesterday");
10801 assert_eq!(jobs[0]["enabled"], true);
10802 assert!(jobs[0]["next_ms"].as_i64().is_some(), "{body}");
10803 assert_eq!(jobs[0]["runs"], 0);
10804 }
10805
10806 #[tokio::test]
10807 async fn a_cron_write_without_the_token_is_refused_and_changes_nothing() {
10808 let dir = tempfile::tempdir().unwrap();
10809 let app = router(cron_state(dir.path()));
10810 let r = app
10811 .clone()
10812 .oneshot(cron_req(
10813 "POST",
10814 "/api/cron",
10815 None,
10816 Some(json!({"name": "brief", "schedule": "hourly", "prompt": "x"})),
10817 ))
10818 .await
10819 .unwrap();
10820 assert_eq!(r.status(), StatusCode::FORBIDDEN);
10821 let left = eclipse_core::cron::load(dir.path()).unwrap();
10822 assert!(left.is_empty(), "a refused write wrote {:?}", left.len());
10823 }
10824
10825 #[tokio::test]
10826 async fn a_new_job_is_written_into_the_file_the_timer_reads() {
10827 let dir = tempfile::tempdir().unwrap();
10828 let app = router(cron_state(dir.path()));
10829 let r = app
10830 .clone()
10831 .oneshot(cron_req(
10832 "POST",
10833 "/api/cron",
10834 Some(TEST_CSRF),
10835 Some(json!({
10836 "name": "brief",
10837 "schedule": "daily 07:30",
10838 "prompt": "what happened yesterday",
10839 })),
10840 ))
10841 .await
10842 .unwrap();
10843 assert_eq!(r.status(), StatusCode::CREATED);
10844 let body = body_text(r).await;
10845 let created: serde_json::Value = serde_json::from_str(&body).expect("json");
10846 assert_eq!(created["schedule"], "daily 07:30", "{body}");
10847 let jobs = eclipse_core::cron::load(dir.path()).unwrap();
10850 assert_eq!(jobs.len(), 1);
10851 assert_eq!(jobs[0].name, "brief");
10852 assert_eq!(jobs[0].prompt, "what happened yesterday");
10853 assert!(jobs[0].enabled);
10854 }
10855
10856 #[tokio::test]
10857 async fn a_schedule_the_parser_refuses_is_refused_in_the_parsers_words() {
10858 let dir = tempfile::tempdir().unwrap();
10859 let app = router(cron_state(dir.path()));
10860 let r = app
10861 .clone()
10862 .oneshot(cron_req(
10863 "POST",
10864 "/api/cron",
10865 Some(TEST_CSRF),
10866 Some(json!({"name": "brief", "schedule": "every tuesday-ish", "prompt": "x"})),
10867 ))
10868 .await
10869 .unwrap();
10870 assert_eq!(r.status(), StatusCode::BAD_REQUEST);
10871 let body = body_text(r).await;
10872 let from_parser = eclipse_core::cron::Schedule::parse("every tuesday-ish")
10875 .unwrap_err()
10876 .to_string();
10877 let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
10878 assert_eq!(parsed["error"], from_parser.as_str(), "{body}");
10879 }
10880
10881 #[tokio::test]
10882 async fn a_job_whose_name_is_taken_is_a_conflict_rather_than_a_second_block() {
10883 let dir = tempfile::tempdir().unwrap();
10884 seed_job(dir.path(), "brief", "the first one");
10885 let app = router(cron_state(dir.path()));
10886 let r = app
10887 .clone()
10888 .oneshot(cron_req(
10889 "POST",
10890 "/api/cron",
10891 Some(TEST_CSRF),
10892 Some(json!({"name": "brief", "schedule": "hourly", "prompt": "the second"})),
10893 ))
10894 .await
10895 .unwrap();
10896 assert_eq!(r.status(), StatusCode::CONFLICT);
10897 let jobs = eclipse_core::cron::load(dir.path()).unwrap();
10898 assert_eq!(jobs.len(), 1);
10899 assert_eq!(jobs[0].prompt, "the first one");
10900 }
10901
10902 #[tokio::test]
10903 async fn editing_a_job_rewrites_it_and_keeps_its_name() {
10904 let dir = tempfile::tempdir().unwrap();
10905 seed_job(dir.path(), "brief", "the old prompt");
10906 let app = router(cron_state(dir.path()));
10907 let r = app
10908 .clone()
10909 .oneshot(cron_req(
10910 "PUT",
10911 "/api/cron/brief",
10912 Some(TEST_CSRF),
10913 Some(json!({
10914 "name": "brief",
10915 "schedule": "weekly mon 09:00",
10916 "prompt": "the new prompt",
10917 })),
10918 ))
10919 .await
10920 .unwrap();
10921 assert_eq!(r.status(), StatusCode::OK);
10922 let jobs = eclipse_core::cron::load(dir.path()).unwrap();
10923 assert_eq!(jobs.len(), 1, "an edit is not an append");
10924 assert_eq!(
10925 jobs[0].schedule,
10926 eclipse_core::cron::Schedule::parse("weekly mon 09:00").unwrap()
10927 );
10928 assert_eq!(jobs[0].prompt, "the new prompt");
10929 }
10930
10931 #[tokio::test]
10932 async fn a_rename_through_the_edit_route_is_refused() {
10933 let dir = tempfile::tempdir().unwrap();
10934 seed_job(dir.path(), "brief", "keep me");
10935 let app = router(cron_state(dir.path()));
10936 let r = app
10937 .clone()
10938 .oneshot(cron_req(
10939 "PUT",
10940 "/api/cron/brief",
10941 Some(TEST_CSRF),
10942 Some(json!({"name": "digest", "schedule": "hourly", "prompt": "moved"})),
10943 ))
10944 .await
10945 .unwrap();
10946 assert_eq!(r.status(), StatusCode::BAD_REQUEST);
10947 let jobs = eclipse_core::cron::load(dir.path()).unwrap();
10948 assert_eq!(jobs[0].name, "brief");
10949 assert_eq!(jobs[0].prompt, "keep me");
10950 }
10951
10952 #[tokio::test]
10953 async fn a_job_switched_off_stays_in_the_file_and_stops_firing() {
10954 let dir = tempfile::tempdir().unwrap();
10955 seed_job(dir.path(), "brief", "keep me");
10956 let app = router(cron_state(dir.path()));
10957 let r = app
10958 .clone()
10959 .oneshot(cron_req(
10960 "POST",
10961 "/api/cron/brief/enabled",
10962 Some(TEST_CSRF),
10963 Some(json!({"enabled": false})),
10964 ))
10965 .await
10966 .unwrap();
10967 assert_eq!(r.status(), StatusCode::OK);
10968 let body = body_text(r).await;
10969 let view: serde_json::Value = serde_json::from_str(&body).expect("json");
10970 assert_eq!(view["enabled"], false, "{body}");
10971 assert!(
10972 view["next_ms"].is_null(),
10973 "a disabled job has no next fire: {body}"
10974 );
10975 let jobs = eclipse_core::cron::load(dir.path()).unwrap();
10976 assert_eq!(jobs.len(), 1, "switching off is not deleting");
10977 assert_eq!(jobs[0].prompt, "keep me");
10978 }
10979
10980 #[tokio::test]
10981 async fn removing_a_job_keeps_its_run_logs() {
10982 let dir = tempfile::tempdir().unwrap();
10983 seed_job(dir.path(), "brief", "x");
10984 eclipse_core::cron::write_run(
10985 dir.path(),
10986 "brief",
10987 1_700_000_000_000,
10988 "# brief\n\n---\n\nit ran\n",
10989 )
10990 .unwrap();
10991 let app = router(cron_state(dir.path()));
10992 let r = app
10993 .clone()
10994 .oneshot(cron_req("DELETE", "/api/cron/brief", Some(TEST_CSRF), None))
10995 .await
10996 .unwrap();
10997 assert_eq!(r.status(), StatusCode::OK);
10998 assert!(eclipse_core::cron::load(dir.path()).unwrap().is_empty());
10999 assert_eq!(
11000 eclipse_core::cron::recent_runs(dir.path(), "brief", 5).len(),
11001 1,
11002 "the record of what ran outlives the job"
11003 );
11004 let r = app
11006 .clone()
11007 .oneshot(cron_req("DELETE", "/api/cron/brief", Some(TEST_CSRF), None))
11008 .await
11009 .unwrap();
11010 assert_eq!(r.status(), StatusCode::NOT_FOUND);
11011 }
11012
11013 #[tokio::test]
11014 async fn the_logs_route_answers_with_the_text_after_the_header() {
11015 let dir = tempfile::tempdir().unwrap();
11016 seed_job(dir.path(), "brief", "x");
11017 eclipse_core::cron::write_run(
11018 dir.path(),
11019 "brief",
11020 1_700_000_000_000,
11021 "# brief — 2026-11-13 23:13\n\nschedule every 30m\n\n---\n\nthe answer\n",
11022 )
11023 .unwrap();
11024 let app = router(cron_state(dir.path()));
11025 let body = body_text(
11026 app.oneshot(cron_req("GET", "/api/cron/brief/logs?limit=3", None, None))
11027 .await
11028 .unwrap(),
11029 )
11030 .await;
11031 let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
11032 let runs = parsed["runs"].as_array().expect("runs");
11033 assert_eq!(runs.len(), 1, "{body}");
11034 assert_eq!(runs[0]["answer"], "the answer");
11035 assert_eq!(runs[0]["truncated"], false);
11036 assert!(runs[0]["text"].as_str().unwrap().contains("the answer"));
11037 }
11038
11039 #[tokio::test]
11040 async fn run_now_answers_before_the_tick_finishes() {
11041 let _env = cron_env().lock().await;
11042 let dir = tempfile::tempdir().unwrap();
11045 let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
11046 .join("../../target/fixtures")
11047 .join(std::process::id().to_string())
11048 .join("cron-run");
11049 std::fs::create_dir_all(&fixture).unwrap();
11050 let stub = fixture.join("eclipse");
11051 let seen = fixture.join("seen.txt");
11052 let _ = std::fs::remove_file(&seen);
11053 std::fs::write(
11054 &stub,
11055 format!(
11056 "#!/bin/sh\nprintf '%s\\n' \"$*\" >> {}\nsleep 2\n",
11057 seen.display()
11058 ),
11059 )
11060 .unwrap();
11061 #[cfg(unix)]
11062 {
11063 use std::os::unix::fs::PermissionsExt;
11064 std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
11065 }
11066 seed_job(dir.path(), "brief", "x");
11067 std::env::set_var("ECLIPSE_BIN", &stub);
11070 let app = router(cron_state(dir.path()));
11071 let started = std::time::Instant::now();
11072 let r = app
11073 .clone()
11074 .oneshot(cron_req(
11075 "POST",
11076 "/api/cron/brief/run",
11077 Some(TEST_CSRF),
11078 None,
11079 ))
11080 .await
11081 .unwrap();
11082 let took = started.elapsed();
11083 std::env::remove_var("ECLIPSE_BIN");
11084 let status = r.status();
11085 let answer = body_text(r).await;
11086 assert_eq!(status, StatusCode::ACCEPTED);
11087 assert!(
11088 took < std::time::Duration::from_millis(1500),
11089 "the handler waited for the tick ({took:?})"
11090 );
11091 let mut seen_text = String::new();
11093 for _ in 0..50 {
11094 if let Ok(t) = std::fs::read_to_string(&seen) {
11095 if t.contains("cron run brief") {
11096 seen_text = t;
11097 break;
11098 }
11099 }
11100 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
11101 }
11102 assert!(
11103 seen_text.contains("cron run brief"),
11104 "the stub saw: {seen_text:?}"
11105 );
11106
11107 let parsed: serde_json::Value = serde_json::from_str(&answer).expect("the answer is json");
11111 let pid = parsed["pid"].as_u64().expect("the answer names the pid");
11112 let mut reaped = false;
11113 for _ in 0..40 {
11114 if !std::path::Path::new(&format!("/proc/{pid}")).exists() {
11115 reaped = true;
11116 break;
11117 }
11118 tokio::time::sleep(std::time::Duration::from_millis(250)).await;
11119 }
11120 assert!(
11121 reaped,
11122 "/proc/{pid} is still there: the spawned tick was never reaped"
11123 );
11124 }
11125
11126 #[tokio::test]
11130 async fn the_started_tick_is_told_the_profile_and_config_this_dashboard_uses() {
11131 let _env = cron_env().lock().await;
11132 let dir = tempfile::tempdir().unwrap();
11133 let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
11134 .join("../../target/fixtures")
11135 .join(std::process::id().to_string())
11136 .join("cron-profile");
11137 std::fs::create_dir_all(&fixture).unwrap();
11138 let stub = fixture.join("eclipse");
11139 let seen = fixture.join("seen.txt");
11140 let _ = std::fs::remove_file(&seen);
11141 std::fs::write(
11142 &stub,
11143 format!("#!/bin/sh\nprintf '%s\\n' \"$*\" >> {}\n", seen.display()),
11144 )
11145 .unwrap();
11146 #[cfg(unix)]
11147 {
11148 use std::os::unix::fs::PermissionsExt;
11149 std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
11150 }
11151 seed_job(dir.path(), "brief", "x");
11152 let config = dir.path().join("config.toml");
11153 let st = Arc::try_unwrap(state(dir.path(), true))
11154 .unwrap_or_else(|_| panic!("a state built here is not shared yet"))
11155 .with_cron_root(dir.path().to_path_buf())
11156 .with_config_path(Some(config.clone()), Some("work".into()));
11157 std::env::set_var("ECLIPSE_BIN", &stub);
11158 let r = router(Arc::new(st))
11159 .oneshot(cron_req(
11160 "POST",
11161 "/api/cron/brief/run",
11162 Some(TEST_CSRF),
11163 None,
11164 ))
11165 .await
11166 .unwrap();
11167 std::env::remove_var("ECLIPSE_BIN");
11168 assert_eq!(r.status(), StatusCode::ACCEPTED);
11169
11170 let mut said = String::new();
11171 for _ in 0..50 {
11172 if let Ok(t) = std::fs::read_to_string(&seen) {
11173 if t.contains("cron run brief") {
11174 said = t;
11175 break;
11176 }
11177 }
11178 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
11179 }
11180 assert!(said.contains("cron run brief"), "the stub saw: {said:?}");
11181 assert!(
11182 said.contains("--profile work"),
11183 "the tick was started without this dashboard's profile: {said:?}"
11184 );
11185 assert!(
11186 said.contains(&format!("--config {}", config.display())),
11187 "the tick was started without this dashboard's config: {said:?}"
11188 );
11189 }
11190
11191 #[test]
11195 fn an_unnamed_picture_does_not_put_its_data_url_in_the_text() {
11196 let (said, pictures) = compose_attachments(
11197 "what is this?",
11198 &[Attachment {
11199 kind: "image".into(),
11200 name: String::new(),
11201 value: "data:image/png;base64,iVBORw0KGgo=".into(),
11202 }],
11203 )
11204 .unwrap();
11205 assert_eq!(pictures.len(), 1);
11206 assert_eq!(pictures[0].name, "picture");
11207 assert!(
11208 said.contains("--- attached picture: picture (image/png) ---"),
11209 "{said}"
11210 );
11211 assert!(!said.contains("base64"), "the data URL is not text: {said}");
11212 }
11213
11214 #[test]
11218 fn the_body_cap_fits_the_pictures_the_rules_allow() {
11219 let picture_in_base64 = eclipse_core::message::MAX_PICTURE_BYTES / 3 * 4;
11220 assert!(
11221 CHAT_BODY_LIMIT > 2 * picture_in_base64,
11222 "two 2 MiB pictures are {pictures} of data URL and the cap is {CHAT_BODY_LIMIT}",
11223 pictures = 2 * picture_in_base64
11224 );
11225 assert!(
11226 CHAT_BODY_LIMIT > MAX_ATTACHMENTS / 2 * picture_in_base64,
11227 "half a turn of pictures must fit: {CHAT_BODY_LIMIT}"
11228 );
11229 }
11230
11231 fn mcp_state(dir: &std::path::Path, text: &str) -> Shared {
11237 std::fs::write(dir.join("config.toml"), text).unwrap();
11238 state_with(dir, true, Some(dir.join("config.toml")))
11239 }
11240
11241 const FAKE_MCP: &str = r#"#!/usr/bin/env python3
11244import json, sys
11245
11246def send(obj):
11247 sys.stdout.write(json.dumps(obj) + "\n"); sys.stdout.flush()
11248
11249for line in sys.stdin:
11250 line = line.strip()
11251 if not line:
11252 continue
11253 msg = json.loads(line)
11254 mid, method = msg.get("id"), msg.get("method")
11255 if method == "initialize":
11256 send({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": "2024-11-05",
11257 "capabilities": {"tools": {}}, "serverInfo": {"name": "fake", "version": "0"}}})
11258 elif method == "tools/list":
11259 send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
11260 {"name": "echo_text", "description": "Echo", "inputSchema": {"type": "object"}},
11261 {"name": "read_note", "description": "Read", "inputSchema": {"type": "object"}}]}})
11262"#;
11263
11264 fn fake_mcp(dir: &std::path::Path) -> String {
11265 let path = dir.join("fake_mcp.py");
11266 std::fs::write(&path, FAKE_MCP).unwrap();
11267 path.to_string_lossy().into_owned()
11268 }
11269
11270 fn servers_of(body: &str) -> Vec<serde_json::Value> {
11271 let parsed: serde_json::Value = serde_json::from_str(body).expect("json");
11272 parsed["servers"]
11273 .as_array()
11274 .expect("a servers array")
11275 .clone()
11276 }
11277
11278 #[tokio::test]
11282 async fn the_problems_endpoint_answers_the_shape_the_pane_renders() {
11283 let dir = tempfile::tempdir().unwrap();
11284 let app = router(mcp_state(dir.path(), "[provider]\nmodel = \"m\"\n"));
11285 let body = body_text(
11286 app.oneshot(cron_req("GET", "/api/problems", None, None))
11287 .await
11288 .unwrap(),
11289 )
11290 .await;
11291 let parsed: serde_json::Value = serde_json::from_str(&body).expect("json");
11292 assert!(parsed["summary"].is_string(), "{body}");
11293 assert!(parsed["problems"].is_array(), "{body}");
11294 let checked = parsed["checked"].as_array().expect("checked is an array");
11295 assert!(
11296 checked
11297 .iter()
11298 .any(|c| c.as_str().is_some_and(|s| s.starts_with("skill root:"))),
11299 "the readout says what was searched: {body}"
11300 );
11301 for problem in parsed["problems"].as_array().expect("an array") {
11303 assert!(problem["kind"].is_string(), "{problem}");
11304 assert!(problem["text"].is_string(), "{problem}");
11305 }
11306 }
11307
11308 #[tokio::test]
11311 async fn a_config_that_did_not_load_is_reported_beside_the_loader_problems() {
11312 let dir = tempfile::tempdir().unwrap();
11313 let store = SessionStore::new(dir.path().join("sessions"));
11314 let app = router(Arc::new(authed(
11315 None,
11316 store,
11317 "test-<model>",
11318 Some("provider.base_url is not set".into()),
11319 )));
11320 let body = body_text(
11321 app.oneshot(cron_req("GET", "/api/problems", None, None))
11322 .await
11323 .unwrap(),
11324 )
11325 .await;
11326 assert!(
11327 body.contains("provider.base_url is not set"),
11328 "the loader line is carried: {body}"
11329 );
11330 }
11331
11332 #[tokio::test]
11333 async fn an_mcp_entry_in_the_file_is_listed_with_its_source_and_tools() {
11334 let dir = tempfile::tempdir().unwrap();
11335 let script = fake_mcp(dir.path());
11336 let app = router(mcp_state(
11337 dir.path(),
11338 &format!(
11339 "[[mcp]]\nname = \"docs\"\ncommand = \"python3\"\nargs = [\"{script}\"]\n\
11340 timeout_secs = 20\n"
11341 ),
11342 ));
11343 let body = body_text(
11344 app.oneshot(cron_req("GET", "/api/mcp", None, None))
11345 .await
11346 .unwrap(),
11347 )
11348 .await;
11349 let row = servers_of(&body)
11350 .into_iter()
11351 .find(|r| r["name"] == "docs")
11352 .unwrap_or_else(|| panic!("the entry is not in the list: {body}"));
11353 assert_eq!(row["source"], "config:mcp:docs", "{body}");
11355 assert_eq!(row["tools"], 2, "{body}");
11356 assert_eq!(row["started"], true, "{body}");
11357 assert_eq!(row["protocol"], "2024-11-05", "{body}");
11359 assert_eq!(row["server_name"], "fake", "{body}");
11360 }
11361
11362 #[tokio::test]
11363 async fn switching_an_mcp_server_off_reaches_the_file_and_the_list_agrees() {
11364 let dir = tempfile::tempdir().unwrap();
11365 let app = router(mcp_state(
11366 dir.path(),
11367 "[[mcp]]\nname = \"ghost\"\ncommand = \"/nonexistent/eclipse-test-mcp\"\n",
11368 ));
11369 let r = app
11370 .clone()
11371 .oneshot(cron_req(
11372 "POST",
11373 "/api/mcp/ghost/enabled",
11374 Some(TEST_CSRF),
11375 Some(json!({"enabled": false})),
11376 ))
11377 .await
11378 .unwrap();
11379 assert_eq!(r.status(), StatusCode::OK);
11380 let body = body_text(r).await;
11381 let row: serde_json::Value = serde_json::from_str(&body).expect("json");
11382 assert_eq!(row["disabled"], true, "{body}");
11383 assert_eq!(row["started"], false, "{body}");
11385 assert_eq!(row["tools"], 0, "{body}");
11386 let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
11388 assert!(text.contains("disabled = true"), "{text}");
11389 let listed = body_text(
11391 app.clone()
11392 .oneshot(cron_req("GET", "/api/mcp", None, None))
11393 .await
11394 .unwrap(),
11395 )
11396 .await;
11397 let row = servers_of(&listed)
11398 .into_iter()
11399 .find(|r| r["name"] == "ghost")
11400 .expect("switching off is not deleting");
11401 assert_eq!(row["disabled"], true, "{listed}");
11402 let r = app
11404 .clone()
11405 .oneshot(cron_req(
11406 "POST",
11407 "/api/mcp/ghost/enabled",
11408 Some(TEST_CSRF),
11409 Some(json!({"enabled": true})),
11410 ))
11411 .await
11412 .unwrap();
11413 assert_eq!(r.status(), StatusCode::OK);
11414 let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
11415 assert!(text.contains("disabled = false"), "{text}");
11416 }
11417
11418 #[tokio::test]
11419 async fn adding_a_server_writes_the_entry_a_duplicate_refuses_and_a_removal_takes() {
11420 let dir = tempfile::tempdir().unwrap();
11421 let script = fake_mcp(dir.path());
11422 let app = router(mcp_state(
11423 dir.path(),
11424 "# mcp servers live below this note\n",
11425 ));
11426 let add = json!({"name": "docs", "command": "python3", "args": [script], "policy": "ask"});
11427 let r = app
11428 .clone()
11429 .oneshot(cron_req(
11430 "POST",
11431 "/api/mcp",
11432 Some(TEST_CSRF),
11433 Some(add.clone()),
11434 ))
11435 .await
11436 .unwrap();
11437 assert_eq!(r.status(), StatusCode::CREATED);
11438 let body = body_text(r).await;
11439 let row: serde_json::Value = serde_json::from_str(&body).expect("json");
11440 assert_eq!(row["source"], "config:mcp:docs", "{body}");
11441 assert_eq!(row["tools"], 2, "{body}");
11442 let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
11443 assert!(
11444 text.contains("# mcp servers live below this note"),
11445 "{text}"
11446 );
11447
11448 let r = app
11450 .clone()
11451 .oneshot(cron_req("POST", "/api/mcp", Some(TEST_CSRF), Some(add)))
11452 .await
11453 .unwrap();
11454 assert_eq!(r.status(), StatusCode::CONFLICT);
11455 let body = body_text(r).await;
11456 assert!(body.contains("is already declared at line"), "{body}");
11457 let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
11458 assert_eq!(text.matches("[[mcp]]").count(), 1, "{text}");
11459
11460 let r = app
11462 .clone()
11463 .oneshot(cron_req(
11464 "POST",
11465 "/api/mcp",
11466 Some(TEST_CSRF),
11467 Some(json!({"name": "mixed", "transport": "http", "command": "python3"})),
11468 ))
11469 .await
11470 .unwrap();
11471 assert_eq!(r.status(), StatusCode::BAD_REQUEST);
11472 let body = body_text(r).await;
11473 assert!(body.contains("that entry is not usable"), "{body}");
11474
11475 let r = app
11477 .clone()
11478 .oneshot(cron_req("DELETE", "/api/mcp/docs", Some(TEST_CSRF), None))
11479 .await
11480 .unwrap();
11481 assert_eq!(r.status(), StatusCode::OK);
11482 let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
11483 assert!(!text.contains("[[mcp]]"), "{text}");
11484 let listed = body_text(
11485 app.clone()
11486 .oneshot(cron_req("GET", "/api/mcp", None, None))
11487 .await
11488 .unwrap(),
11489 )
11490 .await;
11491 assert!(servers_of(&listed).is_empty(), "{listed}");
11492
11493 let r = app
11495 .oneshot(cron_req("DELETE", "/api/mcp/docs", Some(TEST_CSRF), None))
11496 .await
11497 .unwrap();
11498 assert_eq!(r.status(), StatusCode::NOT_FOUND);
11499 }
11500
11501 #[tokio::test]
11505 async fn editing_an_entry_changes_one_field_and_leaves_the_neighbours_byte_identical() {
11506 let dir = tempfile::tempdir().unwrap();
11507 let before = "# the ghost\n[[mcp]]\nname = \"ghost\"\ncommand = \"/nonexistent/one\"\n\n\
11508 # the other one\n[[mcp]]\nname = \"other\"\n\
11509 command = \"/nonexistent/two\"\npolicy = \"allow\"\n";
11510 let app = router(mcp_state(dir.path(), before));
11511 let r = app
11512 .clone()
11513 .oneshot(cron_req(
11514 "PUT",
11515 "/api/mcp/other",
11516 Some(TEST_CSRF),
11517 Some(json!({
11518 "name": "other",
11519 "command": "/nonexistent/three",
11520 "policy": "allow",
11521 })),
11522 ))
11523 .await
11524 .unwrap();
11525 assert_eq!(r.status(), StatusCode::OK, "{}", body_text(r).await);
11526 let after = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
11527 assert_eq!(
11528 after,
11529 before.replace("/nonexistent/two", "/nonexistent/three"),
11530 "an edit is not a remove and an add:\n{after}"
11531 );
11532
11533 let listed = body_text(
11535 app.clone()
11536 .oneshot(cron_req("GET", "/api/mcp", None, None))
11537 .await
11538 .unwrap(),
11539 )
11540 .await;
11541 let row = servers_of(&listed)
11542 .into_iter()
11543 .find(|r| r["name"] == "other")
11544 .expect("the edited entry is still listed");
11545 assert_eq!(row["program"], "/nonexistent/three", "{listed}");
11546 assert_eq!(row["args"], json!([]), "{listed}");
11547 }
11548
11549 #[tokio::test]
11553 async fn a_token_env_typed_in_the_form_is_written_and_the_listing_says_whether_it_resolves() {
11554 let dir = tempfile::tempdir().unwrap();
11555 let key = format!("ECLIPSE_TEST_WEB_MCP_TOKEN{}", "_SET");
11559 std::env::set_var(&key, "kept-here");
11560 let before = "[[mcp]]\nname = \"ha\"\ntransport = \"http\"\n\
11561 url = \"http://127.0.0.1:9/api/mcp\"\n";
11562 let app = router(mcp_state(dir.path(), before));
11563 let put = |token: String| {
11564 json!({
11565 "name": "ha",
11566 "transport": "http",
11567 "url": "http://127.0.0.1:9/api/mcp",
11568 "token_env": token,
11569 })
11570 };
11571 let r = app
11572 .clone()
11573 .oneshot(cron_req(
11574 "PUT",
11575 "/api/mcp/ha",
11576 Some(TEST_CSRF),
11577 Some(put(key.clone())),
11578 ))
11579 .await
11580 .unwrap();
11581 assert_eq!(r.status(), StatusCode::OK);
11582 let body = body_text(r).await;
11583 let row: serde_json::Value = serde_json::from_str(&body).expect("json");
11584 assert_eq!(row["token_env"], key.as_str(), "{body}");
11585 assert_eq!(row["token"], "env", "it resolves: {body}");
11586 assert!(
11587 !body.contains("kept-here"),
11588 "the row carries the word, never the value: {body}"
11589 );
11590 let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();
11591 assert!(
11592 text.contains(&format!("token_env = \"{key}\"")),
11593 "the variable name is what the file carries: {text}"
11594 );
11595
11596 let absent = format!("{key}_UNSET");
11598 let r = app
11599 .clone()
11600 .oneshot(cron_req(
11601 "PUT",
11602 "/api/mcp/ha",
11603 Some(TEST_CSRF),
11604 Some(put(absent.clone())),
11605 ))
11606 .await
11607 .unwrap();
11608 assert_eq!(r.status(), StatusCode::OK);
11609 let body = body_text(r).await;
11610 let row: serde_json::Value = serde_json::from_str(&body).expect("json");
11611 assert_eq!(row["token"], "unset", "{body}");
11612 assert_eq!(row["token_env"], absent.as_str(), "{body}");
11613 std::env::remove_var(&key);
11614 }
11615
11616 #[tokio::test]
11619 async fn an_unknown_entry_is_a_404_a_bad_body_and_a_rename_change_nothing() {
11620 let dir = tempfile::tempdir().unwrap();
11621 let before = "[[mcp]]\nname = \"ghost\"\ncommand = \"/nonexistent/one\"\n";
11622 let app = router(mcp_state(dir.path(), before));
11623 let config = dir.path().join("config.toml");
11624
11625 let r = app
11626 .clone()
11627 .oneshot(cron_req(
11628 "PUT",
11629 "/api/mcp/nope",
11630 Some(TEST_CSRF),
11631 Some(json!({"command": "/nonexistent/any"})),
11632 ))
11633 .await
11634 .unwrap();
11635 assert_eq!(r.status(), StatusCode::NOT_FOUND);
11636 let body = body_text(r).await;
11637 assert!(body.contains("no `[[mcp]]` entry for `nope`"), "{body}");
11638
11639 let r = app
11641 .clone()
11642 .oneshot(
11643 HttpRequest::builder()
11644 .method("PUT")
11645 .uri("/api/mcp/ghost")
11646 .header("host", "127.0.0.1:8787")
11647 .header("origin", "null")
11648 .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
11649 .header(CSRF_HEADER, TEST_CSRF)
11650 .header("content-type", "application/json")
11651 .body(Body::from("{\"command\": "))
11652 .unwrap(),
11653 )
11654 .await
11655 .unwrap();
11656 assert!(
11657 !r.status().is_success(),
11658 "a malformed body is not a saved entry: {}",
11659 body_text(r).await
11660 );
11661
11662 let r = app
11663 .clone()
11664 .oneshot(cron_req(
11665 "PUT",
11666 "/api/mcp/ghost",
11667 Some(TEST_CSRF),
11668 Some(json!({"name": "renamed", "command": "/nonexistent/one"})),
11669 ))
11670 .await
11671 .unwrap();
11672 assert_eq!(r.status(), StatusCode::BAD_REQUEST);
11673 let body = body_text(r).await;
11674 assert!(body.contains("an edit does not rename"), "{body}");
11675
11676 assert_eq!(
11677 std::fs::read_to_string(&config).unwrap(),
11678 before,
11679 "three refusals, and the file is exactly what it was"
11680 );
11681 }
11682
11683 fn bot_state(dir: &std::path::Path) -> (Shared, std::path::PathBuf) {
11692 let ws = dir.join("ws");
11693 std::fs::create_dir_all(ws.join(".eclipse/skills/one")).unwrap();
11694 std::fs::write(
11695 ws.join(".eclipse/skills/one/SKILL.md"),
11696 "---\nname: one\ndescription: the skill this bot declared\n---\nbody one\n",
11697 )
11698 .unwrap();
11699 let instructions = dir.join("nox.md");
11700 std::fs::write(&instructions, "you are nox, and this is your own prompt\n").unwrap();
11701 let config = dir.join("config.toml");
11702 std::fs::write(
11703 &config,
11704 format!(
11705 r#"
11706[provider]
11707base_url = "http://127.0.0.1:1/v1"
11708model = "test"
11709api_key = "k"
11710
11711[sessions]
11712dir = {sessions:?}
11713
11714[tools]
11715workspace_root = {workspace:?}
11716
11717[bots.nox]
11718instructions = {instructions:?}
11719skills = ["one"]
11720adapter = "telegram"
11721"#,
11722 sessions = dir.join("sessions").display().to_string(),
11723 workspace = ws.display().to_string(),
11724 instructions = instructions.display().to_string(),
11725 ),
11726 )
11727 .unwrap();
11728 let cfg = eclipse_core::config::Config::from_file(&config).unwrap();
11729 let home = dir.join("home");
11730 std::fs::create_dir_all(&home).unwrap();
11731 let env = |key: &str| (key == "HOME").then(|| home.display().to_string());
11732 let store = SessionStore::new(cfg.sessions_dir(&env).unwrap());
11733 let agent = Arc::new(Agent::new(
11734 Arc::new(Canned),
11735 Arc::new(ToolRegistry::default()),
11736 store.clone(),
11737 "sys".into(),
11738 3,
11739 ));
11740 let mut st =
11741 authed(Some(agent), store, "test-<model>", None).with_config_path(Some(config), None);
11742 st.bots = crate::bots::Bots::build(&cfg, &env);
11743 (Arc::new(st), instructions)
11744 }
11745
11746 #[tokio::test]
11747 async fn a_page_with_no_bots_carries_no_bots_tab() {
11748 let dir = tempfile::tempdir().unwrap();
11749 let app = router(state(dir.path(), true));
11750 let page = body_text(app.oneshot(get_req("/", "127.0.0.1:8787")).await.unwrap()).await;
11751 assert!(
11752 !page.contains("id=\"bots\""),
11753 "a config with no bots grew a Bots button: the Sessions tab is not unchanged"
11754 );
11755 assert!(
11756 !page.contains("<section id=\"botspane\""),
11757 "the pane is in the page with no bots"
11758 );
11759 assert!(
11760 page.contains("<ul id=\"sessions\">"),
11761 "the session list is still there"
11762 );
11763 }
11764
11765 #[tokio::test]
11766 async fn a_declared_bot_lists_and_opens_one_session_with_its_own_origin() {
11767 let dir = tempfile::tempdir().unwrap();
11768 let (st, _) = bot_state(dir.path());
11769 let app = router(st.clone());
11770
11771 let listed = body_text(
11772 app.clone()
11773 .oneshot(get_req("/api/bots", "127.0.0.1:8787"))
11774 .await
11775 .unwrap(),
11776 )
11777 .await;
11778 let rows: Vec<serde_json::Value> = serde_json::from_str(&listed).unwrap();
11779 assert_eq!(rows.len(), 1, "{listed}");
11780 assert_eq!(rows[0]["name"], "nox");
11781 assert_eq!(
11782 rows[0]["lane"], "telegram",
11783 "the declaration's lane is what the row says"
11784 );
11785 assert!(rows[0]["last_session"].is_null(), "it has not spoken yet");
11786 assert!(rows[0]["problem"].is_null(), "{listed}");
11787
11788 let open = |app: axum::Router| async move {
11789 body_text(
11790 app.oneshot(
11791 HttpRequest::post("/api/bots/nox/open")
11792 .header("host", "127.0.0.1:8787")
11793 .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
11794 .header("content-type", "application/json")
11795 .body(Body::from("{}"))
11796 .unwrap(),
11797 )
11798 .await
11799 .unwrap(),
11800 )
11801 .await
11802 };
11803 let first = open(app.clone()).await;
11804 let second = open(app.clone()).await;
11805 let first: serde_json::Value = serde_json::from_str(&first).unwrap();
11806 let second: serde_json::Value = serde_json::from_str(&second).unwrap();
11807 let id = first["session_id"].as_str().unwrap().to_string();
11808 assert_eq!(
11809 second["session_id"], first["session_id"],
11810 "opening a bot twice made two conversations"
11811 );
11812 assert_eq!(
11813 st.store.origin(&id).unwrap().as_deref(),
11814 Some("bot:nox"),
11815 "the row the send path reads its identity from"
11816 );
11817
11818 let mine = body_text(
11820 app.clone()
11821 .oneshot(get_req("/api/sessions", "127.0.0.1:8787"))
11822 .await
11823 .unwrap(),
11824 )
11825 .await;
11826 assert!(
11827 !mine.contains(&id),
11828 "a bot's conversation reached the sidebar: {mine}"
11829 );
11830
11831 let agent = st.bots.agent("nox").unwrap().as_ref().unwrap();
11834 assert!(agent.system_prompt().contains("you are nox"));
11835 }
11836
11837 #[tokio::test]
11838 async fn a_bot_conversation_is_cleared_not_deleted() {
11839 let dir = tempfile::tempdir().unwrap();
11840 let (st, _) = bot_state(dir.path());
11841 let app = router(st.clone());
11842 let open = |app: axum::Router, uri: &'static str| async move {
11843 let r = app
11844 .oneshot(
11845 HttpRequest::post(uri)
11846 .header("host", "127.0.0.1:8787")
11847 .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
11848 .header("content-type", "application/json")
11849 .body(Body::from("{}"))
11850 .unwrap(),
11851 )
11852 .await
11853 .unwrap();
11854 (r.status(), body_text(r).await)
11855 };
11856 let (_, body) = open(app.clone(), "/api/bots/nox/open").await;
11857 let first: serde_json::Value = serde_json::from_str(&body).unwrap();
11858 let first = first["session_id"].as_str().unwrap().to_string();
11859
11860 let (status, body) = open(app.clone(), "/api/bots/nox/clear").await;
11861 assert_eq!(status, StatusCode::OK, "{body}");
11862 let cleared: serde_json::Value = serde_json::from_str(&body).unwrap();
11863 assert_eq!(cleared["archived"], 1);
11864 let fresh = cleared["session_id"].as_str().unwrap();
11865 assert_ne!(
11866 fresh, first,
11867 "a cleared bot kept the conversation it was told to file away"
11868 );
11869
11870 assert!(st.store.exists(&first), "clearing deleted the transcript");
11872 let bots = st.store.list_bots().unwrap();
11873 assert_eq!(bots[0].sessions, 2, "both conversations are counted");
11874 assert_eq!(bots[0].last_session, fresh);
11875 }
11876
11877 #[tokio::test]
11878 async fn the_prompt_view_reads_the_instructions_file_from_disk() {
11879 let dir = tempfile::tempdir().unwrap();
11880 let (st, instructions) = bot_state(dir.path());
11881 std::fs::write(
11884 &instructions,
11885 "you are nox, rewritten after the process started\n",
11886 )
11887 .unwrap();
11888 let app = router(st);
11889 let body = body_text(
11890 app.oneshot(get_req("/api/bots/nox/prompt", "127.0.0.1:8787"))
11891 .await
11892 .unwrap(),
11893 )
11894 .await;
11895 let data: serde_json::Value = serde_json::from_str(&body).unwrap();
11896 assert_eq!(data["name"], "nox");
11897 assert!(
11898 data["instructions"]["body"]
11899 .as_str()
11900 .unwrap_or_default()
11901 .contains("rewritten after the process started"),
11902 "{body}"
11903 );
11904 assert_eq!(data["skills"], serde_json::json!(["one"]));
11905 assert_eq!(data["adapter"], "telegram");
11906 }
11907
11908 #[tokio::test]
11912 async fn a_page_with_no_flare_runs_carries_no_flares_tab() {
11913 let dir = tempfile::tempdir().unwrap();
11914 let app = router(state(dir.path(), true));
11915 let page = body_text(app.oneshot(get_req("/", "127.0.0.1:8787")).await.unwrap()).await;
11916 assert!(
11917 !page.contains("id=\"flares\""),
11918 "a person with no flare runs grew a Flares button"
11919 );
11920 assert!(
11921 !page.contains("<section id=\"flarespane\""),
11922 "the pane is in the page with no runs to show"
11923 );
11924 assert!(
11927 page.contains("main.flares #flarespane"),
11928 "the tab's styles are part of the page, not spliced with it"
11929 );
11930 assert!(
11931 page.contains("<ul id=\"sessions\">"),
11932 "the session list is still there"
11933 );
11934 }
11935
11936 #[tokio::test]
11942 async fn a_flare_run_lists_its_children_and_a_cancel_reaches_the_store() {
11943 let dir = tempfile::tempdir().unwrap();
11944 let st = state(dir.path(), true);
11945 let store = st.store.clone();
11946 store
11947 .begin_flare_run(
11948 "run-1",
11949 "audit the retry paths",
11950 &["local".to_string(), "cloud".to_string()],
11951 2,
11952 "web",
11953 )
11954 .unwrap();
11955 store.begin_flare("flare-child-1", "run-1", 1).unwrap();
11956 store
11957 .flare_job_running("run-1", 1, "local", "flare-child-1")
11958 .unwrap();
11959 store
11960 .flare_job_done(&FlareJobRow {
11961 run_id: "run-1".into(),
11962 n: 1,
11963 route: "local".into(),
11964 session_id: Some("flare-child-1".into()),
11965 state: "done".into(),
11966 prompt_tokens: Some(1200),
11967 completion_tokens: Some(340),
11968 iterations: 2,
11969 why: None,
11970 })
11971 .unwrap();
11972 store
11973 .flare_job_done(&FlareJobRow {
11974 run_id: "run-1".into(),
11975 n: 2,
11976 route: "cloud".into(),
11977 session_id: None,
11978 state: "dropped".into(),
11979 prompt_tokens: None,
11980 completion_tokens: None,
11981 iterations: 0,
11982 why: Some("the run was cancelled before it started".into()),
11983 })
11984 .unwrap();
11985 store
11986 .finish_flare_run("run-1", "cancelled", Some(1200), Some(340), 2)
11987 .unwrap();
11988 let app = router(st);
11989
11990 let page = body_text(
11993 app.clone()
11994 .oneshot(get_req("/", "127.0.0.1:8787"))
11995 .await
11996 .unwrap(),
11997 )
11998 .await;
11999 assert!(
12000 page.contains("id=\"flares\""),
12001 "the sidebar has no Flares button"
12002 );
12003 assert!(
12004 page.contains("<section id=\"flarespane\""),
12005 "the pane is missing"
12006 );
12007 assert!(
12008 page.contains("main.flares #flarespane"),
12009 "the pane's styles came with the page"
12010 );
12011
12012 let listed = body_text(
12013 app.clone()
12014 .oneshot(get_req("/api/flares", "127.0.0.1:8787"))
12015 .await
12016 .unwrap(),
12017 )
12018 .await;
12019 let rows: Vec<serde_json::Value> = serde_json::from_str(&listed).unwrap();
12020 assert_eq!(rows.len(), 1, "{listed}");
12021 assert_eq!(rows[0]["id"], "run-1");
12022 assert_eq!(
12023 rows[0]["jobs"], 2,
12024 "the count the run planned, not the children that started"
12025 );
12026 assert_eq!(
12027 rows[0]["routes"],
12028 serde_json::json!(["local", "cloud"]),
12029 "the routes the run named"
12030 );
12031 assert_eq!(rows[0]["state"], "cancelled");
12032 assert_eq!(rows[0]["running"], false);
12033 assert_eq!(rows[0]["prompt_tokens"], 1200);
12034
12035 let one = body_text(
12036 app.clone()
12037 .oneshot(get_req("/api/flares/run-1", "127.0.0.1:8787"))
12038 .await
12039 .unwrap(),
12040 )
12041 .await;
12042 let one: serde_json::Value = serde_json::from_str(&one).unwrap();
12043 assert_eq!(
12044 one["jobs"][0]["session_id"], "flare-child-1",
12045 "the session a click opens in the transcript view"
12046 );
12047 assert_eq!(one["jobs"][0]["completion_tokens"], 340);
12048 assert!(
12049 one["jobs"][1]["session_id"].is_null(),
12050 "a dropped child has no transcript"
12051 );
12052 assert!(
12053 one["jobs"][1]["prompt_tokens"].is_null(),
12054 "a dropped child costs nothing, and `null` is what the page turns into `?`"
12055 );
12056 assert_eq!(
12057 one["jobs"][1]["why"],
12058 "the run was cancelled before it started"
12059 );
12060
12061 let cancelled = app
12064 .clone()
12065 .oneshot(
12066 HttpRequest::post("/api/flares/run-1/cancel")
12067 .header("host", "127.0.0.1:8787")
12068 .header("cookie", format!("{SESSION_COOKIE}={LOGIN_ID}"))
12069 .header("content-type", "application/json")
12070 .body(Body::from("{}"))
12071 .unwrap(),
12072 )
12073 .await
12074 .unwrap();
12075 let status = cancelled.status();
12076 let body = body_text(cancelled).await;
12077 assert_eq!(status, StatusCode::OK, "{body}");
12078 assert!(
12079 body.contains("next boundary"),
12080 "the answer says what a cancel does, not that it is done: {body}"
12081 );
12082 assert!(
12083 store.flare_cancel_requested("run-1").unwrap(),
12084 "the flag the run checks between children"
12085 );
12086
12087 let missing = app
12089 .oneshot(get_req("/api/flares/nope", "127.0.0.1:8787"))
12090 .await
12091 .unwrap();
12092 assert_eq!(missing.status(), StatusCode::NOT_FOUND);
12093 }
12094}